text:
Employing C++ code for Arduino
I have Googled quite a lot regarding using a C++ program for uploading to Arduino and related, however I am confused now. Right, my problem is this:
I have written a C++ program which imports RGB data of a 24 bit bitmap (which was generated using Matlab) and now I would like to use this array (3 arrays - R,G,B) for an Arduino sketch to be used for a LED matrix project that I am working on. I am not exactly a programmer and hence had to resort to this path -- MATLAB to c++ and then Arduino, although this could be entirely done in C++ too (importing a bitmap and extracting pixel info). So, my C++ code spits out the 3 arrays and I am not sure how to get those into an Arduino sketch.
I read a lot about this and I understood this - As the Arduino "language" is C and C++ therefore it is possible to program an Arduino in C++/c. I need a maker file and a compiler. However my question is that isn't there a more non-programmer friendly way to get this done, some software or an IDE which supports Arduino programming in C++? I cannot understand much of this method, hence trying to bypass this.
If anybody's got any better method, I would be really glad if you could share it. I am also looking to use the Arduino package for MATLAB to send the array directly from there using serial communication. But I just wanted to make sure I at least tried this path.
Would really appreciate if somebody could offer some help. I am quite stuck here.
Can share any other info if required.
Thanks a lot!

EDIT 1:
To clarify as Nick Gammon pointed out in the comments below. In brief steps, this is what I have done till now:

Got a 24 bit bitmap (some random image)
Extracted the RGB data for each pixel using Matlab
Have 3 arrays of (for eg.) 122X300 dimensions whose every element has values between 0-255 (8 bit) and for R,G and B colors
Want to get these 3 arrays for use in Arduino sketch for further working
Stuck here - how to do that .....
So I did this - I imported that the RGB data into 3 separate text files and made a c++ program to read those arrays assuming that I should be able to then somehow use this program in Arduino sketch.
Now I am not sure what to do....my goal would be to have these 3 arrays (CRGB arrays, FastLED) in my arduino sketch which I can control and then upload to my Due.
On googling I found that to use c++ for arduino , you need the avr compiler and make file, which I want to avoid. Tried other IDEs too, Eclipse, PlatformIO too .. ummmm ... not that successful to be honest.
as per Paul's ans- Matlab to Arduino method I have to try.
Hope I have clarified my process till now :)

EDIT 2:

C++ code for reading the above array (thought I could use the output in Arduino)
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <sstream>
#include <stdlib.h>

const int HEIGHT = 4;

const int WIDTH = 5;

using namespace std;

int main(){

  int array_req [HEIGHT][WIDTH];

string userinputprompt, filename;

userinputprompt = "COLORDATA FILENAME: ";

cout<<userinputprompt<<endl;

getline(cin,filename);

ifstream inputfile;

inputfile.open(filename.c_str());

 for (int i = 0; i < HEIGHT; ++i)
{
  std::string tmpString;
  std::getline(inputfile, tmpString);

 std::stringstream ss(tmpString);

 for(int j=0;j < WIDTH; ++j)
  {
    ss >> array_req[i][j];
  }
 }

    for(int p=0; p<HEIGHT; p++)
    {
      for(int q=0; q<WIDTH; q++)
    {
        cout<<array_req[p][q]<<" ";
    }
    cout<<"\n";
}

inputfile.close();
getchar();
return 0;

}

Comments are not for extended discussion; this conversation has been moved to chat.

@NickGammon dont have 20 rep for chat. Would have to wait. Sorry.

You have 23 rep now. :)

Although down voted twice by people who apparently are uninformed, many of the C++ problems you are describing as it pertains to your coding environment can be overcome by using Visual Studio free edition with Visual Micro add-in fro Arduino. It makes using C++ a snap for Arduino.

You've got quite an interesting project.
Programming an Arduino (C++)
Arduino is C++ (or atleast a subset).
The Arduino IDE uses the GNU AVR-GCC compiler. And it takes care of all "make" files and stuff. You shouldn't really bother too much. Just paste the code right in, and fix whatever is broken ;)
Also, the Arduino IDE is basically click&install, click&compile/upload, I'm not sure why you're even trying all the other options.

For the sake of clarity/simplicity I'll give you an example of sending a single R/G/B pixel to the Arduino.
Matlab
You should set up your Matlab code something like this.
I'm not a "Matlab guru" nor do I know whatever code you have.
You should open a COM port and write to it.
s = serial('COM1','BAUD',115200);
fopen(s);
Pixel pix = getPixelFromBMP("image.bmp",0);
fprintf(s,'%s',pix.r.to_String()+pix.g.to_String()+pix.b.to_String());
fclose(s);

Arduino
In the Arduino IDE (withouth worrying about makefiles and toolchains).
You do the reverse of what you've done in your Matlab code.
Read the serial input and write it to the LED strip.
I'm quite sure this code won't compile, and there are a lot of fancier ways to read the serial buffer:
#include <ledstrip.h>

LedStrip ledStrip;

int incomingByteR = 0;   // for incoming serial data
int incomingByteG = 0;   // for incoming serial data
int incomingByteB = 0;   // for incoming serial data

void setup() {
        Serial.begin(115200);     // opens serial port, sets data rate to 115200 bps
        ledStrip.begin(1,RGB);    // initializes the ledstrip (RGB).
}

void loop() {
        // send data only when you receive data:
        if (Serial.available() > 3) {
                // read the incoming byte:
                incomingByteR = Serial.read();
                incomingByteG = Serial.read();
                incomingByteB = Serial.read();
                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByteR, DEC);
                Serial.println(incomingByteG, DEC);
                Serial.println(incomingByteB, DEC);
                ledStrip.pixel[0].r = incomingByteR;
                ledStrip.pixel[0].g = incomingByteG;
                ledStrip.pixel[0].b = incomingByteB;
                ledStrip.show();
        }
}

C++
So, you don't really need C++ (other than to program the Arduino). You could interchange Matlab for C++ or Arduino for pure AVR C++, but I wouldn't recommend it.

wow! your answer did clear some of my doubt. Thanks! I just realised when I was trying to use a cpp code for arduino in Codeblocks that I have to eventually go the hard way - Avr compliler,make files etc. etc...installed WinAVR and got lost again. I guess Matlab should save me. Let me try with it, your code and concept and will update here maybe tom. Hope that's fine :)

Everything is fine. You can consider accepting this as an answer. If you run in other problems, you could create a new question.
But I indeed find your project interesting.

Hmmm...Right mate. I will accept it..no issues. I thought creating another similar question would be frowned upon ;) I will look into it and get back on this later. need some time. Thanks!

@fattypanda I'm not such a frowner ;)
But it's very likely you'll run into a problem that's completely different. If you then update/change the question, the inital problem might get lost.
If you'd like to discuss the project or minor questions related to it. I'd be happy to answer them in chat (http://chat.stackexchange.com/rooms/38302/matlab-bmp-to-arduino-rgb-matrix)

@fattypanda it seems you do not have enough reputation to talk in chat, though I'm sure it would be helpfull (I've worked with BMP an APA102 LED strips). You could try to edit an answer/question (if that gets accepted you get +2 rep), by asking another interesting question or by answering a question.

lol yes. .pretty nice to see though you worked with APA102.  Let me see how to get around this (+2 rep min)

You can make some minor edits to my question, if it gets accepted you'll get +2 I believe.

Re: "Arduino is C++." Isn't it more like a subset of C++? Do you have any sources for this claim?

@PeterMortensen I've edited my answer. But for all practical purposes, it's the same. (Especially in this question/context). It's compiled with the AVR GNU GCC toolchain and thus "as close to C++ you can get in an AVR microcontroller".

@PeterMortensen it's by that beyond the scope of the question. http://www.idogendel.com/en/archives/19#comment-2809 and http://arduino.stackexchange.com/questions/816/c-vs-the-arduino-language

Here's a sample program you could use as reference, just replace the values in the array and adjust VALUES_NUMBER accordingly.
Disclaimer: I didn't try to compile/run it, but it should give you an idea of how to use the values you already have.
// These are Arduino Pins that support "analog" output.
const unsigned short ANALOG_RED_PIN = 3;
const unsigned short ANALOG_GREEN_PIN = 5;
const unsigned short ANALOG_BLUE_PIN = 6;

const unsigned int VALUES_NUMBER = 12;

const unsigned short REDS[VALUES_NUMBER] = {
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
  0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B
};

const unsigned short GREENS[VALUES_NUMBER] = {
  0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05
};

const unsigned short BLUES[VALUES_NUMBER] = {
  0x09, 0x0A, 0x0B, 0x03, 0x04, 0x05,
  0x00, 0x01, 0x02, 0x06, 0x07, 0x08
};

void setup() {
  pinMode(analogRed, OUTPUT);
  pinMode(analogGreen, OUTPUT);
  pinMode(analogBlue, OUTPUT);
}

void loop() {
  unsigned int counter;
  for (counter = 0; counter < VALUES_NUMBER; counter++) {
    analogWrite(ANALOG_RED_PIN, REDS[counter]);
    analogWrite(ANALOG_GREEN_PIN, GREENS[counter]);
    analogWrite(ANALOG_BLUE_PIN, BLUES[counter]);
    delay(1000); //sleep 1 second
  }
}

.thanks for the reply. Your code is a very simplified version. However, its my mistake, apologies..i didnt mention..I am implementing this project using APA102 led strips which has a data and a clock pin. So, as far as my knowledge goes, control of strip using individual analog pins is not possible. Also, the second part of the code where the data is passed on to the leds, I am done with that part. Its the first part where I am stuck. Acquiring of data in 3 different arrays. Rest is done using the fantastic FastLED lib. :)

As the arduino "language" is C and C++ therefore it is possible to program an Arduino in C++/c. I need a maker file and a compiler. However my question is that isn't there a more non-programmer friendly way to get this done, some software or an IDE which supports Arduino programming in C++?

Yes, it's called the Arduino IDE. You plug your board into the USB port, write your program, or use an existing example, and then hit the Upload button.

lol...I guess you misconstrued my question :P I meant that I wanted to be more flexible with the Arduino IDE by incorporating c++ environment. I was sort of handicapped (most probably because I am a non-programmer). Couldn't relate the output of a c++ program (or for that matter Matlab) directly into Arduino sketch. I have been using Arduino IDE for the last couple of months :)

I'm not sure where this is heading. In the Arduino IDE you are programming in C++. You don't need to install or change anything to use it - or to "incorporate the C++ environment". It's just there.

Nick Gammon is right. Recently I started programming Arduino in Eclipse though. See here if interested: https://arduino.stackexchange.com/questions/40/what-are-the-other-ides-for-arduino/75491#75491. Also, this is very relevant: https://arduino.stackexchange.com/questions/816/c-vs-the-arduino-language/50839#50839. Lastly, Nick Gammon is an Arduino master. His website is filled with sooo much incredibly useful and detailed information. He is one of the foremost experts in the world when it comes to the ATmega328 microcontroller and Arduino.

Use the Visual Studio free community edition (or the paid versions if you already have them) with the Visual Micro extension for Arduino. Makes life a lot easier since you have indicated your desire to write in C++, and you get true debugging and intellisense as well, which you DO NOT get with the aforementioned IDE's.

Could you please tell me how this is relevant to this question?

Your first line,
I have Googled quite a lot regarding using a C++ program for uploading to Arduino and related, however I am confused now. Right, my problem is this:....and that is what I answered

There is nothing about needing debugging in the original question. If you wanted to say that one can use VS CE then edit the answer appropriately.

@Avamander....is my answer now more suitable for you.


text:
Standalone chipset, power regulation & pinout
I have succesfully (or so the ide says) burned a bootloader on an ATMega328P-PU chipset, and uploaded my sketch on it.
It appears a voltage regulation is absolutely needed, if I want to solder a pcb with the standalone chip, rather than an arduino. Is that correct? Can I build one out of my starter kits parts (assortment of transistors, diodes, zeners, resistors and capacitors)?
In the meantime, I would like to make sure the chispet is functional. Can I power it from GND/5V of an arduino? Will it take care of that power regulation?
If I can, what is the correspondance between the arduino pins, and the ATMega328P-PU pins? I have this page here : http://www.learningaboutelectronics.com/Articles/Atmega328-pinout.php
referencing the chipset pinout. Am I correct in assuming there is a correspondance with the arduino pinout in the reading order of this chart, ie. :
PD0 to PD7 are Rx, Tx, digital pins 2 to 7 on the arduino, PB0 to PB5 are digital pins 8 to 13, and PC0 to PC5 are A0 to A5 on the arduino?
Thanks for reading.

You are correct about the pin correspondence. C.f. this Arduino Uno pinout diagram.

Voltage regulation is needed if the voltage you are providing to the chip is outside (or can drift outside) the allowed range for the chip to operate.
At the upper limit that is 5.5V. The lower limit is 1.8V. Note that at lower voltages you can only reliably run at lower clock speeds.
If your power source is between those two voltages (say a 3.4V LiPo battery) then you don't need a regulator.
If your power source is above 5.5V (say a 9V PP3 battery [urgh]) then you definitely need a regulator.
A proper regulator is quite a complex device, and it is highly unlikely that you have the components to make one.  A simple, very inefficient one, though, can be made using a resistor and a 5V Zener diode if you have one.

Until you have your own regulator of whatever form, yes, you can power the chip from the 5V pin of the Arduino.
The pin mapping for the chip -> Arduino IO numbers is in the file pins_arduino.h for the Uno variant in the IDE.  In the top of that file is this handy drawing:
// ATMEL ATMEGA8 & 168 / ARDUINO
//
//                  +-\/-+
//            PC6  1|    |28  PC5 (AI 5)
//      (D 0) PD0  2|    |27  PC4 (AI 4)
//      (D 1) PD1  3|    |26  PC3 (AI 3)
//      (D 2) PD2  4|    |25  PC2 (AI 2)
// PWM+ (D 3) PD3  5|    |24  PC1 (AI 1)
//      (D 4) PD4  6|    |23  PC0 (AI 0)
//            VCC  7|    |22  GND
//            GND  8|    |21  AREF
//            PB6  9|    |20  AVCC
//            PB7 10|    |19  PB5 (D 13)
// PWM+ (D 5) PD5 11|    |18  PB4 (D 12)
// PWM+ (D 6) PD6 12|    |17  PB3 (D 11) PWM
//      (D 7) PD7 13|    |16  PB2 (D 10) PWM
//      (D 8) PB0 14|    |15  PB1 (D 9) PWM
//                  +----+
//
// (PWM+ indicates the additional PWM pins on the ATmega168.)

Thanks, very nice answer with additional material for me to read! :)

source: Stack Exchange

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

sort: votes


text:
ATmega328p simple shortcircuit button
I am trying to get a simple button (GPIO shortcircuit) to work. I have chosen Pin D0 as input and Pin D7 as output. It works fine in an Arduino sketch but I can't get it to run in pure C. What am I doing wrong? I bet I got the bits all wrong...
My code:
DDRD = 0b11111110; // set all port D pins to Output besides pin 0, which is set to input
PORTD = 0b11111111; // set all D pins to WRITE / PULL-UP
int a = PIND & 1; // a is 0 or 1, depending on whether pins D0 and D7 are physically connected

It doesn't work though, a is never zero, whether the pins are connected or not.
Here is my complete code sample, where the on board LED depends on my pins connection state:
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
 DDRB |= _BV(DDB5);
 DDRD = 0b11111110;
 PORTD = 0b11111111;

     while(1) {
        int a =  PIND & 1;
        if(a != 0)
             PORTB |= _BV(PORTB5); // blink on
         else
             PORTB &= ~_BV(PORTB5); // blink off
         _delay_ms(1000);
    }
}

You wired a pushbutton between digital 0 (PD0) and GND, right?

GND is not involved. I put a direct wire between PD0 and PD7. Is that wrong? It works in Sketch.

Yes, it's wrong, you will always read HIGH.

Pin D7 is HIGH, so if the pins are connected you read HIGH. If they are disconnected you will still read HIGH because you enabled the pull-up resistor. Set D7 to LOW instead. That way you can differentiate between connected and disconnected.

Setting pin D7 to 0 makes my contraption work. I don't understand it though, I thought I could imagine it like this: Setting D7 to High/1 would make it pour out power and setting D0 to read and reading it's value would tell me whether power is pouring in...

The problem here is you set pull-up on D0. So even if button is not pressed it will be at high state because of pull-up. You would need pull-down for this to work (Arduino does not have it).
The pullups are useful if you want to connect pin to GND when button is pressed. When button is not pressed it will have defined state (HIGH because of pull-up) and when pressed it will be pulled LOW by button. You can imagine pull-up as a resistor to Vcc.
So for this to work I would put the other end of button to GND and it will work (One end to D0, second on GND). Condition in code should be altered (a == 0) but otherwise all can be the same.
Other option is to connect external resistor in range 1K-100K Ohm between pin D7 and GND and turn off pull-up in code. That resistor would serve as pull down.
Just one more note. If you are not using other pins it is the best to leave them as inputs. Setting an "unused" pin as output and setting it to HIGH can damage the pin if you accidentally connected it to GND (because in previous sketch you experimented something).

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


text:
Digital pin output voltage, not triggering 71mA relay coil
I have a relay (VRS4H-S-DC5V-C), for which the triggering voltage required is 5V Min.  If I directly use the 5V voltage of Arduino  I'm able to trigger it, but if I use any digital pin in OUTPUT mode in digitalWrite I'm not able to trigger the relay.
Earlier I thought that it must be that because it's a small board its digital pins would be giving HIGH state as 3.3.V, but the fact is when I checked both the voltage of 5V (which is obviously shown 5V on multi meter) and that digital pin one, both show 5V. So the question is why the hell is digital pin not able to trigger the relay, since trigger the relay by 5V is of no use for me since I can't control it, i.e., when it should trigger and when not?

From the datasheet, the coil resistance is 70 ohms at 5V, so it is trying to draw 5/70=0.071A, or 71mA, which is more current than a nano can source.

Okay @Dave X...

The digital output pin cannot output sufficient current to drive the relay directly. Iirc this question was already asked. You need to add between the Arduino and the relay a driving stage, for example with a FET. Or you can use a shield that already has this additional circuitry.
Just google for "Arduino relay driver circuit" and you will get various options.
This is pretty close to your setup.

BTW, I just found out that at least some companies produce what they call "digital transistors" which is a fancy way to say that the component already contains some resistor integrated. Example: the resistor on the base of a BJT.

I used to use those for a while. You can get them with just a base resistor, and also with a base pull-down resistor integrated. Useful if space is a premium and/or you have thousands of them on a board. Other than that, for the cost of a couple of 0603 or 0402 resistors, they're pretty pointless.

Well firstly thank you both for such a quick response....the answer was quite okay...but the comments ...i found that quite overwhelming ...as in I dont belong to Electrical Domain by core I m a mobile Developer...so could you just explain it in rather simple words...i mean the comments part...i got the answer quite well...

When you follow the link I provided, you can see that it instructs you to build a circuit. Such circuit contains a transistor and several resistors. The comments were referring to special components called "digital transistors" which put, inside the same package, both the transistor and one or more resistors, thus reducing the number of individual packages that you have to interact with. It's just an optimization that you can safely ignore.

well okay got that...i found something after googling the keys u gave me....as in using 2 resistors , a transistor and a diode...i didnt remember exact values of them... but using them i can increase the current rate and therefore do my needful thing... :)


text:
Translating accelerometer angle to PWM output (was MPU-6050 DMP6 example)
I'm trying to make a self balancing robot with MPU-6050. When I try the DMP6 example it works good and the Serial Monitor gives me the yaw pitch roll angles but whenever I try to output PWM on pin 6 nothing happens and I don't know why.
Here is the code:
// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
// 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
//      2013-05-08 - added seamless Fastwire support
//                 - added note about gyro calibration
//      2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
//      2012-06-20 - improved FIFO overflow handling and simplified read process
//      2012-06-19 - completely rearranged DMP initialization code and simplification
//      2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
//      2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
//      2012-06-05 - add gravity-compensated initial reference frame acceleration output
//                 - add 3D math helper file to DMP6 example sketch
//                 - add Euler output and Yaw/Pitch/Roll output formats
//      2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
//      2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
//      2012-05-30 - basic DMP initialization working

/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/

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

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

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

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

/* =========================================================================
   NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
   depends on the MPU-6050's INT pin being connected to the Arduino's
   external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
   digital I/O pin 2.
 * ========================================================================= */

/* =========================================================================
   NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
   when using Serial.write(buf, len). The Teapot output uses this method.
   The solution requires a modification to the Arduino USBAPI.h file, which
   is fortunately simple, but annoying. This will be fixed in the next IDE
   release. For more info, see these links:

   http://arduino.cc/forum/index.php/topic,109987.0.html
   http://code.google.com/p/arduino/issues/detail?id=958
 * ========================================================================= */

// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
// quaternion components in a [w, x, y, z] format (not best for parsing
// on a remote host such as Processing or something though)
//#define OUTPUT_READABLE_QUATERNION

// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
// http://en.wikipedia.org/wiki/Gimbal_lock)
//#define OUTPUT_READABLE_EULER

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#define OUTPUT_READABLE_YAWPITCHROLL

// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
//#define OUTPUT_READABLE_REALACCEL

// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
//#define OUTPUT_READABLE_WORLDACCEL

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
//#define OUTPUT_TEAPOT

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

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

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

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

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

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

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

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

    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial.begin(115200);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately

    // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Arduino
    // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
    // the baud timing being too misaligned with processor ticks. You must use
    // 38400 or slower in these cases, or use some kind of external separate
    // crystal solution for the UART timer.

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

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

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again

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

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(29);
    mpu.setYGyroOffset(44);
    mpu.setZGyroOffset(21);
    mpu.setZAccelOffset(1407); // 1688 factory default for my test chip

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

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

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

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

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

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
  analogWrite(6,255);
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
        // .
        // .
        // .
        // if you are really paranoid you can frequently test in between other
        // stuff to see if mpuInterrupt is true, and if so, "break;" from the
        // while() loop to immediately process the MPU data
        // .
        // .
        // .
    }

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

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

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

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

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

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

        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif

        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
}

Are you sure that dmpReady is being set?

It looks like the only analogWrite(6...) is the analogWrite(6,255) at the top of loop(){} which makes the output on pin 6 insensitive to any changes.

yes it is but it does not output anything on pin 6 although

authors: Ɗααɳιടԋ Sყҽԃ


text:
Not being able to use pushbutton
I've been trying to detect a push button based on this tutorial, but due to my lack of skills/knowledge I haven't been able to make it work, could you guys point out what I'm doing wrong?
Any help is appreciated
My project on 123d circuits
My code:
void setup() {
  pinMode(2, INPUT);
  pinMode(3, OUTPUT);
  digitalWrite(3, HIGH);
  Serial.begin(9600);
}

void loop() {
  trigger();
}

void trigger(){
  if (digitalRead(2) == HIGH) {
    Serial.println("Hey");
    //turn();
  }
}

You seem to be suffering from three problems here:

A lack of understanding how the button's pins are configured
A lack of understanding of how breadboard works
A strange notion (that I have seen around a lot recently for some reason) that a button needs to be driven from an output.

For the button's pins you should know that the pins are paired on the long sides. That is, if you hold the button so it is in "landscape" orientation (wider than it is high) the two upper pins are joined together, and the two lower pins are joined together.

Breadboard consists of strips of connections which, in your diagram, would be running horizontal. Pins plugged into holes horizontally in line with each other on the same side of the board (the gap in the middle is a gap in the connections too) will be connected together.

Finally for the wiring of the button. Nowhere in the tutorial you link to does it ever mention connecting the button to two IO pins. The button should only be connected to one IO pin. It also connects to +5V and, through the resistor, to ground.  Wire it up exactly as it shows you in the tutorial and make it work like that before you try fiddling with it.

Thank you so much for helping me out and for having patience to explain to me what I was doing wrong

so electrons from the black jumper go to red one and if I push the button they will get to pin 2? a weird question, will the electrons go through pin 2 and get out of the 5V pin? if not, where will they go?

At your stage of development you shouldn't be concerning yourself with electrons. For input pins you are only concerned about the voltage at the pin. With the button released the voltage is 0V. With the button pressed it is 5V.


text:
Why am I only receiving the first address byte? (I2C Protocol)
Expecting the slave to ACKnowledge and return data, but it does not. This is my protocol. This is my Datasheet.
Also FYI I'm on an Arduino Fio but I am not inheriting the Arduino library.
#include <avr/io.h>
#include <util/delay.h>
#include <stdlib.h>
#include <uart.h>
#include <i2c_master.h>

#define LED PB5

#define I2C_READ 0x5A

char buffer[1];

//char data[9];
uint16_t val = 0;
uint8_t status = 0;

void getVal()
{
  if(i2c_start(I2C_READ))
    {
        uart_puts("Start ");

        val = ((uint8_t)i2c_read_ack())<<8;
        val |= i2c_read_ack();

    status = ((uint8_t)i2c_read_nack());

      i2c_stop();

    } else
  {
        uart_puts("Error");

        i2c_stop();
    }
}

int main(void)
{
  init_uart(57600);
  i2c_init();

  DDRB = _BV(5);

    for(;;)
    {

      getVal();

            itoa(status, buffer, 10); //convert decimal to string base 10
            uart_puts(buffer);

      PORTB = 0xFF;
      _delay_ms(500);
      PORTB = 0x00;
      _delay_ms(500);
    }
    return 0;   /* never reached */
}

(Acknowledging this is an old question.) The TI article "Troubleshooting I2C Bus Protocol", suggests several common reasons for no ACK:
1. Timing
2. Missing / Unexpected SCL pulses
3. Incomplete 8 bit block
4. Missing Bytes
5. False slave address
6. Unsuccessful address change

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


text:
Ultrasonic Range Sensor won't print distance in Serial Monitor
I'm using the red Ultrasonic Range Sensor with
Sig -> Digital Pin 4
VCC -> 5V
GND -> GND
The code uploads fine and i can hear the sensor clicking away, but for some reason it won't print the distance into the Serial Monitor.
//Settings
int echoPin= 4;
int trigPin= 4;
unsigned long pulsetime = 0;
unsigned distance = 0;
unsigned OldDistance = 0;

void setup (){
  pinMode (echoPin, INPUT);
  pinMode (trigPin, OUTPUT);
  Serial.begin(9600);
}

void loop(){

  //Work out the distance
  digitalWrite(trigPin, LOW);
  delayMicroseconds(100);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(100);
  digitalWrite(trigPin, LOW);
  pulsetime = pulseIn(echoPin, HIGH);
  distance = pulsetime / 58;
  delay(10);

  //Send value if it's changed
  if (OldDistance != distance) {

  Serial.print(distance);

  OldDistance = distance;
  }

  delay(50);  // Wait .1 Seconds
}

What kind of sensor?

Is it this one? http://www.rhydolabz.com/wiki/?p=895

Yup, that was the one.

You have to manually switch from OUTPUT (for sending the trigger pulse) and INPUT (for reading the distance) mode on the shared IO pin.
//Work out the distance
pinMode(trigPin, OUTPUT);    // << ADD THIS
digitalWrite(trigPin, LOW);
delayMicroseconds(100);
digitalWrite(trigPin, HIGH);
delayMicroseconds(100);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);     // << ADD THIS
pulsetime = pulseIn(echoPin, HIGH);
distance = pulsetime / 58;
delay(10);

To save some confusion you might like to change your code to just use sigPin instead of a pair of pins that are both the same pin.  That way you would avoid confusing bits like:
pinMode (echoPin, INPUT);
pinMode (trigPin, OUTPUT);

Which of course is the equivalent to:
pinMode (4, INPUT);
pinMode (4, OUTPUT);

Brilliant! Problem solved and i took your advice to just use a trigpin instead of trig and echo. Thanks!

Two suggestions:
In setup() after you open the serial port, execute something like Serial.println("Sensor Test Program");, and in loop, print the distance value with something like Serial.print("dist: "); Serial.println(distance);
That will tell you two things:

whether your port is open and working at all; and
whether control reached your output statement (in loop) and that it tried to print something.

In this case, it seems unlikely that control didn't reach Serial.print(distance); but more information, at least in the early stages, helps when things don't work as you'd expected them to.
You should have seen some output from your output statement, even if it was wrong. No output suggests:

control didn't get there (perhaps due to a program crash, especially if this is a fragment of a large program);
the terminal program and the Arduino's baud rates don't match;
the terminal program was opened to the wrong port;
the terminal program wasn't opened at all;
the calculation (or operation of the device, perhaps in the manner @majenko suggested) failed such that the distance calculation always yielded zero, and the 'if' statement was therefore never satisfied (my guess), i.e., back to my first point, control didn't get there.


text:
Proper way to run functions in loop
I am having a problem getting my functions to run properly from the loop.
I am building a model railroad crossing gate and need to run the 4 processes once the sensor signals the train entering the crossing zone. For right now I need to learn how to "function" in C++ running in loop, as I'm a C# ASP.Net guy.
My thought process was in loop to

Check entry sensor, this is all the loop should ever do UNTIL its tripped
Once tripped, run the 4 processes functions (close the gates, turn on the sound, turn on the flashers, power down the road that crosses the tracks)
After the entry sensor is tripped and the processes run (the sound and flashers should operate continuously until the exit sensor is cleared) the exit sensor must be monitored, and once its tripped, its monitored until it goes static again indicating the train has cleared. Then the 4 process are run to shut down the flashers, shut the sound, power up the road and raise the gates.

Right now I'm just trying to get the sound functioning properly. Right now, as the code stands, it plays for a split second then stops. I need that file playing until I call the function to stop it.
Here is the code so far. I've removed the includes and defines for brevity.
// These are the pins used for the music maker shield
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

// create shield-example object
Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

//global variables required
boolean crossingSignalInOperation = false;
boolean signalEntrySensor = false;
boolean signalExitSensor = false;
boolean debugMode = false;

boolean checkEntrySensor() {
    //check entry sensor, if tripped return true otherwise false
    /*if () return true;
    return false;*/
    return true;  //hardcoded for testing
}

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    debugMode = true;   //set this to false once code is fully operational
    //initialise music maker shield
        if (!musicPlayer.begin()) {
            if (debugMode)
            {
                Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
            }

        while (1);
    }
    // 1st parameter is left, second parameter is right
    musicPlayer.setVolume(20, 20);
    if (debugMode)
    {
        Serial.println(F("VS1053 found"));
    }

    // initialise the SD card
    SD.begin(CARDCS);

    //ensure our global booleans all start false
    crossingSignalInOperation = false;

}

void loop() {
    // put your main code here, to run repeatedly

    signalEntrySensor = checkEntrySensor();
    if (signalEntrySensor == true) {  //only want to catch the FIRST time it senses
        if (crossingSignalInOperation == false)
        {
            //crossing signal is inactive, activate it
            // turn the sound on and return the music player object
            Adafruit_VS1053_FilePlayer mp = onSignalSound(musicPlayer,"trainxng.mp3");

            while (mp.playingMusic) {
                // file is now playing in the 'background' so now's a good time
                // to do something else
                if (!crossingSignalInOperation)
                {
                    crossingSignalInOperation = true;
                    //run the other three processes
                    //offRoadPower();
                    //lowerSignalArms();
                    //startSignalFlashers();

                }
            }
        }
    }
 }

Here are the functions;
Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {
    // Play the train crossing sound file
    if (debugMode)
    {
        Serial.println(F("Playing track - "));
        Serial.print(fileName);
    }
    //all sound files are on the micro sd card on the music player shield
    if (!mp.startPlayingFile(fileName)) {
        Serial.println(F("Could not open file "));
        Serial.print(fileName);
        while (1);
    }
    return mp;
}
boolean offSignalSound(Adafruit_VS1053_FilePlayer mp) {
    if (mp.playingMusic)
    {
        mp.stopPlaying();
        return true;
    }
    return true;
}

Any assistance would be appreciated.
Update:
New version using the state machine methodology suggested by JRobert and Edgar
Any comments on structure?
// include SPI, MP3 and SD libraries
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>
// include AccelStepper libraries
#include <MultiStepper.h>
#include <AccelStepper.h>
using namespace std;
/*-----( Declare Enums & Constants )-----*/
// Arduino Digital I/O pin numbers for MEGA
//note: digital pins 30-45
//MEGA is a MUST for this project
enum {
    Relay1 = 30, Relay2 = 31, Relay3 = 32, Relay4 = 33, Relay5 = 34, Relay6 = 35,
    Relay7 = 36, Relay8 = 37, Relay9 = 38, Relay10 = 39, Relay11 = 40,
    Relay12 = 41, Relay13 = 42, Relay14 = 43, Relay15 = 44, Relay16 = 45
};

enum { RELAY_OFF = HIGH, RELAY_ON = LOW };

enum {
    CROSSINGZONE_CLEAR, // no train in crossing area, also initialized state
    CROSSINGZONE_OCCUPIED, // train detected by the entry sensor
    CROSSINGZONE_EXITING  // train detected by the exit sensor, when sensor clears state = CLEAR
};

 enum {
     EXITSENSOR_CLEAR, // no train has passed the crossing gate exit sensor
     EXITSENSOR_ENTERED, // train detected by the exit sensor
     EXITSENSOR_WAITINGTOCLEAR // train passed by the exit sensor, when sensor clears state = CLEAR

 };

byte state = CROSSINGZONE_CLEAR;
 //*-----( Declare Variables )-----*/
// hardware is an optocoupler 16 channel 12V relay
const byte relays[] = { Relay1,Relay2,Relay3,Relay4,
Relay5,Relay6,Relay7,Relay8,
Relay9,Relay10,Relay11,Relay12,
Relay13,Relay14,Relay15,Relay16 };
enum { maxRelayCount = sizeof relays / sizeof relays[0] };

byte entrySensorPin = 26;
byte exitSensorPin = 28;
const char* soundFile = "trainxng.mp3";
boolean debugMode = true;
boolean exitSensorTripped = false;

// These are the pins used for the music maker shield
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)
// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see  http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

AccelStepper gateMotor1Left(AccelStepper::DRIVER, 4, 3);  // 1=Stepper driver option, 4=Step pulse pin, 3=Direction
AccelStepper gateMotor1Right(AccelStepper::DRIVER, 6, 5);  // 1=Stepper driver option, 6=Step pulse pin, 5=Direction
AccelStepper gateMotor2Left(AccelStepper::DRIVER, 8, 7);  // 1=Stepper driver option, 8=Step pulse pin, 7=Direction
AccelStepper gateMotor2Right(AccelStepper::DRIVER, 10, 9);  // 1=Stepper driver option, 10=Step pulse pin, 9=Direction
Adafruit_VS1053_FilePlayer musicPlayer =
    Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

class CrossingGate {
  public:
    // hmm voids or booleans?
    boolean GateFlashersOn(byte relayNumber) {
        digitalWrite(relayNumber, RELAY_ON);
        //need a check here to ensure its set LOW which is inactive for these relays
        return true;
    }
    boolean GateFlashersOff(byte relayNumber) {
        digitalWrite(relayNumber, RELAY_OFF);
        //need a check here to ensure its set HIGH which is inactive for these relays
        return true;
    }
    boolean GateArmFlashersOn(byte relayNumber) {
        digitalWrite(relayNumber, RELAY_ON);
        //need a check here to ensure its set LOW which is inactive for these relays
        return true;
     }
     boolean GateArmFlashersOff(byte relayNumber) {
         digitalWrite(relayNumber, RELAY_OFF);
        //need a check here to ensure its set HIGH which is inactive for these relays
        return true;
    }
    boolean GatesUp(byte relayNumber) {
        digitalWrite(relayNumber, RELAY_ON);
        //need a check here to ensure its set LOW which is inactive for these relays
        return true;
    }
    boolean GatesDown(byte relayNumber) {
        digitalWrite(relayNumber, RELAY_OFF);
        //need a check here to ensure its set HIGH which is inactive for these relays
        return true;
    }

};

 class CrossingGateRoad {
   public:
       void PowerOn(byte relayNumber) {
           digitalWrite(relayNumber, RELAY_ON);

       }
       void PowerOff(byte relayNumber) {
           digitalWrite(relayNumber, RELAY_OFF);

       }
};
//  Sensor methods
int CheckEntrySensor(byte esp) {
    if (digitalRead(esp) == HIGH)
    {
         state = CROSSINGZONE_CLEAR;
         return CROSSINGZONE_CLEAR;
    }
    else {
        state = CROSSINGZONE_OCCUPIED;
        return CROSSINGZONE_OCCUPIED;
    }
     return -1;
}
int CheckExitSensor(byte xsp) {
    if (digitalRead(xsp) == HIGH && state == CROSSINGZONE_OCCUPIED)
    {
        state = CROSSINGZONE_OCCUPIED;
        return CROSSINGZONE_OCCUPIED;
    }
    else if(digitalRead(xsp) == LOW && state == CROSSINGZONE_OCCUPIED)
    {
        state = CROSSINGZONE_CLEAR;
        return CROSSINGZONE_OCCUPIED;
    }
    return -1;
}

boolean CrossingBellsOn(Adafruit_VS1053_FilePlayer & mp, const char* soundFile) {
    if (!mp.startPlayingFile(soundFile)) {
        Serial.println("Could not open file trainxng.mp3 using the passed in object");
        while (1);
    }
    return true;
}
boolean CrossingBellsOff(Adafruit_VS1053_FilePlayer & mp) {
    if (mp.playingMusic) {
        mp.stopPlaying();
         return true;
    }
    if (mp.stopped())
    {
        return true;
    }
    return false;
}

CrossingGate xGate1Left;
CrossingGate xGate1Right;
CrossingGate xGate2Left;
CrossingGate xGate2Right;

CrossingGateRoad xGateRoad;

void setup() {
    Serial.begin(9600);
    // Set max speed. Steps per second
    gateMotor1Left.setMaxSpeed(500);
    gateMotor2Left.setMaxSpeed(500);
    gateMotor1Right.setMaxSpeed(500);
    gateMotor2Right.setMaxSpeed(500);
    // set motor acceleration
    gateMotor1Left.setAcceleration(35);
    gateMotor2Left.setAcceleration(35);
    gateMotor1Right.setAcceleration(35);
    gateMotor2Right.setAcceleration(35);
    // set motor speeds
    gateMotor1Left.setSpeed(20);
    gateMotor2Left.setSpeed(20);
    gateMotor1Right.setSpeed(20);
    gateMotor2Right.setSpeed(20);

    Serial.println("Adafruit VS1053 Library Test");
    // initialise the music player
    if (!musicPlayer.begin()) { // initialise the music player
         Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
        while (1);
    }
    Serial.println(F("VS1053 found"));
    //musicPlayer.sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working
    // check the card reader
    if (!SD.begin(CARDCS)) {
        Serial.println(F("SD failed, or not present"));
        while (1);
    }
    Serial.println("SD OK!");
    // Set volume for left, right channels. lower numbers == louder volume!
    musicPlayer.setVolume(20, 20);

    // This option uses a pin interrupt. But DREQ must be on an
    //  interrupt pin. For Uno/Duemilanove/Diecimilla that's Digital #2 or #3
    // See http://arduino.cc/en/Reference/attachInterrupt for other pins
    // * This is the preferred method
    if (!musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT))
        Serial.println(F("DREQ pin is not an interrupt pin"));

}
void loop() {

    switch (state) {
        case CROSSINGZONE_CLEAR:
          // Check entry sensor. If tripped, turn on the sound.
         if (CheckEntrySensor(entrySensorPin) == 1) {
            // first go around i'll try to tun all these here otherwise
            // I will break out to more states
            //these happen instantly
            xGateRoad.PowerOff(relays[0]);
            xGate1Left.GateArmFlashersOn(relays[1]);
            xGate1Right.GateArmFlashersOn(relays[2]);
            xGate2Left.GateArmFlashersOn(relays[3]);
            xGate2Right.GateArmFlashersOn(relays[4]);
            xGate1Left.GateFlashersOn(relays[5]);
            xGate1Right.GateFlashersOn(relays[6]);
            xGate2Left.GateFlashersOn(relays[7]);
            xGate2Right.GateFlashersOn(relays[8]);
            //these take some time
            xGate1Left.GatesDown(relays[9]);
            xGate1Right.GatesDown(relays[10]);
            xGate2Left.GatesDown(relays[11]);
            xGate2Right.GatesDown(relays[12]);
            //this is the last process, if it completes change state
            if (CrossingBellsOn(musicPlayer, soundFile)) {
                state = CROSSINGZONE_OCCUPIED;
            }
        }
        else {
            state = CROSSINGZONE_CLEAR;
        }
        break;
    case CROSSINGZONE_OCCUPIED:
        // Once zone is occupied, monitor the exit sensor
        if (CheckExitSensor(exitSensorPin) == 0) { // Exit sensor not tripped yet
            state = CROSSINGZONE_OCCUPIED;
        }
        else {
            exitSensorTripped = true;
        }
        if (exitSensorTripped)
        {
             // need to code here to wait until Exit Sensor has 1500 milliseconds where its clear
            // to indicate that the last car of train has passed it
            // if above set exitSensorTripped back to false and state to EXITING
            state = CROSSINGZONE_EXITING;
        }
        break;
    case CROSSINGZONE_EXITING:
        // Check if the train has cleared, then shut the sound.
        if (CheckExitSensor(exitSensorPin) == 1) {
            // first go around i'll try to tun all these here otherwise
            // I will break out to more states
            //these happen instantly
            xGateRoad.PowerOn(relays[0]);
            xGate1Left.GateArmFlashersOff(relays[1]);
            xGate1Right.GateArmFlashersOff(relays[2]);
            xGate2Left.GateArmFlashersOff(relays[3]);
            xGate2Right.GateArmFlashersOff(relays[4]);
            xGate1Left.GateArmFlashersOff(relays[5]);
            xGate1Right.GateArmFlashersOff(relays[6]);
            xGate2Left.GateArmFlashersOff(relays[7]);
            xGate2Right.GateArmFlashersOff(relays[8]);
            //these take some time
            xGate1Left.GatesUp(relays[9]);
            xGate1Right.GatesUp(relays[10]);
            xGate2Left.GatesUp(relays[11]);
            xGate2Right.GatesUp(relays[12]);
            //this is the last process, if it completes change state
            if (CrossingBellsOff(musicPlayer)) {
                state = CROSSINGZONE_CLEAR;
            }
        }
        break;
    }
}

What do the debugging prints show?

Just checked this last versions of your code. Looks to me like it should work, but I have a bunch of comments and suggestions: the code would be clearer if you get rid of unused stuff (EXITSENSOR_*, maxRelayCount, GateFlashersOff(), the AccelSteppers). The state should have the proper enum as its type instead of byte. Do not change the state in the checkSensor() methods. Failure of playing the sound should not prevent the state to become OCCUPIED...

...exitSensorTripped is useless: case CROSSINGZONE_OCCUPIED: if (CheckExitSensor()) state = CROSSINGZONE_EXITING; break; is enough. The various else { state = the_current_state; } are useless. The return values of the CrossingGate methods are never checked. The pin numbers should be private data of CrossingGate rather than method parameters. Only two methods are needed in CrossingGate: open() and close(), the details can be taken care of by the class.

@Edgar... I did some refactoring on plane ride home. I had already removed the EXITSENSOR...ENUM and refactored my other enums to use C++11 style i.e. enum class CrossingRoadState {blah = 0,blah1 = 1}. The problem in the exiting zone is that 2 things have to happen. The exit sensor trips BUT then I have to monitor it to capture when two full seconds of HIGH (which I believe is inactive) THEN set back to Clear, as once exit sensor is tripped the train is still passing it making the sensor bounce back and forth HIGH/LOW.

Re. " The return values of the CrossingGate methods are never checked." I already changed all the methods in the class to voids from booleans.

Elaborating on JRobert's answer, which I think is definitively the way
to go. Here is a typical way of writing a state machine with only three
states:

No train in the area. You are monitoring the entry sensor.
You have detected the train on the entry sensor. You started playing
the sound. You are monitoring the exit sensor.
You have detected the train on the exit sensor. You are still
monitoring the same sensor in order to know when the train clears the
area.

Notice that the actions you perform (starting and stopping the sound
for instance) are not associated with a particular state but with a
transition between states: you start the sound on the 1 → 2
transition and stop it on 3 → 1.
Here is the code for loop():
void loop() {
    static enum {
        NO_TRAIN,        // no train in the area
        TRAIN_ENTERED,   // train seen by the entry sensor
        TRAIN_EXITING    // train seen by the exit sensor
    } state = NO_TRAIN;  // initial state

    switch (state) {
        case NO_TRAIN:
            // Check entry sensor. If tripped, turn on the sound.
            if (checkEntrySensor()) {
                musicPlayer.startPlayingFile("trainxng.mp3");
                flashers.turnOn();
                gates.close();
                road.powerDown();
                state = TRAIN_ENTERED;
            }
            break;
        case TRAIN_ENTERED:
            // The exit sensor must be monitored.
            if (checkExitSensor()) {
                state = TRAIN_EXITING;
            }
            break;
        case TRAIN_EXITING:
            // Check if the train has cleared, then shut the sound.
            if (!checkExitSensor()) {
                musicPlayer.stopPlaying();
                flashers.turnOff();
                gates.open();
                road.powerUp();
                state = NO_TRAIN;
            }
            break;
    }
}

This may be a bit oversimplified: if an action need some time, you may
have to create an extra state for it. For example, in order to avoid
blocking the program while the barrier goes down, you can split the
transition NO_TRAIN → TRAIN_ENTERED in two:
NO_TRAIN → LOWERING_BARRIER → TRAIN_ENTERED

and the action “lower the barrier” is itself split into “start lowering
the barrier” (on the first transition) and “stop lowering the barrier”
(on the second transition).

Thank you for the example. I've followed essentially the same path except I have it broken down to 12 states as there are other processes that need to run when the entry sensor trips

@dinotom: If those processes can be started fast, and you can afford waiting for them, you can live with only three states. See amended answer.

Although I am traveling and don't have the hardware to test this with me. I've updated the post to include the new state machine code. Any comments appreciated.

This is a classic state-machine problem. That isn't the only way to do it but it's just made for this kind of problem, one in which only certain external events are interesting at a given time; and when such an event occurs, the controller must tweak the outside world in some way, and then start paying attention to a different set of interesting events.
Does playing a sound file totally occupy the Arduino until the sound is done? And if so, can your process tolerate the controller being unresponsive for the duration of the sound track? Because otherwise you'll need something more capable than an Arduino, or you'll need to be able to program the Arduino to feed the sound in small pieces to a buffered sound card, so it (the Arduino) can continue monitoring the interesting set of possible events while the sound is playing. That probably means some clever programming with the SimpleTimer library or similar, or using interrupt service routines to inform some part of your code when an event occurs. Probably the ideal cases would be to have a "sound machine" that can play 'n' different tracks, and would do so autonomously when told to start playing track 'j'. Begins to sound like another MCU just handling sound, doesn't it?
Update:
Look up state machine diagrams - basically circles representing states and arrows representing transitions to a new state in response to an events. There are several ways to put the state machine's control of the external equipment; my choice is that each state "does something" then "waits for something to happen", where something to happen may include a clock signal indicating the event(s) it was waiting for didn't happen (i.e. a timeout). Look at some state diagrams to get an idea how they are used, then start diagramming your own project.
I draw the "happy path" straight down the page - that path that represents the normal or expected operation - with less usual or error paths drawn to either side. At that point you should be pretty confident in your algorithm.
There are several ways to code state machines - that'll be a further discussion.

the way I've defined the shield, uses its interrupts and other events and processes can occur while its playing (at least according to the documentation) Any examples or references to point me to for the state machine method or operating this ?

I found something to work from.

State 0: pinging entry sensor to determine when it changes state (S)
State 1: crossing gate sound playing (T)
State 2: crossing gate arms lowering (T)
State 3: crossing gate flashers flashing (T)
State 4: road power turned off (T)
State 5: pinging exit sensor to determine when it changes state (S)
State 6: once triggered, continue pinging exit sensor to determine when it changes back (S)
State 7: crossing gate sound off (T)
State 8: crossing gate arms raising (T)
State 9: crossing gate flashers off (T)
State 10: road power turned on, return to state 0 (T)....You agree with these states?

Would love some guidance on this as I've never coded a state machine before.Ill work on it tonight and tomorrow. Ill create a new post sometime late tomorrow if I run into trouble.

Sure, see my profile.

I think your problem here is that you are using multiple instances of Adafruit_VS1053_FilePlayer.
Namely:
Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

That's two already.
Then you pass a copy here:
Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {

And return another copy:
return mp;

All this creating/destroying copies is probably stopping the playback of the current copy.
I've reworked your code to avoid all that:
#include <Adafruit_VS1053.h>

// These are the pins used for the music maker shield
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

// create shield-example object
Adafruit_VS1053_FilePlayer musicPlayer (SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

//global variables required
boolean crossingSignalInOperation = false;
boolean signalEntrySensor = false;
boolean signalExitSensor = false;
boolean debugMode = false;

boolean checkEntrySensor() {
    //check entry sensor, if tripped return true otherwise false
    /*if () return true;
    return false;*/
    return true;  //hardcoded for testing
}

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    debugMode = true;   //set this to false once code is fully operational
    //initialise music maker shield
        if (!musicPlayer.begin()) {
            if (debugMode)
            {
                Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
            }

        while (1);
    }
    // 1st parameter is left, second parameter is right
    musicPlayer.setVolume(20, 20);
    if (debugMode)
    {
        Serial.println(F("VS1053 found"));
    }

    // initialise the SD card
    SD.begin(CARDCS);

    //ensure our global booleans all start false
    crossingSignalInOperation = false;

}

void loop() {
    // put your main code here, to run repeatedly

    signalEntrySensor = checkEntrySensor();
    if (signalEntrySensor == true) {  //only want to catch the FIRST time it senses
        if (crossingSignalInOperation == false)
        {
            //crossing signal is inactive, activate it
            // turn the sound on and return the music player object
            onSignalSound(musicPlayer,"trainxng.mp3");

            while (musicPlayer.playingMusic) {
                // file is now playing in the 'background' so now's a good time
                // to do something else
                if (!crossingSignalInOperation)
                {
                    crossingSignalInOperation = true;
                    //run the other three processes
                    //offRoadPower();
                    //lowerSignalArms();
                    //startSignalFlashers();

                }
            }
        }
    }
 }

void onSignalSound(Adafruit_VS1053_FilePlayer & mp, const char* fileName) {
    // Play the train crossing sound file
    if (debugMode)
    {
        Serial.println(F("Playing track - "));
        Serial.print(fileName);
    }
    //all sound files are on the micro sd card on the music player shield
    if (!mp.startPlayingFile(fileName)) {
        Serial.println(F("Could not open file "));
        Serial.print(fileName);
        while (1);
    }
}
boolean offSignalSound(Adafruit_VS1053_FilePlayer & mp) {
    if (mp.playingMusic)
    {
        mp.stopPlaying();
        return true;
    }
    return true;
}

Untested, because I don't have the hardware, but that should work better.
The Adafruit_VS1053_FilePlayer object is passed by reference to the function, which avoids another copy being made. We are using the original one at global scope, so we don't keep creating and discarding copies. In fact, since we are using the global one you could avoid passing it to the function at all.

Ok. I see your point . 2 things, the Adafruit library defines the object the way I wrote it... Adafruit_VS1053_FilePlayer musicPlayer =
Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);    Unless that's a C++ specific way of declaring variables? That wouldn't fly in C#

And what is the ampersand for in the sound on function music player parameter?

Opening port
Port open
VMDPV_1|1_VMDPV
VS1053 found
Playing track -
trainxng.mp3.... is the out put to the serial mointor, but the file still only plays for a split second, with your changes

Unless there is something different about C++ vs C# my function is of type Adafruit_VS_FilePlayer, not creating a new one and I'm passing in the originally created one, so not creating another one there either. My code and your update are both functioning identically. And mine is returning the original instance

The ampersand passes a variable by reference. Normally variables are passed by value. To pass by value a copy is made. I'm passing in the originally created one - a copy of the original one. And why return it? You already have it at global scope. My code and your update are both functioning identically - you are running my code exactly as posted?


text:
User callback functions
I want to write a class that allows the user to attach his own function to a member function that listens for messages coming from a wireless module, so that the user's function can be called depending on the message.
I am thinking about using function pointers but I don't know how it will work since I don't know the user's function parameters, return type and number of functions that will be added.
//sketch.ino

<unknown> (*funcPtr)(<unknown>)[<unknown>];

void receive() {
  message.type = 'o';
  if (message.available()) {
    message.receive();
  }
  switch (message.type) {
    case 'p': {
      Serial.println(p);
      break;
    }
    case 'f': {
      funcPtr[message.funcID](message.parameter1, message.parameter2);
      break;
    }
    default: break;
}

void userFunction1() {
  Serial.println("User function 1");
}

int userFunction2(int x) {
  return x * 2;
}

funcPtr[0] = &userFunction1;
funcPtr[1] = &userFunction2;

void setup() {}

void loop() {
  receive();
}

Is this kind of thing possible?

I don't know the user's function parameters,

A common way for dealing with this issue is to pass a generic pointer to
arbitrary data. See below.

return type

It makes little sense to allow for arbitrary return types, as your
library would have no way of knowing what to do with the returned value.

and number of functions that will be added.

Either you allocate the callback array statically with a fixed size, or
you use dynamic allocation. In the first case, the array size could be
decided by the user if it is a template parameter. In the second case,
you risk memory fragmentation unless all the callbacks are registered
once and for all at program startup, which is a common scenario anyway.

About the generic pointer technique
This is a very common way of defining callbacks in C: a callback
contains both a function and a void * pointer to arbitrary data, which
will be given as a parameter to the function. It is up to the user to
decide if and how he will use this pointer: he could completely ignore
it, like he could make it point to the root of a complex data tree.
Here is a simple example:
// A callback contains both a function and a pointer to arbitrary data
// that will be passed as argument to the function.
struct Callback {
    Callback(void (*f)(void *) = 0, void *d = 0)
        : function(f), data(d) {}
    void (*function)(void *);
    void *data;
};

Callback callbacks[3];

// This callback expects an int.
void print_int(void *data)
{
    int parameter = * (int *) data;
    Serial.println(parameter);
}

// This one expects a C string.
void print_string(void *data)
{
    char * parameter = (char *) data;
    Serial.println(parameter);
}

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

    // Register callbacks.
    static int seventeen = 17;
    static int forty_two = 42;
    static char hello[] = "Hello, World!";
    callbacks[0] = Callback(print_int, &seventeen);
    callbacks[1] = Callback(print_int, &forty_two);
    callbacks[2] = Callback(print_string, hello);
}

void loop()
{
    // Test all the callbacks.
    for (size_t i = 0; i < 3; i++)
        callbacks[i].function(callbacks[i].data);
    delay(500);
}

Notice that the two callback functions take different types of
parameters, only disguised into the same generic pointer. Notice also
that print_int is used in two different callbacks with different data.
In this example, the data does not change, but this need not be the
case: both the callbacks and the rest of the user code could change the
data pointed to by the generic pointers. Again, it is up to the user to
decide how he will use this facility to communicate between his
callbacks and the rest of his code.

Thank you for your answer and sorry for the delay. I modified it to take the address of the function, send it to the server (without saving it on the Arduino), then sending the address back from the server to the Arduino with information about how to recast it into function pointer.

You are a life saver my man!!!

You can't call arbitrary functions (with random return types, and any number of arguments) but you can specify a callback function that takes a certain number of specific arguments, and returns a certain thing (or nothing).
See http://www.gammon.com.au/callbacks
Example code:
typedef void (*GeneralMessageFunction) ();

void sayHello ()
  {
  Serial.println ("Hello!");
  }  // end of sayHello

void sayGoodbye ()
  {
  Serial.println ("Goodbye!");
  }  // end of sayGoodbye

void checkPin (const int pin, GeneralMessageFunction response); // prototype

void checkPin (const int pin, GeneralMessageFunction response)
  {
  if (digitalRead (pin) == LOW)
     {
     response ();  // call the callback function
     delay (500);  // debounce
     }
  }  // end of checkPin

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (8, INPUT_PULLUP);
  pinMode (9, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  checkPin (8, sayHello);
  checkPin (9, sayGoodbye);
  }  // end of loop

I don't know how it will work since I don't know the user's function parameters, return type and number of functions that will be added.

You will need to tell the user what sort of function to write. For example, a function that takes a string (ie. the message) and returns a boolean (whether it was handled or not).

Thank you for the answer, I went with the other method, because it was closer to what I needed.


text:
How to get power for a nexus 7 while reading serial data from an arduino over usb?
Does anyone know how to simultaneously power a Nexus 7 tablet while simultaneously reading serial data from an arduino over USB? I have had quite some trouble with this and have attempted multiple combinations of usb splitters but no luck. I have also tried to use the nexus's inductive charging while using the arduino usb power. While this does work I need to use the Nexus NFC chip at the same time. What I really need is a solution that allows me USB Data, NFC, and power all at the same time.

You could make a custom cable with three plugs. Connect all red and black wires, but only the other two between the arduino and the nexus. When you plugin the third plug into an DC-Source, both devices get powered. The serial connection should work. Did this with an openmoko freerunner once.

Do you have any tutorials or articles you could point me to for how to get started with this?

I have been at this for 3 days with no luck. Ive cut up and spliced every combination of usb cable i can think of. Does anyone else have any other thoughts?

Oh, I remember that I had to solder a resistor somewhere to make the phone charger think, he can deliver more mA. The charger tend to limit the power to 500mA, which may not be enough though. Try to trick the charger into thinking, that he could provide more mA, because the client can "load" faster. Also try a completely different power supply, preferably not a phone charger.

I can speak only to the USB power, and this is a good article (you can ignore the parts about USB-C): https://www.androidauthority.com/usb-type-c-and-3-1-explained-656552/
To be clear, it's POSSIBLE you wired the cable correctly (did communication work??) but without the resistor then the Nexus will deliberately limit it's power draw to 500ma, or not try to charge at all.  a USB OTG cable might also do the trick..


text:
Trying to send data to the server and AT+CIPSEND not working correctly
Sending data to the server(thingspeak.com/184.106.153.14) with AT commands on serial monitor works fine but whenever i upload the sketch ,the following always return false if(Serial.find( ">" ) ). I am not sure if AT+CIPSEND is not working correctly or what. I am using Arduino with ESP8266. Any help will be appreciated.Thanks you in advance. Here is my code.
  #include <SoftwareSerial.h>
  SoftwareSerial softSerial(2, 3); // RX, TX

  #define SSID "myssid"
  #define PASS "Mypass"
  #define IP "184.106.153.149" // ThingSpeak

  void setup()
  {
   uint32_t baud = 9600;
   Serial.begin(baud);
   softSerial.begin(baud);

   connectWiFi();
   }

   void loop()
   {
    updateTS();
    }

    void updateTS()
    {
    String cmd = "AT+CIPSTART=\"TCP\",\"";// Setup TCP connection
    cmd += IP;
    cmd += "\",80";
    sendDebug(cmd);
    delay(2000);

    String url = "GET /update?key=P55Z0BDASNQBFQKT&field1=15&field2=25\r\n\r\n"; //hard code value 15 and 25
    String stringLength="AT+CIPSEND=";
    stringLength +=String(url.length( ));
    Serial.println(stringLength);
    //delay(10000); I even tried to delay for few seconds

   //Here is where it fails,it jumps to closing the connection
   if(Serial.find( ">" ) )
    {
     softSerial.print(">");
     softSerial.print(cmds);
     Serial.print(cmds);
    }
    else
    {
     sendDebug( "AT+CIPCLOSE" );//close TCP connection
    }

    }

   void sendDebug(String cmd)
    {
      softSerial.print("SEND: ");
      softSerial.println(cmd);
      Serial.println(cmd);
     }

     boolean connectWiFi()
    {
      Serial.println("AT+CWMODE=1");
      delay(2000);
      String cmd="AT+CWJAP=\""; // Join accespoint
      cmd+=SSID;
      cmd+="\",\"";
      cmd+=PASS;
      cmd+="\"";
      sendDebug(cmd);
      delay(5000);
      if(Serial.find("OK"))
      {
       softSerial.println("RECEIVED: OK");
       return true;
      }
      else
      {
       softSerial.println("RECEIVED: Error");
       return false;
       }
     }

To what Arduino pins have you connected the ESP?

On arduino i made pin 2 as Rx and 3 as Tx.All these go through logic converter. But like i mentioned above when i run the AT commands on serial monitor data get sent fine to the server only when i upload the sketch.

Your code looks like you connected the ESP to the hardware serial port, but your comment says otherwise so:
Your sketch isnt working because you're writing to the wrong serial port half the time, and even when you do use the right serial port (softSerial) you're sending garbage along with it.
Serial.println(stringLength); and Serial.find("OK") should be softSerial.println(stringLength); and softSerial.find("OK").
Serial.find( ">" ) should be softSerial.find( ">" ). You should look for '>' in the buffer between the Arduino and the ESP8266 and not the one between the Arduino and the PC.
softSerial.print(">");, softSerial.println("RECEIVED: OK"); and similar statements should not be there at all. They are not commands or arguments to a command so why are you printing them to the ESP? Whenever you write to softSerial, make sure its a command. Dont send your debug messages to softSerial; use Serial instead.
There's no variable called cmds and yet you're printing it to the serial port. Assuming this code compiled, its probably a typo in your question?
Finally, your code structure is unreliable at best, what with all the delays in it and not a single Serial.available() or softSerial.available(), not to mention the abundant usage of Arduino Strings. I suggest you first learn how to read from a serial port and build C strings from the results and then re-design your code again. Majenko's blog is as good a tutorial as any. Or you could download a library like this one that provides an easy API to the ESP8266, shielding you from the mess of AT commands, while providing you with example sketches that already do what you want. Of course, you could choose to go through their library (.cpp and .h files are the place to be) and figure out how they used AT commands with the ESP and then write your own sketch, library or whatever. Good luck.


text:
'Non-Deterministic' memory usage on Arduino
I had a problem with a memory leak in my sketch and cornered it with MemoryFree.h. This works great and I was able to fix my leak.
My sketch is not really static, but My var sizes are. I observed, that the free memory on the arduino reaches a different values and stays there.
For Example

Run 1: 1655 Bytes Free
Run 2: 1659 Bytes Free
Run 3: 1654 Bytes Free

For every run, I get a different, but over a short time, fixed memory usage. Is this normal?
P.S: The serial input to the script just repeats forever with the exact same data.

You haven't posted any code, so any answer is guesswork. However ... if your code makes decisions based on external events (eg. readings from sensors) then it may allocate memory differently, and in a different order, each time.
Sometimes memory allocation leaves gaps (known as "heap fragmentation"). Small differences in your results probably show slightly different sized gaps, due to the allocation order.

Indeed, I added no code, because I wanted an abstract answer. Since it is just an observation, not a real problem. Thanks anyway.

I see. This site is not supposed to be used to ask questions which are not about real problems. I am pleased I could help, but please ask practical questions in the future, about real problems.

Thanks for your reply and any bit of information, you shared with me. I am fully aware of the rules and would categorize this as 'potential real future problem'.


text:
PFC8574 4x4 keypad: correct wiring?
I bought a few PFC8574 and 4x4 keypads for a small project. I'm unclear on the correct wiring of the keypad to the PFC8574.
On the Arduino Playground's site, there are pull-up resistors for each column, but on a few other sites (like this one that I can't read, but I understand a schematic and there's a third example too, but I don't have the reputation to post it), the wiring does straight into the IC.
Does it depend on the library that's being used?  Or what am I missing?
Thanks!

Ok look at this image:

I'm not sure how your keypad is layed out but if you use a probe pin to test your connections via a multimeter, you can mark which ones correspond to the image.
I am ASSUMING you are going to use the code from arduino playground.
This is the format:
Pins of keypad (IN THE IMAGE) - Pins of PFC8547
Here are the pin connections:
1 - nothing
2 - 9
3 - 4
4 - 6
5 - 7
6 - 10
7 - 11
8 - 5
Also include the pull-up resistors.
Your ABCD keys will be ignored
(This is like wiring a bomb...)


text:
Ethernet shield or Wifi sheild - Arduino?
To control some LEDs through internet using Arduino UNO, which type of connection  is better ? Ethernet or Wifi? (Later, I may connect some relays instead of LEDs, and control (turn on and off) some devices using this setup).
The only difference I know is the wired and wireless connectivity.
Is there any other difference?

If you are beginner with Arduino its better to start with Ethernet Shield. Its much more easy to connect with Arduino.
WiFi Module - ESP8266 required some more knowledge, that you will learn in future.
The bought products are cheap, so you can start with Ethernet and after that to switch to ESP.


text:
Using Processing to send data to Arduino
  import processing.serial.*;
import java.io.*;
Serial myPort;
int mySwitch;
String transmitter[] = new String[1280000]; //initialize array

void setup(){
         mySwitch=1;
         //Open the serial port for communication with the Arduino
         //Make sure the COM port is correct
         myPort = new Serial(this, "COM6", 9600);
         myPort.bufferUntil('\n');
}

void draw() {
        if(mySwitch == 1)
        {
           readData("input.txt");
           int index = 0;
           while(index < 128000)
           {
             myPort.write(transmitter[index++]);
             if(index%128 == 0)
               delay(100);
           }
        }

         mySwitch = 0;
}

void readData(String myFileName){

         File file=new File(myFileName);
         BufferedReader br=null;

         try{
           br=new BufferedReader(new FileReader(file));

           String transmit=null;
           int i = 0;
           /* keep reading each line until you get to the end of the file */
                while((transmit = br.readLine()) != null)
                   transmitter[i++] = transmit;

         }catch(FileNotFoundException e){ e.printStackTrace(); }

         catch(IOException e){ e.printStackTrace(); }

         finally{
                 try {
                   if (br != null) br.close();
                 }
                 catch (IOException e) { e.printStackTrace(); }
         }
}

In the above code, I have an String array and I'm reading lines from a file and saving them as strings. How would I save them as byte/char inside an array of byte/char?
Basically, I have a file of integers on each line, each integer in the range [0, 255]. And I want to read this integer and send it to the Arduino. The Arduino serial.read() function reads a byte at a time. This is the issue I am trying to solve.

Hi, please could you give us an idea of what you have tried or written and what your results have been so far.

Well I am writing each index in my transmitter array and each index holds a "String" value. Thus, serial.write() will write a string to the serial port. However, I want it to write it as an integer for the purposes of speed and efficiency.

how are your values arranged on each line of the file?

just a number in the range of [0, 255] on each line. No other splits such as comma, etc.

I believe I have actually found a very efficient solution to this problem by re-writing the code the following way by using the "Scanner" class and not the "BufferedReader" class. Any input on making this more efficient is welcome!
import processing.serial.*;
import java.io.*;
import java.util.*;
Serial myPort;
int mySwitch;
Scanner file;
byte transmitter[] = new byte[1280000]; //initialize array

void setup(){
    mySwitch=1;
    //Open the serial port for communication with the Arduino
    //Make sure the COM port is correct
    myPort = new Serial(this, "COM6", 9600);
    myPort.bufferUntil('\n');
}

void draw() {
    if(mySwitch == 1)
    {
        readData("input.txt");
        int index = 0;
        while(index < 128000)
        {
            myPort.write(transmitter[index++]);
            if(index%128 == 0)
                delay(100);
        }
    }

    mySwitch = 0;
}

void readData(String myFileName){
    try{
      file = new Scanner(new File(myFileName));
    }
    catch(Exception e){System.out.println("NOT FOUND!");}

    int i = 0;
    while(file.hasNextByte())
      transmitter[i++] = file.nextByte();

    file.close();
}


text:
Regarding the output voltage and current in arduino
This is basically an off-shoot from https://arduino.stackexchange.com/questions/20569/unexpected-output-pin-behavior-was-relay-on-off-doesnt-loop. It's the same schematics and so on, however, I'm now wondering what the output voltage and current is.
I've a 9V battery and the MOSFET transistor from the arduino starterpack (doesn't say the specs) connected to the 5V pin on the board. I need the following output current/voltage for it to activate a solenoid:

6V: 160 mA
7V: 190 mA
8V: 220 mA
9V 240 mA
10V :270 mA
11V :300 mA
12V :320 mA

and I'm just not sure how to calculate it since I'm not sure about the output from the transistor and all the way to the solenoid.
The solenoid: http://www.electrokit.com/en/plastic-water-solenoid-valve-1-2-12v.51108

Your transistor is backwards: you should ground the emitter and connect the collector to the solenoid. Also, put a few hundred ohms between it's base and the Arduino output.

In fact he says it's a mosfet, so even the schematic symbol is wrong. Now.. Can you rephrase the question so that we can understand what is the question? I mean, what are those numbers? You said you have a 9V battery, so what is 6V? and 12V? And if your question is "will the transistor be able to let 240mA pass?" the answrer is "it depends". Usually it can, because that current is quite low, but you will have to read its specifications (aka datasheet) to be sure..

the transistor is connected as: (left) gate to pin 9, (middle) drain to the solenoid, (right) source to gnd. I thought the schematics would help even with errors in it but maybe it caused more confusion instead! The numbers are the current and voltage needed for the valve-solenoid to open/close., "relay" in the image.. ugh, another error

You don't need to "calculate" anything with a MOSFET.  You will be using it in the saturation zone. That means it is fully turned on and will allow through the current you need.
However, the gate of a MOSFET looks, to all intents and purposes, like a small capacitor. That means there will be a certain amount of inrush current to the gate when you turn it on. To limit that inrush current you need a small resistor (say 100-220Ω) on the gate.
When using a BJT, though, you need to ensure that you allow enough current through the base to allow enough current through the collector.  Divide the current you need through the collector by the Hfe (typically 100 for a small signal transistor) and that is the minimum current you need to allow through the base. Subtract a silicon junction voltage (0.6V) from the voltage of the IO pin (5V). Divide it by your base current calculated above, and that is the maximum resistor you can use on the base.
And also your transistor symbol in your schematic is backwards.

I think it works better now than before when I added a 220Ohm resistor.  Not sure if it's the solenoid that doesnt open enough when I connect it to a valve so perhaps it's the solenoid that is broken or bad quality

Ok, so the retailer told me that a 9V battery is too weak because of the inner resistance. I need something like http://www.electrokit.com/en/timer-1s60h-startstop.50293

9V PP3 batteries are not suitable for anything. I rue the day someone first posted a tutorial online using one with an Arduino. If you must use batteries, use AAA or AA batteries (6), or a 7.4V LiPo.

Oh, I actually used the arduino starterpack guide tutorial 09 - motorizzed pinwheel, although I removed some stuff and switched the DC motor out for a the solenoid, and they are using a 9V batteri. In any case, I'll try it out with another battery say http://www.amazon.co.uk/Duracell-MN21-A23-12V-Batteries/dp/B001PAZU0Y


text:
Can I reassign my Arduino Uno COM Port?
The Arduino SW, under Tools, identifies my Uno as COM Port 3. However, COM Port 3 on my computer is in use by a chip set. My computer assigned COM Port 4 to my Arduino Uno.
Can I reassign my Uno to COM Port 4?
Edit: This question also applies to people who don't have administrative privileges. They do not have privileges to change the port via Windows Device Manager.

If the Arduino IDE identified your Uno as COM Port 3, your computer most likely has already assigned COM Port 3 to your Uno. You can double check the port assignment in Device manager > Ports.

The issue is that I am not an admin and do not have the ability to re-assign ports on the computer. Therefore, I would like to Re-assign the port that Arduino is requesting. It can't be that hard.

This is not an answer. You can reassign the com port via the device manager... Assuming you are on a Windows PC

You can change your COM Port number for a device by following these instructions:
http://plugable.com/2011/07/04/how-to-change-the-com-port-for-a-usb-serial-adapter-on-windows-7


text:
How can I control neopixels attached to a Digispark?
I want to use a string of Neopixels attached to a Digispark hanging off of a RasPi3 as indicators for various situations.  For example: a motor (connected to a driver hat on the I2C bus of the RasPi) turns on or reverses direction.  Can I use Firmata, or is there something like it for the Digispark that I can use with Python?

It's a ATTiny85, right? The NeoPixel library seems to support it. But it might not be able to control a lot off them. Check the RAM usage and current draw

What is a Digispark? It is a company, no? :)

Digispark is a tiny Arduino compatible (sort of) ATiny85 dev board first released by the company Digistump.  I should have mentioned that I HAVE managed to get Adafruit's strandtest example loaded and working.

Damn edit limitations caught me--The Digispark plugs into a USB port like a dongle, and uses pins 3 and 4 for USB communication, but apparently it's "wierd" in ways I don't quite understand.  There is a deprecated sketch "digiUSB" and a newer one "digiCDC" but they're a little beyond what I grok at this point.  I guess I should take a closer look at them.

You can drive APA102 bases strips from the raspberry pi (though they might need 3.3v to 5v logic level converteren).

Also, I've found a source explaining on how to use the NeoPixels with an Raspberry Pi direclty: http://popoklopsi.github.io/RaspberryPi-LedStrip/#!/ws2812

You need a dedicated microcontroller since you need very precise timing for controlling the neopixels. It works well on an ATTiny85, we are using Adafruit Trinket boards to control Neopixels and work well. So far up to 12 pixels :)
You can download a Trinket Neopixel library, which is modded for an internal osc ATTiny85 from Adafruit.
Then your Raspi can talk to the microcontroller. It is a little problematic, though, since the software serial port handling consumes too much memory on ATTiny, and the ATTiny will ignore all serial input while refreshing the neopixels. Therefore you may get it easier by using an Arduino UNO, or Leonardo or Micro which is powerful enough for many pixels, and have a built-in hardware serial port.
As a matter of fact, you can talk to these Arduino boards as if it would be a serial port, so just plug in a Leonardo over USB and you'll get a new serial port in Rpi to talk to.

I'm using a max of 8 pixels, and I've already gotten strandtest to work.  I need to wrap my head around how to get it to talk to the Raspi using Python, the way Firmata does.  The fact that it plugs in like a dongle is a very attractive feature for me.  Tho, if I can't get the Neopixels to turn on and off under the Raspi's control, I guess that's a moot point.

Send the RGB value through the USB/serial/COM port. And read them at the Arduino side. Then set your strand accordingly.

Afaik, Firmata is for low-level bit-banging of the ports of the Arduino side. You can nicely turn them on and off, however the speed and timing is not good enough to simulate the Neopixel communication.
I am afraid you need to make your hands "dirty", and extend the strandtest app with handling of serial commands, instead of fiddling with Firmata.

A circuit can be made using two 74HC121s and an OR gate that would be connected to the SPI peripheral in the microcontroller. The timing would be accomplished by the multi-vibrators while each byte would be output through the serial port.