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

Constant current draw is 26.8 microamps.
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.
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:

Arduino pro mini with on board LEDs and voltage regulator removed.
LDR sensor with 10k resistor
LED with 220K resistor for low battery warning
5v boost converter with on board LEDs removed (used to boost the 3.7v LiPo battery to 5v; actually boosts to about 5.27v)
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.

Hello 28µA in sleep mode still quite high, have a look on this board... talk2.wisen.com.au/product-talk2-whisper-node-avr less the 4µA when sleeping and you can have the node powered by a single AA while the servo is powered by some fat batteries, like two Alkaline D.This setup will isolate the high drainage servo from the MCU and you can even monitor the all voltages. Finally, avoid rechargeable cells as the self discharge is quite high. For best results you could try the 3.6V Lithium thionyl chloride for the servos, but they're quite expensive.

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.

Alberto, thanks for you input.  So I have those current draw measurements.  In standby or power down mode the project draws 26.8 microamps.  When the servo is rotating, the project draws about 11 milliamps.  On any given day, the project will spend 99% of its time in standby mode and the other 1% active.  So why can't I get a 2,500 mah 3.7v LiPo battery to last longer than a couple of weeks?

With some approximation, the battery in your setup will last 20 days at its best, so it seems to respect what you saw.

Alberto, looks like your right.  The darn servo current draw in idle mode is draining the battery more than I expected.  Need to isolate the servo with its own power source.

Or you should use a relay to detach the servo when in idle

I though about using a relay but I have read some posts that stay that the servo "Jumps" when powered on and moves to the manufacturer established angle before executing my sketch.  I guess that isn't really a big deal as I'm just controlling the angle of windows blinds and am more concerned with battery life.  What kind of relay would I use?  I have used DC to AC relays before; am i looking for a DC to DC relay?

You could use an optocoupler (til113 or similar) or a transistor seen your current draw. If you want to use a relay, you can use any relay with the coil rated at 5v. For less power consumption I suggest optocoupling or transistors.

did some research on the optocoupler and I wonder if I need to use a transistor as well with this circuit?  Can I just go from from the arduino through a resistor to the optocoupler then through another resistor to the servo?  Thanks.

4N35 has a Ic max of 50 mA so it should be fine if your servo just needs 11 mA

The scheme isn't correct, you should connect servo pos to battery pos then servo neg to opto collector and opto emitter to battery neg. The sig wire should be connected to an arduino pin directly, or if you want to isolate it, use also an optocoupler.

thanks.  Updated the scheme.  Need to order some optocouplers and test out.  Will let you know if all goes well.  New scheme here: https://postimg.org/image/j39natiel/

Ok thank you, I've seen the scheme, the resistor on the servo isn't necessary, but is all well connected.

If you look at the discharge curves of LiPo batteries, you can see the voltage will drop a bit faster when full. Then flatten out, and have a big voltage drop when they are almost empty. So I'm not sure you can tell from the 0.44V drop that the battery is being discharged faster.
If there is a problem, I think it is either the boost converters quiescent current, or the servo. Also not that because you have to convert the 3.7V up to 5V, the current coming from the battery will have to increase by 1.35 times (at 100% efficiency).
What booster are you using? How do you turn off the servo?
PS1;
I always use this calculator to get an approximate battery life.
PS2; I'd connect the pull-up resistor on the LDR to a digital pin, so you can activate it only when you need to measure the light level, saving 2-5 µA.

thanks for the reply.  I am in the process of putting together a picture that shows the wiring of the project.  I believe I have already connected the pull-up resistor of the LDR to a digital pin (const int ldrPower = 8;).  As far as the boost converter goes I am using one of those postage stamp size modules available from eBay.  According to the seller, the quiescent current is 130 microamps.  The servo is turned on and off via code right before and after an angle change.  Thanks.

Have you tried measuring the power going out of the battery, so including everything (servo, booster, and arduino)?

just checked the battery with a multi-meter and the power coming out before the booster is 3.68v.  The power coming off the booster going in to the servo and arduino is 5.27v.

link to picture of project: https://s6.postimg.org/cn0okq9v5/Screen_Shot_2016_06_25_at_8_45_37_PM.png

You measured voltage. What I meant was current.

I still don't see how you are turning off the servo!

it is prolly more appropriate to say that I am detaching the servo.  I guess there is no way to TURN OFF the servo unless I use a relay or attach it directly to one of the arduino pins.

So physically detached. In that case it can't use any current. I'd use a P-CHANNEL MOSFET to provide power to the servo when needed. Did you measure the current (so Amps, not volts) coming from the battery?

thanks.  I'll look into the P-Channel MOSFET.  As far as the amps go, I isolated just the servo and it is pulling 3.65 milliamps while the arduino is in sleep mode.  I don't know why I'm only getting 26.8 microamps for the whole project.  When I checked the current draw for the whole project I put one lead of the multimeter just before the battery and the other just after all of the other positive leads for all the sensors (LDR, LED, and servo).
P.S. I'm an electronics novice so most of what I know comes from research not extensive practical application.

these MOSFETs are making my brain hurt.  Link to picture of project with PFET providing power to servo.  Does it look right?  Im using pin 8 to momentarily provide power to the servo and pin 9 (PWM) to rotate the servo.  If I understand PFETs correctly I have to take pin 8 LOW to power the servo, so does that means that the PIN will be HIGH the rest of the time?  That seems like it will draw power from my battery during sleep.  https://postimg.org/image/irs6y21yl/

So, not sure which PFET to use.  I just need to power a 5v servo that will draw less than 100 ma. Any recommendations?

Pin 8 will be high during sleep but there is no current flowing from this pin to the mosfet. From what I read I get the feeling you are measuring the current wrong. The leads of the meter should be connected in series. It should be connected in such a way that if you were to remove the multimeter, the entire project would be without any power.

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

thanks for the very detailed response.  Prolly gonna take me a bit to digest.  One correction: The 11 mA draw only occurs maybe 4 times per day rather than 6 times per hour.  Everything is being power from the one 18650 LiPo. The pro mini is the 5v variety.  Picture of project: https://s6.postimg.org/cn0okq9v5/Screen_Shot_2016_06_25_at_8_45_37_PM.png

I'm going to try to test one of my 18650 batteries using the resistor.  Is the process as simple as connecting one end of the resistor to the positive lead and one end to the negative?  Will any 100KΩ–150KΩ resistor do? Do I need to worry about resistor wattage rating?  Thanks.

@darksidekilo6, see edit. Note, feel free to upvote any and all useful answers. Note, almost any such resistor should be ok; power dissipation is on the order of 30 μA times 4 V, or 120 μW which is under a milliwatt.  Yes, just connect it straight across the battery.  Possibly use an ammeter in series, at first, to verify about 30 μA current.   Note, if Pro Mini is powered straight from battery, to measure voltages above battery voltage you would need a voltage divider (two resistors in series)

copy all on the resistor type and ability to run the 5v pro mini from VCC at less that 5v; I'm going to give it a try on the next battery test.  Your posts have been very helpful and should get me closer to my answer.  I have upvoted your comments but because I am a newbie to this forum, I don't have enough "wasta" yet the upvote count isn't showing.

could you provide me with a link to the spec sheet you are referencing.  The one's I have found online don't seem to match with the section references you are providing.  Thanks.

I think I found the current culprit.  So, I tried a different approach and place my multimeter inline with the positive lead from the servo only. Low and behold, it is drawing 3.65 milliamps in sleep mode.  Doing the math using the battery life calculator I get about 27 days which is about what I would expect based on the current draw for the last 12 days.  Anyway to get the servo to draw no current during sleep mode.  I figured using the software code myservo.detach() would do the trick; obviously not.

Atmel-42176-ATmega48PB-88PB-168PB_Datasheet.pdf is like the spec sheet I ref'd, but I was looking at the Oct 2015 version instead of the March 2016 version [see link].  For the March 2016 version, add 4 to the main section numbers in my answer.

Great, thanks.  I guess because the servo is always pulling some current that I just need to use more batteries.  If I can make 1 last about 27 days then 3 in parallel should get me close to the 90 days I'm looking for.


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

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

I will say I have very little knowledge of relay/transistor and the wiring part of it, so Im guessing thats where the problem is.
My parts:
Transistor P2N2222A:
http://www.onsemi.com/pub_link/Collateral/P2N2222A-D.PDF
Relay:
JZC-11F
Sketch used:
  void setup() {
  digitalWrite(2,LOW);
}

void loop() {

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

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

}

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

http://electronics.stackexchange.com/questions/63950/arduino-trigger-an-iphones-touch-screen-with-no-human-interaction

Capacitive touch screens are design (both the hardware and software) to work with human fingers and human like movements.  It could be that you are not only working against the physical aspects of influencing capacitance at the screen location you are interested in controlling, but also the software which is trying to reject noise and "unwanted touches".
That said, this stack exchange question / answer addresses some of your questions and even proposes an (untested) circuit to try.  I would suggest to skip the "accepted" answer and read the answer with the highest score.
Based on the above response, I would suggest changing your strategy.  I might try connecting the Arduino directly to the metal probe.  Then changing the software to alternate between putting a negative then positive voltage potential on the metal probe.  Avoiding using the Atmel's input or high impedance configuration.  I might also try a smaller metal probe that covers a smaller area of the target device.  Perhaps something that is conductive and easily reforms to a flat screen as if it were a finger tip.  Something like a small ball of aluminum foil. Also, make sure that there is nothing else touching the screen like tape or a stray wire.  Such objects may cause the target's software to consider all touch events as noise or as "unwanted touches".

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


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

}

What board are you using? What IDE version? What operating system?

The arduino micro, on windows 8, IDE version 1.0.5

Genuine micro? OR chinese clone?

Its genuine as far as I know

Have you tried programming the Blink sketch to the board?

Might need a "while (!Serial);" after "Serial.begin(9600);" in setup().

Definitely need that.

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?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Sharp GP2Y0A710K0F IR sensor behaving strangely
I have just purchased a new Sharp GP2Y0A710K0F IR sensor online. As a sanity check, I wrote this simple code to check if the sensor is working correctly. The code is expected to print output voltage from the sensor, which is based on the distance
int sensorpin = A5;
int val = 0;

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

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

Now the output is quite strange. The output values start from zero and keep on increasing until they reach 1023, and then gradually decrease down to zero and this keeps on happening, even if something is kept in front of the sensor.
Is my sensor a faulty one? or is it supposed to give out similar outputs. If it has to, how do I convert these values to meter or centimeters.
The product description on the manufacturer's website said that it has a 3 pin interface, however it has a 5 pin one, the wires being Red, Black, Yellow, White, Green if seen from the left side. I guessed from the datasheet that Red and Black are for power and Yellow for signal output and hence I have connected only these 3 wires. The Green and White wires are unconnected. Also, pin numbers aren't marked.

The datasheet says there are 5 pins. 2 are Vcc and 2 are ground.

How close is "in front of the sensor"?

@Majenko , so I connected the Red and Black wires as Vcc and ground respectively. Used the yellow wire for output.

@Majenko roughly 40-50 cm away, it is supposed to be atleast 100 cm away right?

Well, that's probably why then. Does the graph on page 5 of the datasheet look like what you are describing? Also, did you note the description? Distance Measuring Sensor Unit Measuring distance: 100 to 550 cm Analog output type

@Majenko I tested with an object placed at about 200 m. Still the same problem. Since the object is at a constant distance, the reading should be stable right?

I suspect you have it wired wrongly.
You need to consult the outline diagram in the datasheet and work out which colour wire is which function. It's this bit:

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

Did the experiment, connected pin 3 to 5v on Arduino, 5 to GND on Arduino and 4 to A5. This time the readings start off with 927 and go to 1023 and then come back to 927 and the process repeats.

I think I have got it working. Connected both the postives to 5v and both the ground to 5v, I then get the voltage readings ranging between 355-388. If that's 3.5 to 3.8v, its horribly wrong as then according to the graph,it should be roughly 2v as the object is 1.5 m away from the sensor

Those are raw ADC values. You have to convert them to voltage.

But anyways, since I've got the sensor working, how to read its values is another question. Thanks


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

The maximum value you can pass to analogWrite() is 255, not 1024, unless you are using something that isn't an Arduino.

well that explains a lot!  What am I think that takes 1024?

The ADC can return a value between 0 and 1023 - that's analogRead(). That may be what you are thinking of.

Ah yes! You're correct.  I just got back into doing Arduino stuff after a years absence. Thank you!

To be fair, analogWrite() on a ESP8266 takes values up to 1023 by default, but then I suppose that falls under "isn't an Arduino".

@Majenko, If you'd like to place your comment as an answer, I'd be happy to upvote and accept!

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.


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

Does 13 not give it away?

An unexpected carriage return could indeed be an issue, though it's an implementation quirk if an actual character is returned by strcmp().  But the code also fails to terminate the string in the receive buffer - it may work if the startup code zero initializes memory and it has not been touched since but subsequently it may run away comparing residual garbage until finally finding a zero byte.

Bahh stupid copy paste error... was taken for another uart read sequence where the message ends with a line feed and a carriage return!
somehow I stared my self blind..

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

In general, yes, but we don't actually know that the data providing function will return nulls at this point, or if how much data we over or under read will leave the next run in a bad starting condition.  Sigfox perhaps implies packets more than streams, but the interface being used looks at least momentarily stream-like.

Ok, I change the wording so as to explicitly state strcmp() string arguments should be terminated by NULL.


text:
PWM Every Other Pin Doesn't Read
Scenario
I've plugged 6 pins from my RC receiver into my Arduino in order to read the incoming values.
Problem
I'm using Digital PWM~ pins 2-6. Oddly the Arduino only reads odd channels:
1480, 0, 1175, 0, 991, 0

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

I've found that if I go back to my initial pin setup and merely flip neighbors (2-3, 4-5, 6-7) that works as well.
Question
What could possibly be causing this?
Code
Here is the current code I've written

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

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

  Serial.begin(9600);
}

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

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

//  delay(100);
}

Photo

EDIT
Since posting this question I've found that reversing the chXpin values accomplishes the same effect as reversing the physical pins. This makes me thing it's a software issue so I'm digging in further.
TEMPORARY SOLUTION
I'm not sure why this works but flipping the neighbor order of pulseIn fixed the issue:
  /* OLD
  ch1 = pulseIn(ch1Pin, HIGH, 25000);
  ch2 = pulseIn(ch2Pin, HIGH, 25000);
  ch3 = pulseIn(ch3Pin, HIGH, 25000);
  ch4 = pulseIn(ch4Pin, HIGH, 25000);
  ch5 = pulseIn(ch5Pin, HIGH, 25000);
  ch6 = pulseIn(ch6Pin, HIGH, 25000);
  */

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

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

As a matter of course, not that it's related to your current issue, but your use of the String class at the end of loop is terribly wasteful and the over-use of the + operator on memory limited systems like an Arduino is known to lead to crashes.  There's no reason to assemble that all into a single string to send it.  You could just use back to back Serial.print lines and you would use a lot less memory.  Probably not an issue on this little test code, but as you advance that one will get you into trouble later.

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:

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

The other possible choices having these nice properties would be pins
8 – 13 (PCINT0_vect, port B) or A0 – A5
(PCINT1_vect, port C).
/*
 * Read 6 PWM signals from an RC receiver.
 *
 * Channels 0-5 are on digital pins 2-7 (i.e. PD2-PD7 = PCINT18-23).
 */

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

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

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

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

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

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

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

    Serial.begin(9600);
}

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

    delay(1000);
}

Would this sort of integration count? http://playground.arduino.cc/Main/PinChangeInterrupt

The code you linked to sets individual bits in PCMSKn, PCIFR and PCICR, and it defines the ISR(PCINTn_vect). This is exactly the kind of “low-level” programming I was talking about. Note that if using pins 2 – 7, you only need to set one PCMSK (namely PCMSK2) and only define ISR(PCINT2_vect).

I see you added example code afterward, I must have missed it the first time. I plugged it in and it worked with my RC flawlessly the first time. I modified the delay from 1000 to 10 and that's it. This answer deserves more than the +1 I already gave it.


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

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


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

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

Thanks! It didn't work using
say(pgm_read_byte(*phrase+i));
But it worked using:
say(pgm_read_byte(phrase+i));
I guess I'm still not clear on the difference between phrase and *phrase inside the function

@RampantCreativeGroup Oh, I didnt notice that in the body of the function. Copy and paste. phrase is the pointer, the address of the first element of the array. *phrase is the element pointed to by phrase. If you want to use pgm_read_byte(), it means you want to read a byte from some address in flash, so it makes sense to pass the pointer, phrase, but not the first array element, *phrase.

I have some extensive examples of accessing PROGMEM here.
I've adapted one of the examples to show how you might do something similar to what you want:
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 () { }

It's better to use pgm_read_ptr rather than pgm_read_word because it expresses the intent better and doesn't rely on the assumption that a pointer is the same size as a word. (It usually is the same size as a word, but that may not be true for all boards.) Additionally, rather than performing an unncessary copy, you could take advantage of Arduino's __FlashStringHelper type.

Sounds sensible enough. The original (which makes a copy) might be more general (you might need the string in a context where the __FlashStringHelper type doesn't apply), but I accept your suggested changes.

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.

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.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


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

Is there something useful in http://arduino.stackexchange.com/questions/13299/inappropriate-ioctl-for-device?

Don't you also have a /dev/tty.usbserial-AL00YS9R?

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.

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.


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

So... just like a callback then?

The great thing about Java is that it was designed to have a similar syntax as C++ and Arduino will gladly compile C++. So if you're familiar with Java this should be pretty easy for you.
check out This Tutorial
As for your example...
Much like Java, it is best practice to put C++ classes in their own files, but it is not required. If you use Java you are used to "importing" modules and classes into the class you are creating. Similarly C++ imports header files (behind the scenes it is much different, but functionally the same).
To do this first you would create a header file. This is just a text file with the extension ".h" or ".hpp" intead of ".txt" - traditionally .h is used only for c files and .hpp would be for c++. The header file will include the class and method prototypes.
Before I get to your example, as a side note:
Your example using the "sketch" variable is somewhat confusing because a sketch is just what the world of Arduino calls a program and it would not be used as variable.
"DoClass.hpp"
class DoClass {
  int var;
public:
  DoClass(int var);
  int getVar();
};

"DoClass.cpp"
#include "DoClass.hpp"

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

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

The "::" means "member of" so the getVar() is a method of DoClass.
These files should be saved in your sketch folder. If you are creating a class that will be reused you can place it in ../sketches/libraries/.
#include "DoClass.hpp"
setup(){
  ...
}

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

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

}

This worked wonderfully when the callback is to a function in the sketch. Where I am having problems is when the callback is in a class. See here for more: https://arduino.stackexchange.com/questions/68299/parent-class-callback-from-child-class

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

class DoClass {

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

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

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

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

/*
 * Main program.
 */

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

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

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

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

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

Precisely what I was looking for. Thanks!


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

Not practically and especially not cost effectively.  If you want more memory, choose something which has it, not an Arduino.  Cheap embedded Linux boards will tend to have tens to today hundreds of megabytes, and systems with gigabytes are available.  If you only need 200K or so look at some high-end single chip ARM Cortex M4 parts, some of which may be able to run Arduino ports.

No.  And welcome to Arduino SE.  Be sure to take the tur at https://arduino.stackexchange.com/Tour

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

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

Or OpenRISC.

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.%20Linux%20on%208bit
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.

If you try hard enough it might work, but it will not be easy.
In general there are 2 types of RAM.  Static and Dynamic.  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.  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 that you can use with your Arduino.  But they likely do not look like the memory chips in your computer.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
What does "+=" mean?
I'm working with an esp8266 and want to have it default to an access point when it cannot connect to a wifi network.  I'm using chriscook8's example from github here.
chriscook8 uses "+=" in several places and I can't find an explanation of what that means.
Here is an example from setup():
void setup() {
  Serial.begin(115200);
  EEPROM.begin(512);
  delay(10);
  Serial.println();
  Serial.println();
  Serial.println("Startup");
  // read eeprom for ssid and pass
  Serial.println("Reading EEPROM ssid");
  String esid;
  for (int i = 0; i < 32; ++i)
  {
    esid += char(EEPROM.read(i));  //<- here
  }

What does += do?

This belongs on stackoverflow.com, not here. Stackoverflow is the site for programming questions, as this asks about C++'s syntax.

Google for C++ operators

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.

Thank you.  Is it considered better form to use +=?

It makes no real difference. It's just quicker to type. Also it's a historical thing - when storage space was at a premium saving bytes here and there could make a difference. I recall at University I had a maximum storage space of 4MB for all my work on the servers. Saving space like that was good.

I'm not sure it's correct to say that it "assigns the result to the value on the left. A "value" is the result of evaluation; you cannot assign anything to a value. The right word would be variable, or maybe location.

The computer will not function differently with A += 1 or A = A + 1, but the code is simply easier to read.  If your variables are more descriptive, say AmountOfDaysWorked, then AmountOfDaysWorked += 1 is easier to read than AmountOfDaysWorked = AmountOfDaysWorked + 1.  It gets worse if you have to add a variable to another variable.

@Sahuagin: You're right that value is not precisely correct. But neither is variable: I can assign to str->field, but this is not a variable; it is a (compound) expression. The term you are looking for is lvalue ("ell-value"), which is merely "something that can appear on the left-hand side of an assignment expression." (Circular? Perhaps. But that is the term.)

@wchargin I forgot about the word "lvalue". Its name suggests that I may have been wrong to say that "value" was incorrect, though I think "value" alone generally means "rvalue". "Variable" is correct in this specific case, though isn't the broadest possible term.

@sahuagin agreed!

+= 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 /=

The assignment versions of binary operators include the arithmetic, bitwise logical, and shift operators: *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, and |=. Expr1 = Expr2 is equivalent to Expr1 = Expr1  Expr2, except that Expr1 will only be evaluated once (important if Expr1 has side effects).

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.

But as other comments have said, general programming questions have their own StackExchange sites...actually several of them...


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

This is unanswerable without knowing the voltage supplied and the load on the regulator, especially from any add-on devices, or how the power adapter itself will react.  The ATmega itself should be suited to continuous operation at rated voltage and clock speed, at least in a reasonable thermal environment.

I have one of mine running 24/7.

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.

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.

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.

It won't be harmed.
However, if the code crashes, it wont reset itself, so if the code crashes, the purpose of running you Arduino 24/7 will defeat itself.


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

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.

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.

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


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

That really depends on what your goals are. As written, this question can only be answered with personal opinions. Arduino StackExchange is better suited for more objective questions and answers. You may be able to re-write or add to the question to make it possible to answer more objectively.

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.

Yes I know how to design circuits and drivers such as h-bridge and I use unipolar and bipolar steppers but I don't use the graphical lcd because I use raspberry pi and python Gui instead

The stack exchange paradigm of specific questions and concise answers does not really allow for your type of question ... which, no matter how you word it, is too broad.  That said, do not take my answer too literally.  Instead of arguing against it, find some other hardware (an accelerator chip maybe?) and write an Arduino C++ library for it.  The process actually parallels real life embedded engineering more than most realize.  And, because of that, will give you marketable experience.  Or, in other words, not too many companies will pay for sketches, but C++ HW drivers?  That's a yes.

I will try that

May I add: Python and its GUI is hardly embedded. Being able to program a graphical interface with only 2K of RAM - now that's programming!

Yes I know gui using tkinter and kivy with python

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

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

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.

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.


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

What sort of precision do you want? For something like 2 seconds on and 5 seconds off, I would have thought that simply toggling a pin by checking if time is up in the main loop would do it.

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.

Start with a custom pre-scaler of 1.
While the count period is > 65535:

Multiply the pre-scaler by 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.


text:
100khz square wave with 50% duty cycle
How to generate 100khz square wave with 50% duty cycle using arduino uno
The following code was tried but did not give appropriate output
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

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

https://www.arduino.cc/en/Reference/DelayMicroseconds and https://www.arduino.cc/en/Reference/Micros explain that the micros has a resolution of 4µS: "has a resolution of four microseconds (i.e. the value returned is always a multiple of four)."

Let us start with something easy: What are you assuming about loop() and digitalWrite()? 0 us?

The problem with your program is that it does not loop fast enough. Each
call to delayMicroseconds() should take roughly the requested time to
execute, but the CPU also needs time to execute the rest of your code,
including the time needed to return from loop() and call it again.
The period of the signal ends up being considerably longer than the
desired 10 µs.
The simplest software-only approach would be to get rid of the delay
using the technique described in the Blink Without Delay Arduino
tutorial. With one twist: instead of
// save the last time you blinked the LED
previousMillis = currentMillis;

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

This way the small timing errors do not add up: you get, on average
the correct period. Oh, and obviously, you track time in microseconds,
not milliseconds:
const uint16_t TOGGLE_TIME = 5;  // toggle pin every 5 us

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

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

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

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

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

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

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

And now the signal looks still worse: with the program running faster,
levels are held most of the time for only 3.5 µs, and then one out
of every ≈ 4 levels is held for about 9 µs. The average
frequency is probably right, but the jitter is absolutely awful, which
is likely due to the 4 µs resolution of micros() noted by user
Talk2.
The conclusion from these tests is: your only hope to get a somewhat
clean signal at this frequency is to generate it in hardware, not in
software. Choose one of the timers and have it generate the signal you
want. I would avoid timer 0, as it is needed by the Arduino timing
functions (delay(), millis()...). Here is how it can be done with
timer 2:
void setup() {
    // The output will be on digital 3 = PD3 = OC2B.
    pinMode(3, OUTPUT);

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

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

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

First, be sure to use the "{}" in the menu to show your code in a code block
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT); }

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

I think you could benefit from reading the Secrets of PWM
using a microsecond delay will only give you an approximate pwm signal.

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


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

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

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.


text:
How do I use interrupt service routines inside libraries and classes?
I'm trying to have a millis() timer run to emulate a hardware timer inside a library, but I'm having issues compiling the code. I want the callback (pseudo ISR) to be part of the class, and not use global variables.
I'm using Christensen's / Monk's Timer library, but I'm open to suggestions if there are other better/easier timer libraries out there.
This is what I have so far. It's just an example for me to understand how this might work. I'm sure there are better ways of making an LED blink, but this is just for illustrative purposes.
Compiling gives a bunch of "invalid use of member variables in static functions" errors.

error: invalid use of member 'Blink::_led_status' in static member function
           int _led_status;

EDIT
After trying to add glue routines as per your other answer I can seem to get one instance working, but adding another stops the first light from blinking, and the second one blinks on and off at the wrong times.
The test library is on github
Blink.h
#ifndef Blink_h
#define Blink_h

#include "Arduino.h"
#include <Timer.h> // https://github.com/JChristensen/Timer/master
    // Timer.h uses millis() instead of built in timers

class Blink {
public:
  Blink (int led_pin, int duration);
  void begin ();
  void updateTimer();

private:
  static void _callbackGlue();
  void _callback();

  static Blink *_instance;
  Timer *_blink_timer;
  int _led_pin;
  int _duration;
  int _led_status;
  int _blink_event;
};
#endif

blink.cpp
#include "Arduino.h"
#include "Blink.h"

Blink *Blink::_instance;

Blink::Blink (int led_pin, int duration) {
  _blink_timer = new Timer();
  _led_status = 0;
  _led_pin = led_pin;
  _duration = duration;
  pinMode(_led_pin, OUTPUT);
  digitalWrite(_led_pin, LOW);
}

void Blink::begin () {
  _blink_event = _blink_timer->every(_duration, _callbackGlue);
  _instance = this;
}

void Blink::_callbackGlue() {
  _instance->_callback();
}

void Blink::_callback() {
  if (_led_status == 0) {
    digitalWrite(_led_pin, HIGH);
    _led_status = 1;
  } else if (_led_status == 1) {
    digitalWrite(_led_pin, LOW);
    _led_status = 0;
  }
}

void Blink::updateTimer() {
  _blink_timer->update();
}

test/test.ino
#include "Blink.h"

Blink first_blink (13, 500);
//Blink second_blink (12, 1000);

void setup() {
  Serial.begin(9600);
  Serial.println("Starting...");
  first_blink.begin();
  //second_blink.begin();
}

void loop() {
  first_blink.updateTimer();
  //second_blink.updateTimer();
}

I think this is a duplicate of Pass class's public function as an argument to external command - see my answer there.

@NickGammon Thanks for pointing me to your other answer. After trying to follow your example from the other answer, I was seemingly able to get a single instance working, but adding another blink object stops the first one from working, and the second one blinks randomly.

Yes, well you only have one instance variable. You can't easily work around this. Classes (can) have multiple instances. For a static function to know which one to use you need to help it. The instance variable is static so there is only one copy of it.

Nick Gammon's answer is good for one Timer - but now you want two!
OK, then you can take advantage of the Timer Library's context parameter. What's that? If you take a look at the header for every(), you'll see as well as passing in the function to call, you can also pass in another value (called context) to pass back to that function when it fires*. So instead of you remembering just one copy of instance, get each Timer to remember it for you.

*If you can't see the context parameter in Timer.h, then make sure you're using the v2.1 branch, not master.

So:

Get rid of _instance everywhere.
Change:
static void _callbackGlue();
to
static void _callbackGlue(void *context);
Change:
void Blink::_callbackGlue()
{
_instance->_callback();
}
to
void Blink::_callbackGlue(void *context)
{
((Blink *)context)->_callback();
}
Change:
_blink_event = _blink_timer->every(_duration, _callbackGlue);
to
_blink_event = _blink_timer->every(_duration, _callbackGlue, this);

Note that I've submitted these changes as a Pull Request on your GitHub repo.

Incidentally:
You don't need _blink_timer to be a pointer. Get rid of the *, get rid of the line with new Timer() in it, and replace all your _blink_timer-> with _blink_timer.

Thanks, that worked great. Is the only downside to using pointers to objects that you have to manually delete the pointer when deleting its parent?

Sort of. Yes, that's a concern, but new also uses heap (which is inefficient in both memory and time). By having it as a sub-object it merely makes the parent larger. Plus with pointers you have to use -> everywhere. Once you program enough, you'll get into the habit of thinking "Wait! Is that pointer actually 0?" No pointer: no test.

You may add handler (AKA hook) functions using function pointer to the Timer0 ISR inside the core wiring.c source file shipped with Arduino core, and assign latter (attache) this function pointer to any desired function in the other library/class or in the main application code.
More about this trick in this article here.


text:
Computer to Arduino to hardware, controlling on / off state of hardware via user input on computer
First time coding for Arduino. I'm working on code to operate an electronic valve switch. We have a laptop connected to an Arduino Mega, and that Arduino is hooked up to the valve (hardware) on Pin 53.
I was trying to work off of the "blink" example originally, but that gives no basis for user prompted control. Basically I want to have the computer ask me if I should turn it on or off, type in my response (I was using "HIGH" for on and "LOW" for off, as in voltage control), and have that activate or deactivate the hardware.
My main problem right now stems from how best to ask for that input. I've been trying to work with the Messenger.h library thus far. I'm definitely getting hung up on how to define the pin, or what the simplest method for user input would be. (HIGH or LOW? 0 or 1? Something else?)
Code is below. Thanks!
#include <Messenger.h>

Messenger message = Messenger();

// Variable definitions. Switchinput is what the user commands, current state is whether the air is flowing or not.
boolean currentstate;
boolean switchinput;
String pin53; // Something is up on this line?? How to define this pin??

// FUNCTION DEFINITIONS
// Startup fxn
void start()
{
  Serial.print("LOW = off, HIGH = on. Switch is ");
  Serial.println(currentstate);
  Serial.print("Enter LOW to turn on or HIGH to turn off: ");
  switchinput = Serial.read();
}

// Go off to on
void offtoon()
{
    digitalWrite(pin53,HIGH);
    currentstate = switchinput;
}

// Go on to off
void ontooff()
{
    digitalWrite(pin53,LOW);
    currentstate = switchinput;
}

// Stay same -- already off
void staysameoff()
{
  if ((currentstate = switchinput) && (switchinput = LOW))
  {
      void start();
  }
}

// Stay same -- already on
void staysameon()
{
  if ((currentstate = switchinput) && (switchinput = HIGH))
  {
    void start();
  }
}

// Running actual code
void setup()
{
  // initialize digital pin 53 as an output.
  pinMode(pin53, OUTPUT);

  // Sets default state to switch being off (Off = LOW, On = HIGH)
  String currentstate = LOW;
}

void loop()
{
   if ((currentstate != switchinput) && (switchinput = HIGH))
  {
      void offtoon();
  }

  if ((currentstate != switchinput) && (switchinput = LOW))
  {
      void ontooff();
  }

  if ((currentstate = switchinput) && (switchinput = LOW))
  {
      void staysameoff();
  }

  if ((currentstate = switchinput) && (switchinput = HIGH))
  {
      void samestayon();
  }
}

if ((currentstate = switchinput) && (switchinput = LOW)) - this (and all similar lines) are wrong. You use == for comparing, not =.

{ void start(); } - that does not call the function start. Don't use the word void here.

String pin53; - not a String. Try: const byte pin53 = 53; - although what that achieves I am not sure. How about: const byte valvePin = 53;

As for reading serial input, see How to process incoming serial data without blocking

Fixed the first three comments-- those are all things I really should've caught.
So this works pretty similarly to the state machine example on your link, right? Except I've only got two possible inputs, whereas that has three options. Correct?

@CEL If you have fixed Nick's comments can you update your code, because I was about to flag them up too :)

@CEL I appreciate this comment is a bit off target, but you might want to look at using parameters to the functions you have written to reduce the amount of code you have.  i.e. void offtoon() and ontooff() could become
void changeState(const int& newState)
{
digitalWrite(pin53, newState);
currentstate = switchinput;
}

Please amend your question with your updated code (which unfortunately makes the comments here look silly). Or, post underneath (in the question) the corrected code which is probably better. Edgar Bonet's solution looks pretty good to me.

This seems way too complex for your purpose:

you really do not need to do anything to stay in the same state
if you want to switch the valve ON, no need to check whether it's OFF:
there is no harm in switching ON a valve that is already ON.

Here is a simplified version of the program:
void setup()
{
    Serial.begin(9600);
    Serial.println("Type '0' to turn OFF, '1' to turn ON");
}

void loop()
{
    int command = Serial.read();
    if (command == '0') digitalWrite(53, LOW);
    if (command == '1') digitalWrite(53, HIGH);
}

Notice that Serial.read() returns -1 if there is nothing in the input
buffer, and since -1 is neither '0' nor '1', this will not change the
output.
If you want to use more elaborate commands (not single characters), you
may want to take a look at this simple command-line
interpreter. It is intended to be easy to adapt to
different purposes.

Thank you! I've only got one switch with two states happening for now, but I'm going to be working with multiple states later on as more components are added. Single digits might still work for that but for other users who aren't me later on it might be worth switch over to the single command line interpreter.


text:
ATtiny85 (Sparfun Clone/Trinket), detect/read operation voltage
I just started with Arduino programming and currently I'm using this Sparkfun clone board:
o http://nl.aliexpress.com/item/Digispark-kickstarter-Micro-development-board-ATTINY85-module-for-Arduino-usb/32584975067.html
It's really nice and like the way to program it and 'burn' it, it's easy to do. For the first project, I came along this instructable, an USB volume knob:
o http://www.instructables.com/id/Digispark-Volume-Control/
I'm using the Sparkfun Arduino programming IDE with added AdaFruit Trinket USB library (Trinket is also ATtiny85), download source, tweak it a bit to my needs and it's working perfectly. Had some programming question though, see also:
o https://stackoverflow.com/questions/37740026/change-override-trinket-attiny85-usb-identification-name-device-name/37743886#37743886
o  https://stackoverflow.com/questions/37769451/arduino-make-a-library-more-optional-by-project?lq=1
o https://stackoverflow.com/questions/37824336/arduino-trinket-attiny85-usb-possible-to-read-the-state-of-all-keys
Anyway, optimized the source code (original not really a beauty), play with it and added also a fade-In/fade-out idle feature to the LED on PIN 1 and it blinks when turning the dial encoder.
I want to add add some more features to this knob, such as pushbuttons to change some internal modes. For example:

Toggle button for knob sensitivity (3-modes: slow (default), normal, fast)
A mute button

I want to that device 'remember' the state of the toggle button but there is no option (flash memory) to save the state. So I came with the idea to use a backup button cell to keep the device 'alive' when disconnected from USB (or computer turned off). A Button cell is 3V and USB is 5V so maybe is possible to 'test' the input voltage. If this is possible you can put the device in sleep mode (low power mode) directly after detecting USB connection lost and this voltage drop.
I have read already an article how to put the device into sleep mode (and awake from it):
o https://bigdanzblog.wordpress.com/2014/08/10/attiny85-wake-from-sleep-on-pin-state-change-code-example/
Question is:
Can I measure somehow the voltage is used to power the device? Any ideas (code example please if it is possible)?

The attiny85 does have a 512B EEPROM.

There are a few solutions.

If you want to save te state of your toggle button you can save it in the eeprom of your attiny85
You can use an ADC pin to check your VCC against the internal 1.1V reference
alternatively you can read the 1.1ref aganist Avcc. https://digistump.com/board/index.php?topic=1104.0