# Question
Title: 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
}

```

# Answer
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);

```
> 1 votes

# Answer
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:

1. whether your port is open and working at all; and
2. 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.
> 0 votes

---
Tags: arduino-uno, sensors
---


title: Employing C++ code for Arduino

text:
# Question
Title: 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:

1. Got a 24 bit bitmap (some random image)
2. Extracted the RGB data for each pixel using Matlab
3. 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
4. Want to get these 3 arrays for use in Arduino sketch for further working
5. Stuck here - how to do that .....
6. 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.
7. 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.
8. 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.
9. 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;

}

```

# Answer
> 3 votes
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.

# Answer
> 2 votes
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
  }
}

```

# Answer
> 1 votes
> 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.

# Answer
> -1 votes
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.

---
Tags: programming, c++, arduino-due, matlab, array
---


# Question
Title: 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);
    }
}

```

# Answer
> 1 votes
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.

---
Tags: mpu6050
---


# Question
Title: '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

1. Run 1: 1655 Bytes Free
2. Run 2: 1659 Bytes Free
3. 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.

# Answer
> 2 votes
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.

---
Tags: programming, memory-usage, debugging
---


# Question
Title: 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?

# Answer
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.
> 1 votes

---
Tags: arduino-uno, wifi, ethernet
---


title: User callback functions

text:
# Question
Title: 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?

# Answer
> 6 votes
> 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.

# Answer
> 3 votes
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).

---
Tags: c++, pointer, callbacks
---


# Question
Title: 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

# Answer
> 2 votes
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.

---
Tags: arduino-uno, relay, transistor
---


title: PFC8574 4x4 keypad: correct wiring?

text:
# Question
Title: 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!

# Answer
> 1 votes
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...)

---
Tags: arduino-uno, i2c
---


title: Proper way to run functions in loop

text:
# Question
Title: 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;
    }
}

```

# Answer
> 2 votes
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:

1. No train in the area. You are monitoring the entry sensor.
2. You have detected the train on the entry sensor. You started playing the sound. You are monitoring the exit sensor.
3. 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).

# Answer
> 1 votes
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.

# Answer
> 0 votes
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.

---
Tags: arduino-uno, programming, sound
---


title: Can I reassign my Arduino Uno COM Port?

text:
# Question
Title: 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.

# Answer
> 1 votes
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.

# Answer
> 0 votes
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

---
Tags: usb, uploading
---


# Question
Title: 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.

# Answer
> 0 votes
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();
}

```

---
Tags: processing-lang
---


title: Arduino (Or Raspberry Pi) As HID Device

text:
# Question
Title: Arduino (Or Raspberry Pi) As HID Device
I have an Arduino Uno and A Raspberry Pi B+. I was wandering how I could use either as a Programbel HID Device (EX: https://srlabs.de/badusb/). The Reason I ask under the arduino section is I want to preferably use it. If not I can use either.

# Answer
The Uno cannot be used as a HID device through the on board USB. You might be able to use the V-USB Library to be a HID device using the digital IO pins. See this tutorial.

There are several arduino compatible boards that do can act as a HID device natively. Most boards built around the ATMega32u4 can be a HID device. For example the Arduino Micro

See this question about the Raspberry Pi.
> -1 votes

---
Tags: arduino-uno, raspberrypi
---


# Question
Title: Streaming audio from PC to Arduino over WiFi
Say I wanted to, *purely hypothetically*, set up a pirate radio station by connecting an Arduino to a WiFi network away from home, streaming music to the Arduino, decoding it, and broadcasting it with an FM transmitter.

Given an **Arduino (Genuino) Uno**, a **Sparkfun ESP8266 Thing Dev** breakout board for WiFi connectivity, and an **Adafruit Si4713 Stereo FM Transmitter** breakout board, how would I go about the actual streaming of music (in MP3 or WAV format) from a (Windows) computer to the Arduino over WiFi? Would an Arduino Uno be powerful enough for this? Which components would I need to decode the audio?

# Answer
> 4 votes
Well, a sort of... You can stream 64kbps MP3, get it via wifi from esp8266. Then for all the rest, forget the Arduino.

You need a dedicated MP3 decoder chip (many out there, sta013 was one of the oldest beasts) which can take the digital mp3 stream and convert it to analog output.

You can feed the line level analog output to the FM Transmitter, and then you're golden.

Note that you shall develop some application on the PC to actually stream out the MP3 - an off the shelf solution such as a Shoutcast server may not work, as the usual web-radio stations inject station data and currently played track metadata into the mp3 stream what you have to remove from the MP3 decoder chip.

Since the actual wifi bandwidth with ESP is limited (as well as the processing power of the Arduino), you may switch to a more efficient compression format. For example, a 64kbps WMA sounds far better than a 64kbps MP3, and at 64kbps AAC is superior to any of the other formats. Ensure that your decoder chip can work well with a modern codec comperssion format.

---
Tags: arduino-uno, esp8266, adafruit, audio, system-design
---


# Question
Title: CC3000 cannot sending post data with content length more than 104
I'm trying to post data from my Arduino due to my web server (php) through POST using the CC3000 breakout board and for some reason, data with content length more than 104 is not being sent?

I've tried posting directly with postmaster with content length value greater than 104 to verify that it wasn't my server denying the request and it wasn't. So something with the Arduino or cc3000?

Right now, my post request looks like this which works:

```
POST /new/path/post.php HTTP/1.1
Host:  www.mywebsite.com
User-Agent: Arduino/1.0
Connection: close
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 104

userId=32&sscId=43&raVal=52&cvVal=62&bbvfgTempInF=723&bbvfgLevel=82345&humidity=92&lmassLevel=0283838383

```

And this is the one that doesn't (notice only one character difference in userId):

```
POST /new/path/post.php HTTP/1.1
Host:  www.mywebsite.com
User-Agent: Arduino/1.0
Connection: close
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 105

userId=322&sscId=43&raVal=52&cvVal=62&bbvfgTempInF=723&bbvfgLevel=82345&humidity=92&lmassLevel=0283838383

```

And here is my full code:

```
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include "utility/debug.h"

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   28  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  26
#define ADAFRUIT_CC3000_CS    22
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                                         SPI_CLOCK_DIVIDER); // you can change this clock speed

#define WLAN_SSID       "mynetwork"   // cannot be longer than 32 characters!
#define WLAN_PASS       "mypassword"
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

#define IDLE_TIMEOUT_MS  10000      // Amount of time to wait (in milliseconds) with no data
                                   // received before closing the connection.  If you know the server
                                   // you're accessing is quick to respond, you can reduce this value.

/**************************************************************************/
/*!
    @brief  Sets up the HW and the CC3000 module (called automatically
            on startup)
*/
/**************************************************************************/

uint32_t ip;

void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

  /* Initialise the module */
  Serial.println(F("\nInitializing..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }

  // Optional SSID scan
  // listSSIDResults();

  Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID);
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  /* Display the IP address DNS, Gateway, etc. */
  while (! displayConnectionDetails()) {
    delay(1000);
  }

  ip = 0;
  // Try looking up the website's IP address
  Serial.print(WEBSITE); Serial.print(F(" -> "));
  while (ip == 0) {
    if (! cc3000.getHostByName(WEBSITE, &ip)) {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }

  cc3000.printIPdotsRev(ip);

  // Optional: Do a ping test on the website
  /*
  Serial.print(F("\n\rPinging ")); cc3000.printIPdotsRev(ip); Serial.print("...");
  replies = cc3000.ping(ip, 5);
  Serial.print(replies); Serial.println(F(" replies"));
  */

  /* Try connecting to the website.
     Note: HTTP/1.1 protocol is used to keep the server from closing the connection before all data is read.
  */
  Adafruit_CC3000_Client www = cc3000.connectTCP(ip, 80);
  if (www.connected()) {
    Serial.println("Connected");
    String PostDatat = "userId=32&sscId=43&raVal=52&cvVal=62&bbvfgTempInF=723&bbvfgLevel=82345&humidity=92&lmassLevel=0283838383";

    Serial.println();
    Serial.println("POST /new/path/post.php HTTP/1.1");
    Serial.println("Host: www.mywebsite.com");
    Serial.println("User-Agent: Arduino/1.0");
    Serial.println("Connection: close");
    Serial.println("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
    Serial.print("Content-Length: ");
    Serial.println(PostDatat.length());
    Serial.println();
    Serial.println(PostDatat);

    //HANGS HERE IF CONTENT LENGTH > 104

    www.println("POST /new/path/post.php HTTP/1.1");
    www.println("Host: www.mywebsite.com");
    www.println("User-Agent: Arduino/1.0");
    www.println("Connection: close");
    www.println("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
    www.print("Content-Length: ");
    www.println(PostDatat.length());
    www.println();
    www.println(PostDatat);

    Serial.println();
    Serial.println("POST /new/path/post.php HTTP/1.1");
    Serial.println("Host:  www.mywebsite.com");
    Serial.println("User-Agent: Arduino/1.0");
    Serial.println("Connection: close");
    Serial.println("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
    Serial.print("Content-Length: ");
    Serial.println(PostDatat.length());
    Serial.println();
    Serial.println(PostDatat);

    Serial.println("SENT");
  } else {
    Serial.println(F("Connection failed"));
    return;
  }

  Serial.println(F("-------------------------------------"));

  /* Read data until either the connection is closed, or the idle timeout is reached. */
  unsigned long lastRead = millis();
  while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
    while (www.available()) {
      char c = www.read();
      Serial.print(c);
      lastRead = millis();
    }
  }
  www.close();
  Serial.println(F("-------------------------------------"));

  /* You need to make sure to clean up after yourself or the CC3000 can freak out */
  /* the next time your try to connect ... */
  Serial.println(F("\n\nDisconnecting"));
  cc3000.disconnect();

}

void loop(void)
{
 delay(1000);
}

/**************************************************************************/
/*!
    @brief  Begins an SSID scan and prints out all the visible networks
*/
/**************************************************************************/

void listSSIDResults(void)
{
  uint32_t index;
  uint8_t valid, rssi, sec;
  char ssidname[33];

  if (!cc3000.startSSIDscan(&index)) {
    Serial.println(F("SSID scan failed!"));
    return;
  }

  Serial.print(F("Networks found: ")); Serial.println(index);
  Serial.println(F("================================================"));

  while (index) {
    index--;

    valid = cc3000.getNextSSID(&rssi, &sec, ssidname);

    Serial.print(F("SSID Name    : ")); Serial.print(ssidname);
    Serial.println();
    Serial.print(F("RSSI         : "));
    Serial.println(rssi);
    Serial.print(F("Security Mode: "));
    Serial.println(sec);
    Serial.println();
  }
  Serial.println(F("================================================"));

  cc3000.stopSSIDscan();
}

/**************************************************************************/
/*!
    @brief  Tries to read the IP address and other connection details
*/
/**************************************************************************/
bool displayConnectionDetails(void)
{
  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

  if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
  {
    Serial.println(F("Unable to retrieve the IP Address!\r\n"));
    return false;
  }
  else
  {
    Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
    Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
    Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
    Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
    Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
    Serial.println();
    return true;
  }
}

```

So after running this code and changing the PostDatat variable to the two data being 104 char long and 105 char long, the 104 char long goes all the way through and prints the message `SENT` to the Serial monitor. But the 105 char long just hangs after the first `Serial.println()` blocks and before the "www.println(..." Has anyone had or encountered this problem or can suggest a solution to this? Thanks!

# Answer
I've gone through the library to locate the buffer where data is stored before being transmitted and I noticed that the minimum TX buffer size is set to 130 bytes. Certain control information in the form of headers are sent along with your data to the CC3000. The CC3000 interprets these headers, strips them away and re-formats your data for transmission to your gateway. So when your 105-byte content was added to these headers, the whole packet exceeded the 130-byte buffer and so caused it to overflow, overwrite a 'magic number' at its end, that is meant to detect this condition, and cause the program to stall indefinitely; this is all by design. From `ccspi.h`:

```
// The magic number that resides at the end of the TX/RX buffer (1 byte after the allocated size)
// for the purpose of detection of the overrun. The location of the memory where the magic number
// resides shall never be written. In case it is written - the overrun occured and either recevie function
// or send function will stuck forever.
#define CC3000_BUFFER_MAGIC_NUMBER (0xDE)

```

The value of the number itself doesnt matter; its presence/absence is what is important. So this is where your code most likely got stuck:

```
/* The magic number that resides at the end of the TX/RX buffer (1 byte after the allocated size)
   * for the purpose of overrun detection. If the magic number is overwritten - buffer overrun
   * occurred - and we will be stuck here forever! */
  if (wlan_tx_buffer[CC3000_TX_BUFFER_SIZE - 1] != CC3000_BUFFER_MAGIC_NUMBER)
  {
    DEBUGPRINT_F("\tCC3000: Error - No magic number found in SpiWrite\n\r");
    while (1);  //Infinite loop; end of the road
  }

```

And the reason you didnt get this error message is because debug mode is disabled by default in the library. You can enable it by changing `#define DEBUG_MODE (0)` to `#define DEBUG_MODE (1)` in `debug.h` in the `utility` folder in the library. Note that this buffer limitation applies to incoming data, as well as outgoing data.

Now you can increase the buffer size by changing:

```
#define CC3000_MINIMAL_TX_SIZE      (130 + 1)

```

to:

```
#define CC3000_MINIMAL_TX_SIZE      (150 + 1) // buffer size is now 150 bytes

```

in `cc3000_common.h` in the `utility` folder in your library folder, save the file and try again.

Even if this works though, I suggest you choose a fixed chunk size for sending data, one that is reasonably below 130 bytes. What happens next time when you want to send a 200-byte string? You increase the buffer again and you deprive the rest of your sketch of valuable SRAM. What you do is pass your POST content to some function that splits the string into chunks and sends them one at a time. Assuming you send only ASCII strings:

```
#define CHUNK_SZ  80  // your chunk size

void send_all(Adafruit_CC3000_Client * conn, const uint8_t * data, uint16_t len){
  while (len >= CHUNK_SZ){   // while the length is greater than your chunk size
    conn->write(data, CHUNK_SZ);  // write a chunk to the socket
    data += CHUNK_SZ;  // advance the pointer to the start of the next chunk
    len -= CHUNK_SZ;  // get how many bytes are left
  }
  if (len)  // send whatever remains if anything remains
    conn->write(data, len);
}

void loop(){
  ...

  Adafruit_CC3000_Client www = cc3000.connectTCP(ip, 80);
  const uint8_t[] PostDatat = "userId=32&sscId=43&raVal=52\r\n";
  send_all(&www, PostDatat, sizeof(PostDatat) - 1); // -1 is to ignore the null byte

  ...
}

```

The function takes a pointer to your CC3000 socket object, a pointer to your data and the size of the data (array or not) in bytes. It should work for C strings. Note that I explicitly added `\r\n` at the end of the POST content, since `println()` isnt used here. I used the `uint8_t` type so that you can also use the function to send an arrays of `int`s or other numeric types, as long as you cast the array to `uint8_t *` and specify the length of the array in *bytes* with `sizeof()`.

Finally, try to make your chunk size as large as you can without getting too close to the limit. A large chunk size means fewer chunks, which means less overhead (remember those pesky headers) and time taken to transmit your whole request.
> 0 votes

# Answer
Does it print out the part "Free Ram: " If not, then I doubt its a memory problem. Not too familiar with the CC3000, but possibly related to a UART Break Condition.
> 0 votes

---
Tags: arduino-due
---


# Question
Title: Can't make my stepper motor run clockwise and counterclockwise with AccelStepper Library
I'm relatively new to arduino thus need your help to figure out why my stepper motor doesn't rotate clockwise and counterclockwise. All I could do was to make it rotate only in one direction.

Here is my code:

```
#include <AccelStepper.h>

int pos=16000;
AccelStepper stepper(1,4,5);

void setup() {
stepper.moveTo(pos);
stepper.setMaxSpeed(6400);
stepper.setSpeed(6400);
}

void loop() {
if (stepper.distanceToGo() == 0)
{
  stepper.setCurrentPosition(0);
  pos = -pos;
  stepper.moveTo(pos);
  stepper.setSpeed(6400);
}
   stepper.runSpeed();
}

```

Will appreciate any help you can give me :)

# Answer
The “Performance” paragraph of the “Detailed Description” section of AccelStepper documentation says:

> The fastest motor speed that can be reliably supported is about 4000 steps per second at a clock frequency of 16 MHz on Arduino such as Uno etc. ...

and the AccelStepper::setSpeed () documentation says:

> ... Speeds of more than 1000 steps per second are unreliable

Try changing your 6400-steps-per-second setting to a some plausible number, eg 500 or 1000.

Actually, it would make sense to start out with moderate destination settings and speeds, like a target position of 200 instead of 16000, and steps-per-second of 100, or whatever count it takes for say exactly two shaft revolutions. Once you have that working right, then start doubling numbers until it no longer works, after which you can back off by a factor of say four (to allow for variations in load, etc).
> 1 votes

# Answer
Actually after trying different options, I could finally find a solution that seems to work for me:

```
if (stepper.distanceToGo() == 0 && stepper.currentPosition()==50000) {
    delay(1000);
    stepper.setCurrentPosition(0);
    stepper.moveTo(-50000);
    stepper.setSpeed(10000);
    stepper.runSpeedToPosition();
  }
  else if (stepper.distanceToGo() == 0 && stepper.currentPosition()==-50000) {
    delay(1000);
    stepper.setCurrentPosition(0);
    stepper.moveTo(50000);
    stepper.setSpeed(10000);
    stepper.runSpeedToPosition();
  }
  stepper.runSpeed();

```
> 1 votes

---
Tags: arduino-uno, motor, stepper
---


# Question
Title: Disable other buttons while one of buttons is pressed
I'm making a project with three buttons. What I'm trying to do is to disable other buttons (make them not respond to a click event) when one of three buttons is pressed.

For now I have this code:

```
    const int button1=3;
    const int button2=4;
    const int button3=5;

    int button1State=0;
    int button2State=0;
    int button3State=0;

    void setup() {
    pinMode(button1, INPUT);
    pinMode(button2, INPUT);
    pinMode(button3, INPUT);
    }

   void loop() {
   button1State=digitalRead(button1);
   button2State=digitalRead(button2);
   button3State=digitalRead(button3);

   if( button1State == HIGH){
   // do some stuff
   }

    if( button2State == HIGH){
    // do some stuff
    }

    if( button3State == HIGH){
    // do some stuff
    }

    }

```

Do you have any ideas how I could do it?

Thanks is advance for any suggestions!

# Answer
The best solution for this is a finite state machine. There are lots of tutorials on state machines, just google.

Finite state machines are a very important concept in coding. You will find the need for them everywhere. Do yourself a favour, and read up about them, practice them, understand them, love them. Understand when they will be useful, and when they are not. If you do not, you will be back here shortly, with another question, which could also be solved by a finite state machine.

I strongly recommend you use this task as a practice task for learning about finite state machines.

Note also that, in electrical circuits, you frequently get bounce - when you push a button, your arduino will see many "button presses" (from off, to on, back to off), until it settles down. See http://blog.kennyrasschaert.be/images/20140401/Bouncy\_Switch.png for example. A state machine can also help you with this.

If you don't want to learn about FSMs, read on:

```
initialise last_button_pressed to 0 (meaning no button pressed)
if last_button_pressed>0
   if not(is_button_pressed(last_button_pressed) then
      last_button_pressed=0
else (no button is pressed)
   for each button_to_check (1,2,3)
      if last_button_pressed=0 and is_button_pressed(button_to_check) then
         last_button_pressed=button_to_check

```
> 2 votes

---
Tags: arduino-nano, button
---


# Question
Title: 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;
       }
     }

```

# Answer
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.
> 1 votes

---
Tags: arduino-uno, esp8266
---


# Question
Title: Problem controlling a Stepper motor with AccelStepper
I have an Arduino connected to a stepper motor with an Easy Driver as follows:

I am controlling the position of the stepper motor using the Serial. This is my code:

```
#include <AccelStepper.h>
AccelStepper stepper(1, 9, 8);

void setup()
{
  Serial.begin(9600);
  stepper.setMaxSpeed(10000);
  stepper.setAcceleration(5000);
}

void loop()
{
  char c;
  if(Serial.available())
  {
   int steps = Serial.parseInt();
   Serial.print(steps);
   stepper.moveTo(steps);

  }
  stepper.run();
}

```

The code works well but I'm facing a problem, when I set a high position value, it starts turning in the opposite direction, like if there was a limit on the steps. Does anyone know why it starts turning to the opposite direction?

I have tried to solve this problem by using:

```
if (stepper1.distanceToGo() == 0)
         {
            stepper1.setCurrentPosition(0);
         }

```

so I can set lower values to the serial. But the problem goes back again when the value goes up to the power of 6 (like 1000000).

Any idea?

Thanks!

# Answer
> 0 votes
Ints on vanilla Arduinos are 16 bits, and signed, which means they hold values from -2^15 to +2^15-1, so of course you cannot assign 10^6 to one of them. Use unsigned long (4 bytes), or, better yet, specify the length explicitly by using uint32\_t.

---
Tags: motor, stepper
---


# Question
Title: Can I power a LilyPad with an iPhone lightning port?
I want to make a toy car that follows a black line on the ground by using two sensor on the left and right sides of the car both pointing down. The sensor converts the light into a voltage that I will use to make the car turn left or right. I know that I can use batteries, but I am still very curious to find out if I could use my iPhone to power an Arduino because I also want to make a case with different sensors in it, and it would be thinner if I didn't have to put a 9V battery in the case.

# Answer
> 1 votes
If the phone has an accessible battery you could conceivably use the battery terminals to power a device such as Arduino. However, I think current smartphone batteries have complex monitoring circuits so this wont work.

If it doesn't, you'd be looking at using the USB/charger port on the phone.If your phone supports USB On-The-Go, I know that it allows phones to act as USB hosts, and according to USB-OTG specifications, the host must be able to supply at least 8mA of current between 4.4V and 5.25V.

If that's enough for you it could work.

# Answer
> 0 votes
Try to look at the pinout of the lightning port and create your own breakout. Then you can try taking power from the iPhone.

# Answer
> 0 votes
For those coming here from Google.

**The short answer is:**

Yes you technically can, but it wont be dirt cheap or very pretty depending on your wallet and tastes/requirements.

**Longer answer:**

I was researching the same thing. The problem is that Lightning connector is fairly complicated, and before it will start giving you power it requires software authentication by a chip that is built into the cable. That said you can use the USB camera connection kit or you can buy one of the IK Multimedia mini usb cables:

http://www.ikmultimedia.com/products/cat-view.php?C=spareparts

I have had success trying to tap into their cable for iRig Pro cause I happen to have one, and it gives out solid 3.3V on one of the pins which is good enough for my Arduino Mini Pro. But I would vouch that their full blown mini usb cable should be supplying regular 5V.

---
Tags: power
---


title: code to force a gentle servo power up

text:
# Question
Title: code to force a gentle servo power up
So I am new to the board and looking for a source to answer an Arduino servo project's rough power up. The project uses a pair of servos operating together to swing a small door. I have been working with intro level sketches over the last few weeks. I have powered and re-powered my Arduino Uno several times with different codes and each time the unit is powered the two servo motors move to their last position at what appears to be full speed resulting in a rather jerky and jumpy power up.

What can you suggest in the code that would force the servo motors to gently move toward their new code starting position? Like a 'warm up cycle'.

# Answer
> 2 votes
You cannot do that with ordinary servos. This is because of the way the communication protocol is built: the only thing a servo understands is a command which in effect means “go to that position as fast as you can”. You can achieve smooth movements by updating the requested position (the so called “set point”) many times by tiny steps, but you still have the problem at startup.

I see two possible solutions to your problem:

1. Make sure you know the position at which the servo was left when you powered down your Arduino. You can either arrange to leave it always at the same position, or you can store the last position in EEPROM before powering down. Then, at startup, you initialize the servo with that last known set point.
2. Use a special type of servo known as a feedback servo, or convert a regular servo to get a feedback. A feedback servo is a type of servo that tells you its actual position, so you can arrange for the initial set point to match that position.

# Answer
> 0 votes
I would recommend an S curve for the angular positioning of the door.

That should guarantee a smooth start and stop.

---
Tags: arduino-uno, programming, servo
---


title: Arduino serial non-blocking

text:
# Question
Title: Arduino serial non-blocking
I'm writing an Arduino program to communicate with another module using RS485, so I need to control data flow with one pin. But when I set the pin to HIGH (line 88) it almost instantly falls (as you can see in the image, line 70). So my guess is that Arduino Serial.write() function is non-blocking, but I need it to be blocking so the flow control pin stays high during whole packet transmit. Please help. Thank you.

# Answer
> 3 votes
You are right: `Serial.write()` is non blocking: it puts the data in a buffer and waits for an interrupt routine to send it through the UART. If you want to wait for the transmission to complete, you can call `Serial.flush()`.

---
Tags: c, rs485
---


# Question
Title: ESP8266 module cutting connection with PC via USB
My Arduino UNO is connected directly to the ESP8266 (01) WiFi module. The Red and Blue LED flashes and it seems to work properly. But when I connect the UNO to my computer, the module refreshes at irregular intervals and the PC produces sounds as that of ejecting and inserting a USB. I don't know whether this is caused due to low voltage supplied from the USB or some other reason. Please help me out...

# Answer
> 1 votes
At which pins you connected the ESP8266? The pins pin 0 (RX) an 1 (TX) are connectet internaly to the FTDI USB-to-TTL Serial chip. If you using Serial.begin() to communicate with the ESP8266, you can't communicate with the pc at the same time. Use SoftwareSerial to communicate with the ESP8266 an Serial to PC.

It is also recommed to feed the ESP8266 with an external 3.3V power supply and stabilize with an capacitor. This could produces the sounds of ejecting and inserting a USB.

---
Tags: arduino-uno, esp8266
---


title: Drop alpha character from serial input

text:
# Question
Title: Drop alpha character from serial input
I receive strings over the serial port like so:

VLT=53.0, AMP=-30.2, AHR=-10, SOC=98, TMP=136, STS=192

I want to reduce the use of string functions with the idea of dropping all non-digits, keeping numbers dot and comma, to get this:

53.0,-30.2,-10,98,136,192

in an array and simple read \[0\], \[1\], etc.

Regular expressions would be idea, but do not exist like in PERL. Any hint would be much appreciated.

Relevant code used:

```
    char inByte = SerialPortOne.read(); // read byte
    strRecordIn.concat(inByte);         // add byte to receive buffer
    for (int i = 0; i <= 3; i++) {    // VLT, AMP, AHR, SOC
    strWord = getValue(strRecordIn, ',', i);  // get data item from RecordIn array
      strWord.remove(0, 4);           // remove field identifier (1st 3 char plus =)
      strRecordOut += ',';            // add delimiter
      strRecordOut += strWord;        // add value
      strWord = "";                   // reset strWord
    }

```

Ideally:

```
    char inByte = SerialPortOne.read(); // read byte
    if (inByte = [%d.,]+) {
      strRecordIn.concat(inByte);       // add byte to receive buffer
    }

```

# Answer
> 0 votes
If you just want to remove the letters:

```
#include <ctype.h>

char inByte = SerialPortOne.read();  // read byte
if (!isalpha(inByte)) {              // not letter
    strRecordIn.concat(inByte);      // add byte to receive buffer
}

```

Or you may test it for `isdigit()` and explicitly compare to `','` and `'.'`:

```
if (isdigit(inByte) || inByte == '.' || inByte == ',') {
    strRecordIn.concat(inByte);      // add byte to receive buffer
}

```

C.f. the documentation of \<ctype.h\>.

---
Tags: arduino-uno, string
---