body:
I've bought this sensor module board to link to an Arduino nano: http://www.ebay.com/itm/For-Arduino-Liquid-PH-Value-Detection-detect-Sensor-Module-Monitoring-Controller/321764233326

I assumed the two screws were for calibration (low point + slope), but it seems the operation is different and I can't figure out how. I've got two reference liquids for pH of 4.0 and 7.0. When I put the probe in either one, I get readings. Turning one of the two screws seems to offset the reading so for instance I had pH 4 = 900 and pH 7 = 1000 (0 - 1023 range). Turning one of two screws would lower the value a bit, but it never gets below 500 or so.

So what I can do is measure two points (4.0 and 7.0) and their respective measurement values. That way I could calculate points in between, but as far as I know pH is not a linear scale, but logarithmic. If I get this wrong, the reading might seem right but only show 4.0 and 7.0 correct and not the rest of the values (I don't have 10.0 reference fluid at the moment).

Now onto the second screw, that one at first seemed to do nothing. But then I noticed that it sets some kind of threshold value, turning a LED on the board on and off. That LED seems to be linked to the value being read, but it's further purpose? Calibration? No idea.

Ok so best case someone has an equal module and wants to detail how it works. Otherwise maybe some of you have some bright ideas on what I could try in order to get this to work the way I want it to :)

**Update 09-11-2015**

Got feedback from the seller. She sent me the following ZIP: http://1drv.ms/1MSk1DX. It contains some files in Chinese but one had sourcecode in it. Tried it on my Arduino but unfortunately the values still don't make much sense. Depending on how I turn the knob on the print, I get values between 9 and 17 for a liquid that's in real life 7.0. I didn't try but doubt that doing a -7 offset is sensible.

The code itself is pretty straightforward, taking a 6-center average of ten consecutive measures. The interesting lines are these:

     avgValue = 0;
     for (int i=2;i<8;i++)       // take the average value of 6 center sample
       avgValue+=buf[i];

     float phValue = (float)avgValue*5.0/1024/6; // convert the analog into millivolt
     phValue=3.5*phValue+Offset;

Maybe someone can make sense of this, because I can't. I don't understand the 5.0 multiplication and the 3.5 after that one. Where do these come from?

Anyway, when I dip the probe into the storage liquid, my normal meter plummets to pH 0.5 whilst the software is giving me 17 (which is a higher value than the one I got from reading my 7.0 liquid). So either my board is broken or this sample code is useless.

Schematics can be found in the ZIP file by the way.

**Update 11-11-2015**

Did some more experimenting. First I found out that the readings from the module increased for more acidic liquid. So I reversed the value by using

    buf[i]=1024 - analogRead(SensorPin);

Ok, now the values made more sense. Then I adjusted the pot to be in the middle of the available range. I dipped the probe in the 7.0 liquid, read the value and adjusted the offset. Then dipped in 4.0, adjusted the pot to match with 4.00, here are the results:

    pH 7.0 reference --> 6.27
    set offset to: 0.73
    pH 4.0 reference --> 5.17
    adjusted the pot so value read 4.0
    pH 7.0 reference --> 5.86

So as I expected, adjusting the pot also messes up the 7.0 reference measurement. I then though it might be because of the slope of the pot (if there would be any), so I went to the lowest value first to have the least difference. Again the readings:

    pH 7.0 reference --> 8.70
    set offset to: -1.70
    pH 4.0 reference --> 5.17
    adjusted the pot so value read 4.0
    pH 7.0 reference --> 5.70

The interesting thing here is that the 4.0 value reads 5.17 in both cases, even though the pot was in a different position. I cannot explain why though.

To make sure the probe is fine I re-calibrated my normal pH meter, operates as usual. This one also has two pots, one for 7.0 calibration and one for 4.0 slope. Calibration is done by setting 7.0, then measuring 4.0 and ajusting the slope pot. Measure 7.0 again, change 7.0 pot, measure 4.0 again, etc. until the values match their liquids. Usually takes me about 3 - 4 loops to get it right.

**Another update**

Took the two containers of reference fluids and started mixing. This gave me measurements in the range of pH 4 - 7.5. Also measured the storage liquid which has a pH of 1.00. Results are in an Excel sheet: http://1drv.ms/1lkAO6e. Next question is how to convert this into a suitable formula?

**Update 18-11-2015**

Working on @slash-dev's solution, here's what I did:

I first turned the pot all the way down to the lowest value. The readings (for pH 7.0) are as follows: low = 540 and high = 1017. Code as follows:

    int rawValue = analogRead(SensorPin);
    int buf[10];                //buffer for read analog

    for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
    {
       buf[i] = rawValue;
       delay(10);
    }

    // sorting left out to reduce the sample length

    int avgValue=0;
    for(int i=2;i<8;i++)  // take the average value of 6 center samples
       avgValue += (buf[i] - CENTER);

In this stage I'm printing the raw value of course.

The shorting of the BNC connector I don't exactly understand, should I short the inside (where the pin goes) or the outside of the connector? And short it to the GND? I used the reference solution instead.

Now I added the formula to determine the voltage. For the low value that reads 0.10. I now put in the center value of 540 which brings the voltage reading to 0.0, seems good.

Now for step 2 I placed the probe into the 4.0 reference solution. The voltage now reads 0.48, raw value 637. I start adjusting the pot to where the voltage reads 2.25, takes quit some adjusting. Raw now reads 1000.

Now comes the part I don't exactly get. You say we can now calculate the pH/V, but with what variables? I mean, -3 / 2.25 will always result in -1.33 but shouldn't there be a variable here depending on how far I actually adjusted the pot?

When I now put in the formula to calculate the pH as expected it reads 4.0 for the 4.0 reference solution. But it now screws up the 7.0 solution as we adjusted the pot but didn't compensate for it as far as I see? I also tried the adjusted pH formulas but I guess those are meant for the first code we had and not this adjusted one.

So what am I missing between step 2 and 3 that messes up things here? Also, you state that the inverting by subtracting from 1024 is correct, but when I do that the voltage readings become minus.

Another thing I wonder about; if the pot has to be a slope, shouldn't it be a different one than the one next to it (where a linear one makes more sense)? Cause it isn't, they both read "W103 / 143C". In the meantime, the vendor is kindly sending over a replacement one to ensure it's not a hardware defect somewhere.

**Next update: :)**

So I now reverted to my original code to try the adjusted pH calculations. I used the 7.0 reference solution to calibrate again and then measured the 4.0 solution. It reads 4.1! Ok, not completely spot on but not bad either. It's a small difference which might as well come from the probe, not the most expensive one.

So I wonder whether we should still try to get the other approach working cause it sounds better (more scientific?) for some reason. Anyway, this is at least a whole lot better than nothing :)

**USB power vs linked?**
Another strange thing seems to happen when I disconnect the Nano from the USB port of my laptop and instead power it via a Raspberry. I want to use I2C to send the value from the Nano to the RPi. This works, but as soon as I power the nano from the RPi (5V connected to vIn), the calculated pH value drops?

title: Using / calibrating pH sensor module

Answers: 6

body:
I don't know if this is a complete answer, but I can't comment yet.

The analogRead function in Arduino which is used by your sensor reads values from 0 - 5V. It divides the values between 0 and 5V in 1024 steps. So it returns a value between 0 and 1023. That is why it is multiplied by 5. It is easier to understand if the calculation is done in reverse order. Example:

analogRead returns 512, so that is on 1024 / 512 = 0,5th part of its range. Multiply that by 5.0 to get the actual voltage. 0.5 * 5.0 = 2.5. It is then divided by 6 to get the average.

I would also change the order of the calculation. The comments say that it calculates the average, but it doesn't it just adds the values. It does divide it by 6 eventually so that does not cause the error, but for readability it is generally good practice to let your code do what the comments say.

body:
As a first approach, I'd collect a number of measurements from each of as many knowns as you can find or make, and plot them for a visual clue to the linearity or not (probably not) of the sensor's output vs. pH. You could try to eyeball-fit a curve to the data; interpolate linearly between sample points if you have enough of them; or run a least-squares approximation fit. The key is you'll need enough data - knowns - to make whatever approach you use give results accurate enough for your intended use. (Obviously this will be different if you just need to know if something is acidic or basic, or you're monitoring tropical fish tanks, etc.)

Update:
If your pH meter is good enough for the fish, and if your sensor is reliably repeatable and sensitive enough, why not check your meter against the two standards, then calibrate the sensor to your meter? Once you're happy with the result, lock down the screws with a dab of nail polish (it's not very tamper-proof but it will be tamper-evident). A pH 10.0 standard won't be very useful to you; at that extreme you'll already know the pH is out and you probably won't care about the exact value. You need your precision between the fish-tolerable limits, close to the pH goal.
In fact, if you trust your meter, you don't even need the standards. In that case you need only make up a few samples as you described, covering the pH range of interest, and use them to calibrate your sensor to the meter.

body:
The schematic only shows one trim pot (R23), and it does, as you suspect, set a level for the LED to illuminate.  More of a GOOD/BAD indicator, and is available on pin `DO`.

The other trim pot is not on the schematic.  Is it marked on the board?  R6, R7, R8 or R9 maybe?  It probably controls the gain on `p_AOUT`.

`t_AOUT` is an analog temperature voltage, and appears to measure the temperature of the board.

**Edit - official but totally bogus:** According to my secret source, you are supposed to put the probe in the pH 7.0 reference solution and, with `Offset` defined to be 0.0, run the program and display the calculated pH value.  You may need to decrease the trim pot gain to get smaller (the smallest?) numbers.  Now take that displayed value and modify the `Offset` constant in the sketch to be 7.0 minus the displayed value.  If the displayed value is 8.1,

    #define Offset (-1.1)

Build and upload the modified sketch.  This time, put the probe in your pH 4.0 reference solution and adjust the gain pot until the displayed value is as close to 4.0 as you can get.  This will calibrate it for mostly acidic solutions.

# Edit 1: Iterate?

It's not clear, but I also wondered if this procedure is supposed to be iterated.  Go back to 7 and make sure that adjusting the gain didn't change `Offset`. Then test the pH 4 solution again; the gain pot may require a small(er) change. If it seems to be diverging, um, don't do that. ;)  I think it would diverge only if the probe had an inverted response, which would probably mean it's bad.

If you are measuring basic solutions, do the same procedure with reference solutions of pH 7.0 (of course) and a basic reference solution.

Voilà!

NB: For the 7.0 test, you could short the probe pins together. It really should look like a short circuit when pH == 7.0.  If switching to using the real probe in the pH 7.0 solution gives wildly different readings, the probe _may_ be bad.  If you're able to calibrate it, it _may_ be "good enough".

# Edit 2: Fix the formulas in the provided sketch.

The schematic shows a non-inverting op amp with `PH+` on the input, and `p_AOUT` on the output.  The (adjustable?) gain is

    R9/R8 + 1 = 10k/10k + 1 = 2

The slope of an ideal probe response is -59mV/pH.  You were experimentally getting a negative slope, which agrees with the schematic.  I believe it was correct to "invert" the `analogRead` value by subtracting it from 1024.  There is no way that the provided code could have worked with a positive slope of 3.5.

The reference voltage provided to the the `PH-` pin is half the zener diode voltage... which is unidentified.  It could be the very-common 5.1V part, which is essentially forcing `PH-` to be at

    5.1V/((R6+R7)/R6) = 5.1V/2 = 2.55V

I say probably, because you usually want the plus or minus probe voltage swing to have as much room as possible.  This would imply (an ideal) `analogRead` of pH 7.0 to be

    2.55V/5.0V * 1024 = 522

This is the "center" of the probe swing about pH 7.0.

### Step 1: Determine the reference voltage
At pH 7.0, print out the raw `analogRead` return value, before inverting it.  (The pot wiper should be at it's limit.  Which way, I don't know.  Changing the gain pot shouldn't change the `analogRead` very much at the low-gain end.  If it does change it, turn it to the other extreme.)

As stated before, you can run the pH 7.0 test by shorting the BNC connector pin to the shield or by using your reference solution.  I recommend shorting for now, to eliminate any possible interference from the probe.  It will absolutely determine the offset, but only if the gain is as small as possible.  You have to start here.  Once you know the center reading, you can change the code to display the voltage:

    #define CENTER 522
    int avgValue=0;
    for(int i=2;i<8;i++)  // take the average value of 6 center samples
      avgValue += (buf[i] - CENTER);
    float voltage = (((float)avgValue) / 6.0) * (5.0 / 1024.0);

Print this out.  You'd better get something close to 0.0... don't make me come over there.  :)

### Step 2: Set the gain pot.
This is determining the slope, but you need to maximize the swing for the most extreme pH you want to read, say 4.0.  Using the 4.0 reference solution, adjust the gain pot so that the displayed voltage is close to +2.5V, say +2.25V to make sure it's not pegged at 1024.  (Let's see, slope is negative, 4.0 is < 7.0, so voltage should increase...)  With that reading, you can calculate the pH/V:

    -3pH/2.25V  =  -1.33 pH/V

### Step 3: Calculate and print pH
Modify the original computation to use the pH/V slope:

    float phValue = voltage * (-1.33) + 7.0;

This is not even close to `phValue = 3.5*voltage + Offset`.  -\_-    I have found several source now that echo my original answer.  Totally wrong, and wrong to the point of misleading.  I do think these steps will do it.  It sounds good in my head, anyway.  :D

# Edit 3: "Next question is how to convert this into a suitable formula?"

Ok, if you don't want to fix the formula in the code, you can fit a linear or quadratic curve to your data.  Linear is actually recommended as "good enough", and that is effectively the change suggested in **Edit 2**.  If we just use your data points, though, this would be the linear approximation:

    float adjustedPh = phValue * 1.627 - 2.499;

...and the quadratic approximation:

    float adjustedPh = (-0.01796 * phValue + 1.8056) * phValue - 2.94;

body:
I can't ask a question but make sure you're giving it enough power for the heating element, its not much but you never know try a separate power source if you are not.

Now you mentioned the nano, are you using a 3.3v nano or 5V nano?  (the regulator would have a 33 or 50 on it after a letter or two)  if 3.3V and assuming by example code they give the analog output is 5V you'll need a level shifter of sorts to map to 3.3V, then change the calculations to use 3.3 instead of 5 value.    if that's not the case and it's not power or connections then it may be broke or the probe etc.... there's a few variables.

body:
>**USB power vs linked**

[Read it][1] and use current Vcc instead of 5.0 in your code.

I have the same sensor and have the same problem. I'll be glad if you share full working code in this thread.

  [1]: http://forum.mysensors.org/topic/186/new-library-to-read-arduino-vcc-supply-level-without-resistors-for-battery-powered-sensor-nodes-that-do-not-use-a-voltage-regulator-but-connect-directly-to-the-batteries

body:
> **USB power vs linked**

Just to add my 2 cents on your latest update about the USB or 5V from the PI.

You say you connect it to the VIN:

> as soon as I power the nano from the RPi (5V connected to vIn), the calculated pH value drops?

If you look at the below image you see that Vin goes to a good old 7805, which needs a IN voltage > 7.5V, thus the output when its connected to the 5V of the PI is going to be very low and thus mess up readings.

![enter image description here][1]

I recommend you connect your ***power from the PI to the arduino's VCC*** as this is a regulated 5v and doesn't need to be regulated again.

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


body:
Im trying to use the millis() function as a replacement for the delay() function in order to debounce a mechanical button. This is for an electric drum kit I am building. Im using a teensy Arduino to send MIDI signals from the drum pads to an external music program. The mechanical button needs to be responsible for cycling through five different states which change the MIDI signal sent from each pad, thus changing the sound, as well as lighting up one of five LEDs on my drum pad so I know which state i'm in.  However I cant use delay() to debounce the button because that effects the efficiency of the drum pads, with some hits not being registered, latency etc.

Im trying to debug the code by just getting the LEDs to light up correctly when I press the button. This was the original code I wrote with the delay() function. This worked perfectly to debounce the button, but messed with my drum pads:

    int but = 12;
    int led0 = 7;
    int led1 = 8;
    int led2 = 9;
    int led3 = 10;
    int led4 = 11;

    int ledCase = 0;
    int butState = 0;
    int oldButState = 0;

    void setup()   {
    pinMode(led0, OUTPUT);
    pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);
    pinMode(led3, OUTPUT);
    pinMode(led4, OUTPUT);
    pinMode(but, INPUT_PULLUP);
    }

    void loop()    {

       oldButState = digitalRead(but);
       delay(10);
       butState = digitalRead(but);

       if (butState != oldButState && butState == LOW) {
         ledCase += 1;
         oldButState = butState;
       }

       if (ledCase > 4) {
        ledCase = 0;
       }

       Serial.println(ledCase);

    switch (ledCase) {
    case 0:
    digitalWrite(led0, HIGH);
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    digitalWrite(led4, LOW);
    break;
    case 1:
    digitalWrite(led0, LOW);
    digitalWrite(led1, HIGH);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    digitalWrite(led4, LOW);
    break;
    case 2:
    digitalWrite(led0, LOW);
    digitalWrite(led1, LOW);
    digitalWrite(led2, HIGH);
    digitalWrite(led3, LOW);
    digitalWrite(led4, LOW);
    break;
    case 3:
    digitalWrite(led0, LOW);
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, HIGH);
    digitalWrite(led4, LOW);
    break;
    case 4:
    digitalWrite(led0, LOW);
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    digitalWrite(led4, HIGH);
    break;
    }
    }

This is what I tried to use to replace the delay() function, but that hasn't worked. Note I added these lines in and removed the delay section:

    unsigned long onTime;
    unsigned long delayTime;

    void setup() {
    delayTime = millis() + 10;
    }

    void loop()    {
    oldButState = digitalRead(but);
    onTime = millis();
    if (onTime >= delayTime) {
    butState = digitalRead(but);
    delayTime = millis() + 10;
    }
    }

Any pointers as to how I can make the millis() function work to debounce this would be would be very much appreciated, thank you :)

title: How to simulate delay() to debounce mechanical button using millis()?

Answers: 2

body:
To better understand how you can do this it is good to understand first just what goes on when a button bounces.

It is, literally, bouncing - just like a ball when you drop it.  Due to the fact that it's either connected to ground or pulled up to +5V by the pullup resistor it's either going to be LOW or HIGH with very little time between when it's not in either state, so we can pretty much ignore the rise and fall times of the signal.  It's either connected to ground, or it's not connected to ground.  And we're only really interested in when it's connected to ground.

More importantly we're interested in *how long* it's been connected to ground for.

By remembering the time it transitioned from HIGH to LOW and then comparing that time to the current time you can know how long it has been connected to ground.  By noticing when it's no longer connected to ground and "forgetting" the time you remembered you can start counting afresh with the next transition from HIGH to LOW.

Take the following diagram for instance:

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

The blue line is the state of the button.  As you can see it starts HIGH, then it gets pressed to be LOW and bounces between HIGH and LOW a number of times before it settles on being LOW.

The red line is the difference between a timestamp that is set to be equal to `millis()` at the moment the button transitions from HIGH to LOW and the current `millis()` value, and is ignored when the button is HIGH.  As you can see the difference between that timestamp and the current `millis()` value steadily increases. Whenever the button bounces to the HIGH state it resets that difference, and it starts again with the next LOW transition.

When the button has finished bouncing there is nothing to change the state of the timestamp, so the difference keeps increasing.  Eventually that difference will pass a trigger point (the yellow line in this diagram) and at that point you can be fairly sure that the button has finished bouncing and you should react to it.

To translate that into some code, you may end up with something like this (untested):

    // Two variables to store remembered state information - the time
    // of the last HIGH-LOW transition and the previous state of the
    //  button.
    static uint32_t debounceTime = 0;
    static uint8_t buttonState = HIGH;

    // Check to see if the button has changed state
    if (digitalRead(buttonPin) != buttonState) {
        // Remember the new state
        buttonState = digitalRead(buttonPin);
        // If the new state is LOW ...
        if (buttonState == LOW) {
            // ... then record the time stamp
            debounceTime = millis();
        } else {
            // ... otherwise set the time stamp to 0 for "don't care".
            debounceTime = 0;
        }
    }

    // If the time stamp is more than 0 and the difference between now and
    // then is greater than 10ms ...
    if (debounceTime > 0 && (millis() - debounceTime > 10)) {
        // ... set the time stamp to 0 to say we have finished debouncing
        debounceTime = 0;
        // and do whatever it is you need to do.
        digitalWrite(ledPin, HIGH);
    }

There are various tweaks and additions that could be made to that method, but that gives you the basic idea of how you split the debouncing away from the reacting, and it's the *results* of the debouncing that you react to, not the button state itself.

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

body:
Actually, Majenko's diagram assumes the interplay of the pullup resistor forces the line back to a HIGH position (as quickly as the internal transistors can overpower the drop from the switch).  If the switch itself is mechanical with a pullup resistor (external or internal), then the only thing "bouncing" is the switch.  If you use a digital switch, the rise is much sharper without significant bounce.

A cheap and effective debouncing tactic is to add a capacitor in parallel with the switch.  The cap will drop to GND quickly as the switch drains the charge stored in the cap.  But the cap will take a while to recharge since its only source is through the resistor (during which time the mechanicals settle down).  (This looks much better in a diagram, but I haven't figured out how to draw on here yet.) I wish I could recommend values, but it really depends on the mechanicals of the switch and the certainty of the debounce desired--make everything HUGE and you're guaranteed no bounce, use values in between and you go on probabilities.  I usually start out with 0.1uF and vary it up or down until I get a balance between reliability and speed.

The main advantage is, of course, you use absolutely no computing time to debounce any number of switches.

Potential disadvantages:

 - Added hardware cost for each switch, making this technique less desirable in production scenarios

 - 0/1 thresholds of input pins will vary across the manufacturing process, so one cap / input pin may have a different debounce time than another on an identical circuit.

 - Software debouncing schemes can note that the switch is pushed on the first drop to GND, where this hardware-only tactic relies on the last actual contact with GND.  As the switch ages, I've seen this delay exceed 50 mSec.

 - Since the bounce is mechanical at its core, bounce worsens over the life of the mechanical part (in this case the switch).  Typically, software can be fine-tuned easier than hardware. Often, however, swapping out a cap is easier than reflashing firmware.


body:
Is it possible to use the [Adafruit PN532 NFC/RFID Controller Shield][1] with the [Johnny Five API][2]? I've searched the depths of google and I'm unable to find anything so far. If it is possible, how can I go about this?

I'm using an Arduino Uno with this.

  [1]: http://www.adafruit.com/products/789
  [2]: http://johnny-five.io

title: Using Johnny-five API with RFID Controller Shield

Answers: 0


body:
I'm using Arduino Pro Micro (5v version) in one of my project for my car. The car's 12V +ve connected to RAW input of ProMicro and everything seems to work perfectly until I crank the ignition of my car.
Here's what actually happened, my circuit works perfectly fine when car's ignition is in ON state. However, as soon as I started my car the voltage dropped from 12v to between 9-10volt and the LG33 (SMD voltage regulator) burned out. Now, I want a good solution as what should I do now?
I have already LM2596 DC 3A Step-Down regulator. So should I use that to step-down 12v to 5v OR is there anything else I can do which might be a better solution?

title: Pro Micro Voltage regulator burned

Answers: 1

body:
What happened was the ignition caused massive spikes on the 12V power. You require an automotive grade regulator that can cope with spikes in excess of around 70V or more.

Your best bet is probably a car USB charger adapter since they are cheap and easy to get hold of.


body:
I'm new to Arduino and microcontroller . I want to connect my Arduino Mega to three slaves which Arduino Unos. I know that these slaves will share MISO, MOSI, and SCK lines. However, SS is unique to each slave.

For single slave, the SS is pin 53. So, for three slaves, which other two pins can I use as SS?

Thank you for your help.

title: Arduino Mega 2560 multiple slave via SPI

Answers: 2

body: Any you like. There's nothing magic about them, as long as you have the main SS pin as an output to ensure the SPI port is in master mode.

body:
You can use any pin for the Slave Select. The SS pin on the Arduino is only used as SS when the arduino is an SPI slave, not (like in your case) when it's the master. The only thing you have to take care of is to not use the SS pin as an Input.

Just make sure the library you are using allows you to specify your own SS output pin.


body:
I want to modify (extend) g_APinDescription array defined in the variant.cpp.
It is necessary for new pin addition. I want to use PB0-PB7 ports as an external interrupts.

I tried the following code:

    g_APinDescription = (const PinDescription *) realloc(g_APinDescription, (103 * sizeof(const PinDescription)));

I have a compilation errors:

 > invalid use of array with unspecified bounds

I'm not C expert and don't know what is wrong here.

I want to use several pins which are unconnected on the DUE.
Usual read and write is simple to implement but if I want to use the interrupts then difficulties arrive.

title: How to add new pins in the Arduino Due

Answers: 0


body:
I have a simple set of 8 push buttons wired to a Teensy 3.2 board (which uses Arduino via Teensyduino plugin). The 8 buttons are on pins 1-8 and their common ground line (one line soldered to each of them) is on the GND pin. I have code to get any one button working that works. It's currently set to make pressing the second button type "A."

I'd like to make push buttons 1 through 8 type out A,B,C...etc respectively as you press them. I've been told of two problems with my setup, the first being that copying the code for every button is a bad way to go about it and second that it's subject to bouncing issues (creates a keystroke once every 5 presses or so.) I'd also like to set this up so in the future I can write a 3rd party app that configures the keys based on the user's preference.

Adding those needs up I'm not sure where to go next. I'm beginner enough that I'm not sure how to properly incorporate the bounce class or if that's the right way to go given the needs.

Is a matrix the way to go or is there an elegant way to manual set each button and compensate for bounce? I'd really appreciate a small example if anyone has done this. Thanks~ Current code follows:

    #define CHECK_EVERY_MS 20
    #define MIN_STABLE_VALS 5

    unsigned long previousMillis;
    char stableVals;
    char buttonPressed;

    void setup() {
      // make pin 2 an input and turn on the
      // pullup resistor so it goes high unless
      // connected to ground:
      pinMode(2, INPUT_PULLUP);
      Keyboard.begin();
    }

    void  loop() {
        if ((millis() - previousMillis) > CHECK_EVERY_MS)
        {
            previousMillis += CHECK_EVERY_MS;
            if (digitalRead(2) != buttonPressed)
            {
                stableVals++;
                if (stableVals >= MIN_STABLE_VALS)
                {
                    buttonPressed = !buttonPressed;
                    stableVals = 0;

                    if (buttonPressed)
                    {
                        //Send an ASCII 'A',
                        Keyboard.write(65);
                    }
                }
            }
            else
                stableVals = 0;
        }
    }

**-------**
**Edit: WORKING CODE FOLLOWS**

    /*  jw - 3 Nov 2015 - Program for button debounce demo
    Ref: http://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin
    */

    //--------------------------------------------------------
    enum { sw0=3, sw1=4, sw2=5, sw3=6, sw4=7, sw5=8, sw6=9, sw7=10}; // Switchbutton lines
    enum { nSwitches=8, bounceMillis=42}; // # of switches; debounce delay
    struct ButtonStruct {
      unsigned long int bounceEnd;  // Debouncing-flag and end-time
      // Switch number, press-action, release-action, and prev reading
      byte swiNum, swiActP, swiActR, swiPrev;
    };

    struct ButtonStruct buttons[nSwitches] = {
      {0, sw0, 'A'},
      {0, sw1, 'B'},
      {0, sw2, 'C'},
      {0, sw3, 'D'},
      {0, sw4, 'E'},
      {0, sw5, 'F'},
      {0, sw6, 'G'},
      {0, sw7, 'H'}};
    //--------------------------------------------------------
    void setup() {
      for (int i=0; i<nSwitches; ++i)
        pinMode(buttons[i].swiNum, INPUT_PULLUP);
    Keyboard.begin();
    }
    //--------------------------------------------------------
    byte readSwitch (byte swiNum) {
      // Following inverts the pin reading (assumes pulldown = pressed)
      return 1 - digitalRead(swiNum);
    }
    //--------------------------------------------------------
    void doAction(byte swin, char code, char action) {
      Keyboard.write(action);
    }
    //--------------------------------------------------------
    void doButton(byte bn) {
      struct ButtonStruct *b = buttons + bn;
      if (b->bounceEnd) { // Was button changing?
        // It was changing, see if debounce time is done.
          if (b->bounceEnd < millis()) {
        b->bounceEnd = 0;    // Debounce time is done, so clear flag
        // See if the change was real, or a glitch
        if (readSwitch(b->swiNum) == b->swiPrev) {
          // Current reading is same as trigger reading, so do it
          if (b->swiPrev) {
            doAction(b->swiNum, 'P', b->swiActP);
          } else {
            doAction(b->swiNum, 'R', b->swiActR);
          }
        }
          }
      } else {  // It wasn't changing; but see if it's changing now
        if (b->swiPrev != readSwitch(b->swiNum)) {
          b->swiPrev = readSwitch(b->swiNum);
          b->bounceEnd = millis()+bounceMillis; // Set the Debounce flag
        }
      }
    }
    //--------------------------------------------------------
    long int seconds, prevSec=0;
    void loop() {
      for (int i=0; i<nSwitches; ++i)
        doButton(i);
    }

title: Arduino sending keystrokes via push-buttons. Proper bouncing and manually setting buttons?

Answers: 1

body:
I'm not sure what you mean by “Is a matrix the way to go”, so will ignore that question.

Shown below is a way of using an array of structs (one of C's ways of organizing a collection of items) to keep data for several buttons, such that it's straightforward to use one subroutine to process each button the same way, using a for-loop to call the routine for each button.

Each element of the array `buttons` is a `ButtonStruct`, and each `ButtonStruct` contains five items: bounceEnd, swiNum, swiActP, swiActR, swiPrev, which respectively represent a debouncing-flag and end-time; a switch number [ie a pin number]; a code for action to take on a press; a code for action to take on a release; and previous state of button.  (In many special cases, some of these items will be irrelevant and you can leave them out of the `ButtonStruct`.)  The form `b->x` that is used in the `doButton()` routine says to access element `x` of the struct that `b` points to.

At the start of each `loop()` pass, `doButton()` is called once for each button.  It first tests if debouncing was underway for the button.  If so, it sees if enough time has gone by to suppose button bounce is over.  If so, it reads the button's state, and if different from previous state, does an action for whichever way the button changed.  (If the button state is unchanged after a debounce delay, the program supposes there was a glitch.)  If debouncing was not underway, the program checks if the button state is different from most recent pass.  In that case, it sets up a debounce test for the button.

The buttons are tested and debounced individually, as you can see in the sample output that is shown following the program.  (This program was tested on an Uno, with four independent buttons used in the test. *Edit: Made corrections to handle 32-bit overflow, 2016.10.17*)

    /*  jw - 3 Nov 2015 - Program for button debounce demo
    Ref: http://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin
    */

    //--------------------------------------------------------
    enum { sw0=8, sw1=9, sw2=10, sw3=11}; // Switchbutton lines
    enum { nSwitches=4, bounceMillis=42}; // # of switches; debounce delay
    struct ButtonStruct {
      unsigned long int bounceGo; // Debouncing-flag and end-time
      // Switch number, press-action, release-action, and prev reading
      byte swiNum, swiActP, swiActR, swiPrev;
    };

    struct ButtonStruct buttons[nSwitches] = {
      {0, sw0, 'A','a', 0}, {0, sw1, 'B','b', 0}, {0, sw2, 'C','c', 0}, {0, sw3, 'D','d', 0}};
    //--------------------------------------------------------
    void setup() {
      for (int i=0; i<nSwitches; ++i)
        pinMode(buttons[i].swiNum, INPUT_PULLUP);
      Serial.begin(115200);
      Serial.println("Starting");
    }
    //--------------------------------------------------------
    byte readSwitch (byte swiNum) {
      // Following inverts the pin reading (assumes pulldown = pressed)
      return 1 - digitalRead(swiNum);
    }
    //--------------------------------------------------------
    void doAction(byte swin, char code, char action) {
      Serial.print("Switch ");
      Serial.print(swin);
      Serial.print(code);
      Serial.print(' ');
      Serial.print(action);
      Serial.print(" at t=");
      Serial.print(millis());
      Serial.println();
    }
    //--------------------------------------------------------
    void doButton(byte bn) {
      struct ButtonStruct *b = buttons + bn;
      if (b->bounceGo) { // Was button changing?
        // It was changing, see if debounce time is done.
          if (millis() - b->bounceGo > bounceMillis) {
     b->bounceGo = 0;    // Debounce time is done, so clear flag
     // See if the change was real, or a glitch
     if (readSwitch(b->swiNum) == b->swiPrev) {
       // Current reading is same as trigger reading, so do it
       if (b->swiPrev) {
         doAction(b->swiNum, 'P', b->swiActP);
       } else {
         doAction(b->swiNum, 'R', b->swiActR);
       }
     }
          }
      } else {  // It wasn't changing; but see if it's changing now
        if (b->swiPrev != readSwitch(b->swiNum)) {
          b->swiPrev = readSwitch(b->swiNum);
          b->bounceGo = millis(); // Set the Debounce flag
        }
      }
    }
    //--------------------------------------------------------
    long int seconds, prevSec=0;
    void loop() {
      for (int i=0; i<nSwitches; ++i)
        doButton(i);
    }

In the sample output below, a P line indicates a button press, detected at given `millis()` time, and an R line indicates a button release.   Observe, near the end, overlaps among separate button presses and releases.

    Starting
    Switch 8P A at t=2170
    Switch 8R a at t=2322
    Switch 9P B at t=2789
    Switch 9R b at t=2969
    Switch 10P C at t=3395
    Switch 10R c at t=3562
    Switch 11P D at t=4087
    Switch 11R d at t=4260
    Switch 11P D at t=6518
    Switch 10P C at t=6961
    Switch 8P A at t=7070
    Switch 10R c at t=7112
    Switch 11R d at t=7427
    Switch 8R a at t=7598
    Switch 10P C at t=8502
    Switch 9P B at t=8642
    Switch 10R c at t=8961
    Switch 9R b at t=9054
    Switch 9P B at t=9954
    Switch 11P D at t=10073
    Switch 8P A at t=10164
    Switch 8R a at t=10215
    Switch 9R b at t=10315
    Switch 11R d at t=10354


body:
I am using an Arduino Mega 2560.

I have a code in a c file, that looks like this:

        #include <avr/io.h>             /* for DDRB, PORTB, etc. */
    #include <util/delay.h>         /* for _delay_ms () */
    #include <arduino.h>

    int main(void){
      DDRB    |= ((1 << DDB7)); // Define pin 13 as output

      noInterrupts();

    //set timer1 interrupt at 1Hz
      TCCR1A = 0;// set entire TCCR1A register to 0
      TCCR1B = 0;// same for TCCR1B
      TCNT1  = 0;//initialize counter value to 0
      // set compare match register for 1hz increments
      OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
      // turn on CTC mode
      TCCR1B |= (1 << WGM12);
      // Set CS12 and CS10 bits for 1024 prescaler
      TCCR1B |= (1 << CS12) | (1 << CS10);
      // enable timer compare interrupt
      TIMSK1 |= (1 << OCIE1A);
      interrupts();

      while(1){
            asm("nop");
      }
    return 0;
    }

      ISR(TIMER1_COMPA_vect)          // timer compare interrupt service routine
    {
      PORTB ^= ((1 <<  PB7));   // toggle LED pin
      PINB |= _BV(7);
      PINB = PINB | _BV(7);
    }

Which is called from an ino file, like this:

        extern "C"
     {
     void foo ();
     }

    void setup ()
      {
      foo ();
      }  // end of setup

    void loop ()
      {
      }  // end of loop

However, if I set up another timer interrupt (ex Timer Interrupt 0 or 2, the blink will stop happening, for some reason...

For example:

    //set timer0 interrupt at 2kHz
      TCCR0A = 0;// set entire TCCR2A register to 0
      TCCR0B = 0;// same for TCCR2B
      TCNT0  = 0;//initialize counter value to 0
      // set compare match register for 2khz increments
      OCR0A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)
      // turn on CTC mode
      TCCR0A |= (1 << WGM01);
      // Set CS01 and CS00 bits for 64 prescaler
      TCCR0B |= (1 << CS01) | (1 << CS00);
      // enable timer compare interrupt
      TIMSK0 |= (1 << OCIE0A);

Now, the strangest part happens that if all the three (or just the same two) timer interrupts are set, and with everything defined in the INO file, it works fine...

    //this code will enable all three arduino timer interrupts.
    //timer0 will interrupt at 2kHz
    //timer1 will interrupt at 1Hz
    //timer2 will interrupt at 8kHz

    //storage variables
    boolean toggle0 = 0;
    boolean toggle1 = 0;
    boolean toggle2 = 0;

    void setup(){

      //set pins as outputs
      pinMode(8, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(13, OUTPUT);

    cli();//stop interrupts

    //set timer0 interrupt at 2kHz
      TCCR0A = 0;// set entire TCCR2A register to 0
      TCCR0B = 0;// same for TCCR2B
      TCNT0  = 0;//initialize counter value to 0
      // set compare match register for 2khz increments
      OCR0A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)
      // turn on CTC mode
      TCCR0A |= (1 << WGM01);
      // Set CS01 and CS00 bits for 64 prescaler
      TCCR0B |= (1 << CS01) | (1 << CS00);
      // enable timer compare interrupt
      TIMSK0 |= (1 << OCIE0A);

    //set timer1 interrupt at 1Hz
      TCCR1A = 0;// set entire TCCR1A register to 0
      TCCR1B = 0;// same for TCCR1B
      TCNT1  = 0;//initialize counter value to 0
      // set compare match register for 1hz increments
      OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
      // turn on CTC mode
      TCCR1B |= (1 << WGM12);
      // Set CS12 and CS10 bits for 1024 prescaler
      TCCR1B |= (1 << CS12) | (1 << CS10);
      // enable timer compare interrupt
      TIMSK1 |= (1 << OCIE1A);

    //set timer2 interrupt at 8kHz
      TCCR2A = 0;// set entire TCCR2A register to 0
      TCCR2B = 0;// same for TCCR2B
      TCNT2  = 0;//initialize counter value to 0
      // set compare match register for 8khz increments
      OCR2A = 249;// = (16*10^6) / (8000*8) - 1 (must be <256)
      // turn on CTC mode
      TCCR2A |= (1 << WGM21);
      // Set CS21 bit for 8 prescaler
      TCCR2B |= (1 << CS21);
      // enable timer compare interrupt
      TIMSK2 |= (1 << OCIE2A);

    sei();//allow interrupts

    }//end setup

    ISR(TIMER0_COMPA_vect){//timer0 interrupt 2kHz toggles pin 8
    //generates pulse wave of frequency 2kHz/2 = 1kHz (takes two cycles for full wave- toggle high then toggle low)
      if (toggle0){
        digitalWrite(8,HIGH);
        toggle0 = 0;
      }
      else{
        digitalWrite(8,LOW);
        toggle0 = 1;
      }
    }

    ISR(TIMER1_COMPA_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
    //generates pulse wave of frequency 1Hz/2 = 0.5kHz (takes two cycles for full wave- toggle high then toggle low)
      if (toggle1){
        digitalWrite(13,HIGH);
        toggle1 = 0;
      }
      else{
        digitalWrite(13,LOW);
        toggle1 = 1;
      }
    }

    ISR(TIMER2_COMPA_vect){//timer1 interrupt 8kHz toggles pin 9
    //generates pulse wave of frequency 8kHz/2 = 4kHz (takes two cycles for full wave- toggle high then toggle low)
      if (toggle2){
        digitalWrite(9,HIGH);
        toggle2 = 0;
      }
      else{
        digitalWrite(9,LOW);
        toggle2 = 1;
      }
    }

    void loop(){
      //do other things here
    }

Is anybody able to explain why it works in the first case, doesn't work in the second, and in the third, it works as well?

title: Timer interrupt won't work if the ISR is not set

Answers: 1

body:
I found out that it's not enough to just define the interrupts, there must also be an ISR method with the compare vector...

      ISR(TIMER0_COMPA_vect)          // timer compare interrupt service routine
    {
      PORTB ^= ((1 <<  PB6));   // toggle LED pin
      PINB |= _BV(6);
      PINB = PINB | _BV(6);
    }

There was no error at compile, though.


body:
Basically i would like to create a horse racing game, (5 horses starting all to a point A and finishing in a random position to a point B).

I did an animated GIF for you to understand it more clearly :

https://i.stack.imgur.com/oOZvB.jpg

This exactly what i want to do, but in real.

I was thinking of using 5 motors (one for each horse) with a string they pull where the horse is attached on it (like this : https://www.youtube.com/watch?v=NjuoCS9-pCY), and to create randomness at each race, do a random speed for each motors every 1 or two seconds and then stop when each horse hit the finishing line (by pushing a sensor ?). Finally when all horses hit the finishing line, the motors goes backward and get the horses back to the start line.

The horses will be tiny like 1 inch (2.5cm) and the distance from start to finish line will be like 20inch (50cm) and i need the race to last at least 5-10 sec so motors don't need to turn too fast.

I don't know if it is the best way or if it is even possible (and how ? with what components?)

I have been searching for solutions to my project but didn't found anything suitable yet so here i am..

Thank you a lot for you help

title: Horse racing game

Answers: 1

body: If it is going to be tiny, I would use continuous rotation servos and rubber belts. They are nice because you dont need motor drivers, unlike stepper motors. Also they consume a lot less power than stepper motors, so you may not need to attach them to external power (not just the arduino 5v). However, because you can not control how far they move, you will need buttons at the end of the race. I think you can get them from Adafruit.


body:
I'm working on a battery-powered data logger, using a bare Atmega 328. I'm using sleep between sensor readings, via the Narcoleptic library. Everything seems to work fine, until I connect my multimeter to check on the current.

The multimeter uses manual range-setting (i.e., not autoranging). If I set the multimeter to the 0-20 mA range, I can see that my idle current is about 0.250 mA, but the upper value is off-scale. If I try to get a reading on the 0-200 mA range, the circuit misbehaves, never goes into sleep, and doesn't record any data. The current stays constant somewhere around 14-20mA.

Do I need to do something special to accurately measure current in the range of 0.25-40+mA? Or do I need a different kind/quality of multimeter?

My multimeter is a $15 digital unit from Circuit Test, model DMR-1100A.

title: Circuit doesn't work when multimeter/current meter is attached

Answers: 2

body:
If your tester has autorange function, you have to disable it, as it can interfere with normal operations by changing the internal shunt resistor.

Did you configure the meter as current meter, DC, connected in series between the power supply/battery and the rest of the circuit?

The tester might give a poor reading at low current values but it shouldn't interfere(much) with the circuit itself.

body:
Multimeters have something called a "burden voltage". See this PDF: [uCurrent - A professional precision current ... - EEVblog](http://www.eevblog.com/files/uCurrentArticle.pdf).

Also see Dave Jones' video: [µCurrent](https://www.youtube.com/watch?v=i069j6S80OU)

Meters measure current by dropping voltage over an internal resistor, and measuring the drop. By definition therefore, there is a voltage drop, which is the "burden voltage".

>  the circuit misbehaves, never goes into sleep, and doesn't record any data

If you put a voltmeter on the processor side of the ammeter you will probably find that the voltage going into your processor is somewhat less than you think. That would account for the misbehaving.

One possible approach is to crank up the voltage from your power source, checking the voltmeter to see that it reaches the expected voltage on the **processor** side of the ammeter, however in a circuit which might turn on and off (ie. sleep) this voltage might jump around (depending on the current) so this should be done with caution (to not exceed the maximum processor voltage).

---

> Or do I need a different kind/quality of multimeter?

A higher quality meter may well help - watch that video and look at the PDF to see what I am talking about. My meters (which cost more than $15) don't have this problem to the same extent.


body:
I have a basic mp3 trigger with arduino uno setup:

Trigger - https://www.sparkfun.com/products/11029

Arduino Uno code:

    #include <MP3Trigger.h>

    //  Script Function:  RobertSonics mp3trigger (v2) paired with an Arduino UNO
    //
    //  Jumper Connections:   UNO  ------  mp3trigger (v2)
    //             (UNO RX)     0  ------  TX
    //             (UNO TX)     1  ------  RX
    //             (Ground)   GND  ------  GND
    //           (+5 volts)    5v  ------  USBVCC

    #include <SoftwareSerial.h>
    void setup(){
        Serial.begin(38400);    // Standard for mp3trigger
        Serial.print("t");
        Serial.write(1);
        delay(50000);
    }

    void loop()
    {

    }

I can't get it to play any tracks. The response in the Serial monitor just says tt

title: Arduino UNO with Sparkfun MP3 Trigger

Answers: 2

body:
So, from the beginning:

 1. Have you got data on you SD card and is it is FT16 or FAT32 format?
 2. Is the MP3 status light giving any indication of life?
 3. Does the MP3 card detect when you start it up without the SD card in (One long flash).
 4. Do you have a data file named "001SomethingOrOther.MP3"?
 5. Have you tried the command "v" 0x00?
 6. Have you tried the commands "S0" and "S1"?
 7. Have you looked at the sample data on http://robertsonics.com/mp3-trigger-support/?

Hope that helps, an please post your finding, because mine arrives next week :)

body:
Finally I got it working yesterday, and by accident!!!! Sorry it was not sooner, hope you had better luck with it. In any case if anyone wants to know what I did, you can read about it here.
https://forum.sparkfun.com/viewtopic.php?f=14&t=44292


body:
I'm making a control system for the heating of a plate using a PID control.

the goal is to regulate the temperature of the plate by changing the power dissipated by the resistance. By using a sensor I read the temperature  of the plate and is then used as the input in the PID control.
I programmed also a signal wave square for the PWM.

but the thing I don't understand is what I'm exactly supposed to do with the output signal I receive.
and I cannot connect between the PWM and the PID.

Code of the square signal:

    void setup()
    {
      pinMode(9, OUTPUT);
    }
    void loop()
    {
       // phase haute
       digitalWrite(9,HIGH);
       delay(30);
       // phase basse
       digitalWrite(9,LOW);
       delay(70);
       //ton+toff = 0.1;
    //   ton = 0.1*Output;
    }

 Code of PID and the sensor

    /********************************************************
     * PID Basic Example
     * Reading analog input 0 to control analog PWM output 3
     ********************************************************/

    #include <PID_v1.h>

    int val;
    //Define Variables we'll be connecting to
    double Setpoint, Input, Output;

    //Specify the links and initial tuning parameters
    PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);

    void setup()
    {
      Serial.begin(9600);
      //initialize the variables we're linked to
      Input = analogRead(1);
      Setpoint = 37; //temperature a reguler

      //turn the PID on
      myPID.SetMode(AUTOMATIC);
    }

    void loop()
    {
      val = analogRead(1);
      float mv = ( val/1024.0)*5000;
      float Input = mv/10;
      myPID.Compute();
      analogWrite(3,Output);
      Serial.print("input temperature is :");
      Serial.println(Input);
      delay (1000);
    //  delay(1000);
      Serial.print("output is :");
      Serial.println(Output);
      delay(1000);
    }

Thank you in advance

title: Regulation of the temperature using PID

Answers: 1

body:
A PID only has one input and one output. In your case, the input will be the temperature. The use of the arduino would be to process the raw data of the temperature sensor and relay the temperature to the PID. Depending on the make and model of the PID, there could be certain transfer protocols you must adhere to. There are most likely open source libraries that will take care of transferring the data properly.

Your PID is the piece of hardware that will "decide" when it is appropriate to turn the heater on and off, therefore it shall be responsible for driving the heater. That is what the output of the PID is responsible for.

Lastly, your PID has a set point. In your case, the set point would be the desired max temperature of the plate. This set point is set and altered manually through user input.

On a side note, if this is a personal project or a non deliverable, I'd recommend not using a PID. Try processing and analyzing all of the data exclusively on the Arduino, as it would be a challenging and rewarding task.


body:
I'm trying to use a W5100 Arduino Ethernet Shield on a ATMega2560 using avr code.

There exists a library written in C, which should work http://www.seanet.com/~karllunt/w5100_webserv.zip from http://www.seanet.com/~karllunt/w5100_library.html

The w5100_webserv.c should be a working example for an ATmega644p. He mentions that the four callback functions should be modified, namely my_select(), my_deselect(), my_xchg() and my_reset()

The w5100_webserv.c also contains the following definitions for SPI_PORT/DDR CS_PORT/DDR/BIT and RESET_PORT/DDR/SPI:

 /*
 *  Define the SPI port, used to exchange data with a W5100 chip.
 */
 #define SPI_PORT     PORTB                /* target-specific port containing the SPI lines */
 #define SPI_DDR      DDRB                /* target-specific DDR for the SPI port lines */

 #define CS_DDR        DDRD                /* target-specific DDR for chip-select */
 #define CS_PORT     PORTD                /* target-specific port used as chip-select */
 #define CS_BIT        2                    /* target-specific port line used as chip-select */

 #define RESET_DDR   DDRD                /* target-specific DDR for reset */
 #define RESET_PORT    PORTD                /* target-specific port used for reset */
 #define RESET_BIT    3                    /* target-specific port line used as reset */

I've changed it to the following according to what i think the ATmega2560's datasheet specifies

    /*
     *  Define the SPI port, used to exchange data with a W5100 chip.
     */
    #define SPI_PORT     PORTB                /* target-specific port containing the SPI lines */
    #define SPI_DDR      DDRB                /* target-specific DDR for the SPI port lines */

    #define CS_DDR        DDRB                /* target-specific DDR for chip-select */
    #define CS_PORT     PORTB                /* target-specific port used as chip-select */
    #define CS_BIT        10                  /* target-specific port line used as chip-select */

    #define RESET_DDR   DDRB                /* target-specific DDR for reset */
    #define RESET_PORT    PORTB                /* target-specific port used for reset */
    #define RESET_BIT    20                   /* target-specific port line used as reset */

Furthermore, in the main(), there are also specific code for the AT644p:

    /*  * Initialize the ATmega644p SPI subsystem */
    CS_PORT |= (1<<CS_BIT);                                    // pull CS pin high
    CS_DDR |= (1<<CS_BIT);                                    // now make it an output

    SPI_PORT = SPI_PORT | (1<<PORTB4);                        // make sure SS is high
    SPI_DDR = (1<<PORTB4)|(1<<PORTB5)|(1<<PORTB7);            // set MOSI, SCK and SS as output, others as input
    SPCR = (1<<SPE)|(1<<MSTR);                                // enable SPI, master mode 0
    SPSR |= (1<<SPI2X);                                        // set the clock rate fck/2

I've changed it to the following according to what i think the ATmega2560's datasheet specifies

    /*
     *  Initialize the ATmega2560 SPI subsystem
     */
    CS_PORT |= CS_BIT;                                    // pull CS pin high
    CS_DDR |= CS_BIT;                                    // now make it an output

    SPI_PORT = SPI_PORT | (1<<PORTB0);                        // make sure SS is high
    SPI_DDR = (1<<PORTB0)|(1<<PORTB2)|(1<<PORTB1);            // set MOSI, SCK and SS as output, others as input
    SPCR = (1<<SPE)|(1<<MSTR);                                // enable SPI, master mode 0
    SPSR |= (1<<SPI2X);                                        // set the clock rate fck/2

Lastly i've changed the my_reset() function:
    void  my_reset(void)
    {
        RESET_PORT |= RESET_BIT;                            // pull reset line high
        RESET_DDR |= RESET_BIT;                            // now make it an output
        RESET_PORT &=~RESET_BIT;                            // pull the line low
        _delay_ms(5);                                            // let the device reset
        RESET_PORT |= RESET_BIT;                            // done with reset, pull the line high
        _delay_ms(10);                                            // let the chip wake up
    }

I am not sure whether my changes are 100 % correct and i don't know what changes needs to be done to my_select() my_deselect and my_xchg. I hope someone can suggest som corrections.

Thanks in advance.

title: Arduino W5100 AVR

Answers: 1

body:
I've managed to specify the correct ports and bits in order to make the library function on the Arduino ATmega2560 using their Ethernet Shield.

The SPI port definitions has to be changed to the following:

 #define SPI_PORT  PORTB    /* target-specific port containing the SPI lines */
 #define SPI_DDR   DDRB    /* target-specific DDR for the SPI port lines */

 #define CS_DDR  DDRB    /* target-specific DDR for chip-select */
 #define CS_PORT  PORTB    /* target-specific port used as chip-select */
 #define CS_BIT  4     /* target-specific port line used as chip-select */

 #define RESET_DDR   DDRB    /* target-specific DDR for reset */
 #define RESET_PORT PORTB    /* target-specific port used for reset */
 #define RESET_BIT 8     /* target-specific port line used as reset */

The section about the AT644p in the main() function has to be changed to the following:

 /*
  *  Initialize the ATmega2560 SPI subsystem
  */
 // Initial SPI Peripheral
 SPI_DDR = (1<<PORTB2)|(1<<PORTB1)|(1<<PORTB0);

 // CS pin is not active
 SPI_PORT |= (1<<CS_BIT);

  // Enable SPI, Master Mode 0, set the clock rate fck/2
 SPCR = (1<<SPE)|(1<<MSTR);
 SPSR |= (1<<SPI2X);

 //Disable the SD card
 DDRB |= (1<<CS_BIT);


body:
I am making a temperature circuit with arduino.
is there any way to plot the value of the temperature in a graph using arduino?
thank you very much in advance

title: graph of a function Arduino

Answers: 1

body:
Yes you can use the [Plot][1] menu command in the new Arduino 1.6.6 or you can use the [Visual Micro debugger][2] to create graphs in Visual Studio

  [1]: https://blog.arduino.cc/2015/11/03/arduino-ide-1-6-6-released-and-available-for-download/
  [2]: http://www.visualmicro.com/post/2015/08/16/Arduino-Breakpoint-Command-Syntax-Plotting-Values-Example.aspx


body: I am following a DIY guide that requires me to patch two arduino core library files: `HID.cpp` and `USBAPI.h`. This is not really practical for many reasons. I am not a native C programmer, but I am sure there are better ways to achieve the same without messing directly with system files. How can I override system library files without modifying the originals?

title: Alternative to patching core library source and header files

Answers: 1

body: Unfortunately there *really* isn't any way of doing that other than modifying those files. The good news is that it is perfectly viable to make the modifications under a different "core" and then amend boards.txt with the core containing the modifications.


body:
I am quite new to all the arduino stuff and right now I am struggling with a Problem that seems to be easy, but I have honestly no idea how to deal with it.

I would like to read the data from a gyroscop and transmit the raw values via bluetooth to another device.

I am using the arduino uno r3 (it should be quite new since I bought it yesterday), the famous MPU-6050 Gyro-GY521 and for bluetooth De-HC-06BT.

I could already manage to assemble everything and send the data via bluetooth. To read the data from the gyro I am using the famous library MPU6050, which comes with some examples and seems to be the de facto standard for this.

The whole script is based on the `MPU6050_DMP6` example and utilizes a `SoftwareSerial` to transmit the data.

Unfortunatly has two major issues:

1. It just stops to send data after some time (~2 Minutes) and a restart makes it send again.

2. It prints `FIFO Overflow` ~ each 20th frame, so I guess there is an ongoing failure which might stop the system.

If anybody could give some hint how to solve the »FIFO-« and »Breakdownissue« I would be very glad and I appreciate any kind of help!

Thanks in Ahead!

The whole code:

    #include <SoftwareSerial.h>

    // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
    // for both classes must be in the include path of your project
    #include "I2Cdev.h"

    #include "MPU6050_6Axis_MotionApps20.h"
    //#include "MPU6050.h" // not necessary if using MotionApps include file

    // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
    // is used in I2Cdev.h
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include "Wire.h"
    #endif

    // class default I2C address is 0x68
    // specific I2C addresses may be passed as a parameter here
    // AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
    // AD0 high = 0x69
    MPU6050 mpu;
    //MPU6050 mpu(0x69); // <-- use for AD0 high

    //RX und TX gekreuzt vom Bluetooth board
    SoftwareSerial serial2(10, 11); //RX, TX

    #define OUTPUT_READABLE_YAWPITCHROLL

    //#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
    //bool blinkState = false;

    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer

    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorInt16 aa;         // [x, y, z]            accel sensor measurements
    VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
    VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

    // packet structure for InvenSense teapot demo
    uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

    // ================================================================
    // ===               INTERRUPT DETECTION ROUTINE                ===
    // ================================================================

    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
        mpuInterrupt = true;
    }

    // ================================================================
    // ===                      INITIAL SETUP                       ===
    // ================================================================

    void setup() {
        // join I2C bus (I2Cdev library doesn't do this automatically)
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
            TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif

        Serial.begin(115200);
        while (!Serial); // wait for Leonardo enumeration, others continue immediately

        serial2.begin(9600);
        //serial2.println("Hello");

        // initialize device
        Serial.println(F("Initializing I2C devices..."));
        mpu.initialize();

        // verify connection
        Serial.println(F("Testing device connections..."));
        Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

        // load and configure the DMP
        Serial.println(F("Initializing DMP..."));
        devStatus = mpu.dmpInitialize();

        // make sure it worked (returns 0 if so)
        if (devStatus == 0) {
            // turn on the DMP, now that it's ready
            Serial.println(F("Enabling DMP..."));
            mpu.setDMPEnabled(true);

            // enable Arduino interrupt detection
            Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
            attachInterrupt(0, dmpDataReady, RISING);
            mpuIntStatus = mpu.getIntStatus();

            // set our DMP Ready flag so the main loop() function knows it's okay to use it
            Serial.println(F("DMP ready! Waiting for first interrupt..."));
            dmpReady = true;

            // get expected DMP packet size for later comparison
            packetSize = mpu.dmpGetFIFOPacketSize();
        } else {

            Serial.print(F("DMP Initialization failed (code "));
            Serial.print(devStatus);
            Serial.println(F(")"));
        }

        // configure LED for output
        //pinMode(LED_PIN, OUTPUT);
    }

    void loop() {

        // if programming failed, don't try to do anything
        if (!dmpReady) return;

        // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {

        }

        // reset interrupt flag and get INT_STATUS byte
        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();

        // get current FIFO count
        fifoCount = mpu.getFIFOCount();

        // check for overflow (this should never happen unless our code is too inefficient)
        if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
            // reset so we can continue cleanly
            mpu.resetFIFO();
            //Serial.println(F("FIFO overflow!"));

        // otherwise, check for DMP data ready interrupt (this should happen frequently)
        } else if (mpuIntStatus & 0x02) {
            // wait for correct available data length, should be a VERY short wait
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

            // read a packet from FIFO
            mpu.getFIFOBytes(fifoBuffer, packetSize);

            // track FIFO count here in case there is > 1 packet available
            // (this lets us immediately read more without waiting for an interrupt)
            fifoCount -= packetSize;

            #ifdef OUTPUT_READABLE_YAWPITCHROLL
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

                serial2.print(ypr[0] * 180/M_PI);
                serial2.print(",");
                serial2.print(ypr[1] * 180/M_PI);
                serial2.print(",");
                serial2.print(ypr[2] * 180/M_PI);
                serial2.print("\n");

            #endif

            delay(5);
        }
    }

title: MPU6050, Bluetooth — FIFO Overflow and Breakdown

Answers: 0


body:
A TMP35/36/37 is giving very high voltage readings, which results in high temperature readings. The serial monitor looks like this: [![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/4RMhI.png
As you can see, the sensor value is in the 900s, voltage is almost 5, and temp is in the 400s. The circuit is very simple, just a TMP connected to 5V and ground and pin A0. Here is my code:

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

    const int sensorPin = A0;
    const float baselineTemp = 20.0;

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

    }

    void loop() {
      int sensorVal = analogRead(sensorPin);
      Serial.print("Sensor value: ");
      Serial.print(sensorVal);

      float voltage = (sensorVal / 1024.0) * 5.0;
      Serial.print(", volts: ");
      Serial.print(voltage);

      Serial.print(", degrees C: ");
      float temperature = (voltage - .5) * 100;
      Serial.println(temperature);
      delay(1000);
    }

This is a very simple program and a very simple circuit, so I'm not sure what is going on. Maybe the problem is the sensor itself. I have also tried this sensor with multiple other circuits and programs and the same thing happens.

If anyone knows anything about this, help would be great.

title: Why is my TMP35 giving me weird values?

Answers: 2

body: Part seems to be broken; voltage is unusually high.

body:
I use voltage dividers a lot and have seen this before.

In each and every case where ALL my readings are high, yet they vary predictably (like on my solar panels - they go up during day and down at night), there has always been proven to be a very simple, single cause.

**Resistance in the ground lead.**

Such as if it is plugged into a breadboard hole that is not holding it well, or if I have extended it and have connections along the way.

So that would be the first thing I would look for.

----------
Having said that, if the readings are very high and do NOT vary predictably, then I would look for a disconnected ground lead.

----------
**If all the connections are good but it still misbehaves then I would swap it out with another one to make sure the part itself isn't the problem.**


body:
I have an Arduino Uno with a motor shield, as well as a DS1307 RTC that I am using to control 2 pumps.

Ideally I would like to set a start time (startHour + startMinute) and end time (endHour + endMinute) for each pump.

I have had luck using `if` statements to control my timer like below (adapted from Iain Foulds):

    byte startHour=8
    byte startMinute=15
    byte endHour= 14
    byte endMinute= 20

    byte startHour2=22
    byte startMinute2=30
    byte endHour2= 2
    byte endMinute2= 45

    void loop() {
      byte checkStartTime1() {
        DateTime now = RTC.now();
        // Read in what our current datestamp is from RTC
        if (now.hour() == startHour && now.minute() == startMinute) {
          validStart1 = 1;
        } else {
          validStart1 = 0;
        }
        return validStart1;
        // Return the status for powering up
      }
    }

But my concern is that this only checks for equivalency at the moment, and if I lost power when my start time came up my pump would not come on. So I was hoping to set up an `if` statement that can deal with ">=" as opposed to just "==".

Which I can use if I only deal with the hour section:

    if (now.hour() >= startHour && <= endHour)

But things get complicated when I try to add in minutes to the control structure. I end up with a series of nested for loops that do not work.

I'm hoping someone can help me write an `if` statement (or `switch case`) that can accommodate hours and minutes. So that any time between 8:15-14:20

    validStart1=1

and anytime other time

    validStart1=0

And please note the addition of the second set for this timer (StartHour2)- which I threw as my second pump will need to deal with the switch over past midnight.

title: Creating a timer using a Real Time Clock with start and stop times

Answers: 6

body:
What you need to do is convert the time into some standard single number and then compare those numbers.

A popular method is to calculate the number of seconds since an *epoch*.  An *epoch* is an arbitrary point in time that you measure time since.  Microsoft chose 01/01/0000 for their epoch - Unix chose 01/01/1970.

The Time.h library contains functions for manipulating time values - one of the functions in it can convert a full date and time specification into the number of seconds since 01/01/1970 (Unix epoch).  If you want ideas then look at the source code for that.

A similar approach can be used to just work on the hours and minutes within a day.  One hour is 60 minutes, so you can create a number that is the number of hours multiplied by 60 plus the number of minutes in the current hour.  That will give you the number of minutes since midnight.  You can even add in the seconds if you want even more accuracy.

Once you have that single value it's very easy to compare it with a `>=`.

body:
    byte startHour=8
    byte startMinute=15
    byte endHour= 14
    byte endMinute= 20

    byte startHour2=22
    byte startMinute2=30
    byte endHour2= 2
    byte endMinute2= 45

    void loop()
    {
      DateTime now = RTC.now();  // Read in what our current datestamp is from RTC

      if (
       ( (now.hour()==startHour && now.minute()>= startMinute) || (now.hour()>startHour)
       && ( (now.hour()==endHour && now.minute()< endMinute) || (now.hour()<endHour) ) {
        validStart1 = 1;

      } else {
        validStart1 = 0;  //
      }

    return validStart1; // Return the status for powering up
     }
    }

body:
I had a similar problem when i tried to control some heating source here at home.This was how I made my steps to get it working.
First I will assume you are using the library time.h and DS1307RTC.h (check here for info: <https://www.pjrc.com/teensy/td_libs_Time.html>).

Assuming that you will need 3 variables of the type tmElements_t.
tm will store your current time( the one you get from DS1307). The other two are auxiliary for defining time you start and time you stop the pump.
In similar way, you will need 3 variables of type time_t for the same reasons.
time_t variables store a the timestamps since 01/01/1970 (Unix epoch) which are easier to work with but tmElements structures are more human friendly.

    tmElements_t tm, tm_hour_start, tm_hour_end;
    time_t now, t_hour_start, t_hour_end;

Now in your loop you need to get the current time from rtc:

    time_t now = RTC.get();
after, use the breaktime funtion to convert the timestamp value to tmElements struture:

    breakTime(now, tm);

Next step is to copy contents of tm to the other auxiliary structures, use the memcpy function:

    memcpy(&tm_hour_start, &tm, sizeof(tm));
 memcpy(&tm_hour_end, &tm, sizeof(tm));

after, change the the auxiliaries vars to meet your correct schedule of start and stop (are seconds important? if so, do similar way):

    tm_hour_start.Hour = startHour;
    tm_hour_start.Minute = startMinute;
    tm_hour_start.Second = 0;
    tm_hour_end.Hour = endHour;
 tm_hour_end.Minute = endMinute;
 tm_hour_end.Second = 0;

Ok, we have the more human friendly start and end structures, lets get the timestamps from them. To do soo we use the makeTime function that converts tmElements_t structures to time_t:

    t_hour_start = makeTime(tm_hour_start);
    t_hour_end = makeTime(tm_hour_end);

All you need to do now, is check if your current timestamp (now) is between this newly created timestamps:

    if ((t_hour_start <= now) && (now <= t_hour_end)){
       //do something is soo...
    }else{
       // do something if not...
    }

**Extra tip:** In case your stop hour goes past midnight, add one more day to the timestamp:

    if (startHour > endHour) //past midnight correction
    t_hour_end = t_hour_end + SECS_PER_DAY;

clean code:

    #include <time.h>
    #include <DS1307RTC.h>
    #include <stdio.h>
    // other includes etc...

    byte startHour=8
    byte startMinute=15
    byte endHour= 14
    byte endMinute= 20

    tmElements_t tm, tm_hour_start, tm_hour_end;
    time_t now, t_hour_start, t_hour_end;

    // setup function and other needed things...

    void loop(){
      //get current timestamp
      time_t now = RTC.get();
      // make current date and time structure
      breakTime(now, tm);
      // make auxiliary structures to be more human editable and friendly
      memcpy(&tm_hour_start, &tm, sizeof(tm));
      memcpy(&tm_hour_end, &tm, sizeof(tm));
      // change auxiliary structures to meet your start and end schedule
      tm_hour_start.Hour = startHour;
      tm_hour_start.Minute = startMinute;
      tm_hour_start.Second = 0;
      tm_hour_end.Hour = endHour;
      tm_hour_end.Minute = endMinute;
      tm_hour_end.Second = 0;
      // reverse process to get timestamps
      t_hour_start = makeTime(tm_hour_start);
      t_hour_end = makeTime(tm_hour_end);
      // check if end time is past midnight and correct if needed
      if (startHour > endHour) //past midnight correction
        t_hour_end = t_hour_end + SECS_PER_DAY;

      //final part
      if ((t_hour_start <= now) && (now <= t_hour_end)){
              //do something is soo...
      }else{
              // do something if not...
      }

    }

**EDIT:** to correct the thing about midnight checks spotted in comments. New code:

    #include <Wire.h>
    #include <Time.h>
    #include <DS1307RTC.h>
    #include <stdio.h>
    // other includes etc...

    byte startHour = 8;
    byte startMinute = 15;
    byte endHour = 14;
    byte endMinute = 20;

    tmElements_t tm, tm_hour_start, tm_hour_end;
    time_t now_, t_hour_start, t_hour_end;
    boolean update_tm = 1;

    // setup function and other needed things...
    void setup(){};

    void loop(){
      //get current timestamp
      time_t now_ = RTC.get();
      // make current date and time structure
      breakTime(now_, tm);
      // make auxiliary structures to be more human editable and friendly
      if(update_tm){
        memcpy(&tm_hour_start, &tm, sizeof(tm));
        memcpy(&tm_hour_end, &tm, sizeof(tm));
        // change auxiliary structures to meet your start and end schedule
        tm_hour_start.Hour = startHour;
        tm_hour_start.Minute = startMinute;
        tm_hour_start.Second = 0;
        tm_hour_end.Hour = endHour;
        tm_hour_end.Minute = endMinute;
        tm_hour_end.Second = 0;
        // reverse process to get timestamps
        t_hour_start = makeTime(tm_hour_start);
        t_hour_end = makeTime(tm_hour_end);

        // check if end time is past midnight and correct if needed
        if (startHour > endHour) //past midnight correction
          t_hour_end = t_hour_end + SECS_PER_DAY;
      }
      //final part
      if ((t_hour_start <= now_) && (now_ <= t_hour_end)){
        /* if we got a valid schedule, don't change the tm_hour structures and the
        respective t_hour_start and t_hour_end timestamps. They should be updated
        after exiting the valid schedule */
        if(update_tm)
          update_tm = 0;

        //do something is soo...
      }else{
        if(update_tm == 0)
          update_tm = 1;
        // do something if not...
      }

    }

body:
Gerben, thanks for your code. I took it and added seconds to the check, and tidied up a few typos. This isn't as sophisticated as other methods, but might be good for beginners to follow logic. hope it helps

    #include <TimeLib.h>
    #include <Wire.h>
    #include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

    int openHH = 9;
    int openMM = 10;
    int openSS = 0;
    int closeHH = 9;
    int closeMM = 40;
    int closeSS = 0;

    bool isOpenTime()
    {
      time_t t = now(); // Read in what our current datestamp is from RTC
    //  DateTime now = RTC.now();  // if using timeRTC lib, i think

      int nowHH = hour(t); int nowMM = minute(t); int nowSS = second(t);  // put into local variables for easier read

      if ((
            (nowHH>openHH)                        // check hours first
            || ((nowHH==openHH) && (nowMM>openMM))             // check minutes if in same hour
            || ((nowHH==openHH) && (nowMM==openMM) && (nowSS>=openSS))    // check seconds if in same hour & minute
          )
          &&                                  // both conditions must be valid
          (
            (nowHH<closeHH)                       // check hours first
            || ((nowHH==closeHH) && (nowMM<closeMM)))             // check minutes if in same hour
            || ((nowHH==closeHH) && (nowMM==closeMM) && (nowSS<=closeSS)) // check seconds if in same hour & minute
          )
      { return true; } else { return false; }
    }

      // usage
      if (isOpenTime) {
        // ... do something, eg open door
      } else {
        // ... do something, eg close door
      }

body:
Use the time in number of seconds total.

    ontime=((sethour*60)+(setmin*60)+setsec);
    offtime=((ofsethour*60)+(ofsetmin*60)+ofsetsec);
    currenttime=((t.hour*60)+(t.min*60)+(t.sec);
    if ((currenttime>ontime)&&(currenttime<offtime));
      {
      pumpon();
      }
    else
      {
      pumpoff();
      }
    delay(1000);

body:
A simple and effecient way is to use relative days and make use of the fact that the days, hours, minutes, and seconds are byte-sized data types that can fit into a single 32-bit data type.

| byte 3 | byte 2 | byte 1 | byte 0 |
| :---:  | :---:  | :---:  | :---:  |
| Day    | Hour   | Minute | Second |

This can be achieved with the following function:

```cpp
constexpr uint32_t MakeTimestamp(const byte day, const byte hour, const byte minute, const byte second)
{
  // Pack the 4 individual bytes into a single 4-byte data type in order of precedence.
  return uint32_t(day) << 24 | uint32_t(hour) << 16 | uint32_t(minute) << 8 | uint32_t(second);
}
```

This 32-bit timestamp can be easily compared with other ones to test whether a timestamp is within a timespan:

```cpp
bool WithinTimespan(const uint32_t& timestamp, const uint32_t& begin, const uint32_t& end)
{
  if (end < begin)
  {
    // Crossing midnight.
    return timestamp >= begin || timestamp <= end;
  }
  // Single day.
  return timestamp >= begin && timestamp <= end;
}
```

By using relative days to declare the motor start and stop times, the comparison takes care of the rollover to tomorrow:

```cpp
const byte motor1_start_hour = 8;
const byte motor1_start_minute = 15;
const byte motor1_stop_hour = 14;
const byte motor1_stop_minute = 20;

const byte motor2_start_hour = 22;
const byte motor2_start_minute = 30;
const byte motor2_stop_hour = 2;
const byte motor2_stop_minute = 45;

const uint32_t motor1_start_time = MakeTimestamp(0, motor1_start_hour, motor1_start_minute, 0);
const uint32_t motor1_stop_time = MakeTimestamp(0, motor1_stop_hour, motor1_stop_minute, 0);

const uint32_t motor2_start_time = MakeTimestamp(0, motor2_start_hour, motor2_start_minute, 0);
const uint32_t motor2_stop_time = MakeTimestamp(0, motor2_stop_hour, motor2_stop_minute, 0);
```

Then the `loop()` is simply something like this:

```cpp
void loop()
{
  const DateTime now = rtc.now();
  const uint32_t timestamp = MakeTimestamp(0, now.hour(), now.minute(), now.second());

  bool motor1_on = WithinTimespan(timestamp, motor1_start_time, motor1_stop_time);
  bool motor2_on = WithinTimespan(timestamp, motor2_start_time, motor2_stop_time);

  UpdateMotor1(motor1_on);
  UpdateMotor2(motor2_on);
}
```


body: I would like to know the specs of the accelerometer used on a LightBlue Bean before buying one, but I couldn't find any info online. Anybody has an idea?

title: Can anyone tell me about the onboard accelerometer of LightBlue Bean?

Answers: 2

body: There is a reference to the [accelerometer datasheet](http://ae-bst.resource.bosch.com/media/products/dokumente/bma250/bst-bma250-ds002-05.pdf) from the [Arduino Reference page](http://legacy.punchthrough.com/bean/the-arduino-reference/accelerationreading/)

body:
> I would like to know the specs of the accelerometer used on a LightBlue Bean before buying one, but I couldn't find any info online. Anybody has an idea?

Start by checking the Adafruit [LightBlue Bean][1] product description. There you can find a link to the [schematics and board layout][2]. On page two there is accelerometer, a BMA250 just as @Jason links to.

That took "30 seconds" web search plus writing this answer :)

Cheers!

  [1]: https://www.adafruit.com/products/2732
  [2]: https://www.adafruit.com/images/product-files/2732/Bean_revE_board_export.pdf


body:
I am (currently) parsing a PPM analog signal using an Arduino Uno R3 using the analog comparator ASCR and analog hardware interrupts using AIN0 and AIN1. I am applying a specific negative comparison voltage using a linear voltage regulator on AIN0 and the signal on AIN1.

**Code snippets:**

*setup*

      ACSR  = B00011011;

*outside other closures*

    ISR(ANALOG_COMP_vect) {
       CRCArduinoPPMChannels::INT0ISR();
    }

I am trying to move this project to an Arduino (compatible) [Pro Micro from SparkFun](https://www.sparkfun.com/products/12640). The [datasheet](http://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/ATMega32U4.pdf) specifies AIN0 on ATmega32u4 pin 1 but do not see a reference to AIN1.

The datasheet outlines use of the analog comparator on page 289:
>  AIN+ can be connected either to the AIN0 (PE6) pin, or to the internal
Bandgap reference. AIN- can only be connected to the ADC multiplexer.

I have connected the signal to Arduino pin 7, the comparison voltage to Arduino pin 20 (analog 2) and set the following options of the ADMUX register:

    ADMUX = B11000101;

The interrupts trigger but the comparator voltage (AIN-) is not being observed. Any help would be appreciated.

title: Using Analog Comparator on ATmega32u4

Answers: 1

body: AIN- won't be connected to the ADC mux unless ACME is set and ADEN is cleared. Don't forget to do so.


body:
This is more of a C/C++ question. However the files I am asking about are a part of the Arduino library.

In */arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/Arduino.h* :

    #ifndef Arduino_h
    #define Arduino_h

    #include <stdlib.h>
    #include <stdbool.h>
    #include <string.h>
    #include <math.h>

    #include <avr/pgmspace.h>
    #include <avr/io.h>
    #include <avr/interrupt.h>

    #include "binary.h"

    #ifdef __cplusplus
    extern "C"{
    #endif

How are these blocks found at compile time in the main sketch?

    #include <avr/pgmspace.h>
    #include <avr/io.h>
    #include <avr/interrupt.h>

Does `#include <avr/somelibrary.h>` mean that this is a standard library from either *avr-g++* or *avr-gcc*? As opposed to a standard g++ or gcc compiler?

One last question, how can there be an *Arduino.h* without an *Arduino.c*? I searched through the project but could not find an *Arduino.c*. All of these are probably stupid questions, as I am in the process of learning C/C++. I am completely new to it.

title: Question about include statements and details in Arduino.h file from core library

Answers: 2

body:
> Does `#include <avr/somelibrary.h>` mean that this is a standard library from either *avr-g++* or *avr-gcc*? As opposed to a standard g++ or gcc compiler?

No. It simply means that the compiler should check both its built-in include paths as well as any passed via the `-I` command line option (or its local equivalent) for a file called "avr/somelibrary.h". That AVR GCC knows where AVR Libc is located is incidental.

> One last question, how can there be an *Arduino.h* without an *Arduino.c*?

There is no obligation to match each header file with a .c/.cc/.cpp file, or vice versa.

body:
I think after all this time, you may found the answers for your question.

But to add some information to this topic incase if anyone opened this question.

> Does #include <avr/somelibrary.h> mean that this is a standard library
> from either avr-g++ or avr-gcc? As opposed to a standard g++ or gcc
> compiler?

Yes, what is included with `avr/` is related to avr standard libraries, which is also found in avr standard compilers.

> One last question, how can there be an Arduino.h without an Arduino.c?

Because, as Mr @Ignacio Vazquez-Abrams answered that there's no obligation for connecting the header file for anything else. You can write multiple header files and use them for one source file.


body:
I am trying to plot a graph on processing but I'm having challenges going about it. The processing sketch below does work for plotting only one axis, and I'm trying to plot all three axis on the same sketch. Does anyone have an idea on how I could go about it. Below are the Arduino and Processing sketches.

**Arduino**

<!-- language: C -->

    AcceleroMMA7361 ski;
    int x;
    int y;
    int z;

    void setup()
    {
       Serial.begin(115200);
       ski.begin(13, 12,11,10, A0, A1, A2);
       ski.setARefVoltage(3.3);
       ski.setSensitivity(HIGH);
       ski.calibrate();
    }

    void loop()
    {
        x = ski.getXRaw();
        y = ski.getYRaw();
        z = ski.getZRaw();
       //Serial.print("\nx: ");
         Serial.println(x);
       //Serial.print("\ty: ");
       //Serial.print(y);
       //Serial.print("\tz: ");
       //Serial.print(z);
       delay(10);                                     //(make it readable)
    }//End of Arduino Sketch

**Processing**

    import processing.serial.*;

    Serial myPort;        // The serial port
    int xPos = 1;         // horizontal position of the graph

    float fValue;
    boolean newVal = false;

    void setup () {
       size(800, 630);
       println(Serial.list());
       myPort = new Serial(this, Serial.list()[0], 115200);
       myPort.bufferUntil('\n');
       background(2);
       stroke(127, 34, 255);
    }

    void draw () {
        if (newVal) {
           line(xPos, height, xPos, height - fValue);
           if (++xPos >= width) {
             xPos = 0;
             background(2);
           }
           newVal = false;
        }
    }

    void serialEvent (Serial myPort) {
       String inString = myPort.readStringUntil('\n');
       if (inString != null) {
           inString = trim(inString);
           fValue = float(inString);
           fValue = map(fValue, 0, 1023, 0, height);
           newVal = true;
         }
    }

title: Graph plotting on Processing from Arduino sensor data

Answers: 1

body:
I have edited your `serialEvent()` method a little bit, so it could handle the data from the Arduino, when split by a tab.

    void serialEvent (Serial myPort) {
       String inString = myPort.readStringUntil('\n');

       if (inString != null) {
         values=split(inString,"\t");  //Splitting the output of the arduino into a String Array
         for(int i=0;i<values.length;i++){
           values[i]=trim(values[i]); //deleting the whitespaces as before
           float_values[i]=float(values[i]); //cast the string to a float as before
         }
           x = map(float_values[0], 0, 1023, 0, height); //map the value as before
           y = map(float_values[1], 0, 1023, 0, height);//map the value as before
           z = map(float_values[2], 0, 1023, 0, height);//map the value as before
           newVal = true;
         }
    }

so your sending on the Arduino has to look like this:

    void loop()
    {
        x = ski.getXRaw();
        y = ski.getYRaw();
        z = ski.getZRaw();
        Serial.print("\n");
        Serial.print(x);
        Serial.print("\t");
        Serial.print(y);
        Serial.print("\t");
        Serial.print(z);
        delay(10);                                     //(make it readable)
    }

You still have to make the drawing in the `draw()` method of processing, but I think that this is not the problem.

For the 3d draw you should have a look on the [Processing reference][1] or at this special topic, [P3D by Daniel Shiffman][2].

I have not tested the code, but I think that it should work.

If you have questions, feel free to ask ;D

  [1]: https://processing.org/reference/
  [2]: https://processing.org/tutorials/p3d/