message:
Getting Push Button Logic To Stick?

I'm trying to get a sensor to activate if a push button is clicked. And deactivate when a certain condition is met and reactivate when the push button is pressed again.

    #include <SPI.h> // Included for SFE_LSM9DS0 library
    #include <Wire.h>
    #include <SFE_LSM9DS0.h>

    #define LSM9DS0_XM  0x1D // Would be 0x1E if SDO_XM is LOW
    #define LSM9DS0_G   0x6B // Would be 0x6A if SDO_G is LOW
    // Create an instance of the LSM9DS0 library called `dof` the
    // parameters for this constructor are:
    // [SPI or I2C Mode declaration], [gyro I2C address], [xm I2C address]
    LSM9DS0 dof(MODE_I2C, LSM9DS0_G, LSM9DS0_XM);

    const byte INT1XM = 4; // INT1XM tells us when accel data is ready
    //const byte INT2XM = 8; // INT2XM tells us when mag data is ready
    //const byte DRDYG = 7;  // DRDYG tells us when gyro data is ready
    const int buttonPin = 15;     // the number of the pushbutton pin

    int buttonState = 0;

    double X;
    double Y;
    double Z;

    void setup(){

      pinMode(INT1XM, INPUT);
      pinMode(buttonPin, INPUT);

      Serial.begin(9600);
      Serial1.begin(9600); // Start serial at 115200 bps
      // Use the begin() function to initialize the LSM9DS0 library.
      // You can either call it with no parameters (the easy way):

      uint16_t status = dof.begin();
      // Or call it with declarations for sensor scales and data rates:
      //uint16_t status = dof.begin(dof.G_SCALE_2000DPS, dof.A_SCALE_6G, dof.M_SCALE_2GS);

      // begin() returns a 16-bit value which includes both the gyro and
      // accelerometers WHO_AM_I response. You can check this to make sure
      // communication was successful.
      // Serial.println(status, HEX);
      setODR();
    }

    void loop(){

      buttonState = digitalRead(buttonPin); //Read push button logic.

     // Serial.println(buttonState);

      if (buttonState == 1) {   //if push button is pressed

        printAccel(); //print sensor data

      }

    }

    void printAccel()
    {
      // Only read from the accelerometer if the accel interrupts,
      // which means that new data is ready.
      if (digitalRead(INT1XM))
      {
        // Use the readAccel() function to get new data from the accel.
        // After calling this function, new values will be stored in
        // the ax, ay, and az variables.
        dof.readAccel();

        //Serial.print("A: ");

        // Using the calcAccel helper function, we can get the
        // accelerometer readings in g's.
        X=dof.calcAccel(dof.ax);
        Y=dof.calcAccel(dof.ay);
        Z=dof.calcAccel(dof.az);

        Serial.print(X);
        Serial.print(", ");
        Serial.print(Y);
        Serial.print(", ");
        Serial.println(Z);

        // Serial1.println(Z);

        fall(); //jump to check condition

      }
    }

    void setODR(){

      dof.setAccelODR(dof.A_ODR_25);
      dof.setAccelScale(dof.A_SCALE_16G);
    }

    void fall(){

      if(-0.08<X && X<0.08){
        if(-0.08<Y && Y<0.08){
          if(-0.08<Z && Z<0.08){

            Serial1.println("N");
            Serial.println("Fallen!");

            loop(); //if condition is met, jump to loop to wait for push button to be pressed again.

            }
          }
        }
      //else{

        printAccel(); //else continue printing sensor data

      //}
    }

However I am having some trouble getting it to work, above is what I have worked out thus far.

body:
You'll need to store whether the button has been pressed.

    bool buttonActivated = false;

    ...

    void loop(){

      buttonState = digitalRead(buttonPin); //Read push button logic.
      if (buttonState == 1 ) {
        buttonActivated = true;
      }

      if( buttonActivated ) {
        printAccel(); //print sensor data
      }

    }

to deactivate, use:

    buttonActivated = false;


sender: user

message:
How to power a Seeeduino Stalker v2.3 - water proof with charger instead of solar panel

I am currently coding on a Seeeduino Stalker v2.3 - water proof kit.

http://www.seeedstudio.com/wiki/Seeeduino_Stalker_-_Waterproof_Solar_Kit

It is sold with a solar panel to recharge the battery. Unfortunately, I will not have a lot of light where my sensor will be installed and I would like to power the board with a charger from 110V-220V plug and keep the battery only for potential power shortage.

My questions are:

1. What is the best option for connection and charger?

2. I have a previous Arduino Uno charger (9V-1A). Would it work with some linear regulator? What wiring should I use?

3. Any recommendation for a Li-Ion battery that could I buy and that would last longer than this 3.7 V at 1000mA?

Thank you for your help :)

sender: assistant

body:
1. You can charge the battery and power the board, via USB. The CN3063 requires between 4.4V to 6V, so not a huge range of options besides a 5v wall-wart

2. No. 9V would be too high.

3. How many mains power failures / brownouts do you get, where you live?


body:
 1. To be as little invasive as possible, I'd remove just the [solar panel][1] and replace it with a power supply with the same typical voltage (5.5V) and at least the same typical power output (0.5W). It should not be too difficult, nor too expensive. Any USB charger that can provide 5V should do. You can just cut the USB connector and attach the wires to the board. Or be more elegant and create an adapter. Either way should work. And the price should be about a couple of bucks.

 2. Yes, I think it would work, although linear regulators 9V -> 5V are really inefficient. See my proposed solution from the previous point.

 3. On ebay there's [plenty][2] of options, but they might not fit in the box of the seeduino. You have to compare the dimensions of the battery vs whatever extra space might be available.

  [1]: http://www.seeedstudio.com/depot/05w-solar-panel-55x70-p-632.html?cPath=155
  [2]: http://www.ebay.com/sch/i.html?_from=R40&_trksid=p2050601.m570.l1313.TR0.TRC0.H0.Xlipo+3.7v.TRS0&_nkw=lipo+3.7v&_sacat=0


message:
Explanation please, of hardware and software serial links

I am starting to use a Seeeduino GPRS shield (please see note), which is essentially an Arduino Leonardo that, among other things, can be used as a mobile 'phone for sending and receiving texts. I have successfully tried the "blink an led" and "fade an led" sketches, so the compiling and uploading are ok

I am using a desktop computer with Linux Fedora 20.

Now I want to go on to use the cell phone network to communicate with my mobile 'phone. However I am puzzled by something I assume everybody else understands already, and that is the references to "select either software serial port or hardware serial port to be connected to GPRS Shield". Please could someone explain what "software or hardware serial port" is, in simple terms, or point me to a web site that does so? Do I need any wired connection with my PC other than the USB link I use for uploading sketches?

Note: I bought a discounted GPRS shield labelled version 1.0a2. All the information on the 'net is of version 1.0 or 2.0 (with no "a2") and photos and diagrams do not correspond with what I have. I am awaiting official documentation, but meanwhile treating it as an Arduino Leonardo seems to be working.

body:
The hardware serial port is the serial port which connects to the computer this takes up pins 1 and 2 I believe. You can read about this here http://arduino.cc/en/reference/serial.

Software serial ports are only on digital IO pins. You can read more about this here
http://arduino.cc/en/Reference/softwareSerial

You should not need anything other the USB connection port.


body:
A `SoftwareSerial` connection is created using the `UART` pins 7 and 8.

Having the device in `HardwareSerial` mode allows the device to connect to pins 0 and 1, allowing direct control from the serial connection to the computer.

In `SoftwareSerial`, you can communicate with the Arduino Via serial, and the Arduino controls the GPRS shield via uart.


body:
Most small micro controllers, AVR's included, have dedicated hardware for communicating with different serial devices. In arduino these are referenced with "Serial", "Serial1", "Serial2" and so on, depending on how many hardware serial ports your particular arduino has.

Leonardo's are an exception, the first hardware port is "Serial1" and "Serial" refers to the PC's usb connection. On the other arduinos that I know of "Serial" is hardware serial used for PC comms, so using it for other hardware requires sacraficing your PC link.

Software serial ports use the processors more generic pin-change interrupt system to communicate on any pins that support said interrupts, but they have a higher processing overhead and often cannot support the same high speeds as the hardware serial. There are different libraries for Software Serial that have different approaches giving different advantages and drawbacks.

To use a software Serial port you will need to make one to be used in your code, which will look something like this, depending on the type name the library you include uses:

    SoftwareSerial softSerial( txPinNumber, rxPinNumber);

So in short, your processor has dedicated hardware for communicating over serial that should be used first, but if you need more ports the processor can simulate some extras which is referred to as "Software Serial". The documentation to your GPRS shield implies that either will work just fine. You should look at the arduino documentation for your board to see how many ports you have and which pins can be used for serial.

The documentation does not imply you will need any special link to your computer outside of the USB connection.


message:
Powering a 5V Arduino Pro Mini with 3.3V

I want to run the 5V board at 3.3V because I can get the 5V version cheaper than the 3.3V version.

I read that you can power the Arduino Pro Mini with a battery by connecting the battery to the 5V pin, bypassing the regulator.

Somewhere else I read that the only difference between a 3.3V and 5V Pro Mini is the regulator.

Are these assumptions correct? If yes, can I use a 5V Pro Mini like a 3.3V by powering it with a 3V Battery on the 5V pin?

body:
Pro Mini 5V has voltage regulator for 5V and 16MHz quartz.
Pro Mini 3.3V has voltage regulator for 3.3V and 12MHz quartz.

According to manufacturer specification Atmega328 chip powered by 3.3V cannot run 16MHz and needs at most about 13MHz. But it's official specification. Some chips are better than specification (faster) some are worse (slower). So you can try whether **your** Pro Mini is better or not. Or you can change quartz to 12MHz, if you can solder SMD parts.

Or better look for cheaper 3.3V clone, they are not much more expensive as 5V version...


body:
I just discovered that I knew the answer to this, because I was accidentally running some 5v/16MHz Pro Mini boards at 3.3v without issue.

**Short Version**

Yes, you can run one feeding it 3.3v, but you need to program it as a 5v/16MHz board to get the clock speeds right.  Also, all your TTL levels (outputs) will be 3.3v, not 5v.  Additionally, at least in my experience, the processor will run at 16MHz and not 12MHz with 3.3v.

**Background Story**

I had some generic Pro Mini boards that didn't mark their voltage at all, so I tried programming (and running) them using my FTDI at 3.3v using the 3.3v/8mHz option in the Arduino IDE.  I was able to upload programs just fine, but the clock was clearly wrong, as the "Blink" program ran about 2x as fast.  That told me that it was running faster than 8MHz .

So I tried again this time telling the IDE it was a 5v/16MHz chip, and everything ran fine, despite the fact that I was feeding it 3.3v.  I even saw that pin 13 was cycling from 0v up to 3.3v - exactly what I was feeding it.  So for a while I just thought they were 3.3v Pro Minis.

But then thinking about it, I realized that having to tell it to run at 16MHz to get the clock right meant it really was a 16MHz chip - which I didn't think was available with the 3.3v model.

So on a whim (and since I have a ton of these little boards), I changed my FTDI to 5V, and was able to run and program the board just fine.

So from that, I conclude that yes, you can run them at 3.3v, but your TTL levels will be just 3.3v.


body:
First I am going to say **it is very much possible.** Allow me to explain.

The 5v version can be powered with 3.3v, but it is **not recommended** to supply power through the 5v pin, bypassing the regulator. **Only *regulated* 5v power should be supplied through the 5v pin. Any other voltage levels should go in the RAW pin.** If you supply the Arduino Pro Mini 5b with 3.3v the chip will only be underclocked to 8-12MHz, and the voltage for Vcc (the board's operating voltage and what it will power its pins with) will be 3.3v; but there is another way.

I primarily source my components from [SparkFun][1] due to their reliability, cheap price and awesome support. They provide the Arduino Pro Mini in [3.3v][2] and [5v][3] variants for only $10. I have used both variants for many purposes, but primarily when working with embedded and small solutions. One of those times I was accessing sensors that ran on 5v TTL logic, but I didn't have room to place a >5v battery, only room for a LiPo (which generally powers 3.3v).

I was able to solve this issue with a [SparkFun 5v Step-Up Breakout][4]*, which boosts the voltage to 5v without any other major issues. I should warn you that there are some issues you could face if you are using a LiPo to feed into the Step-Up. Even if you aren't I'll list it here for reference. The Step-Up's maximum safe input voltage is 4v, and can be a bit unreliable if the voltage goes above it. Unfortunately a LiPo's discharge curve places it above 4v when it is within the upper 95% soc (state-of-charge), so a 3.3v regulator ([which SparkFun also sells][5]) would be needed to reliably power an Arduino Pro Mini 5v through a Step-Up breakout (at least in my experience). Also, power from a Step-Up breakout is regulated.

*Pololu also sells a [comparable Step-Up][6] that could handle an input up to 5.5v in theory, but I haven't personally used it.

  [1]: https://www.sparkfun.com
  [2]: https://www.sparkfun.com/products/11114
  [3]: https://www.sparkfun.com/products/11113
  [4]: https://www.sparkfun.com/products/10968
  [5]: https://www.sparkfun.com/products/526
  [6]: https://www.pololu.com/product/2564


body:
> If yes, can I use a 5V Pro Mini like a 3.3V by powering it with a 3V Battery on the 5V pin?

two options (at least):

1) apply 3.3v at the regulator *output* pin. there may be already a break-out for that on the board;

2) solder in a 3.3v regulator in place of the 5v regulator -> fairly easy to do as well.


body:
Im feeding 5V pro mini clone with 2 AA battery, to VCC pin, about 3V and it works normally. It consumes few current compared to 5V. [![consuming at 3V][1]][1] [![at 5V][2]][2]
And you can see what it the setup in [here][3].
Also [this][4] video can be useful.

  [1]: https://i.stack.imgur.com/CwZiJ.jpg
  [2]: https://i.stack.imgur.com/Lb51E.jpg
  [3]: https://twitter.com/anunidentified/status/1069283092135845888?s=19
  [4]: https://youtu.be/381Rg5YDmRM


message:
Digital Potentiometer not fading LED

So I am trying to test what will eventually be a Arduino controlling 3 110V motors that are currently controlled by an analog pot. But more on that later.

I am trying to test out using a digital pot (never have before) and am running into some issues with tutorials I have found online. For now, I want to control a LED with the digital pot ([Spec Sheet][1]) so that the LED fades in and fades out in a continuos loop.

Here is the [tutorial I followed][2]. It uses a different chip model but it seems from the pot I am using that the pins are the same. (I could be wrong?)

I double and triple checked the wiring and it matches below.

![Wiring Diagram][3]

Here is the code I am running (slightly modified from the tutorial, also tried the tutorial code)

    #include <SPI.h>
    byte address = 0x11;
    int CS= 10;
    int i=0;

    void setup()
    {
      pinMode (CS, OUTPUT);
      SPI.begin();
    }

    void loop()
    {
        for (i = 0; i <= 128; i++)
        {
          digitalPotWrite(i);
          delay(10);
        }
        delay(500);
        for (i = 128; i >= 0; i--)
        {
          digitalPotWrite(i);
          delay(10);
        }
    }

    int digitalPotWrite(int value)
    {
      digitalWrite(CS, LOW);
      SPI.transfer(address);
      SPI.transfer(value);
      digitalWrite(CS, HIGH);
    }

As a result of the two above, I have an LED that stays lit (at about 50% it seems) and does not fade in/out at all.

Being relatively new to wiring and EE in general, is there a better way to replicate an analog pot without using a digital pot? Can I just use PWM to control it? Why would the LED be just staying lit?

Thanks!

  [1]: http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Components/General IC/22060b.pdf
  [2]: http://www.instructables.com/id/Digital-Potentiometer-MCP41100-and-Arduino/?ALLSTEPS
  [3]: https://i.stack.imgur.com/urSnK.jpg

body:
After studying the datasheet differences between **MCP41100** (digital pot used in the tutorial) and **MCP4131** (the one you get), I found **two major differences** between both:

1. Difference in **resolution**:
   - MCP41100 has **257 steps** resolution (8 bits + 1): you can see that at the beginning of [its datasheet][1]
   - MCP4131 has only **129 steps** resolution (7 bits + 1): you can get this information on page 2 of [its datasheet][2]

2. Difference in **commands formats** sent through SPI; both use one "command byte" followed by a "data byte", but have a diffrent format for their command byte:
   - MCP41100 command byte is `X X C1 C0 X X P1 P0` where `X is unused`, `C1 C0` is one of 4 possible commands,  only 2 being valid commands actually: `01` (Write data), `10` (Shutdown), finally `P1 P0` should be always `01` for an MCP41100
   - MCP4131 command byte is `AD3 AD2 AD1 AD0 C1 C0 D9 D8`, where `AD3-AD0` is the address of the "register" on which to perfom a command. For the MCP4131, the most important address is `00` which means "volatile wiper 0" (this is what allows you to change the resistance value of the pot), `C1 C0` is one of 4 possible commands (read data, write data, increment, decrement), in your example the command should be `00` (write data); finally `D9 D8` are the high order bits of the value to write to the register, but `D9` is unused and should always be `0`. For 257-steps pots, `D8`is used to have the full resistance scale, otherwise it should be `0`

Now that we know aht your MCP4131 expects as commands passed through SPI, we can take a look at what the tutorial program passes:

    00010001 value

The first byte can be broken down as such:

- `0001` address of the pot **wiper register 1** (**not 0**): this wiper does not exist on MCP4131 hecne writing to it will have no impact...
- 00 command bits meaning "Write to register specified in previous address"
- 01 high order bits (D9-D8) of the value to write to the wiper register.

Although I don't have an MCP4131 at hand, I think you should adapt the program as follows:

    byte address = 0x00;

And that should be fine! Indeed, now your program passes:

    00000000 value

Which means "write `value` (between `0` and `128` which matches exactly the 129 steps resolution) to the wiper register 0 of the port".

Note that the MCP4131 has more features than the MCP41100 in terms of commands, for instance you could use the special commands "increment" and "decrement", with the advantage they need only one byte (the command byte), e.g.

    void loop()
    {
        for (i = 0; i <= 128; i++)
        {
          digitalPotIncrement();
          delay(10);
        }
        delay(500);
        for (i = 128; i >= 0; i--)
        {
          digitalPotDecrement();
          delay(10);
        }
    }

    void digitalPotIncrement()
    {
      digitalWrite(CS, LOW);
      SPI.transfer(0x04);
      digitalWrite(CS, HIGH);
    }

    void digitalPotDecrement()
    {
      digitalWrite(CS, LOW);
      SPI.transfer(0x08);
      digitalWrite(CS, HIGH);
    }

  [1]: http://www.futurlec.com/SFMicrochip/MCP41100.shtml
  [2]: http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Components/General IC/22060b.pdf


message:
Can I use this replacement motor without modifying the circuit?

I have a demo that spins a motor, but the leads on my motor broke. I happen to have another motor lying around that I'd like to swap in, but it's of a different type. Here's my circuit:

![Spin Motor Spin from Node-Ardx][1]

This is the old (broken) motor: https://www.sparkfun.com/products/11696. It has an operating voltage range of 1.0 to 3.0V DC and a no load speed of 6600±10% RPM (@1.0V DC, 110mA).

The new motor that I'd like to use is part of this kit: https://www.sparkfun.com/products/12866. It's a 6VDC motor with a No Load Speed of 90±10rpm and a No Load Current of 190mA(max.250mA).

I'm running this off a Sparkfun Redboard, which is UNO R3 compatible.

Can I swap in the new motor without any circuit changes? Will I have to add additional power for the new motor? Or should I change the circuit with a larger resistor or something else?

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

body:
Regarding voltage, I think there should be no problem as the datasheet for your replacement motor specifies a "suggested voltage 4.5V DC".

However, be careful that there is another important value in motor datasheets: the **stall current**.

Simply stated, this is the current consumed by the motor when it tries to rotate but is unable to, due to its too low torque in comparison with the effort needed for rotation, e.g. if it tries to rotate the wheel of a robot that is too heavy.

The original motor has a stall current of 0.8A according to its datasheet (you can get it from the link you provided).

Your replacement motor has 1A according to the link you provided.

These 200mA can make a big difference for the transistor used in your circuit, a **P2N2222A**.

Indeed, that transistor is [specified][1] to switch a maximum of **600mA** current at the collector.

So in the best case, the motor will run correctly without load, but if you provide some load that makes it stall, then the transistor will raise temperature (you could sense that by approaching your finger) and ultimately would get toasted.

Please also note that some poorly designed motors may consume a current near the stall current, due to internal friction (I have already almost grilled a transistor this way...)

So my answer is:

- you can do it for a simple experiment with no load on the motor
- if you really want to do something with the motor, take another transistor with a higher *Ic* current

  [1]: https://cdn.sparkfun.com/datasheets/Components/General/P2N2222A-D.PDF


message:
How can I pass an object as a parameter to a function?

I am making a tiny game, and want to store high-scores. I made a Highscore-class in the top of the sketch file, like this:

    class Highscore {
    public:
      String name;
      int score;

      String toString() {
        return this->name + " - " + (String)score;
      }

      Highscore(String name, int score) {
        this->name = name;
        this->score = score;
      }
    };

    setup() { // etc

Now. Near the bottom of the sketch, I have a function I want to take a Highscore-object as a parameter, but the compiler will not let me. Example:

    void writeHighscore(Highscore hs) {
      File f = SD.open("high.txt", FILE_WRITE);
      // Do stuff

The complation error is as follows:

> sketch.ino:19:21: error: variable or field ‘writeHighscore’ declared void

sketch.ino:19:21: error: ‘Highscore’ was not declared in this scope

sketch.ino: In function ‘void setup()’:

sketch.ino:64:20: error: ‘writeHighscore’ was not declared in this scope

After changing parameter type to String, int or whatever, all the errors go away. I am able to create Highscore-objects INSIDE the `writeHighscore()` function, but how can I pass objects to it?

**Edit 1 - Object creation**

    Highscore hs = Highscore("John", 975);
    Serial.println(hs.toString()); // Prints "John - 975" as expected
    writeHighscore(hs); // Error

body:
You are doing everything right, but you need to move the class outside of your .ino file for this to work. <del> I'm not sure why the arduino IDE makes you do this </del> (see edit) , but it is something I've run into before.

I just tested this, and moving the class declaration outside the ino and into a header file in the project folder makes it compile correctly. Just remember to include the header you make in the ino and to `#include "Arduino.h"` in the header to get access to "String" again.

Technically, only a forward declaration of the class needs to be in a different file.

**Edit:**

I'm relatively sure what is happening is the IDE is generating forward declarations for all your functions but not the class, which are placed before your class definition.
This means that breaking the function regex the IDE uses with a dummy "throw()" fixes your problem. for example:

    void writeHighscore(Highscore hs) throw() { ...

should work just fine (it worked for me)


body:
<!-- language-all: lang-C++ -->

This is a classic example of the IDE "helping" you by generating function prototypes, and not doing it very well. Example code to reproduce:

    class Highscore {
    public:
      String name;
      int score;
      String toString() {
        return this->name + " - " + (String)score;
      }

      Highscore(String name, int score) {
        this->name = name;
        this->score = score;
      }
    };

    void setup () { }
    void loop () { }

    void writeHighscore(Highscore hs)
    {
    // do stuff
    }

This gives the error:

    sketch_jul06b:4: error: variable or field ‘writeHighscore’ declared void
    sketch_jul06b:4: error: ‘Highscore’ was not declared in this scope

---

If you look at the output of the IDE preprocessor (you can do this by turning on verbose compilation, and finding out the name of the file it is actually compiling) you see this:

    #line 1 "sketch_jul06b.ino"
    #include "Arduino.h"
    void setup ();
    void loop ();
    void writeHighscore(Highscore hs);
    #line 1
    class Highscore {
    public:
      String name;
      int score;
      String toString() {
        return this->name + " - " + (String)score;
      }

      Highscore(String name, int score) {
        this->name = name;
        this->score = score;
      }
    };

    void setup () { }
    void loop () { }

    void writeHighscore(Highscore hs)
    {
    // do stuff
    }

The important part is that it put:

    void writeHighscore(Highscore hs);

**before** where the class is declared.

---

You can fix the error by simply generating your own function prototype like this:

    void writeHighscore(Highscore hs);  // function prototype
    void writeHighscore(Highscore hs)
    {
    // do stuff
    }

Now it compiles without errors. It detects your *own* function prototype, and therefore does not generate its own. The first few lines of the generated file are now:

    #line 1 "sketch_jul06b.ino"
    #include "Arduino.h"
    void setup ();
    void loop ();
    #line 1

That troubling prototype has gone.


message:
What in the example code is different from my test code? LED matrix lights up differently

I'm trying to get my LED matrix to run Conway's Game of Life. After 4 different pin configurations, I've finally been able to run a separate test code, that lights all the LED's in order, and then turns them off in order (Code Below). I've written the entirety of GoL in C#, but the Arduino language is just different enough to where I can write sort of ok in it, but not enough to understand what's going wrong. I got a Game of Life code from [here][1] and it won't even light my LEDs, or when it does, it's incredibly dim, unlike my test code. I'll show my pin layout in the code. I've tried changing the pins in the GoL code, copying the setup from one to the other, and  but for the life of me, I can't seem to figure out why one would light up the LED's without a hitch, and the other is struggling. Can anybody see the changes I'd need to make that would make the GoL code at that link, work like this test code?

Here's my Test code that works fine:

    int speed = 4; //the delay time in milliseconds

    int pauseDelay = 1;    //the number of milliseconds to display each scanned line

    //Pin Definitions
    int rowA[] = {14,15,16,17,2,3,4,5};          //An Array defining which pin each row is attached to
                                         //(rows are common anode (drive HIGH))
    int colA[] = {6,7,8,9,10,11,12,13};  //An Array defining which pin each column is attached to
                                         //(columns are common cathode (drive LOW))

    //The array used to hold a bitmap of the display
    //(if you wish to do something other than scrolling marque change the data in this
    //variable then display)
    byte data[] = {0,0,0,0,0,0,0,0};

    //Setup runs once when power is applied
    void setup()
    {
      Serial.begin(9600);         //Open the Serial port for debugging
      for(int i = 0; i <8; i++){  //Set the 16 pins used to control the array as OUTPUTs
        pinMode(rowA[i], OUTPUT);
        pinMode(colA[i], OUTPUT);
      }
    }

    //repeats
    void loop()
    {
     //Example #1 - test pattern
     //Run a small test program which lights up each light in time
      test();

     //Example #2 - static image
     //Display a defined bitmap
    /*
      data[0] = B10101010; //row 1s bit mask (1 LED is on 0 LED is off)
      data[1] = B01010101; //row 1s bit mask (1 LED is on 0 LED is off)
      data[2] = B10101010; //row 1s bit mask (1 LED is on 0 LED is off)
      data[3] = B01010101; //row 1s bit mask (1 LED is on 0 LED is off)
      data[4] = B10101010; //row 1s bit mask (1 LED is on 0 LED is off)
      data[5] = B01010101; //row 1s bit mask (1 LED is on 0 LED is off)
      data[6] = B10101010; //row 1s bit mask (1 LED is on 0 LED is off)
      data[7] = B01010101; //row 1s bit mask (1 LED is on 0 LED is off)
      showSprite(speed);
    */
     }

    //An array to store power values to act as bit masks
    const int powers[] = {1,2,4,8,16,32,64,128};

    //Runs a pattern where each LED is lit one after another
    void test(){
      for(int i = 0; i < 8; i++){
    for(int ii = 0; ii< 8; ii++){
    data[i] = data[i]+ powers[ii];   //Goes through each row of lights lighting each column one after another
    showSprite(speed);
    }
      }

      for(int i = 0; i < 8; i++){
       for(int ii = 0; ii< 8; ii++){
    data[i] = data[i] - powers[ii];   //Goes through each row of lights turning off each column one after another
       showSprite(speed);
        }
      }
    }

    void showSprite(int speed2){
     for(int iii = 0; iii < speed2; iii++){                 //show the current frame speed2 times
      for(int column = 0; column < 8; column++){            //iterate through each column
           for(int i = 0; i < 8; i++){
               digitalWrite(rowA[i], LOW);                      //turn off all row pins
       }
       for(int i = 0; i < 8; i++){ //Set only the one pin
         if(i == column){     digitalWrite(colA[i], LOW);}  //turns the current row on
         else{                digitalWrite(colA[i], HIGH); }//turns the rest of the rows off
       }

       for(int row = 0; row < 8; row++){                    //iterate through each pixel in the current column
        int bit = (data[column] >> row) & 1;
        if(bit == 1){
           digitalWrite(rowA[row], HIGH);                   //if the bit in the data array is set turn the LED on
        }

       }
       delay(pauseDelay);                       //leave the column on for pauseDelay microseconds (too high a delay causes flicker)
      }
     }
    }

[1]: http://brownsofa.org/blog/2010/12/30/arduino-8x8-game-of-life/

body: I ended up using a different PIN layout, and the GoL code had the pins As anodes where they were Cathodes in the other code. Switched rows pins to Columns pins in the code and Problem solved.


message:
Have Arduino write data to a MySQL database?

Would it be possible to have an Arduino write directly to a MySQL database?

I'm a web programmer, so I'm familiar with how to get records from a MySQL database. I have MAMP installed on my mac, so I have the ability to build an interface, directly in the web browser, that retrives the records from a MySQL database.

What I'm thinking is to connect the Arduino directly to my computer via USB, and write data from the sensors, or the pins, directly to my MySQL database.

I'm using two phototransistor to record whenever something blocks the light. Each sensor records individually a timestamp for when the blocking occur.

Is that possible?

body:
It's possible if you forget about the Arduino directly writing to the database.

Simply put, the Arduino is restricted to a serial connection.  To directly communicate with MySQL you would need a network connection, and then implement the MySQL protocol - a huuuge amount of work.

The normal way is to have an adapter program running on the PC which receives data from the Arduino over the serial connection, then performs any insert, select, etc instructions on the MySQL for you.

There is a "MySQL Connector" available* (https://launchpad.net/mysql-arduino) but of course that requires you to have an active network connection of some form to your Arduino.  Remember that the Arduino (certainly the Uno) is very limited on memory and program space, so having the Arduino connect direct, and doing anything else, might be mutually exclusive.

-----
*Nice find, @SomeHardwareGuy...


body:
You can do that using an Arduino Yun: the Yun has a linux cpu paired with the ATMega32U4, so you can delegate things like accessing a mysql database, either local or remote.

Take a look at this [instructable][1].

There are different ways for delegating logging sensors readings to the linux side and have them stored on a mysql: the easiest is to code a short python script and call it from the sketch using [Process][2].

  [1]: http://www.instructables.com/id/Control-Access-of-Arduino-YÚN-with-MySQL-PHP5-and-/?ALLSTEPS
  [2]: http://arduino.cc/en/Tutorial/Process


message:
Can the Arduino use this i2c LCD Panel

Can the Arduino Mega2560 use the [New Haven NHD-0420D3Z-NSW-BBW-V3][1] LCD panel by controlling it with the [New LiquidCrystal library][2]? What cable will you use to connect the LCD to Arduino, are there screw terminals on the LCD board to secure the connections? It seems like only 4 connections are needed, for `GND`, `VCC`, `SDA`, `SCL`.

  [1]: http://www.newhavendisplay.com/nhd0420d3znswbbwv3-p-5745.html
  [2]: https://bitbucket.org/fmalpartida/new-liquidcrystal

body:
Unfortunately you cannot control that display using that library; the library expects to be connected to a HD44780-compatible driver but the display uses a fully custom control scheme. You may be able to adapt the library to the scheme, but I have not looked at that specifically.

I2C itself only requires 3 connections: SDA, serial data; SCL serial clock; GND, ground reference. Since the display is not powered separately it also requires power, in this case 5V. Since the display can only communicate at 100kHz you don't need to be *too* terribly concerned about cable quality; Cat3 or even telephone cable is acceptable as long as you don't exceed a few feet in length. Don't forget the external pullup resistors though, on SDA and SCL.


message:
Using PBC library on Arduino

I want to know if there is a way to install/use the [PBC library][1] on Arduino UNO. I want to implement some cryptographic primitives using PBC library.

Thank you.

  [1]: http://crypto.stanford.edu/pbc/

body:
You could use the [RELIC][1] toolkit. It has PCB and they have scripts to compile for Due and Mega. I'm not sure if you could use this with Uno. But this library targets resource-constrained devices.

  [1]: https://github.com/relic-toolkit/


message:
Read data from 3 ColorPal 28380 simultaneously on Uno/Mega

I've been trying to get an Arduino (I have a Mega and Uno lying around) to read values from a small array of 3 [ColorPal 20380][1], which individually, work as intended with some reflective material. The [demo][2] gives no problem, but I am confused as to how to approach activating all the 3 sensors and reading the 3 different sets of values so that I can analyze them in a program on the Arduino.

**How can I get all three sensors to output data to my program in parallel?** I want to use the values at the same point in time on all three sensors to do some calculations in my program. Should I approach something like a state machine? Or at least near-parallel (a few ms delay is fine too)? How would an example look like?

The most confusing thing for me is the non-inverted, open-drain protocol it uses. From the documentation:

> Because of the open-drain protocol, the pin used to communicate with the ColorPAL should always be configured as an input, except when being driven low. Also, when starting up, you should wait for this pin to be pulled high by the ColorPAL before trying to send it any commands.

I tried modifying the demo to something silly in sequence like this just to see how it would work in the Arduino but I got nothing (pins 2, 4 and 6 are the data pins):

    /* ColorPal Sensor Example for Arduino
      Author: Martin Heermance, with some assistance from Gordon McComb
      This program drives the Parallax ColorPAL color sensor and provides
      serial RGB data in a format compatible with the PC-hosted
      TCS230_ColorPAL_match.exe color matching program.
    */

    #include <SoftwareSerial.h>

    int sio = 0;
    const int unused = 255;   // Non-existant pin # for SoftwareSerial
    const int sioBaud = 4800;
    const int waitDelay = 10;

    // Received RGB values from ColorPAL
    int red;
    int grn;
    int blu;

    // Set up two software serials on the same pin.
    SoftwareSerial serin = SoftwareSerial(sio, unused);
    SoftwareSerial serout = SoftwareSerial(unused, sio);

    void setup() {

      // Unoptimized setup

          sio = 2;
          serin = SoftwareSerial(2, unused);
          serout = SoftwareSerial(unused, 2);
          Serial.begin(9600);
          reset();      // Send reset to ColorPal
          serout.begin(sioBaud);
          pinMode(2, OUTPUT);
          serout.print("= (00 $ m) !");       // Loop print values, see ColorPAL documentation
          serout.end();     // Discontinue serial port for transmitting

          serin.begin(sioBaud);           // Set up serial port for receiving
          pinMode(2, INPUT);

          sio = 4;
          serin = SoftwareSerial(4, unused);
          serout = SoftwareSerial(unused, 4);
          Serial.begin(9600);
          reset();
          serout.begin(sioBaud);
          pinMode(4, OUTPUT);
          serout.print("= (00 $ m) !");
          serout.end();

          serin.begin(sioBaud);
          pinMode(4, INPUT);

          sio = 6;
          serin = SoftwareSerial(6, unused);
          serout = SoftwareSerial(unused, 6);
          Serial.begin(9600);
          reset();
          serout.begin(sioBaud);
          pinMode(6, OUTPUT);
          serout.print("= (00 $ m) !");
          serout.end();

          serin.begin(sioBaud);
          pinMode(6, INPUT);
    }

    void loop() {

      sio = 2;
      serin = SoftwareSerial(sio, unused);
      serout = SoftwareSerial(unused, sio);
      readData();

      sio = sio + 2;
      serin = SoftwareSerial(sio, unused);
      serout = SoftwareSerial(unused, sio);
      readData();

      sio = sio + 2;
      serin = SoftwareSerial(sio, unused);
      serout = SoftwareSerial(unused, sio);
      readData();
    }

    // Reset ColorPAL; see ColorPAL documentation for sequence
    void reset() {
      delay(200);
      pinMode(sio, OUTPUT);
      digitalWrite(sio, LOW);
      pinMode(sio, INPUT);
      while (digitalRead(sio) != HIGH);
      pinMode(sio, OUTPUT);
      digitalWrite(sio, LOW);
      delay(80);
      pinMode(sio, INPUT);
      delay(waitDelay);
    }

    void readData() {
      char buffer[32];

      if (serin.available() > 0) {
        // Wait for a $ character, then read three 3 digit hex numbers
        buffer[0] = serin.read();
        if (buffer[0] == '$') {
          for(int i = 0; i < 9; i++) {
            while (serin.available() == 0);     // Wait for next input character
            buffer[i] = serin.read();
            if (buffer[i] == '$')               // Return early if $ character encountered
              return;
          }
          parseAndPrint(buffer);
          delay(10);
        }
      }
    }

    // Parse the hex data into integers
    void parseAndPrint(char * data) {
      sscanf (data, "%3x%3x%3x", &red, &grn, &blu);
      char buffer[32];
      sprintf(buffer, "R%4.4d G%4.4d B%4.4d", red, grn, blu);
      Serial.println(buffer);
    }

[1]: http://www.parallax.com/product/28380
[2]: http://learn.parallax.com/colorpal-arduino-demo

body:
I'm doing something similar with you right now. I'm troubleshooting this right now so we can collaborate.

First of all, even though you have setup 3 pins, you're only telling the Arduino to read only 1 sensor because they're using the same variable (pin6 since it's the last one you set up). You have to declare each pin with a different variable then create 2 more readData() functions to read each pin as a start. But even after I set it up with that, it only read one colorpal. Reading up a little more on the Uno board, it seems that only pin 2 and 3 can do serial interrupt which we need to use to communicate with the ColorPal. I'm not 100% sure as I'm a novice still, but from what my analysis and research shows, that's the problem right now. I'll update if I find anything.


body:
Try using `serin.listen()` for each SoftwareSerial before using `serin.read()`.

Only one pin can be read at a time and by default it's reading from the last pin initialized.


message:
Assuring an unsigned long int?

Basic question: How far do I have to go to assure that integer math is done correctly? For example, this is probably overdone:

    unsigned long burnTime = 0UL;
    unsigned long curBurnTime = 0UL;
    // Do some stuff that sets the above variables to millis() at various times
    // Later on...
    unsigned long adjustedBurnTime = (unsigned long) ((burnTime + curBurnTime) / 1000UL);

Would the math be done correctly if I went to a more minimal last statement (since all the elements of the equation are unsigned longs)? Like this:

    unsigned long adjustedBurnTime = ((burnTime + curBurnTime) / 1000UL);

Or even:

    unsigned long adjustedBurnTime = ((burnTime + curBurnTime) / 1000);

body:
Any good C manual will tell you the result type for each basic math operation on given types. But briefly, the basic math operators return a result as wide as the widest operand, with the narrower operand being widened to match the wider one, if they differ. The same with assignment: assigning a result of a given type to a variable of the same type will not involve any conversion.

tl;dr: No, you're not missing anything. You don't need any casts in your example.

PS: One thing you do need to be aware of is whether any of your intermediate results will overflow the arithmetic type you're using. For example, the final result may be not exceed an unsigned long but the expressions `(burnTime + curBurnTime)` must also not exceed it. This is a greater concern with smaller data-types, of course.

PPS: Good on you for tackling fixed point arithmetic rather than just reaching for the floating-point library!


message:
How can I implement double buffering with an Arduino UNO?

I am creating a tiny game on my Arduino UNO with an Adafruit ST7735 1.8" TFT / SD breakout. I am performing screen operations using the built-in TFT-library.

The problem is screen flickering. Even though I take care to prepare data and minimize the time between clearing the screen and writing the new stuff to it, the screen "refresh()" is significant. I heard someone mention something called double buffering, so I read a bit up on it, but I am frankly clueless on how to implement it on an Arduino UNO.

Is it possible to implement double buffering on an Arduino UNO to prevent screen flickering, and if so, how?

Libraries used:

    #include <TFT.h>
    #include <Wire.h>
    #include <SPI.h>
    #include <SD.h>

<br>The screen is "cleared" like this:

    screen.background(0,0,0);  // Clear it
    screen.text(buf, 10, 25);  // Write new stuff

body:
If you're already preparing the next screen's-worth of data before you clear the screen, then double buffering won't help. In that case, the time taken to re-write the screen data is what causes the flicker, and the only way to improve it is to write the screen faster. If the software is to blame, it will be in screen.text(). If the software is already driving the hardware as fast as the hardware will go, then that's the best you can do.

Double-buffering would let you prepare the next screen while the currently-prepared one is loading (and will require interrupt-driven I/O to do it). The result would be more screen refreshes per unit time, but it doesn't sound like that is your problem.

One easy experiment to try is to not clear the screen before you re-write it, if that is possible to do. Then your next screen will overlay the current screen with (we hope...) no blanking period. That might prevent the blinking.


body:
> How can I implement double buffering with an Arduino UNO?

Full screen [double buffering][1] (aka [off-screen bitmap][2]) for an ST7735 (128 x 160 x 16 bit color) would require 40 Kbyte. With only 2K byte SRAM on the Arduino Uno double buffering is not possible.

Some of the flickering is due to the Arduino core unoptimized SPI protocol and the graphics library. They could be optimized to reduce some of the flickering.

Please see the Cosa [ST7735][3] driver and [SPI][4] support for examples of high speed inter-leaving SPI transfer and graphics optimizations.

Smaller mono-chrome screens (such as ST7565) can be supported with double buffering. An example is the Cosa [OffScreen Canvas][5] that can be used to create a bitmap that is transfered to the screen in a [single operation][6].

Cheers!

  [1]: https://en.wikipedia.org/wiki/Multiple_buffering
  [2]: https://stackoverflow.com/questions/7347367/whats-concept-of-off-screen-bitmap
  [3]: https://github.com/mikaelpatel/Cosa/tree/master/libraries/ST7735
  [4]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/SPI.hh
  [5]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/Canvas/Canvas/OffScreen.hh
  [6]: https://github.com/mikaelpatel/Cosa/blob/master/examples/LCD/CosaST7565/CosaST7565.ino#L157


body:
To add to previous answers:

Double-buffering is an approach where you _write to the actual device_ - but in an off-screen area. Then you switch to the new area in a single instruction, indistinguishable to the naked eye, rather than clear the visible area and write while it's still being displayed.

This requires that the _device_ has extra memory to support the two areas: on-screen and off-screen. Absent that extra memory, then the best that you can do is pre-calculate as much as possible, and write to the screen as fast as possible.


message:
How to split in string

I want to split this:

    char* value = "12;32;blue";
    or
    string value = "12;32;blue";

into this vars:

    TV = 12;
    AR = 32;
    LED = "blue";

is it possible?

body:
Scan function should do the job.

    int tv, ar;
    char color[10];
    sscanf(value, "%d;%d;%s", &tv, &ar, color);


body:
For C-strings (`char*`), your best option (in terms of performance and memory consumption) is to use [`strtok`][1]:

    char* value = "12;32;blue";
    char* token = strtok(value, ";");
    int TV = atoi(token);
    token= strtok(0, ";");
    int AR = atoi(token);
    token = strtok(0, ";");
    char* LED = token;

**Note 1**: the code above takes it for granted that `value` is properly formatted, i.e. contains 3 parts split by `;`. If it is not sure, then you should add additional checks on `token` value returned by `strtok`.

**Note 2**: `strtok` is modifiying its `value` argument, so that at the end of the code above, `value` will not be equal to `12;32;blue` any longer.

**Note 3**: `LED` variable above will point directly to the character `b` inside `value`, which means that if `value` is modified afterwards, `LED` might be modified as well.

  [1]: http://www.cplusplus.com/reference/cstring/strtok/


message:
Measure Water Flow in literes using Arduino Mega 2560 Board and Water Flow Sensor

I have a water flow sensor with Arduino Megs 2560 board. I am trying to conceptualize the concept to calculate amount of water getting dispensed esp. in 1,2,3,4 and 5 liters quantity.

Water flow sensor specification:

http://www.seeedstudio.com/wiki/images/b/b7/Water_flow_sensor_datasheet.pdf

I would connect the sensor input to any pin from 22-53 pin.

Suppose I connect to ping 23 so in my setup() function I would add:

    attachInterrupt(23, pulseCounter, FALLING);

where pulseCounter is an interrupt function triggered on each signal generated from sensor and increments a variable

    void pulseCounter()
    {
      // Increment the pulse counter
      pulseCount++;
    }

Now how do I calculate the flowrate and water dispensed in milliliters using this information?  How do I know the freqz of the MCU (which is required as water dispensed per pulse is different for different MCUs)?

body:
the pulse rate can be derived without knowledge of the CPU clock speed. To achieve the pulse rate from your sensor input you can do two things:

 1. count the pulses **dn** within a certain (i.e. fixed) interval **T** of time) or
 2. measure the time **dt** between two pulses.

I'll come back later on this concerning accuracy.

To measure time, you can use the function millis(). This function returns you the milliseconds since bootup as an integer upon calling it. Method 2 is rather simple to implement.

 - Setup three global integers *a*, *b* and *c*.
 - At the end of setup set *a* to current millis();
 - In your ISR set b to current millis();
 - Also in ISR: set a=b;
 - calculate *c=b-a* (i.e. your **dt**);

c holds your current full wave pulse length in milliseconds, which is updated every pulse. You can derive your flow then from it.

The first method uses a counter as demonstrated in your suggestion. You then need a timer outside your ISR, two variables *d* and *e*. Either you poll millis() in your main "loop()" or you install a timer interrupt, both will work here.

 - At the end of setup set *d* to current millis();
 - If your predefined time **T** is passed (by comparing *d* with millis(),
 - save your counted pulses to *e=pulseCount*
 - reset: *pulseCount=0*

*e* holds your pulse count during interval **T**, from which you can derive your pulse rate.

Accuracy
---
Method 1's accuracy increases with higher **T** and higher flow speeds. Therefore the update rate of your measurement is low. By changing **T** you can easily increase accuracy on cost of responsiveness. This is perhaps a good idea, if you have pulsating flows in your tubings, or the sensor is a bit rattling.

Method 2's accuracy increases with lower flow speeds. It is best to measure very low flow speeds. Update frequency is minimal (1/**dt**).

Regarding this sensor you should calibrate it yourself. It is a cheap and rugged device (I'm using it, too), but its output depends on several parameters like mounting position, fluid viscosity and so on. Make sure, there are no bubbles, foam or contaminants in your fluid systems as they garble the results effectively.

n.b.: make sure to take care of an overflow of millis().


message:
Proto Shields wthout breadboard?

I want to use a proto shield (brand is unimportant) and solder some components to it, to make something more premanent than using a breadboard.

My question is can the components be soldered directly to the middle area where there are a lot of small holes?

I would assume this is possible, but everywhere I look people add mini breadboards to their proto shields.

If it's possible, then I assume components and wires can't just be connected in a row like on a breadboard and would instead need some solder between 2 holes where for example a component and seperate wire are connected?

body:
There are many different types of photo-shields, sometimes they have interconnected rows or they just have individual solder holes or even breadboards.  What you get all depends on what you are doing.  My personal favorite are the interlocked rows so I buy that and use a breadboard while I am developing my project then take off the breadboard and solder everything into place.

[Example of non interlocked rows][1]  and an [My favorite proto-shield, it has a little of both kinds][2]

  [1]: http://www.amazon.com/Ventisonic®-MEGA2560-Prototype-ProtoShield-breadboard/dp/B00K992NTI/ref=sr_1_2?ie=UTF8&qid=1416068414&sr=8-2&keywords=protoshield arduino mega
  [2]: http://www.amazon.com/MEGAshield-KIT-Arduino-MEGA-2560/dp/B006SJSBBM/ref=sr_1_1?ie=UTF8&qid=1416068735&sr=8-1&keywords=MEGAshield KIT for Arduino MEGA 2560 R3


message:
Dead reckoning with an accelerometer

Is it possible to use an Arduino, connected to a 3 axis accelerometer, to estimate a platform's continuous change in position and orientation? I have a small mobile robot, and given an initial position and velocity vector and sequence of acceleration changes, I'd like to calculate the current position and velocity vector.

From [this question][1], it sounds possible, but I can't find any reference to projects or code to accomplish it with an Arduino. I understand the main problem will be the build-up of errors over time, but that's ok, as a rough estimate is acceptable. I'm also using wheel encoders to calculate the same values, and I want to use the accelerometer to account for errors in the encoders, like slippage. e.g. If the encoders say we're accelerating at 1cm/sec but the accelerometer says we're at a constant speed, then I know to ignore the encoders because the wheels are probably slipping.

I understand the math behind this, so the problem is how to write it in C to run on an Arduino. Is anyone aware of existing open source code for something like this? I'd like to avoid reinventing the wheel in-case anyone's implemented a similar system.

  [1]: https://electronics.stackexchange.com/questions/110506/dead-reckoning-with-accelerometer-gyro-possible

body:
    for each accelerometer:
       sample the accelerometer;
       low-pass filter its values (current and recent history) to remove noise;
       multiply by the sample interval to get the velocity increment;
       add the increment to a running sum to get velocity;

       sample the velocity (the running sum you just updated);
       maybe low-pass filter, as above;
       multiply by the sample interval, as above, to get the position increment;
       add the increment to a running sum to get position;
    end;

Noise, the artifacts created by filtering, and the double summation all work against your accuracy. That said, if your problem is to sense traction or loss of it, how about sensing real velocity more directly such as by dragging an encoded but otherwise free fifth wheel? Or if circumstances allow, optically sense the velocity of the surface underneath you as an optical mouse does?


message:
How do you benchmark an Arduino?

I am trying to run a test of the speed of an Arduino, and how it's affected by different temperatures. Does the following code assess this properly?

    long num = 0;
    long startTime = 0;
    long endTime = 0;
    int duration = 0;
    String buffer;

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

    void loop(){
      startTime = millis();
      benchmark();
      endTime = millis();
      duration = endTime - startTime;
      Serial.print(startTime);
      Serial.print(", ");
      Serial.print(endTime);
      Serial.print(", ");
      Serial.println(duration);
    }

    void benchmark() {
      num = 0;
      for(num = 0; num < 1000000; num++);
    }

I'm using an Uno, if that matters.

body:
No.

That is because millis will be equally affected by any frequency change (due to temperature) as the benchmark code. You would need an external clock source that is precise enough.

Note that temperature doesn't have that big an impact on crystal oscillators. Somewhere around 10ppm between -20 and +20 degrees C. The crystal itself is probably already 50ppm precision to start with (higher precision ones are more expensive).


body:
First of all, compiler will just remove your loop, unless you disable compiler optimization, witch will invalidate your test.
Also don't worry about clock drift; as clock also run instruction, a faster clock will also mean a faster instruction cicle, so in the end if you calculate instruction/s the value will be valid.

Also serial communication slowness is not a problem as you calculate the value BEFORE sending anything.

Now, exactly what you want benchmark? In your case, you should put some instruction the for, like a variable++, and then print that sum (if you don't use it, again compiler will optimize all away)

But the you are bancharking for and ++. You may use a NOP() instruction, and then a float, a bitshift, a function call, and so on; you will find very different result, sometimes, sometimes compilator will trick your code.

Then when you'll have banchamark, against what will you compare your result?


body:
Quite simply, you cannot measure the stability of a device using routines that themselves depend on the device clock.

 To do this properly you need an external measuring device that has a clock source at least 10 times more stable than the Arduino xtal. Most frequency counters would qualify.
Just set up a timer to provide a constant output frequency, and attach the counter to the pin.


message:
MHz Sampling Rate for Arduino

How can we increase the Arduino's ADC sampling rate to 1 MHz while maintaining a 10 bit resolution? Can we change the prescaler to 16 to get 1 MHz ADC clock?

If not, what alternatives are there? Another Atmel chip that works with the Arduino library? Or any external ADC?

body:
The problem with driving the ADC faster is that the S+H circuit won't have enough time to reach the final value before the conversion is performed, meaning that precision will be lost.

The best thing to do would be to use an external ADC from e.g. TI or Microchip that has the capabilities you're looking for.


message:
Arduino GSM shield GSM_READY not ready ever

I am using an Arduino Mega and an Arduino GSM shield. I am using the receive SMS example under GSM in the Arduino IDE. My GSM shield's hardware IP is set correctly.

Here is the sketch:
<!-- language-all: lang-cpp -->

    /*
     SMS receiver

     This sketch, for the Arduino GSM shield, waits for a SMS message
     and displays it through the Serial port.

     Circuit:
     * GSM shield attached to and Arduino
     * SIM card that can receive SMS messages

     created 25 Feb 2012
     by Javier Zorzano / TD

     This example is in the public domain.

     http://arduino.cc/en/Tutorial/GSMExamplesReceiveSMS

    */

    // include the GSM library
    #include <GSM.h>

    // PIN Number for the SIM
    #define PINNUMBER ""

    // initialize the library instances
    GSM gsmAccess;
    GSM_SMS sms;

    // Array to hold the number a SMS is retreived from
    char senderNumber[20];

    void setup() {
      // initialize serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      Serial.println("SMS Messages Receiver");

      // connection state
      boolean notConnected = true;

      // Start GSM connection
      while (notConnected) {
        if (gsmAccess.begin(PINNUMBER) == GSM_READY)
          notConnected = false;
        else {
          Serial.println("Not connected");
          delay(1000);
        }
      }

      Serial.println("GSM initialized");
      Serial.println("Waiting for messages");
    }

    void loop() {
      char c;

      // If there are any SMSs available()
      if (sms.available()) {
        Serial.println("Message received from:");
        // Get remote number
        sms.remoteNumber(senderNumber, 20);
        Serial.println(senderNumber);
        // An example of message disposal
        // Any messages starting with # should be discarded
        if (sms.peek() == '#') {
          Serial.println("Discarded SMS");
          sms.flush();
        }

        // Read message bytes and print them
        while (c = sms.read())
          Serial.print(c);
        Serial.println("\nEND OF MESSAGE");

        // Delete message from modem memory
        sms.flush();
        Serial.println("MESSAGE DELETED");
      }
      delay(1000);
    }

The issue is this line:

    if (gsmAccess.begin(PINNUMBER) == GSM_READY)

The serial monitor outputs everything until that line.

It just never gets past it, so I assume it cannot connect? The SIM has no pin code: I have tried it with my phone. The SIM has full signal strength when in my phone. I have tried my other SIM card also but the same thing happens.

This seem to be the same question, yet no answer:
http://forum.arduino.cc/index.php?topic=270551.0

body:
You could always try setting a pin code and then retry
http://arduino.cc/en/Tutorial/GSMToolsPinManagement

What version of the Arduino IDE are you using ? Also, are you sure you are suppying the board correctly ? "It is recommended that the board be powered with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current for when the modem is in heavy use."


body:
I Have The Same Problem.
But First Of All you have to set your modem Network Band according to your cellular Network Band.

    GSMBand band;
    String newBand= "GSM_MODE_EGSM_DCS";// Your Band In My case That was
      band.begin();
      Serial.println("Modem restarted.");
      String bandName = band.getBand(); // Get and print band name
      Serial.print("Current band:");
      Serial.println(bandName);

    band.setBand(newBand);

Band Help:

      GSM_MODE_EGSM                ---- E-GSM(900)
      GSM_MODE_DCS                 ---- DCS(1800)
      GSM_MODE_PCS                 ---- PCS(1900)
      GSM_MODE_EGSM_DCS            ---- E-GSM(900)+DCS(1800) ex: Europe
      GSM_MODE_GSM850_PCS          ---- GSM(850)+PCS(1900) Ex: USA, South Am.
      GSM_MODE_GSM850_EGSM_DCS_PCS ---- GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)

Then You Have To use

    gsm.access.begin();


body: I had the same problem. Then I used `gsm.shutdown();` before `gsm.begin(PINNUMBER)`. After that it goes past `gsm.begin(PINNUMBER)` but not always. I don't know if this is the right way to do it, but it works for me.


message:
Arduino works bad when powered by 9V battery

At first I am sorry for my bad English.

I am making robot which can do a lot of things...

If I connect arduino on my robot with PC via USB, the robot works properly. If I use external power supply (9V battery) the robot is doing almost nothing.. The diodes are little bit blinking and sometimes dc motors make motion... And thats all. Batteries are charged. Where's the problem?

Everything I want is make into motion dc motors.. With 5V USB it works. With external power supply not (9V battery).

body:
I got a fresh 9 V out of a packet and measured it.

     9.58 volts

Now with a load of 500 mA (which you quite likely would get with a robot) it dropped to:

     7.4 volts

With a load of 750 mA the voltage dropped to 6.6 V which is below what you are supposed to supply via the power jack.

And that was with a fresh battery, testing for a few seconds.

Those 9 V batteries are just not designed to drive motors.

I suggest a somewhat heavier-duty battery, like 5 x AA batteries, at least for the robot part.


message:
Can I use a spare Darlington Pair on my ULN2003A to drive a DC motor?

I'm successfully running a stepper from my Arduino via a ULN2003A and a secondary power supply. It uses the first four of the seven Darlington Pairs on the chip, leaving three spare.

A) Is there any reason I wouldn't be able to use one of the remaining pairs to drive a standard DC hobby motor? (For the sake of helping future visitors .. what about running three motors off the remaining three pairs?)

B) Do I need anything other than to connect the motor to the chip? (The chip's board has LEDs and resistors on each of pins 1 - 4, but I don't believe they're in series and thus my guess is they can be left off.)

C) The DC motor is on a PWM Pin. Is that the correct way to control its speed?

The image attached shows the setup in case I haven't been clear.

![enter image description here][1]

*(I could probably just build it and see, but I'm new to Arduino and still scared of the blue smoke if I get something wrong!)*

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

body:
Should work just fine. But you'd have to connect the motor to the positive rail, and since the ULN2003 can only sink current.

Normally when connecting a motor, you'd add a flyback diode. But the ULN2003 already has those inside the chip.

PWM is the easiest way to (somewhat) control the speed of a DC motor.


message:
Not in sync: resp=0x00

I had problems with Arduino uno and reseted firmware. Followed this [tutorial][1]. Now I can't upload my code Arduino IDE says:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

I tried loop-back mode, everything is fine.

Firmware was located in this location:

    /usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex

  [1]: http://bartruffle.blogspot.fr/2013/09/dfu-programming-atmega16u2-on-arduino.html

body:
There are two processors on the Uno board.

* The Atmega328P which is the "main" processor with your sketches on it
* The Atmega16U2 which handles the USB interface

> Firmware was located in /usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex

Hopefully you reflashed the **Atmega16U2** with that file. Did you?

>  I tried loop-back mode, everything is fine.

Therefore the Atmega16U2 is OK. The problem may be with the Atmega328P.

---

> I had problems with Arduino Uno and reseted firmware.

You shouldn't need to do this, I never reflash the firmware on my Atmega16U2.

What problems did you have? Did it involve motors? LEDs? High voltages? Sparks? Flames? Screaming?

Please see the steps described here, run through them, and see if that fixes the problem: https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board


message:
Arduino hangs after 3-4 minutes on battery power, but not on USB

I have a simple sketch running on a BE Leonardo-compatible board.

It reads input from a potentiometer, and outputs to two RGB LEDs which change colour over time - in a different pattern if certain inputs are received.

Other than that, the only code is serial I/O for debug purposes.  (It's disabled using a #define in the running version, to prevent serial buffer overflow when not connected.)

When the board is powered by USB, everything works.

When the board is powered by 9V battery, after about 4 minutes it hangs - the LEDs go off, and the L13 light on the board starts glowing at varying strength.  (There is nothing connected to pin 13.)  Even the reset button doesn't work.

If the board is then connected to the computer's USB port, after a few seconds the hang clears and the program resumes.

Can anyone offer a possible explanation for (and solution to) this fault?

body:
As somebody else suggested, 9V batteries are pretty weak. They only provide a very small number of mAh (milliamp/hours) before their voltage starts to drop. Once the voltage drops to around 7 volts, the regulator in the Arduino can't keep providing 5 volts, so your Arduino resets.

Wire up 6 AA batteries in series. That will provide a much "stiffer" 9 volt supply (more instantaneous current) plus a lot more mAh of total power. If you REALLY want long life, wire up 6 C or D batteries in series, or an external 9V supply through a "wall wart" power supply.


message:
Arduino Serial buffer

I am trying to write one code that takes data from serial
ie. `0x4E`, `0x20`, `0x--`, `0x0D`.

`0x--` may be any hex in `--`

The user will input these hex one by one and raspi will take all of them in buffer.
Whenever 1st, 2nd and 4th data is matched, the 3rd one will be printed in serial
ie.

    Serial.print(3rd); //Decimal value
    else Serial.print() // may be 00

I was trying with this code:

    byte buffer[4];
    int cnt = 0;

    void setup()
    {
     Serial.begin(9600);
     Serial.println("Start");
    }

    void loop(void)
    {

     // read max 12 bytes
     if ((cnt <= 4) && Serial.available()) buffer[cnt++] = Serial.read();

     if (cnt == 4)  // all bytes read...
     {
       // assume the arrays are the same
       boolean same = true;

       // the ans array holds the right answer
       byte ans[]={0x4E,0x20,0x01,0x0D};

       for (int i=0; (i<= 4) && same; i++) same = (buffer[i] == ans[i]);

       if (same)
       {
         Serial.println("Yes");
       } else {
         Serial.println("Enter another number");
       }
       Serial.flush();
       cnt = 0;
     }
      //Serial.print("Done");
     // do something
    }

But I was not able to do it. Anyone have a suggestion?

**Edit: I have tried this state machine in Arduino :**
It accepts those data and according to it, it should bi color LED light. But not working properly. Not lighting up anything

    //int currState;
    //int reChk, data, confirm;
    const int pingPin = 13;
    int inPin = 12;

    void setup()
    {
      Serial.begin(9600);
        // initialize digital pin 13 as an output.
      pinMode(32, OUTPUT);
      pinMode(34, OUTPUT);

      digitalWrite(32, LOW);
      digitalWrite(34, LOW);
      //currState = 0;
      //reChk = 0;
      //confirm = -1;

    }

    void loop() // run over and over
    {
      static int currState = 0, reChk = 0, confirm = -1;
      int data;
      if(reChk == 0)
      {
        //ultrasonic();
        if(Serial.available())
        data = Serial.read();
        else
        currState = 5;
      }

      switch(currState)
      {

        case 0:
        reChk = 0;
        if(data == 78)
          currState = 1;
        else
          currState = 0;
        break;

        case 1:
        reChk = 0;
        if(data == 32)
        currState = 2;
        else
        {
          currState = 0;
          reChk = 1;
        }
        break;

        case 2:
        reChk = 0;
        switch(confirm)
        {
          case -1 :
          confirm = data;
          currState = 3;
          break;
          case 0 :
                digitalWrite(32, LOW);
                digitalWrite(34, LOW);
                delay(10);
          confirm = -1;
          currState = 0;
          break;
          case 1 :
                digitalWrite(34, HIGH);
                digitalWrite(32, LOW);
                delay(10);
          confirm = -1;
          currState = 0;
          break;
          case 2 :
                digitalWrite(32, HIGH);
                digitalWrite(34, LOW);
                delay(10);
          confirm = -1;
          currState = 0;
          break;
          default :
          confirm = -1;
          reChk = 1;
          currState = 0;
        }

        case 3:
        reChk = 0;
        if(data == 20)
        {
          reChk = 1;
          currState = 2;
        }
        else
        {
          confirm = -1;
          currState = 0;
        }
        break;

        default:
        reChk = 0;
        currState = 0;
        confirm = -1;
      }
      delay(10);
    }

    void ultrasonic () //ultrasonic
    {
          const int pingPin = 13;
          int inPin = 12;
          //raw duration in milliseconds, cm is the
          //converted amount into a distance
          long duration, cm;

          //initializing the pin states
          pinMode(pingPin, OUTPUT);
          //pinMode(greenLed, OUTPUT);
          //pinMode(redLed, OUTPUT);

          //sending the signal, starting with LOW for a clean signal
          digitalWrite(pingPin, LOW);
          delayMicroseconds(2);
          digitalWrite(pingPin, HIGH);
          delayMicroseconds(5);
          digitalWrite(pingPin, LOW);

          //setting up the input pin, and receiving the duration in
          //microseconds for the sound to bounce off the object infront
          pinMode(inPin, INPUT);
          duration = pulseIn(inPin, HIGH);

          // convert the time into a distance
          cm = microsecondsToCentimeters(duration);

          if(cm > 50)
          {
          //printing the current readings to ther serial display
          Serial.print("5");
          }
          else
          {
          Serial.print("0");
          }
          //Serial.print("cm");
          //Serial.println();

          //checking if anything is within the safezone, if not, keep
          //green LED on if safezone violated, activate red LED instead
          //if (cm > safeZone)
          //{
          //  digitalWrite(greenLed, HIGH);
          //  digitalWrite(redLed, LOW);
          //}
          //else
          //{
          //  digitalWrite(redLed, HIGH);
          //  digitalWrite(greenLed, LOW);
          //}

    delay(1000);
    }

    long microsecondsToCentimeters(long microseconds)
    {
    // The speed of sound is 340 m/s or 29 microseconds per centimeter.
    // The ping travels out and back, so to find the distance of the
    // object we take half of the distance travelled.
       return microseconds / 29 / 2;
    }

body:
It's unclear how the users input the hex numbers.

If i assume a simple serially attached terminal the user doesn't enter hex numbers but characters.

As an example when the user types `0`, `x`, `4`, `E` the user has only typed one hex number but already four bytes or characters. Instead the user has to type `N`, ` `, `whatever letter`, `Enter`. (Depending on the OS or terminal you will get "CR", "LF" or "CR+LF" when you press enter)

I'm not familiar with C, but your code seems to have also a coding flaw: The 3rd byte will be checked for equality too. You would need something like:

    boolean same = true;

    if (buffer[0] == ans[0]) { same = false }
    if (buffer[1] == ans[1]) { same = false }
    if (buffer[3] == ans[3]) { same = false }

Only three tests not four.


message:
Atmega168 interrupt error handling

I'm using an Atmega168 in a project that involve using the ISRs from multiple sources. I have an ISR hooked up to an external button and a timer, to use it as a reset button after a predetermined hold time.

I'm also using an ISR hooked upto UART. The UART is connected to an external Linux based SoC. Upon receiving specific commands from the linux machine, the atmel will perform certain functions.

In very rare occasions, the linux hangs up during tranmission and is always sending out the UART commands. This saturates the ISR and it also prevents the reset button ISR to function.

Although this happens rarely, I would like to take measures for this. As far as I know, there are no way to set priority in avr ISRs. So what can I do if the UART ISR is always called and prevents the rest of the board from functioning?

EDIT:
I think the problem arises when the linux machine sends an empty string to the atmel.
the UART_receive() on the atmel gets stuck at: `while ( !(UCSR0A & (1<<RXC0)) );`

Any way I can avoid this?

    unsigned char USART_Receive_string(unsigned char *x, unsigned char size)
    {
 unsigned char i = 0;

 if (size == 0) return 0;            // return 0 if no space

 while (i < size - 1) {              // check space is available (including additional null char at end)
  unsigned char c;
  while ( !(UCSR0A & (1<<RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received
  c = UDR0;
  if (c == '\0') break;           // break on NULL character
  x[i] = c;                       // write into the supplied buffer
  i++;
 }
 x[i] = 0;                           // ensure string is null terminated

 return i + 1;                       // return number of characters written
    }

body:
> Any way I can avoid this?

I think the whole concept of reading "n" bytes is flawed. It will indeed hang if you don't get the number you expect.

Why not just do what normal serial comms does. Accept bytes as they arrive in an ISR, and put them in a buffer? Then use the line-terminator to know when you have enough to process.

> So what can I do if the UART ISR is always called and prevents the rest of the board from functioning?

The UART ISR won't be called if there is no data, so it won't be "always called".


body:
    while ( !(UCSR0A & (1<<RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received

The comment hits the nail on the head.

It'll wait forever, but it's so because it has been "designed" in such a way.

You've got 2 options:

 - Re-think your "design":

Do not make your UART wait for an n-amount of characters. You could buffer the received characters, and handle/clear the buffer. There should be a lot of info about this on the web.

 - Quick and dirty fix:

Add a timeout to the waiting.

    for (unsigned int timeout = 16000; (!(UCSR0A & (1<<RXC0))) && timeout > 0; timeout-- );

This isn't very efficient, but should work.
Be sure to check for what reason the waiting stopped (if the timeout ran out, or if you actually received something), to avoid pushing in nonesense that's in the UDR0 at that moment (when you timeout).


message:
Using external power supply to power leds on multiple pins (A0-A5)

I'm totally new to Arduino, and microcontrollers for that matter, so I'm having a hard time figuring out how to connect LEDs to multiple pins, but using a common external power supply...

I've created a starting light that's connected to pin A0-A4 + A5 (turn all LEDs on). I hooked each LED to its own pin directly (A0-A4) for the countdown part ("5, 4, 3, 2, 1, ..."), and then 5 additional LEDs to pin A5 ("GO!").

For the countdown part, when only one LED is on at a time, there's enough power. But if I were to light them all up at the same time, there won't be. So I figured that I should put a relay into the mix for that part, and have them draw power from an external 12 V power supply.

I did manage to make the relay work in the circuit - switching all LEDs on/off, and getting power from the external power supply, but only through one pin.

I'm not sure how to have the start lights use an external power supply, and at the same time get signals from multiple pins. How do I do that?

I'm sorry if my description is unclear. So please let me know if you need more information.

 - The LEDs are 3.4 V 20 mA.
 - The power supply I'm planning to use is 12 V.

I'm planning to have this start light - which is built in its own casing - use its own power supply, while the Arduino is running of the power from USB. So all I want to do, is to have the signals sent over to this starting light unit, and not power and ground.

UPDATE:

Here's a quick overview of how I'm testing this whole thing at the moment:

![Friting diagram of Arduino and LEDs][1]

The 5 red countdown LEDs (red) is getting powered by the board itself through the pins, while the 5 "GO!" LEDs (green) are getting powered from a 12 V power supply since they're all are going to be turned on simultaneously.

My question is how I can get both the 5 red LEDs, that uses separate pins, to get powered from the external power supply as well?

Since all the LEDs are built in its own casing, apart from the microcontroller because that also handles other stuff...

Did that make any more sense at all?

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

body:
**Caveat: I too am new to this. The answer below is my understanding and I need an expert to confirm.**

Current in your Arduino:

* A single digital pin on a Uno will provide 40mA -- and could conceivably power two of your LEDs.
* The VCC pin outputs 200mA and could therefore conceivably power ten.

So all you need to do is power your LEDs from your VCC, but use your digital pin as a switch. One idea, which you had, was to use a relay. But a relay is an inductor so don't connect it directly to the Arduino. Make sure it's on a shield. But that shield will essentially do exactly what you need to do, but to drive the relay rather than drive your LEDs: It will use the digital pin to switch the VCC and activate the relay.

Luckily this isn't hard. All you need is the most magical of all components: the transistor. A transistor can be used as a switch to turn on a higher current. In your case, the transistor can switch the VCC connection to the LED array when the digital pin is high.

* This question was [answered nicely over at the electronics stack exchange][1].
* Here's a [PDF tutorial on using transistors as switches][2].
* Found a nice [reference on figuring out the transistor / resistor relationship][3].

Here's the circuit I believe you need based on my understanding. Note that the values of the resistors and transistors are just made up. Read the docs above to get the correct values.

![Power five LEDs from one digital pin][4]

  [1]: https://electronics.stackexchange.com/questions/65996/turning-on-multiple-leds-with-arduino-using-transistor
  [2]: https://www.techhouse.org/~dmorris/projects/tutorials/transistor.switches.pdf
  [3]: http://www.sqlskills.com/blogs/paulselec/post/arduino-figuring-out-transistors-and-associated-resistors.aspx
  [4]: https://i.stack.imgur.com/NAsTa.png


body:
I think one of the best way for you would be to use 74HC595 chip. You will learn a lot while developing board with this chip. It is well documented [Serial to Parallel Shifting-Out with a 74HC595][1]. Using 3 pins you will be able to turn on & off as many LED's as you wish, use external power supply and so on.

Also there is MAX7219 chip. [The MAX7219 and MAX7221 Led drivers][2]. And there are a lot more ways to do this.

  [1]: http://arduino.cc/en/tutorial/ShiftOut
  [2]: http://playground.arduino.cc/Main/MAX72XXHardware


body: If you really want an external power supply, you can use ULN2003 / ULN2803, which are 7/8 darlington 500 mA each transistor


message:
How to ensure electronic components make good connection with breadboard

I just began following the projects in the Arduino Projects Book included in the Arduino Starter Kit.

While using LEDs, as in the first few examples of the book, I am having a difficult time keeping them in contact with the breadboard. I can usually move the LED around until it turns on, but even a push of a button can make it lose contact with the board. I haven't used much more than switches, jumpers, LEDs and resistors, so I don't know if any of the other components behave the same. For the more complex projects, it seems like it would be hard to tell if you have it setup properly if you can't be sure the components are making a connection with the breadboard.

Is there a particular way to get all the components to sit nicely in the breadboard, or to modify them to do so?

body: Sounds like you may not be pushing the leads into the board,I find long nose pliers handy for components with thicker leads.


message:
How to Segment Accelerometer Signal at idle points

I'm using an 3 axis Accelerometer(GY-521) to get the acceleration data and also the gyroscope to get the gyro data. I want to segment the signals at the idle points so that i can get the segmented signal at the idle points.

![enter image description here][1]

Is there any algorithm or example code that i could use to segment this kind of signal?

Any help would be appreciated.

Thank You.

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

body:
There are many algorithms you can use. I would advise you to look carefully at the data and the "idle state" and see what is always different. Try everything you can think of and see what works best, or if one does everything you need just stop there.

It might be that you can just calculate if the accelerometer values go over a certain threshold, but that requires that either the orientation be know or the threshold being over 1g.

You could also calculate the rate at which the accerometer value is changing by subtracting the last value (the derivative if you are up on your calculus) and threshold that value, which might produce better results.

You could also calculate a running average and then compare the current value with that. If the numbers match (or are very close) then you can say the accelerometer has been idle. This has the effect of making a changing threshold relative to the most recent activity tuned by the average's response.

I doubt any of these will be perfect, so you might require the algorithm to say "idle" multiple times in a row before changing state from "active" to "idle", or something to that effect.


message:
Shift Register 74HC595 not working

I am trying to learn how to make a shift register work. I have been working off of the [Arduino ShiftOut tutorial](http://arduino.cc/en/tutorial/ShiftOut).

My issue is that the shift register isn't working when the circuit is powered and I am not sure what is wrong. I suspect the issue is with pins 10-13 on the 74HC595?

I have done this with an actual board and the 123d.circuits.io simulator with the same result:

http://123d.circuits.io/circuits/444111-shift-register

![enter image description here][1]

The code is very simple and taken from [the tutorial](http://arduino.cc/en/Tutorial/ShftOut12):

    // SH_CP; 11
    const int clockPin = 9;
    // DS; 15
    const int dataPin = 8;
    // ST_CP; 12
    const int latchPin = 10;

    void setup() {
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(latchPin, OUTPUT);

      Serial.begin(9600);
      Serial.println("reset");
    }

    void loop() {
      for (int number = 0; number < 256; number++) {
        Serial.println(number);
        digitalWrite(latchPin, LOW);
       shiftOut(dataPin, clockPin, MSBFIRST, number);
       digitalWrite(latchPin, HIGH);
       delay(500);
      }
    }

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

body:
Solution: Remove ground from Q0 as Gerben correctly pointed out in comments.

Also: rotate LEDs 90 degrees so that the anode and cathode are on different rows.

What was tripping me up is in the Arduino tutorial diagram is a little unclear on this (I now understand why their way is correct and my way (in the question) was wrong:

![enter image description here][1]

  [1]: https://i.stack.imgur.com/JYzEK.gif


message:
Arduino Wire Types?

I don't know what wires to get for my first Arduino project. I am planning on getting a pre-made light strip that I would control with an Arduino from across my room. Is there any specific type of wire to get? It needs to be about 15 feet. There are so many choices, but I don't know what I need. Does anyone else know?

body:
Choosing wire all depends on what you're going to do with it, and most of the choice is based on how much current it will carry and how durable it needs to be. Generally, you're going to use insulated copper wire - aside from that, your answers are mostly here: https://electronics.stackexchange.com/questions/16948/choosing-the-right-type-of-wire

For experimentation - which you will need to do a lot of before attempting your goal project - you can use the little wires which come in the Arduino starter kit. They are "jumper wires" designed for use on a bread board - they can not carry large amounts of electricity.

This product here: https://www.sparkfun.com/products/8431 - these have "male" ends designed to be stuck into the holes in the breadboard, and connect to the holes on the headers of the Arduino.

Here's an example of a project laid out on a breadboard:
![Compass Project][1]

None of those wires carry a lot of current. If you're hooking up 50 LEDs that might be almost a full 1-AMP of current, so I would use thicker wire. Do yourself a favor and start with a kit like in this video, learn the basics, then attempt a 'real' project. Every Arduino user should be able to do all the experiments in the training book and understand them. You will be lost if you jump in deep right away...

https://www.youtube.com/watch?v=pf4qosqpv3A

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


message:
Infrared interruption counter

Is it possible to create a infrared based interruption counter with an Arduino Uno? If yes, then what additional hardware would be necessary?

body:
You can use photo any transmissive or reflective photo interrupter (wire or TH) ideally with integrated Schmitt trigger and connect to IRQ driven AVR input to have quick trigger reaction. For production is cheaper photo interrupter with external Schmitt but for prototyping it does not matter.
Don't forget serial resistor to limit current.

Search e.g. "photo interrupter Schmitt" at Farnell.


message:
Blend Micro uploading sketch

I have just got the [Blend Micro][1] board.
After following the [getting started tutorial][2] I can't manage to upload sketches on the board. Now, in Arduino v. 1.0.6 I see the voices

- Blend
- Blend Micro 3.3V/8Mhz
- Blend Micro 3.3V/16Mhz (Overclock) as in this picture:

![enter image description here][3]

While the L Led is switch on if I upload the sketch the TX and RX leds stay off. The modified Arduino IDE says "Done uploading". As port I choose /dev/tty.Bluetooth-Serial-1 and I don't see any other port and I think this is critical.

But if I open the Android BLE application BLE Controller, after tried to upload the __BLEControllerSketch__ (from RBL_nRF8001 libraries) it finds the board but print the error __No Response from the BLE Controller sketch__. If I try with __SimpleChat__ example and the SimpleChat Android application if finds the board but prints only "Hello World" and nothing else if I send strings from the android app.

Any kind of advice?

EDIT

I am on a Mac 1.8.5. I have tried also with Codebender, but anything change: I can't see the `/dev/tty.usb*` in the listed ports

  [1]: http://redbearlab.com/blendmicro/
  [2]: http://redbearlab.com/getting-started-blendmicro
  [3]: https://i.stack.imgur.com/pzKcF.png

body:
Did you follow the setup exactly? In particular, did you modify `main.cpp` to have this:

    #if defined(BLEND_MICRO_8MHZ)
        // As the F_CPU = 8000000UL, the USB core make the PLLCSR = 0x02
        // But the external xtal is 16000000Hz, so correct it here.
        PLLCSR |= 0x10;             // Need 16 MHz xtal
        while (!(PLLCSR & (1<<PLOCK)));     // wait for lock pll
    #elif defined(BLEND_MICRO_16MHZ)
        // The CPU clock in bootloader is 8MHz, change to 16MHz for sketches to run (i.e. overclock running at 3.3v).
        CLKPR = 0x80;
        CLKPR = 0;
    #endif

If not, what happens is once the sketch starts the USB stops working and you can't see the serial port due to the clock speed being incorrect. This is why you can only see `/dev/tty.Bluetooth-Serial-1` in the port list.

1. Modify `main.cpp` according to http://redbearlab.com/getting-started-blendmicro

2. Press the reset button on the Blend Micro, then quickly select *Tools* -> *Serial Port* in the Arduino IDE. The Blend Micro serial port should be there because the boot loader is still running. It will be named like `/dev/tty.usb????????`

3. Select that serial port. Compile your code. Now press reset at the same time as pressing upload. Your sketch will upload and the serial port should now be present when the sketch is running.

**Update: The Timing Tricks**

Note: Blend Micro is basically the same as Arduino Leonardo.

This is the timing:

1. The reset button is pressed.

2. The ATMega32u4 restarts. It jumps to the bootstrap loader code.

3. The bootstrap loader starts up the USB as a CDC device (serial port) and waits for firmware upload instructions. (Pulsing L LED)

4. If no upload instructions are received within a certain time (8 seconds?), it jumps to the application code.

5. The application code starts up the USB as a CDC device again.However, since the oscillator (clock) on the Blend Micro is different to the Leonardo, it requires the modifications above, otherwise the USB clock will wrong, and the USB won't work.

If the modifications above were not done, Step 3 is the only time when the USB is working and the serial port can be selected in the Arduino software.


body: For anyone else who is having an issue with this. What worked for me, was replacing the cable with a shorter cable. I could of been using a charging only usb cable or the cable was long enough to not upload correctly.


message:
NRF24L01 Direct Communication Library Logics

Actually I'm using the RF24 Library mantained by TMRh20 (https://github.com/TMRh20/RF24).
I'm trying to get some type of direct communication between multiple modules working, but I don't want to use the RF24Network Library (https://github.com/TMRh20/RF24Network) which creates a mesh of connections.

I currently have several arduinos that have to communicate between them. Every arduino has its own address starting from 0x0001 (0x0000 is for a main module that manages everything) and finishing to 0xFFFF.
I want to directly communicate between the two NRF24L01+ modules without any intermediator, because I don't have problems of distance.

The main thing that I want to be able to do is communicate directly not with just one module, but choose if I want to broadcast to all the modules in an area (I know that it can be done with range power modifications in the code) or talk with just one module.

What is the best way to do this type of communication?

body:
If you set pipe 1 to a common address (let's call it the broadcast address) anytime you send a packet to that address all the modules will receive it on that pipe!
It's as simple as that, but you will not be able to use auto-ack (you will receive multiple acks, one per each receiver) and you can't also use ack payloads.

I wrote a series of [blog posts][1] on this modules and I'm going to keep writing on the topic.

  [1]: https://rlogiacco.wordpress.com/2015/09/21/nrf24-walk-through-introduction/


body:
Both of the Libraries you mentioned are well written. I've used both, but decided to write my own based those libraries. For me, the network libraries were written for their project and didn't really fit my needs. So I decided to write my own. I combed the internet for a bare bones NRF24 Library and found this [one][1]. This was my starting point. It didn't need the Arduino Core Library and handled all the SPI functions. Then I read the NRF24L01 datasheet several times, then read it again.

With that said, you can broadcast up to 6 radios at a time. Per the datasheet, the receiver knows which radio sent the packet. The STATUS register (0x07), should tell you who sent the packet:

[![STATUS Register 0x07][2]][2]

I was unable to get this working (I am still working on it), so for now, I send my packet as a struct:

    typedef struct  {

 uint8_t id;
 uint32_t data;

    }
    Packet;

    Packet pck;
    pck.id = 2; // id of my second radio

Keep in mind when you program your Arduino as the receiver, you have to tell it who it will be receiving from. The transmitter and receiver have to be on the same RF channel, speed and same pipe. To choose who receives the packet may not work the way you think, but as I mentioned you can program the receiver to know who the transmitter was and code around it.

I would suggest you dig into the datasheet.

  [1]: https://github.com/kehribar/nrf24L01_plus
  [2]: https://i.stack.imgur.com/ZwL67.png


body:
You need to dig into the [datasheet][1] and read about ESB (Enhanced ShockBurst).  This is technology that is integrated into the radios and allows for broadcasting and direct pipes.  One of the limitations is that the mesh only works for up to 6 pipes, so be aware that this limits the number of devices that will be able to hear your transmission.

Another option is to have all the nodes listening on the same pipe, and then when node x wants to talk, he stops listening on pipe 1234 and starts writing to it.  You would put some sort of addressing header in the payload section of the packet, then when all of the nodes receive that packet, they can check that address and see whether or not to process it.  This might work well in your situation.

For example, if you have a packet that is sent on the communal pipe with a payload of [broadcast address,data] then your receiving nodes (those within "earshot") can receive the packet, see that it is a broadcast, then process the data.  If you want to send to a single node, create a packet that has a payload of [destination node id,data].  When each node receives that packet on the communal pipe, they will check the destination, and when it doesn't match either their own address or the broadcast address, then they dump it.  Only the intended receiver will actually process the data.

  [1]: https://www.sparkfun.com/datasheets/Wireless/Nordic/nRF24L01P_Product_Specification_1_0.pdf


message:
Arduino SoftwareSerial library basic example doesn't work

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

I come to you again because I have a problem with the Arduino SoftwareSerial library. With a basic example I fail to see results in the serial monitor.

The basic code example:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10, 11);
    void setup() {
      mySerial.begin(4800);
    }
    void loop() {
        mySerial.println("HELLO");
        delay(100);
    }

I guess it should show the string "HELLO" on the serial port, but nothing appears. I have found that the baud setting is correct. The hardware is simple. Only an Arduino Uno v3 without any connected component.

body:
If your Arduino is connected via the built-in USB port then you need to use the hardware serial port (pins 0 and 1). To do that, call `Serial.begin(..)` and `Serial.println(..)`, instead of `mySerial...`.

`SoftwareSerial` is used when you want to connect via serial on some other pins. It allows your program to emulate serial input/output in software instead of relying on dedicated hardware. In this case, your program is trying to setup software serial on pins 10 and 11. That won't show up on the serial monitor because it's not connected to those pins.