message:
Exit status 1 expected primary-expression before ']' Arduino

Here's the whole error:

     Arduino: 1.6.7 (Windows 7), Board: "Arduino/Genuino Uno"

     *\readMifare\readMifare.ino: In function 'void loop()':

     readMifare:113: error: expected primary-expression before ']' token

        if (uid[] == { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

                ^

     readMifare:113: error: expected primary-expression before '{' token

        if (uid[] == { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

                     ^

     readMifare:113: error: expected ')' before '{' token

     readMifare:121: error: expected '}' at end of input

        }

        ^

     exit status 1
     expected primary-expression before ']' token

       This report would have more information with
       "Show verbose output during compilation"
       enabled in File > Preferences.

Here's the code

     #include <Wire.h>
     #include <SPI.h>
     #include <Adafruit_PN532.h>

     // If using the breakout with SPI, define the pins for SPI communication.
     #define PN532_SCK  (2)
     #define PN532_MOSI (3)
     #define PN532_SS   (4)
     #define PN532_MISO (5)
     // If using the breakout or shield with I2C, define just the pins connected
     // to the IRQ and reset lines.  Use the values below (2, 3) for the shield!
     #define PN532_IRQ   (2)
     #define PN532_RESET (3)  // Not connected by default on the NFC Shield

     // Uncomment just _one_ line below depending on how your breakout or shield
     // is connected to the Arduino:

     // Use this line for a breakout with a software SPI connection (recommended):
     Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);

     // Use this line for a breakout with a hardware SPI connection.  Note that
     // the PN532 SCK, MOSI, and MISO pins need to be connected to the Arduino's
     // hardware SPI SCK, MOSI, and MISO pins.  On an Arduino Uno these are
     // SCK = 13, MOSI = 11, MISO = 12.  The SS line can be any digital IO pin.
     //Adafruit_PN532 nfc(PN532_SS);

     // Or use this line for a breakout or shield with an I2C connection:
     //Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

     #if defined(ARDUINO_ARCH_SAMD)
     // for Zero, output on USB Serial console, remove line below if using      programming port to program the Zero!
     // also change #define in Adafruit_PN532.cpp library file
     #define Serial SerialUSB
     #endif
     #include <Servo.h>

     Servo servo1;

     void setup(void) {
       #ifndef ESP8266
       while (!Serial); // for Leonardo/Micro/Zero
       #endif
       Serial.begin(115200);
       Serial.println("Hello!");

       nfc.begin();

       uint32_t versiondata = nfc.getFirmwareVersion();
       if (! versiondata) {
         Serial.print("Didn't find PN53x board");
         while (1); // halt
       }
       // Got ok data, print it out!
       Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
       Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
       Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

       // configure board to read RFID tags
       nfc.SAMConfig();

       Serial.println("Waiting for an ISO14443A Card ...");
       servo1.attach(9);
     }

     void loop(void) {
       uint8_t success;
       uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
       uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

       // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
       // 'uid' will be populated with the UID, and uidLength will indicate
       // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
       success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

       if (uid[] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

          int position;
          for(position = 0; position < 180; position += 2){
           servo1.write(position);
           delay(20);
          }

       }

Please note that I'm using an example from the *Adafruit official PN532 library examples* and trying to edit it.

body:
You probably need something like:

    uint8_t uidTarget[] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 };

    ...
    if (success && !strncmp((const char*) uidTarget,(const char*)uidSource,8)) {

Your '=' tries to do an assignment, and an '==' would check if the pointers to the arrays are identical, rather than the contents of the arrays.  strncmp() tests equality of strings of characters, and the (const char*) casts the uint8_t values as characters.

Nick Gammon's answer is better.


sender: user

sender: assistant

body:
I wouldn't use `strncmp` because the UID might have zeroes in it. This looks safer:

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

       uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
       uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

       const uint8_t wantedUid [] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 };

       // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
       // 'uid' will be populated with the UID, and uidLength will indicate
       // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
       success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

       if (success &&
          uidLength == sizeof (wantedUid) &&
          memcmp (uid, wantedUid, sizeof wantedUid) == 0) {
          ...

I threw in a test for the uidLength being the expected size, otherwise you might find a 4-byte card happens to match the first four bytes of the wanted UID.

`memcmp` compares a block of memory for the number of bytes you specify. It returns zero on a match.


message:
Arduino array length

So I have a programme that loads a text file from an sd card into a string array. Each line in the text file is stored in a different string in a string array. Well its supposed to be.

    file = SD.open("/classes/basic.txt", FILE_READ);
    Serial.print("Reading, Checking and Compiling \n\n\n");

    for(int i = 0; i < sizeof(result)-1;i++){
     while(file.available()) {
      character23 = file.read();
      content.concat(character23);

    }
    if (content != "") {
      result[i] = content;
        Serial.println(content);

    }

  }

I want each line in the txt file to be stored in a different string in the array, in chronological order and each string has to be accessible individually. The problem with this code is that it stores the whole text file in one string. How can I fix this?

EDIT: here is what I have now

      file = SD.open("/classes/basic.txt", FILE_READ);
      Serial.print("Reading, Checking and Compiling \n\n\n");

     for(int i = 0; i < sizeof(result)-1;i++){
       while(file.available()) {
      character23 = file.read();
      if (character23 == '^') break;
      content.concat(character23);

    }
    if (content != "") {
      result[i] = content;
      Serial.println(content);

      delay(1000);
    }

  }
 Serial.println(result[3]);

body:
To do that, you need to read the file until you reach a line break.

Replace this code:

    while(file.available()) {
      character23 = file.read();
      content.concat(character23);
    }

by this:

    while(file.available()) {
       character23 = file.read();
       if (character23 == '\n') break;
       content.concat(character23);
    }


message:
Powering a stepper motor

I'm working on a project where I need a high torque stepper motor. The stepper motor being used is rated at 12 - 24 volts and when I used a 12 volt battery supply composed of 8 AA batteries it appeared to work fine.

Because I wanted higher torque I set the pot on the Easy Driver to 0.5 amps which is within what was recommended for the motor, and used a Lithium Ion battery originally being used for a power drill rated at 18V and 1.5Ah.

When I connected the battery to the easy driver the motor got very hot and would shake when I tried to turn it but not turn. Now the motor will not work with the 8 AA batteries either. Heres a link to the motor [US Ship OSM 5:1 Planetary Gearbox Nema 8 Stepper Motor Samll Size High Torque][1].

[![Project][2]][2]

What did I do wrong and how can I fix it?

P.S. I am using a photon as the micro controller and the motor is being controlled using the Blynk app I eliminated the chance of it having to do with the photon or Blynk App.

I found out that the battery I'm using is the Makita BL1815 and it is really composed of 2 batteries which are both rated at 15C. I am not sure if C-rating adds or stays the same when you are using two batteries. When I measure the Voltage on the test points I get 4.27V and when using a formula to find current for the Easy Driver I get 0.480A.

  [1]: http://www.ebay.com/itm/US-Ship-OSM-5-1-Planetary-Gearbox-Nema-8-Stepper-Motor-Samll-Size-High-Torque-/231616295885?hash=item35ed6833
  [2]: https://i.stack.imgur.com/snDwc.jpg

body:
How did you set the amps on the http://www.schmalzhaus.com/EasyDriver/ to 0.5A?   What was the voltage at the test point?  The EasyDriver v4.5 schematic says the formula for coil current is A = V/6.  So rearranging, V=A*6, and to get 0.5A, the voltage should be 0.5*6=3V at the motor driver's test point.

The linked motor spec is 0.6A max per coil, and if things went wrong, you could have overloaded a motor.  The 18V battery could have easily provided 1.8 amps to the 10ohm coil in the motor for a bit, before 3x the rated current of the coils would burn it out, or the easydriver went into thermal shutdown or something.

The easydriver looks like it would be capable of controlling the current adequately, but if misconfigured, could easily overcurrent the motor.


message:
Don't know how to work IMU and NRF24 together

I'm having problem  on how can I use IMU and NRF24 together.

 This is the code that i'm trying to use,

     /*
     Copyright (C) 2012 James Coliz, Jr. <maniacbug@ymail.com>
     This program is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     version 2 as published by the Free Software Foundation.

     Update 2014 - TMRh20
    */
    /**
    * Simplest possible example of using RF24Network
    *
    * TRANSMITTER NODE
    * Every 2 seconds, send a payload to the receiver node.
    */
    #include <RF24Network.h>
    #include <RF24.h>
    #include <SPI.h>
    #include <Wire.h>
    #include "I2Cdev.h"
    #include "RTIMUSettings.h"
    #include "RTIMU.h"
    #include "RTFusionRTQF.h"
    #include "CalLib.h"

    RTIMU *imu;                                           // the IMU object
    RTFusionRTQF fusion;                                  // the fusion object
    RTIMUSettings settings;                               // the settings object

    //  DISPLAY_INTERVAL sets the rate at which results are displayed

    #define DISPLAY_INTERVAL  300                         // interval between
    pose displays

    //  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

    #define  SERIAL_PORT_SPEED  11520
    unsigned long lastDisplay1;
    unsigned long lastRate1;
    int sampleCount1;

     RF24 radio(7,8);                    // nRF24L01(+) radio attached using
     Getting Started board
     RF24Network network(radio);          // Network uses that radio
     const uint16_t this_node = 01;        // Address of our node in Octal
     format
     const uint16_t other_node = 00;       // Address of the other node in Octal
     format
     const unsigned long interval = 2000; //ms  // How often to send 'hello
     world to the other unit
     unsigned long last_sent;             // When did we last send?
     unsigned long packets_sent;          // How many have we sent already
     struct payload_t {                  // Structure of our payload
     unsigned long ms;
     unsigned long counter;
     };
     void setup(void)
     {
     int errcode;

     Serial.begin(SERIAL_PORT_SPEED);
     Wire.begin();
     imu = RTIMU::createIMU(&settings);                        // create the imu
     object

     Serial.print("ArduinoIMU starting using device "); Serial.println(imu-
     >IMUName());
     if ((errcode = imu->IMUInit()) < 0) {
     Serial.print("Failed to init IMU: "); Serial.println(errcode);
     }

     if (imu->getCalibrationValid())
        Serial.println("Using compass calibration");
     else
        Serial.println("No valid compass calibration data");

     lastDisplay = lastRate = millis();
     sampleCount = 0;

    // Slerp power controls the fusion and can be between 0 and 1
    // 0 means that only gyros are used, 1 means that only accels/compass are used
    // In-between gives the fusion mix.

    fusion.setSlerpPower(0.02);

    // use of sensors in the fusion algorithm can be controlled here
    // change any of these to false to disable that sensor

    fusion.setGyroEnable(true);
    fusion.setAccelEnable(true);
    fusion.setCompassEnable(true);

    Serial.println("RF24Network/examples/helloworld_tx/");

    SPI.begin();
    radio.begin();
    network.begin(/*channel*/ 90, /*node address*/ this_node);
    }
    void loop() {

    unsigned long now1 = millis();
    unsigned long delta1;
    int loopCount1 = 1;

    while (imu->IMURead()) {                                // get the latest
    data if ready yet
    // this flushes remaining data in case we are falling behind
    if (++loopCount1 >= 10)
            continue;
        fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(),
    imu->getTimestamp());
        sampleCount++;
        if ((delta1 = now1 - lastRate1) >= 1000) {
            Serial.print("Sample rate: "); Serial.print(sampleCount);
            if (imu->IMUGyroBiasValid())
                Serial.println(", gyro bias valid");
            else
                Serial.println(", calculating gyro bias");

            sampleCount = 0;
            lastRate1 = now1;
        }
        if ((now1 - lastDisplay1) >= DISPLAY_INTERVAL) {
            lastDisplay1 = now1;
         RTMath::display("Gyro:", (RTVector3&)imu->getGyro());                // gyro data
          RTMath::display("Accel:", (RTVector3&)imu->getAccel());              // accel data
          RTMath::display("Mag:", (RTVector3&)imu->getCompass());              // compass data
            RTMath::displayRollPitchYaw("Pose:", (RTVector3&)fusion.getFusionPose()); // fused output
           Serial.println();
        }
    }

       network.update();                          // Check the network regularly

      unsigned long now = millis();              // If it's time to send a
      message, send it!
      if ( now - last_sent >= interval  )
      {
      last_sent = now;
      Serial.print("Sending...");
      payload_t payload = { millis(), packets_sent++ };
       RF24NetworkHeader header(/*to node*/ other_node);
       bool ok = network.write(header,&payload,sizeof(payload));
      if (ok)
      Serial.println("ok.");
      else
      Serial.println("failed.");
      }
      }

My question is what  should I put in this part

       [code]struct payload_t {                  // Structure of our payload
        unsigned long ms;
        unsigned long counter;
        };
so that the output for

     RTMath::display("Gyro:", (RTVector3&)imu->getGyro());                //
     gyro data
          RTMath::display("Accel:", (RTVector3&)imu->getAccel());
     // accel data
          RTMath::display("Mag:", (RTVector3&)imu->getCompass());
     // compass data
          RTMath::displayRollPitchYaw("Pose:",
     (RTVector3&)fusion.getFusionPose()); // fused output[/code]

 will Transmit to the RX ..

What will I put in this part :

       Serial.print("Sending...");
       payload_t payload = { millis(), packets_sent++ };
       RF24NetworkHeader header(/*to node*/ other_node);
       bool ok = network.write(header,&payload,sizeof(payload));
       if (ok)
       Serial.println("ok.");
       else
       Serial.println("failed.");

Please help me guys. Thanks :)

body:
> My question is what should I put in this part

You need to take the data from IMU sensor and put it into the payload. Remember that NRF24L01 allows max 32 byte payload and the library uses some of that.

The RTVector3 is a C++ class with 3 floating point numbers. With AVR float/double that is 12 bytes. This means that you will have to send several messages.

    enum {
       GYRO_TYPE = 0,
       ACCEL_TYPE = 1,
       COMPASS_TYPE =2
    };

    struct payload_t {
      int8_t type;
      float data[3];
    };

This assumes that the sender and receiver have the same data representation. The type field is for the value type (GYRO, ACCEL, COMPASS).

Cheers!


message:
SPI with a level converter in the other end of connection

I have an Arduino MEGA hooked up with a NRF24L01, and working nicely, talking with another Arduino Uno. It works as described, power supply to 3.3V, and SPI lines (MISO,MOSI,CLK) connected directly to the Arduino;

However, when I hook up a level converter in the end (5V to 3V, bidirectional) (making the NRF module in the middle, like in a T connection), the module stops working, and I don't know why. How does the level converter module is interfering in the connection? Is there any way I can prevent this and use it?

I intend in adding in the future, modules that talk in 3.3V SPI;

This is the level converter I'm using:

[![JY-MCU 5V-3V four channel convert module][1]][1]
<sub>(source: [at-the.space](http://ralphfox.at-the.space/imglink/hGTdg.jpg))</sub>

I suspect it is because of the pullups (5 think that these 10kΩ resistors are pull-ups, but I'm a noob in that part), but I really don't know if that is the problem, as the seller advertises it as being compatible with SPI, I2C, and UART. I have successfully used these for a UART.

I have checked https://arduino.stackexchange.com/questions/9616/slaving-multiple-arduinos-via-spi and tried using an external 5V supply, and a 3.3V supply, but no dice.. However, the 3V side has no connections to it; But, being bi-directional, I don't think there is a problem with this...

I found that 74HCT245D works very well for this, but I'd like to know why with the level converter from JY-MCU this won't work.

Providing the library and connections just in case (the module works without the level converter):

 - Library & sketch comes from [Optimized High Speed NRF24L01+ Driver Class Documenation][2].

 - Connection:

   - NRF2401 Pinout:
     [![NRF24l01][3]][3]

   - My connection:
     [![Arduino with NRF24l01 and Level Converter ][4]][4]

  [1]: https://i.stack.imgur.com/jHsyc.jpg
  [2]: http://tmrh20.github.io/RF24/index.html
  [3]: http://ralphfox.at-the.space/imglink/nrf24l01.jpg
  [4]: http://ralphfox.at-the.space/imglink/nrf_bb.png

body:
More than probably your level shifter is not fast enough.
A level shifter uses a mosfet to copy signals from one voltage level to the other, but each mosfet has a latency or, if you prefer, a rise time.
Your board probably doesn't use a fast switching mosfet and so the SPI protocol (which is a quite fast one) is not *copied* correctly.

On top of that you **actually don't need a level switcher** for the nRF24 modules: the power pin must be limited to 3.3V, but the signal pins are 5V tolerant.
This means you only need a 3.3V voltage source and all the remaining connections can go directly (and safely) into your Arduino board.

**UPDATE**: the speed concept still applies, it doesn't matter which side of the connection you are using. A mosfet has a little capacitance which *slows* down the signal transmission: higher the capacitance, slower the maximum data rate.
The cheap chinese level shifter is not designed for high speed communication, while the Texas Instrument device is clearly designed for high speed.
If you look at the SN74HCT245 datasheet you'll notice the switching speed is reported for 50pF capacitance and ranges from 8ns to 16ns: that's the time needed to build enough charge in the switching circuit.
[![enter image description here][1]][1]

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


body:
AVR's like all digital have their limits. In this case you're dealing with source resistances that need to charge multiple gate capacitances through series resistances (wires and metal contact connections. Specifically an Absolute MAX 40mA/pin, some milliohms in your copper wire and PCB traces, and pico to nano Farad capacitances, plus depending on how High Speed the SPI is (the spec does not list an upper limit), you will be also contending with frequency limiting parasitics. At MHz frequencies, your wire and PCB traces will have higher resistances due to "skin" effect, where the electrons migrate to the surface of the wire when transferring. Depending on frequency of the wire, adding just a single gate could degredate rise/fall times enough to corrupt data, as the SPI library (whichever you choose) and the SPI peripheral within the AVR probably won't be as sophisticated as a PC based one. The AVR & the SPI library lacks sophistication in that neither has provisions to detect and compensate for extra gate capacitance on the bus line, nor could they compensate for china jumper wires which are quite small (9x40ga) wiring.
There are many factors which could corrupt your SPI project that are coming into play to limit performance.
You should probably do some internet research on high speed bus anatomy if you intend on pushing the SPI bus on the arduino to it's limits.

I think the gate capacitances are combining with source resistance and skin effect and your 40mA/pin is not in fact 40mA per pin but more like 10-20mA is hitting all gate capacitances when skin effect is considered (it effectively raises the resistance of the wire sufficiently to then be a factor).
If connecting the JY-MCU converter AND running SPI at minimum speed corrects communication, then the extra gate capacitances are the factor you should change to higher performance versions. There's the 74AS series with gate times down to 1.7nS and fMAX up to 40MHz!

Hope this helps.


message:
Why need a delay between readings?

When I learn the tutorial in

 - [Analog Read Serial][1]
 - [Digital Read Serial][2]

both of the code examples have a line of code of `delay(1)` and I cannot understand the comments clearly:

     delay(1);        // delay in between reads for stability

 The **stability** for/of what?

  [1]: https://www.arduino.cc/en/Tutorial/AnalogReadSerial
  [2]: https://www.arduino.cc/en/Tutorial/DigitalReadSerial

body:
Those delays are nonsense. They don't add to the stability of anything. The best you could say is that they stop you spamming your serial port. (However 1 ms is not very long).

Sometimes people throw in a delay because "it seems to work better" without examining the underlying cause. I would speculate that in this case the author may have been using delays to improve receiving serial data, and got the idea into their head that the occasional delay now and then "improves stability".


body:
**Analog Stability**

From the [Datasheet of ATMEGA328][1] Page 240:

`When the bandgap reference voltage is used as input to the ADC, it will take a certain time for the voltage to stabilize. If not stabilized, the first value read after the first conversion may be wrong.`

So if you are doing multiple reads, you need to wait a few cycles.

Delays are not required when using auto-triggering:

`When Auto Triggering is used, the prescaler is reset when the trigger event occurs. This assures a fixed delay from the trigger event to the start of conversion. In this mode, the sample-and-hold takes place two ADC clock cycles after the rising edge on the trigger source signal. Three additional CPU clock cycles are used for synchronization logic.`

Also if reading different channels of the same ADC module, you need to provide a delay between the reads so that the analog MUX is positioned and the S&H capacitor is charged.

This information is from hardware perspective and I'm not sure if Arduino internal ADC routines compensate for those delays.

**Digital Stability**

From the digital read tutorial schmatic:

[![enter image description here][2]][2]

In the schematic, the push button is not electrically de-bounced. A delay in reading states would help de-bounce it in software.

As Nick Gammon suggested, they also improve serial flooding.

  [1]: http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet_complete.pdf
  [2]: https://i.stack.imgur.com/GiHD6.png


message:
Arduino how to get amount of elements in an array?

Hello  have an array of strings that loads strings from a txt file on an sd card.
The txt file on the SD card can change from time to time(not while the Arduino is running).I want to be able to get the amount of elements in the array after the txt file has been loaded into the array. The txt file has lines of txt in it. Each line in the file is put into a string in the array. I want to be able to get the amount of elements in the array how can I do this?

body:
You can't. That concept does not exist in C.

An array has a fixed size - as such you know how many elements are in it, since that is the number of elements you created it with.

    String myStrings[4];

That is an array of 4 String objects. It has 4 elements. It will always have 4 elements.


body: numElements = (sizeof(array) / sizeof(array[0]));


message:
Writing not permitted on genuino 101 Built in Bluetooth LE (phonegap)

I have a Genuino 101 which has a built in Bluetooth LE module. I have been trying to connect this to my phone using phonegap. I have been using [cordova-plugin-bluetootle][1] and with it I have been able to receive data from the arduino and display that data on the phone.
I tired adapting it so that I could send data from the phone to the arduino. I noticed in the CurieBle examples there was a project called "Callback LED" but when I connected to the Arduino from the Phone gap app I noticed in the debug message about characteristics it said `"properties":{"notify": true, "read": true}` but nothing about write. I tried writing "Hello world" (converted into bytes then encoded string) I got an error similar to (I couldn't copy it exactly as it was an alert on the phone): `"error": "write", "message": "Error Domain=CBATTErrorDomain Code = 3 \"Writing is not permitted.\" ..."...`There is more detail to the error message that is not at all relevant and is slightly repetitive.
Here is the arduino code (which is almost straight from the example):

    #include <CurieBle.h>

    const int ledPin = 13; // set ledPin to use on-board LED
    BLEPeripheral blePeripheral; // create peripheral instance

    BLEService ledService("19B10000-E8F2-537E-4F6C-D104768A1214"); // create service

    // create switch characteristic and allow remote device to read and write
    BLECharCharacteristic switchChar("19B10001-E8F2-537E-4F6C-D104768A1214", BLERead | BLEWrite);

    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT); // use the LED on pin 13 as an output
      digitalWrite(ledPin, HIGH);
      while(!Serial);
      digitalWrite(ledPin, LOW);
      // set the local name peripheral advertises
      blePeripheral.setLocalName("LEDCB");
      // set the UUID for the service this peripheral advertises
      blePeripheral.setAdvertisedServiceUuid(ledService.uuid());

      // add service and characteristic
      blePeripheral.addAttribute(ledService);
      blePeripheral.addAttribute(switchChar);

      // assign event handlers for connected, disconnected to peripheral
      blePeripheral.setEventHandler(BLEConnected, blePeripheralConnectHandler);
      blePeripheral.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);

      // assign event handlers for characteristic
      switchChar.setEventHandler(BLEWritten, switchCharacteristicWritten);
    // set an initial value for the characteristic
      switchChar.setValue(0);

      // advertise the service
      blePeripheral.begin();
      Serial.println(("Bluetooth device active, waiting for connections..."));
    }

    void loop() {
      // poll peripheral
      blePeripheral.poll();
    }

    void blePeripheralConnectHandler(BLECentral& central) {
      // central connected event handler
      Serial.print("Connected event, central: ");
      Serial.println(central.address());
    }

    void blePeripheralDisconnectHandler(BLECentral& central) {
      // central disconnected event handler
      Serial.print("Disconnected event, central: ");
      Serial.println(central.address());
    }

    void switchCharacteristicWritten(BLECentral& central, BLECharacteristic& characteristic) {
      // central wrote new value to characteristic, update LED
      Serial.print("Characteristic event, written: ");

      if (switchChar.value()) {
        Serial.println("LED on");
        digitalWrite(ledPin, HIGH);
      } else {
        Serial.println("LED off");
        digitalWrite(ledPin, LOW);
      }
    }
Here is the write function (phonegap) which is where the error is being produced from :

    var string = "Hello World";
    var bytes = bluetoothle.stringToBytes(string);
    var encodedString = _arrayBufferToBase64(bytes);
    alert("Service : " + connection.service + "  char : " + connection.char + " Address: " + address);
    var params = {"value":encodedString,"service":connection.service,"characteristic":connection.char,"address":address};
    alert("params : " + JSON.stringify(params));
    bluetoothle.write(function(res) {
    alert("Success writing : " + JSON.stringify(res));
    }, function(err) {
    alert("Error writing: " + JSON.stringify(err));
    }, params);

I think the error lies in the fact that the Arduino appears not to be advertising the "write" characteristic.
BTW the phone tells me that the service was `180d` and the characteristic was `2a37`.

  [1]: https://github.com/randdusing/cordova-plugin-bluetoothle

body:
I finally figured it out thanks to finding [this GitHub issue][1]. It turns out to be an error with CurieBLE which manifests in a way that means that on IOS it reads the original characteristics and services so when I tried to write it was still thought that the characteristic was `read-only`. I had to restart my phone and it is working now.
There was another thing which is that I needed to send a shorter message, I think it was 20 bytes max per message although I'm not sure, but I sent "h" and the Arduino received it.

  [1]: https://github.com/01org/corelibs-arduino101/issues/96


message:
Arduino how to loop a method

Hello I have a method where when you press a button a string is compared with a substring to see if the string contains the substring. The problem is when I load in the string I call the check button press and substring comparing method. Which only ever happens once. I want to know how I can keep calling the method. It sounds simple but it isn't.

    void loadPrograme(){
       file = SD.open("/classes/basic.txt", FILE_READ);
       Serial.print("Reading, Checking and Compiling \n\n\n");

       for (int i = 0; i < arraysize; i++) {
          while (file.available()) {
             character23 = file.read();
             if (character23 == '\n') break;
             if (character23 != '^') {
                content += character23;
             }
          }
          content.trim();
          if (content != "") {
             result[i] = content;
             content = "";
             delay(1000);
          }
       }
       for (int i = 0; i <arraysize; i++) {
          if(result[i].substring(0,5) == "print"){
             printlnMethod(result[i]);

          }else
             if(result[i].substring(0,5) == "delay"){
                delayMethod(result[i]);
             }else
                if(result[i].substring(0,11) == "buttonPress"){
                   buttonMethod(result[i]);

                }

       }

       file.close();
    }

    void buttonMethod(String s){
       s = s.substring(s.indexOf('{') + 1);
       s = s.substring(0, s.lastIndexOf('}'));
       String btn =" ";
       String daction = " ";
       String indaction = " ";
       btn= s.substring(s.indexOf('"')+1 );
       btn= btn.substring(0, btn.lastIndexOf('"'));
       daction = s.substring(s.indexOf(',')+1);
       daction = daction.substring(0, daction.lastIndexOf('('));
       indaction = s.substring(s.indexOf('~')+1);
       indaction = indaction.substring(0, indaction.lastIndexOf('~'));
       int buttonpressed;
       if(btn == "BUTTON_PIN_ENTER"){
          buttonpressed = 2;
       }else if(btn == "BUTTON_PIN_LEFT"){
          buttonpressed = 3;
       }else if(btn == "BUTTON_PIN_RIGHT"){
          buttonpressed = 4;
       }else if(btn == "BUTTON_PIN_DOWN"){
          buttonpressed = 5;
       }else if(btn == "BUTTON_PIN_UP"){
          buttonpressed = 6;
       }else if(btn == "BUTTON_PIN_ACTION"){
          buttonpressed = 7;
       }

       int btncheck = digitalRead(buttonpressed);
       if(btncheck == LOW){
          if(daction.substring(0,5) == "print"){
             printlnMethod(indaction);

          }else if(daction.substring(0,5) == "delay"){
             delayMethod(indaction);
          }
       }
    }

    }

So basically it loads in the txt file into the string array and loops through it and reads each line. each line is executed. for example if it get the substring of buttonpressed it goes to the buttonmethod(). The problem is in the button method. I want to have the button method keep looping until the button is pressed but it only runs through that method once. How can I keep running threw this method until the button is pressed?

body:
Testing for string equality with '==' is a mistake: https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c  The '==' operator on strings will compare the pointers to the strings rather than their content and likely always fail the if() tests.

To loop and block on the last bit, if that is what you mean, you might try:

       int btncheck;
       ...
       while(btncheck = digitalRead(buttonpressed)){ // wait for button
          if(strcmp(daction.substring(0,5),"delay")){
             delayMethod(indaction);
          }
       }  // blocked until btncheck == LOW
       if(strcmp(daction.substring(0,5), "print")){
             printlnMethod(indaction);
       }

This has the blocking on non-pressed button feature, but also has the same logic as the original.  If the string equality tests do not match, it appears you want to do nothing and quickly pass on.

To loop buttonMethod(), put it in a loop:

    while(1)buttonMethod(string);

If you want to condition on getting the button press that corresponds with the string, I'd make buttonMethod return a value and loop conditionally on that:

    int buttonMethod(...
        int retVal = 0;
        ...

      if(btncheck == LOW){
         retVal = 1;
         ...
      }
      return(retVal);
    }

    ...
    while(!buttonMethod(result[i]));  // wait for the button


message:
Can we detect a magnet using Arduino? If so how?

If so, please tell me and also tell me if any interfacing of other microcontroller needed?

body:
I can't comment yet but you probably are looking for a hall effect sensor.

Something like this is a simple version of the sensor. https://www.sparkfun.com/products/9312

You can then do a digitalRead on the DO pin to detect if a magnet is near the sensor.

You would connect the Vdd to 5v arduino supply and GND to the GND of the board.


body: If you don't care about measuring the strength of the magnetic field, you can use a magnetic switch (sometimes called a reed switch). A magnetic switch closes when a magnet is put up to it and opens when there is not. The only problem with this is that the magnet has to be within about one inch from the switch. The magnetic switch works just like a normal switch and usually has two contacts. [Here](http://www.mouser.com/ProductDetail/Standex-Electronics/ORD324-1520/?qs=JzJq8kwFq1kL6csKqXqJlw==&gclid=CjwKEAiA0ZC2BRDpo_Pym8m-4n4SJAB5Bn4xq9r0brZEKWex5eS-FfwskFgNwpZVISwIe8pVCaHRaBoCKxnw_wcB) is an example.


message:
How to run 5 wires hibrid stepper motor with arduino uno?

I have a question. How to run stepper motor (Nema 17) that has 5 wires with arduino and stepper driver.
Here is the driver, stepper and Arduino when stepper has 4 wires.
http://jdreyer.com/projects/Arduino/ArduinoEasyDriverStepperMotorv1_Resize.png

I need help identifying the wires on my hibrid stepper motor. I will provide picture of dissasembled motor.

Questions are:

 1. Wires identification?
 2. How to connect it to ArduinoEasyDriver?
 3. Code example desired.

[![Dissasembled stepper][1]][1]

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

[![enter image description here][2]][2]

  [2]: https://i.stack.imgur.com/T5Bk9.jpg

**UPDATE**

> I am now thinking of making it bipolar (4 wires), because now in 5
> wires configuration motor is unipolar. I did some research and this
> motor is HIBRID. It can be driven as unipolar or bipolar. I will try
> to troubleshoot the wiring and find the common wire. Ill keep you
> informed.

body:
**Finding the ground pin**

We should start off by finding the Ground/GND pin.

Do you have an Ohm-meter? I believe one of the pins should be GND/ground, and should have low resistance when referenced to the other pins.

**Wiring the stepper**

Steppers have a coil and thus are an inductive load, you should really check your wiring with sources, to be sure they're valid.
(At this point I can't give you a 100% accurate wiring diagram, but it should be easy to find, as wiring steppers is quite common.)
You could use a pre-assembled stepper-driver. Having such a thing is usefull when you want to design the circuitry yourself.

**Driving the steppers**

You should generate a signal like this: https://en.wikipedia.org/wiki/Stepper_motor#Phase_current_waveforms

(The source/link describes the different forms of stepping. Like "Wave drive (one phase on)" in which each coil is activated/deactivated in a rotary fashion, making the core turn around.)

**Extra**

Adafruit always has extremely well documented tutorials for beginners:
https://learn.adafruit.com/all-about-stepper-motors/types-of-steppers

The wiki of RepRap should be a good source, since steppers are the hearth of 3D printers (RepRap is a 3D printer brand):
http://reprap.org/wiki/Stepper_wiring


body:
On stepper motors there are a few types of wiring, but essentially there are two coils inside the stepper motor. To figure out where the wiring is you need a way to test if the coils are being connected. On your setup I would suggest to connect two of the wires together at a time and spin the shaft. If the shaft offers resistance then you have found the two wires for one coil.

For your stepper motor it looks like it may have three coils, but out of the 6 wires you may also only come up with 4 wires; which would equal 2 coils.

As far as connecting it to an easy driver, the easy driver only takes two coils. you would need to find a driver that can take three coils, or just connect two coils out of the three and hope for the best.


body:
1) it is probably something like A1, A2, Common, B1, B2.  You could confirm this with an ohmmeter. Common to any of the others would be a certain resistance X, while between any of the others (A1-A2, B1-B2, A1-B1, A1-B2, B1 A2) would be 2X.

2) You can't.  It is a unipolar stepper.

The EasyDriver faq number 5.1 at http://www.schmalzhaus.com/EasyDriver/ says:  "... The only kind you can't use is 5-wire stepper motors. (They need uni-polar drivers.)"

The difficulty with the 5-wire steppers is that they short the middle of the two coils together, which makes it hard to drive the coils independently.

Since you have the motor open, you might be able to do some surgery and disconnect the centers of the coils from each other, but you'll probably be better off getting a 4, 6 or 8 wire stepper instead.


body: Instead of doing surgery on your unipolar stepper, you can use it like a unipolar stepper. Some transistors to hook the motor to power (just get a darlington array chip), and four output pins on the arduino. Works fine.


message:
Arduino loading from file

Hello I have a programme that loads a piece of text from a file. In this case it loads "drawrect(4,10,20,20);" from the txt file and stores it in a string. I then use substrings to change the string into just "4,10,20,20" which is good but I need to simplify it down even more to four strings each with one of those 4 numbers in it.

Currently I use:

    void drawRectMethod(String s){
      String var1,var2,var3,var4;
      s = s.substring(s.indexOf('(') + 1);
      s = s.substring(0, s.lastIndexOf(')'));
      Serial.println(s);
    }
to simplify the string down to "4,10,20,20" but this wont work to store each number in a separate string. How can I can I store each variable in a separate string. The numbers will be stored in var1 - var4.

body:
Need some more help? As I previously wrote that snippet I might as well continue until you understand how to use indexOf() and substring().

      String s = "draw(10,20,30,40)";

      // Parse the argument list
      s = s.substring(s.indexOf('(') + 1);
      s = s.substring(0, s.lastIndexOf(')'));

      // Parse comma separated arguments
      String arg[4];
      for (int i = 0; i < 3; i++) {
        int ix = s.indexOf(',');
        arg[i] = s.substring(0, ix);
        s = s.substring(ix + 1);
        Serial.println(arg[i]);
      }
      arg[3] = s;
      Serial.println(arg[3]);

There is absolutely no error handling in this. You will have to add that. You can also improve the parse of the right parenthesis. That could be added last instead.

Later in the game we will come to why using String is a bad idea and why a character buffer and the standard library functions such as [strtok()][1] is a much better solution strategy both performance and memory footprint and especially heap.

      char* s = (char*) "draw(10,20,30,40)";
      s = strtok(s, "(),");
      Serial.println(s);
      while ((s = strtok(NULL, "(),")) != NULL)
        Serial.println(s);

Maybe the simplest solution is to use [sscanf()][2]. That will also do the conversion from text to binary.

      const char* s = "draw(10,20,30,40)";
      int x, y, w, h;
      int n = sscanf(s, "draw(%d,%d,%d,%d)", &x, &y, &w, &h);
      Serial.print(F("n="));
      Serial.println(n);
      Serial.print(F("x="));
      Serial.println(x);
      Serial.print(F("y="));
      Serial.println(y);
      Serial.print(F("w="));
      Serial.println(w);
      Serial.print(F("h="));
      Serial.println(h);

Cheers!

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__avr__string.html#ga6ace85338eafe22a0ff52c00eb9779b8
  [2]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdio.html


message:
Problem with inaccurate delays between sensor readings

During the last two months I have been working on a project that consists of using a Seeeduino Stalker V2.3, two AM2305 sensors, a TSL2561 sensor, an HC-05 XBee module, a 1,800 mAh 3.7V LiPo, a 7 cm x 7 cm 5V solar cell, and a waterproof suction box, to assemble a portable and waterproof environmental data logger that can be used to take samples on a continuous basis (1 sample every 30 minutes, 48 samples per day).

After struggling to make my logger work, I finally did it last week. It all runs fine, except that the intervals between readings are incorrect. When I program my board to store samples every 30 minutes (1,800,000), it takes them every 30 minutes and some extra seconds. When I try the same but with a rate of 1 sample every 10 seconds, my device logs data every 13 seconds more or less...

Here is the code I have been using:

    #include "SPI.h"
    #include "Wire.h"
    #include "SD.h"
    #include "DS3231.h"**

    DS3231 clock;
    RTCDateTime dt;

    #include "DHT.h"

    #define DHTPIN 8
    #define DHTTYPE DHT21
    DHT dht1(DHTPIN, DHTTYPE);
    #define DHTPIN2 7
    DHT dht2(DHTPIN2, DHTTYPE);
    #include "TSL2561.h"
    TSL2561 tsl(TSL2561_ADDR_FLOAT);

    const int chipSelect = 10;
    int XBEE = 5;
    int FLASH = 4;

    void setup() {
      pinMode(5, OUTPUT);
      digitalWrite(XBEE, HIGH);
      Serial.begin(9600);
      Wire.begin();
      clock.begin();
      analogReference(INTERNAL);
      pinMode(10, OUTPUT);
      pinMode(4, INPUT);
      SD.begin(10);
      dht1.begin();
      dht2.begin();
      Serial.println("EcoLOGGER DE PRUEBA PARA GENERACION DE DATOS ...");
      Serial.println(" ");
      delay(3000);
      Serial.println("RECUERDA QUE ESTE PROYECTO NO HUBIERA SIDO POSIBLE SIN LA AYUDA DE LA COMUNIDAD ARDUINO...");
      Serial.println(" ");
      delay(3000);
    }

    int counter = 0;

    void loop() {
      float h = dht1.readHumidity();
      float t = dht1.readTemperature();
      float f = dht1.readTemperature(true);
      float h2 = dht2.readHumidity();
      float t2 = dht2.readTemperature();
      float f2 = dht2.readTemperature(true);
      dt = clock.getDateTime();
      if (tsl.begin()) {
      } else {
        while (1);
      }
      tsl.setGain(TSL2561_GAIN_0X);
      tsl.setTiming(TSL2561_INTEGRATIONTIME_402MS);
      uint16_t x = tsl.getLuminosity(TSL2561_FULLSPECTRUM);
      uint32_t lum = tsl.getFullLuminosity();
      uint16_t ir, full;
      ir = lum >> 16;
      full = lum & 0xFFFF;
      float vis = full-ir;
      Serial.print("Muestreo: ");
      Serial.println(counter);
      Serial.print("Fecha: ");
      Serial.print(dt.day);
      Serial.print('/');
      Serial.print(dt.month);
      Serial.print('/');
      Serial.println(dt.year);
      Serial.print("Hora: ");
      Serial.print(dt.hour);
      Serial.print(':');
      Serial.print(dt.minute);
      Serial.print(':');
      Serial.println(dt.second);
      Serial.print("Temperatura sistema: ");
      Serial.print(clock.readTemperature());
      Serial.println("*C ");
      Serial.print("Voltaje bateria: ");
      Serial.print(analogRead(A7) * (1.1 / 1024)* (10+2)/2);
      Serial.println(" V ");
      Serial.print("Carga bateria: ");
      Serial.print(-149.4 + 59.52 * (analogRead(A7) * (1.1 / 1024)* (10+2)/2));
      Serial.println("% ");
      Serial.print("Luz FULL: ");
      Serial.println(full);
      Serial.print("Temperatura ambiente: ");
      Serial.print(t);
      Serial.println(" *C ");
      Serial.print("Humedad relativa: ");
      Serial.print(h);
      Serial.println("%");
      Serial.print("Temperatura suelo: ");
      Serial.print(t2);
      Serial.println(" *C ");
      Serial.print("Humedad suelo: ");
      Serial.print(h2);
      Serial.println("%");
      Serial.println(" ");
      digitalWrite (FLASH, HIGH);
      File dataFile = SD.open("datalog.txt", FILE_WRITE);
      if (dataFile) {
        dataFile.print(" Muestreo: ");
        dataFile.print(counter);
        dataFile.print(",");
        dataFile.print(" Fecha: ");
        dataFile.print(dt.day);
        dataFile.print('/');
        dataFile.print(dt.month);
        dataFile.print('/');
        dataFile.print(dt.year);
        dataFile.print(",");
        dataFile.print(" Hora: ");
        dataFile.print(dt.hour);
        dataFile.print(':');
        dataFile.print(dt.minute);
        dataFile.print(':');
        dataFile.print(dt.second);
        dataFile.print(",");
        dataFile.print(" Temperatura sistema: ");
        dataFile.print(clock.readTemperature());
        dataFile.print("*C ");
        dataFile.print(",");
        dataFile.print(" Voltaje bateria: ");
        dataFile.print(analogRead(A7) * (1.1 / 1024)* (10+2)/2);
        dataFile.print(" V ");
        dataFile.print(",");
        dataFile.print(" Porcentaje carga: ");
        dataFile.print(-149.4 + 59.52 * (analogRead(A7) * (1.1 / 1024)* (10+2)/2));
        dataFile.print("% ");
        dataFile.print(",");
        dataFile.print(" Luz FULL: ");
        dataFile.print(full);
        dataFile.print(",");
        dataFile.print(" Temperatura ambiente: ");
        dataFile.print(t);
        dataFile.print(" *C ");
        dataFile.print(",");
        dataFile.print(" Humedad relativa: ");
        dataFile.print(h);
        dataFile.print("%");
        dataFile.print(",");
        dataFile.print(" Temperatura suelo: ");
        dataFile.print(t2);
        dataFile.print(" *C ");
        dataFile.print(",");
        dataFile.print(" Humedad suelo: ");
        dataFile.print(h2);
        dataFile.print("%");
        dataFile.println("");
        dataFile.close();
        digitalWrite (FLASH, LOW);
      } else {
        Serial.println("");
        Serial.println("IMPOSIBLE GUARDAR DATOS");
        Serial.println("");
      }
      counter++;
      if (counter > 5) {
        delay (1000);
        digitalWrite (XBEE, LOW);
        delay (1799000);
      } else
        digitalWrite (XBEE, HIGH);
      delay (10000);
    }

I have been trying to find possible solutions, but I am just lost. Do any of you have an idea of what could be going on?

Thank you in advance :)

body:
The problem is that you are using `delay()`.

`delay()` will wait, from the moment `delay()` is called, for the given number of milliseconds.

That is, in more structured terms:

1. Do something
2. Do something else
3. Do something more
4. Wait 30 minutes

That will only take precisely 30 minutes if steps 1 to 3 take absolutely no time at all.  And that will never be the case. Things take time. Reading from sensors, writing to SD cards, etc, all take time.

So waiting for 30 minutes between doing things means that every 30 minutes will be slightly later than the one before.

And as you saw the difference is more pronounced when you have 10 seconds instead - it ends up as 13 seconds.  So your other actions - reading from sensors, writing to SD card, etc, must be taking about 3 seconds each time.

So instead of "Stop everything for half an hour", you need to think slightly differently:

1. Look at the time.
2. Decide if 30 minutes have passed since the last time you ran the code
3. Remember the time so you can know when 30 minutes have elapsed next time
4. Do your sensor/SD actions.

Since you're now keying things happening on the difference between now and when you last *started* to do things you get a 30 minute *total* delay, rather than a 30 minute delay *plus other bits*.

For an example of how this is done programatically you can look at the *BlinkWithoutDelay* example in the Arduino IDE.


body:
The second problem is that delay() on the arduino uses the on-board clock cycle. This is powered by a resonator, which can be off by as much as 10%. If you need accurate timings and timestamps, you will want to use a Real-Time Clock (RTC) module.

Instead of using delay, the loop() asks the RTC what time it is, and uses that to determine if it's time to take another reading.

Another very common thing for this type of monitoring is for the arduino to go into sleep mode and be woken by a tick from the RTC every second (or longer), in order to extend the battery life.


message:
Change Servo Speed With RedBearLabs BLE Shield

I recently got the RedBearLabs BLE shield to use it to control two high spped continuous rotation servos. I have the BLE example sketch loaded and the ios controller app works. The problem is that the servos are too fast to control and I want to slow them down. I cannot use the app to slow them down. I was wondering how I could modify the example sketch or servo library to change the ax speed or something. Thanks in advance.

BLE Shield Homepage: http://redbearlab.com/bleshield/

BLE Libraries and Example Sketch: https://github.com/RedBearLab/nRF8001

body:
The bi-directional Parallax [High Speed Continuous Rotation Servo](https://www.parallax.com/product/900-00025) responds to “simple pulse-width modulation”, according to its web page.  That is, pulse widths in the range from about 500 μs to 2500 μs will set the speed and direction, with some value near 1500 μs corresponding to zero RPM.

The code in the [BLEControllerSketch](https://codebender.cc/sketch:245943#BLEControllerSketch.ino) uses the following bits of code, among others, to initialize servo-control data structures and to control them:

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

    #include <Servo.h>
    ...
    byte pin_servo[TOTAL_PINS];
    Servo servos[MAX_SERVOS];
    ...
          case 'O': // set Servo
            {
              byte pin = ble_read();
              byte value = ble_read();

              if (IS_PIN_SERVO(pin))
                servos[PIN_TO_SERVO(pin)].write(value);
              pin_servo[pin] = value;
              reportPinServoData(pin);
            }
            break;

Thus, you will need to send an `O` message from your iOS app, together with servo pin number and control value, to set a servo's speed.

As noted on the [ServoWrite](https://www.arduino.cc/en/Reference/ServoWrite) page at arduino.cc, the parameter to Servo's `.write()` method is a number:

> On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. On a continuous rotation servo, this will set the speed of the servo (with 0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement).

You can find out a little more by looking at Servo's `.write()` method in Servo.cpp:

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

    void Servo::write(int value)
    {
      if(value < MIN_PULSE_WIDTH)
      {  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
        if(value < 0) value = 0;
        if(value > 180) value = 180;
        value = map(value, 0, 180, SERVO_MIN(),  SERVO_MAX());
      }
      this->writeMicroseconds(value);
    }

`SERVO_MIN()` and `SERVO_MAX()` are macros that access `min` and `max` fields in a `Servo` object and convert them to microsecond values.  Because the code in BLEControllerSketch.ino lets those fields default, the range evidently will be from 544 to 2400 μs (see the values given in Servo.h).

Note that you can get better resolution – hence, better speed control – by sending values in that range of microseconds to your servos, instead of trying to control it using values in degrees.  The `.write()` method will interpret such numbers as microseconds instead of as degrees.  Servo.cpp appears to use half-microsecond timer ticks; and each degree corresponds to about 10 μs of pulse width; so resolution using microsecond values should be about 10 times better than using degrees.

In short, it appears that you should do some experimenting with `O` messages that send values around 1500, to find the values that correspond to slowest forward and backward speeds.


message:
How to split a string received via a GSM module (message)

I am doing a motorcycle security system. In this system, I will receive a message from GSM in the form `{password:operation (like start,stop,alarm):time}`.
Example:(9990:start:30)

now i need to split  each term seperately (a=9990,b=start,c=30).help me to solve

body:
Simplest solution is to use [sscanf()][1].

      int password;
      char operation;
      int time;
      char* buf = "{14:C:123}";
      int n = sscanf(buf, "{%d:%c:%d}", &password, &operation, &time);
      Serial.print(F("n="));
      Serial.println(n);
      Serial.print(F("password="));
      Serial.println(password);
      Serial.print(F("operation="));
      Serial.println(operation);
      Serial.print(F("time="));
      Serial.println(time);

  [1]: http://www.cplusplus.com/reference/cstdio/scanf/


message:
Double clap sensor not working as intended

I have this double clap sensor code written, it seems it would work but it seems to trigger the double clap even on a single clap, any ideas?

<!-- language: c -->

    int soundSensor = A1;
    int relay = A2;
    int relay2 = A3;
    int relay3 = A4;
    int relay4 = A5;
    int claps = 0;
    long detectionSpanInitial = 0;
    long detectionSpan = 0;
    boolean clapState = false;
    int doubleClap = 0;

    //Light sensor
    int photocellPin = A0;     // the cell and 10K pulldown are connected to a0
    int LEDbrightness;

    //int delayValue = 100;
    int photoSensor = 0;

    // sound sample
    const int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz)
    unsigned int sample;

    //other
    boolean isRelaysOn = false;
    void setup() {
      pinMode(soundSensor, INPUT);
      pinMode(relay, OUTPUT);
      pinMode(relay2, OUTPUT);
      pinMode(relay3, OUTPUT);
      pinMode(relay4, OUTPUT);
      turnRelayOff();
      Serial.begin(9600);
    }

    boolean state = false;
    boolean lastState = true;
    boolean lightTurnedItOff = false;
    void loop() {

      /////////////
      // photo sensor
      ////////////////////

      photoSensor = analogRead(photocellPin) > 623;

      /////////////
      // clap sensor
      /////////////////////
      double sensorState = getSoundLevel();
      Serial.println(sensorState);
      double threshold = .2;

      if (sensorState > threshold)
      {
        if (claps == 0)
        {
          detectionSpanInitial = detectionSpan = millis();
          claps++;
        }
        else if (claps > 0 && millis()-detectionSpan >= 50)
        {
          detectionSpan = millis();
          claps++;
          Serial.println(" CLAP ADDED!!!!");
        }
      }

      if (millis()-detectionSpanInitial >= 400){

        if (claps == 2)
        {
          claps++;
          doubleClap = 1 - doubleClap;
          state = !state;
          Serial.println("TWO claps!");

          if(lastState == state ){
            relayControl(doubleClap);
            lastState = !lastState;
          }
        }
        claps = 0;
      }

      if(isRelaysOn == true && photoSensor == 1){
        turnRelayOff();
        lightTurnedItOff = true;
      }
      if(isRelaysOn == true && photoSensor == 0 && lightTurnedItOff == true){
        turnRelayOn();
        lightTurnedItOff = false;
      }

    }

    void relayControl(int doubleClap){
      /////////////
      // relay control
      /////////////////////

      if(doubleClap == 1){
        turnRelayOn();
        Serial.println("on");
        isRelaysOn = true;

      }
      else{
        turnRelayOff();
        Serial.println("off");
        isRelaysOn = false;
      };

    }

    void turnRelayOn(){
      int delayAmount = 100;
      digitalWrite(relay, LOW);
      delay(delayAmount);
      digitalWrite(relay2, LOW);
      delay(delayAmount);
      digitalWrite(relay3, LOW);
      delay(delayAmount);
      digitalWrite(relay4, LOW);
      delay(100);
      digitalWrite(relay4, HIGH);
      delay(100);
      digitalWrite(relay4, LOW);
    }

    void turnRelayOff(){
      digitalWrite(relay, HIGH);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, HIGH);
    }

    double getSoundLevel(){

      unsigned long startMillis= millis();  // Start of sample window
      unsigned int peakToPeak = 0;   // peak-to-peak level

      unsigned int signalMax = 0;
      unsigned int signalMin = 1024;

      // collect data for 50 mS
      while (millis() - startMillis < sampleWindow)
      {
        sample = analogRead(soundSensor);
        if (sample < 1024)  // toss out spurious readings
        {
          if (sample > signalMax)
          {
            signalMax = sample;  // save just the max levels
          }
          else if (sample < signalMin){
            signalMin = sample;  // save just the min levels
          }
        }
      }
      peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
      double volts = (peakToPeak * 3.3) / 1024;  // convert to volts

      return volts;
    }

Serial monitor:

> 0.02
> 0.02
> 0.02
> 0.02
> 0.01
> 0.01
> 2.20
> 0.30  CLAP ADDED!!!!
> 0.13
> 0.09
> 0.04
> 0.02
> 0.02
> 0.01
> 0.02 TWO claps! on
> 1.11
> 0.06
> 0.05
> 0.07
> 0.15
> 0.10
> 0.03
> 0.10
> 0.06
> 0.03
> 0.04
> 0.06

body:
I have noticed that you have used analogue inputs as your digital outputs by connecting relays to them.

I think this is wrong. You should connect your digital signals to the digital pins.


body: If your first clap rings for more than 50ms, the program counts it as a second clap.  After detecting a clap, you need to wait for the sound to die down before you start listening for a second clap.


body:
What you probably want to track is something more like:

 - high sound period of highMin to highMax ms
 - low sound period of lowMin to lowMax ms
 - high sound period of highMin to highMax ms
 - low sound period of at least lowDone ms (no max needed)

Anything not meeting those time bounds is not two claps, reset state and timers.  If you get to the end of the fourth step, accept as two claps.

I have not tested timing of claps to estimate the periods needed; you need to tweak that with the hardware you are actually using; for example, different microphones may ring for different times after a sharp clap impulse.

States could be:

 - waiting for start of first clap (sample until > threshold)
 - waiting for end of first clap (sample until < threshold or timeout)
 - waiting for start of second clap (sample until > threshold or timeout)
 - waiting for end of second clap (sample until < threshold or timeout)
 - got second clap


message:
Send AND Receive through i2c / set Arduino as master AND slave

For a project I'm using 2 Arduino Uno's, where Arduino#1 (master) sends raw data to Arduino#2 (slave). The slave should receive and encrypt the data and afterwards send the encrypted data back to the master. I'm building my project from the [sketch found at arduino.cc][1].

How can I make the slave send back data, if he's the only one listening on incoming data, should both arduinos be listening to each other, and how to achieve this?

  [1]: https://www.arduino.cc/en/Tutorial/MasterWriter

body:
The I2C protocol is both read and write. Master/Slave depends on who initiates the communication. Typically the master will issue a read command to the slave to retrieve the results.

Cheers!


message:
how to solve Varing duty cycle value while using Pulsein()

Well im new to coding, but i do have the basic knowledge.
I'm using an UNO to measure a duty cycle.
The source of pulse is a Tektronic signal generator (Duty cycle set to 50.000 with frequency of 2khz).
my code is as follows,

    byte PWM_PIN = 3;
    float pwm_value_H;
    float pwm_value_L;
    float D;

    void setup() {
     pinMode(PWM_PIN, INPUT);
     Serial.begin(115200);
    }

    void loop() {
     pwm_value_H = pulseIn(PWM_PIN, HIGH);
     Serial.println(pwm_value_H);
     pwm_value_L = pulseIn(PWM_PIN, LOW);
     Serial.println(pwm_value_L);
     D = ((pwm_value_H) / (pwm_value_H + pwm_value_L)) * 100.0;
     Serial.print("D=");
     Serial.println(D);
     Serial.print("D=%");
    }

but the problem is that my output value of "D" keeps on varying between 49.71, 49.90, 50.00 and 50.7
Is this because of PULSEIN() function ineffiency?
or can anyone suggest a better way to measure the duty cycle with +/- 0.01 accuracy.

Regards,
Cj

body:
I would start by removing Serial interrupts from the pulseIn period.

    void loop() {
        pwm_value_H = pulseIn(PWM_PIN, HIGH);
        pwm_value_L = pulseIn(PWM_PIN, LOW);
        Serial.println(pwm_value_H);
        Serial.println(pwm_value_L);
        D = ((pwm_value_H) / (pwm_value_H + pwm_value_L)) * 100.0;
        Serial.print("D=");
        Serial.println(D);
        Serial.print("D=%");
        Serial.flush();
    }

For higher accuracy I would then look to the Timer based Input Capture.

Cheers!


body:
There's two basic things wrong with what you are doing there:

1. `pulseIn()` isn't good for very accurate measurements
2. The signal is still happening while you're doing other things, such as printing the high/low times.

You're not actually measuring the duty cycle of one single cycle, but the HIGH time of one cycle followed by the low cycle of a later one. If you want to do it properly you will have to ditch `pulseIn()` and instead get your head around interrupts and timestamps.

The basic method is to present the signal to one of the INT pins, and attach an interrupt to that pin with the trigger set to CHANGE.  The interrupt routine you specify will then be triggered every time the signal changes from HIGH to LOW or from LOW to HIGH.

Then the interrupt routine does very little.  It basically records the time the interrupt happened (that must be the very first thing you do), then looks to see if it's a HIGH or a LOW signal on the pin.  You then use the previous timestamp from the last time the interrupt was triggered to work out how long the previous phase lasted and set either a HIGH or a LOW variable depending on the current level of the state (if it's low set a high variable since that was the previous phase level, and if it's high set a low variable) with the time that phase lasted.

Then in your main loop you interrogate those variables periodically to display the duty cycle.

If that still isn't accurate enough then you should look at the hardware *Input Capture* module built into the MCU. That uses a hardware timer in much the same way as the interrupt but is able to capture a much more accurate time stamp for you since the time stamp is grabbed the moment the signal changes, rather than after a short delay once the interrupt routine has been called.  Details can be found in the datasheet for the MCU on your Arduino.


message:
At what level does low dynamic memory effect performance?

I have a few Arduino sketches that take 70-90% of dynamic memory. It seems that over 70%, the compiler gives the warning:

    Low memory available, stability problems may occur.

but otherwise I wasn't noticing any problems.

Then I uploaded a sketch that took 89%, which logged String data to the serial port, and found that only newlines were being written out. When I commented out some global variables so that dynamic memory usage got to 88%, then it started printing out the data.

Is there any hard/fast rule on when this problem occurs? I was surprised by this problem, because the global variables I removed weren't even being used in the sketch, so I had thought the compiler would have removed or optimized them so they didn't waste any space. Are there any ways to automatically improve compilation efficiency and detect wasteful variables?

body:
The problems occur when you run out of memory. That all depends on what you are doing with the memory that is available.

String objects are not good and are wasteful of memory. They really should be avoided, since they use dynamic memory allocation, which uses the "spare" memory that is what's left over from what the compiler says is used.

There is no rule, other than "don't run out of memory", and tracking dynamic usage can be very hard, so try to avoid using it if you can.


body:
The typical build memory statistics is:

    Global variables use XXX bytes (X%) of dynamic memory,
    leaving YYY bytes for local variables.
    Maximum is ZZZ bytes.

What is all this about? First, the maximum number of bytes SRAM depends on the MCU. Arduino Uno is ATmega328 based and has 2K byte SRAM. Arduino Mega2560 has 8K byte. "Dynamic memory" in the print out is SRAM. It is not the heap (malloc/free). To avoid confusion I will use "data memory" below.

The compiler allocates memory for all global variable (objects, struct, etc). It also allocates memory for literal strings (character vectors). These are copied from program memory to data memory at startup. All static variables in functions are also allocated. The sum of all these allocations are the "Global variables".

To execute the sketch data memory is used for the stack. It contains the function parameters, local variables in called functions (that are not allocated to registers), saved registers such as return address to the caller, etc. The size of the frame is known by the compiler and may be found in the assembly listing of a sketch. The maximum stack size required is tricky to calculate as it is the call chain with the largest frame size sum. This is not necessarily the deepest call chain. Also the compiler does to a fair amount of inlining.

The heap (malloc/free) is used by classes such as String. The heap starts directly after the global variables in data memory and grows towards the stack. The heap is blocks of memory allocated and deallocated during the execution of the sketch. This behavior may give heap fragmentation.

Interrupt Service Routines (ISR) need to be able to execute "on top of" any function call. The ISRs are typically called on hardware events such as USART data received. The compiler has to generate code that stores the machine state on stack to execute the ISR. Depending on how many registers the ISR needs more or less of the machine state (registers) need to be stored. The worst case is all 32 registers.

The warning at 30% of SRAM is at approx. 600 bytes left (Arduino Uno, 2K byte). That has to cover the stack and possible heap usage together with ISRs. With a stack heap limit of 32-128 byte, ISR frame of 32-64 byte, that actually leaves worst case approx. 400 bytes for local variables in functions and possible usage of the heap (such as String).

Cheers!


message:
Cannot receive data from GPS SD Shield V2-B

I am attempting to receive GPS data from a GPS SD Shield V2-B purchased from maplin. I have attempted the very simple sketch they provide on their website linksprite.com.
I have also tried following a tutorial found here: http://tronixstuff.com/2014/01/15/tutorial-arduino-mediatek-3329-gps/.
This is the code i am using:

        // Example 19.1

        #include <SoftwareSerial.h>
        SoftwareSerial GPS(2,3); // configure software serial port -

        void setup()
        {
          GPS.begin(9600);
          Serial.begin(9600);
          pinMode(13,OUTPUT);
        }
        void loop()
        {
          byte a;
            if (GPS.available() > 0 )
          {
            a = GPS.read(); // get the byte of data from the GPS
            Serial.write(a);
            digitalWrite(13,HIGH);
            delay(1000);
            digitalWrite(13,LOW);
            delay(1000);
          }
        }

I am using an Arduino 101. The jumpers on the GPS shield are set up as follows:[![enter image description here][1]][1]

I have attempted using both power simply from my Mac and an external 9V battery connected to the Arduino.
The 'blink' has been added the sketch to test whether data was being received but there was a problem with the serial monitor. This is not the case because the blink did not occur. It however did occur when moved outside of the if statement as you would expect.
Any help or suggestions would be much appreciated.

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

body:
You need to set the jumps as per the instructions that came with the shield ...
PAGE4 : short jumpers TX and MRX .... and RX and MTX


message:
if(Serial) not working correctly on micro or pro micro

I have an arduino micro and several clone "pro micro"'s both of which are based on the 32u4, i'm trying to make my project have a debug mode which is only active when the serial port is open, the documentation states that using:

    if (Serial)

on these boards should only return true if the port is open (on uart based connections it always returns true), i wrote my sketch to take advantage of that but it didn't seem to be working properly, so i stripped back to basics and wrote this sketch:

    void setup() {
      // put your setup code here, to run once:
     pinMode(2, OUTPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
     if (Serial){
      digitalWrite(2, HIGH);
     }
     else{
      digitalWrite(2, LOW);
     }
    }

I connected an LED to pin 2 and then tested it by connecting and disconnecting the arduino from the PC, and opening and closing the com port.

after freshly connecting the arduino to the PC the LED is off, when i open a connection to the virtual com port the LED turns on.
however i would expect the LED to go out once the port is closed, but it remains on.

My questions are:
1) have i got an out of date bootloader?
2) if so how do i check?
3) is this intended behavior and if so why?
4) is this a bug in the arduino bootloader or libraries?
5) short of having to change my code to look for serial data to start and stop the debug mode (serial comms are being used for other things in the background) is there any way i can work around this? reading from hidden registers etc?

Edit:
should have mentioned i'm seeing this behavior with or without a call to `Serial.begin`

body:
> 1) have i got an out of date bootloader?

No. This has nothing to do with the bootloader.

> 2) if so how do i check?

See above.

> 3) is this intended behavior and if so why?

In a manner of speaking, yes - see below.

> 4) is this a bug in the arduino bootloader or libraries?

No. Elsewhere.  See below.

> 5) short of having to change my code to look for serial data to start and stop the debug mode (serial comms are being used for other things in the background) is there any way i can work around this? reading from hidden registers etc?

Yes, you can, but only once you understand exactly what is going on.

The problem with USB serial (AKA CDC/ACM) communication is that there is no way of knowing if the port has been opened by the computer or not.  That functionality was just never designed into the protocol.

However, there are two virtual modem signals that the computer can assert that the CDC/ACM device at the other end can examine - one is the equivalent of DTR and the other the equivalent of RTS.

The Arduino's CDC/ACM code examines those, and if either are asserted then it assumes the CDC/ACM port is open. If neither are asserted then it assumes the port is closed.

Now comes the tricky part:  You have little or no control over when those signals are asserted or not.  There are three separate factors that decide what happens:

1. The software being run can manually control the signals.  The Arduino IDE does this to ensure boards that use DTR to reset (like the Uno, etc) actually do reset.
2. The drivers on the computer can decide to automatically control the signals when the port is opened or closed
3. The operating system itself can control the signals when the port is opened or closed.

Some software will control the RTS/DTR signals properly, some won't. Some drivers will control the signals for you, some won't. Some operating systems (such as Linux) will, unless otherwise instructed, default to automatically controlling the modem lines properly. Others, like Windows, won't.

So the only way you can be sure that these signals are being controlled properly is to manually control them from your own software used for debugging, or to find a specific terminal emulator that controls the lines properly.


body:
I am experiencing the same problem. My environment is Windows 10 on the host side and Arduino 1.6.7 with a genuine Arduino Micro board.

In the OP's sketch, after compiling and uploading, the light does not go on until you open the serial monitor. This is as expected and shows that the Arduino side has some way of knowing that the serial monitor has started.

However if you close the serial monitor, the light stays on. It also stays on if you unplug the USB cable. It goes off when you plug the cable back in and goes back on when you restart the serial monitor.

With some further experimentation and poking around the code, I found that _usbLineInfo.lineState > 0 and thus Serial returns True if either DTR or RTS from the host is nonzero. DTR goes to 0 when the serial monitor is closed but RTS stays HIGH so Serial stays True.

The fix is to use the (undocumented) method Serial.dtr(). This is True only if the serial monitor is running.

[edit] If your system has external power so that it should keep working with the USB cable unplugged, testing Serial.dtr() works as long as you you always close the serial monitor before unplugging the USB cable. However it will remain True if the cable is unplugged before closing the serial monitor.

To detect the cable being unplugged, add the line

`USBCON |= 1<<OTGPADE;`

to setup(). This enables detection of an unplugged USB cable. Then in your loop

`(USBSTA & (1<<VBUS))`

will be True if the USB cable is plugged in and has power.


message:
CAN communication with Arduino

I'm a member of a [Formula SAE][1] team and we use the Performance Electronics ECU which uses the CAN protocol with a speed of 250 kbit/s and works fine with our 2D Recording Systems Data logger, but we're trying to build a telemetry system which gathers the same data from the CAN bus using an Arduino Uno and CAN shield provided by SparkFun Electronics.

However the CAN shield we're trying to use has failed to initialise the communication with the bus. Kindly help me out on what can be done or are there any alternatives of communicating using CAN with Arduino?

P.S. The link for the CAN shield: [CAN-Bus Shield Hookup Guide][2]

  [1]: https://en.wikipedia.org/wiki/Formula_SAE
  [2]: https://learn.sparkfun.com/tutorials/can-bus-shield-hookup-guide

body:
Beware, the industry standard pinout for CAN on DB9 connectors is different to what Sparkfun use on their shield:

- pin 3/5 [CAN bus shield schematic][1]
- pin 2/7 (Vector tools for example).

Which software have you been using on the Arduino? Any additional info on the ECU you're using, and the wiring in your system?

  [1]: https://www.sparkfun.com/datasheets/DevTools/Arduino/canbus_shield-v12.pdf


body:
I found this wiki particularly useful: [CAN-Bus Shield Wiki][1]

  [1]: http://www.seeedstudio.com/wiki/CAN-BUS_Shield

And yes, like CQuinson said, you have to pay attention to the pins used. I know Sparkfun is known for having an issue with which pin the CS pin is assigned to (D9 or D10).


message:
Does the VCC Output pin always give out a consistent 5V Voltage supply? What is the current output?

This is the Chip I have. On the chip it says ProMini R160JAC6v. and When i program it. It programs under 5V 16MHz with ATmega 328

[![5V 16MHz with ATmega 328. If I want to power a 3.3V bluetooth chip can I do it with my board? ][1]][1]

Here is the bluetooth chip I am powering:

[![Back Side][2]][2]

  [1]: https://i.stack.imgur.com/meuD5.jpg
  [2]: https://i.stack.imgur.com/1iVWM.jpg

body:
If you power from USB the vcc pin gives you the voltage that USB is providing. Somewhere between 4.75 and 5.25v.

If you use external power it provides 5v since that is what the regulator provides.

The current limit is either the limit of the usb port or the limit of the regulator on your board. Check the datasheet for that regulator (hint: read the schematic to find the model of the regulator).


message:
Is RX1 and TX0 the same thing as TX and RX? Will there be a difference in the way I program it?

I have an Arduino.

I'm not sure if RX1 and TX0 the same thing as TX and RX? Will there be a difference in the way I program it?

For example, do I treat RX1 and TX0 as RX and TX in the Arduino IDE when coding?

This is the chip I have. On the chip it says "ProMini R160JAC6v" and when I program it, it programs under 5V 16MHz with ATmega 328. Notice RST RX1 and TX0 are on the top left corner.

[![ProMini R160JAC6v 5V 16MHz with ATmega 328][1]][1]

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

body:
It's not RX1 and TX0 but RXI and TXO

That is receive input and transmit output,

Exactly the same as RX and TX just with the data direction explicitly shown in the lettering.


body:
Yes you treat them the same, they are the same pins.

It looks like (in the photo) you're connecting a bluetooth module.
Be careful when uploading your sketch.  If you connect something to TX/RX (pins 0 & 1) it may be necessary to disconnect it for arduino-uploading to work.

You may find it a more convenient solution to declare a SoftwareSerial on different ports and use that for the bluetooth communications.


message:
Driver shield providing 24+ pins at 100mA (for Mega 2560)

Do any shields (or similar boards) exist to let the Mega 2560 (or Due) output a full 100mA per pin on at least 24 pins, in a digital on/off fashion? I know there is a motor shield, but it looks to have only a handful of outputs. It seems very common that people need to output higher current than the MCU can provide safely (if at all), but there do not appear to be any shields for this. Of course individual transistors are fine for a few outputs, and some chips can do up to 8, but what about the rest of us who want to use all those nice pins on the Mega, Due, or similar but who need more power?

body: You'll likely have to use an https://www.arduino.cc/en/Main/ArduinoProtoShield with 3+ of those chips you like that do up to 8.


body:
You can:

 * use a driver chip, e.g. ULN2803 which gives you 8 outputs of up to somewhat 500mA from 8 digital pins

 * use a serially addressible power+logic chip, such as TPIC6A595NE which gives you 8 outputs, each can drive 350mA, and has a built-in *short circuit protection*. You can cascade these, 3 chips give 24 outputs, and need only three pins to drive all 24 (or more if you use more chips) outputs.

 * There are 24 output devices, however not in this current range. 24 output devices are usually i2c or spi based led controllers - some of them gives you goodies like rock solid hardware PWM on all 24 ports - but none of them gives you 100mA output.


message:
Using Arduino IDE as an API

I have a project where it would make a lot of sense to generate Arduino compatible source code, compile it and flash it based on some settings in the project software.

Is there any way to do this without having to rely on the user having installed the Arduino IDE/java?

The ideal would be a self-contained library that could be linked to my C/C++ program.

body:
Have you tried [Arduino C Scaffold project][1]?

> ...the scaffolding lives on Github in the Throw The Switch organization as the Arduino C Scaffold project. This should have everything you need to deploy a C project on an Arduino UNO without the Arduino IDE. If you know your way around Git, you can clone this repository and get to work. If you’d rather not mess with Git right now, you can download the latest revision of the scaffold in a zip file. Once you have the scaffold, take a look at the README. This will walk you through getting the AVR toolchain setup on your environment and describe some of the different ways to use the scaffold.
-- https://spin.atomicobject.com/2011/10/15/taking-the-training-wheels-off-the-arduino/

  [1]: https://github.com/ThrowTheSwitch/arduino_c_scaffold


body:
For compiling and uploading Arduino code, you do not need Java, nor the
Arduino IDE: you need avr-gcc, avr-libc, the Arduino core library and
avrdude. With a proper Makefile, your program just needs to

    system("make upload");

C.f. the tutorial [Compiling Arduino sketches using
Makefile](http://hardwarefun.com/tutorials/compiling-arduino-sketches-using-makefile).
On an Ubuntu or other Debian-like OS, you would just
`sudo apt-get install arduino-mk make` to get everything you need installed.


message:
Arduino Due Port Not Found

I've got an arduino due and I'm having great difficulty connecting to it. The problem seems to come and go, I was using it just fine only 3 or 4 hours ago but now it just won't connect. I've got the board set to the Arduino Due Native Port and the port set to the /dev/cu.usbmodem1421 (Arduino Due Native Port). Every time I try and upload the sketch however, it gives me this error:

        Arduino: 1.6.6 (Mac OS X), Board: "Arduino Due (Native USB Port)"

    Sketch uses 10,316 bytes (1%) of program storage space. Maximum is 524,288 bytes.
    processing.app.debug.RunnerException
     at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:130)
     at cc.arduino.UploaderUtils.upload(UploaderUtils.java:78)
     at processing.app.Sketch.upload(Sketch.java:1178)
     at processing.app.Sketch.exportApplet(Sketch.java:1152)
     at processing.app.Sketch.exportApplet(Sketch.java:1124)
     at processing.app.Editor$DefaultExportHandler.run(Editor.java:2452)
     at java.lang.Thread.run(Thread.java:745)
    Caused by: processing.app.SerialException: Error touching serial port '/dev/cu.usbmodem1421'.
     at processing.app.Serial.touchForCDCReset(Serial.java:87)
     at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:119)
     ... 6 more
    Caused by: jssc.SerialPortException: Port name - /dev/cu.usbmodem1421; Method name - openPort(); Exception type - Port not found.
     at jssc.SerialPort.openPort(SerialPort.java:167)
     at processing.app.Serial.touchForCDCReset(Serial.java:81)
     ... 7 more
    Error opening serial port '/dev/cu.usbmodem1421'. (Port not found)

      This report would have more information with
      "Show verbose output during compilation"
      enabled in File > Preferences.

body: Not sure what all that was but a simple restart of my computer seemed to fix it.


message:
Iterate an Object Array

I'm trying to create an array of objects and later iterate over it and do something with each object. My C++ skills just don't go far enough.

Here's what I have so far. I've tried to strip out all the meaningless code. Whats wrong is my tr object is not what I expect it to be. It's numOfCars property is 0 so I know I'm not accessing the train object that I expected.

    #include <stdlib.h>

    class Train {
     public:
      int numOfCars;
      void init();
      void move();
    };

    void Train::init() {
     //code intentionally removed
    }

    void Train::move() {
     //code intentionally removed
    }

    const int trainCount = 2;
    Train train1;
    Train train2;
    Train trains[trainCount] {train1, train2};

    void setup() {
     Serial.begin(9600);
     train1.numOfCars = 5;
     train1.init();

     train2.numOfCars = 5;
     train2.init();
    }

    void loop() {
     for(int n = 0; n < trainCount; n++) {
      Train tr = trains[n];
      Serial.println(tr.numOfCars); //always prints 0
      tr.move();
     }
    }

body:
You are not creating an array of references, you are creating the array from the objects; they are being copied. You can see that this by moving the line (and adding an equals)

    Train trains[trainCount] = {train1, train2};

to the bottom of your setup method. However, that is beside the point, as you are not fully using the power of arrays. You needn't create separate objects everywhere, simply create an array of objects right off the bat with `new[]` and use them. Like this:

    #include <stdlib.h>

    class Train {
        public:
            int numOfCars;
            void init();
            void move();
    };

    void Train::init() {}
    void Train::move() {}

    const int trainCount = 2;
    Train* trains = new Train[trainCount];

    void setup() {
        // initialize trains
        for (int i = 0; i < trainCount; ++i) {
            trains[i].numOfCars = 5;
            trains[i].init();
        }
        Serial.begin(9600);
    }

    void loop() {
        for(int n = 0; n < trainCount; n++) {
            Serial.println(trains[n].numOfCars); //always prints 0
            trains[n].move();
        }
    }


body:
As uint128\_t has already put it, your problem is that you are creating
an array of copies. You should really avoid copying trains around,
especially if you are going to put a significant amount of data in them.
Instead, just create them once in the array, and then you can either
invoke them as array members directly (e.g. `trains[0].init();`) or use
references.

For example, if you initialize your trains like this:

    const int trainCount = 2;
    Train trains[trainCount];
    Train &train1 = trains[0];
    Train &train2 = trains[1];

Then the "real" trains live in the array, and `train1` and `train2` are
references to them. The rest of your code should work fine unchanged. I
would however suggest to avoid copying the trains in loop:

    void loop() {
        for(int n = 0; n < trainCount; n++) {
            Train &tr = trains[n];        // notice the '&'!
            Serial.println(tr.numOfCars);
            tr.move();
        }
    }


message:
What isthe best programming language for embedded systems?

I would start to learn the best programming language for embedded systems to control devices. What I have heard about that is Assembly Language. I want to know if there is any better languages to code for embedded systems?

body:
Before your question gets closed:

**There is no such thing as "the best"**

**Assembly**
Assembly can be a very powerful language. But at the cost of some:

 - Assembly is different per machine. https://cs.stackexchange.com/questions/46935/is-a-universal-assembly-language-for-all-computers-possible
 - Assembly is somewhat less readable as other programming languages in my honest opinion.
 - I personally feel that assembly should only be used for optimalization rather than standard use of code.

**C** C can be as powerful as assembly, only when used correct. In fact, in C (and C++) you can actually inline assembly. https://en.wikipedia.org/wiki/Inline_assembler

**C++** C++ is mostly backwards compatible with C, any C compiler (should?) be able to interpret/compile C code. Which also means you could use inline assembly.

C++ also comes with a lot of usefull tools, though, when used wrongly it can actually backfire you. (Which is with most programming languages that allow a lot, but also give you the possibility to do a lot)

I believe, that C++'s Object Oriented code, with the somewhat backward compatiblity and a little abstraction from the machine (being able to port it to other machines) would be the way to go.
Though, a good C/assembly programmer will out-play an average C++ programmer.

**What about the other languages**

C/C++ could be considered as the standard for embedded devices.

Best thing would be, to ask for individual programming languages, and why one would be better than the other. Or what the differences are.

I havent yet found anything that could "compile" Java for embedded devices. Java typically runs in a "run-time evironment". Which would come down to the fact that it needs an OS or atleast some resources for the code to be run-time interpreted.

C/C++ is also known for being "hard real-time" or atleast deterministic qua timing. Which is probably because of the same reason, not needing another layer and being pre-compiled. (And not having an runtime environment)

By these arguments, I believe C++ or C or Assembly would be the best. Or atleast most widely accepted.
You should check per project, which languages are known by your developers and which other requirements there are (porting to other platforms).
And it's a bit of a taste issue. I think Object Oriented code is very usefull. But some may see it as excessive/annoying.


message:
3-Way Bluetooth Communication?

I need two Arduino units with the HC-06 Bluetooth board to communicate with each other and one of these Arduino units also connected to my Android phone. Is this possible to do with just two HC-06 modules, or even three? Or is there a better solution for this?

To reiterate what is going on here:
I have two Arduinos that are running off battery. Arduino 1 is sending data every 0.5 seconds to the Arduino 2. Arduino 2 collects this, adds its own bit of data to it, and then sends this new data packet to my Android phone which will only be connected to Arduino 2.

I haven't completely decided upon what kind of Arduino board to get, but it needs to be fairly small, but I am planning on the Adafruit Pro-Trinket 5v.

Hopefully you get the basic scenario, let me know if you need more clarification and what you think could be done here.

Thanks a lot!

body:
Should be possible, but only if you setup the Bluetooth module of Arduino 2 as the master. You see, Bluetooth requires to connect to a master. A master can connect to 8 slaves in total. Because Arduino 2 connects to multiple devices (Arduino 1 and your Android device) it should be the master. This also means your Android device cannot connect to any other devices.

Hope this gives you a place to start exploring.


message:
Serial Monitor not displaying anything

I have a very basic script that is supposed to display something to the serial monitor but no matter what I try the serial monitor won't display anything...I;ve watched about 5 tutorials now and each one has failed to display anything. Any ideas what I'm doing wrong?

Here is my code:

    char rx_byte;

    void setup() {
      Serial.begin(115200);
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
    }

    void loop() {
      if(Serial.available() > 0){
        rx_byte = Serial.read();
        Serial.print("You typed: ");
        Serial.println(rx_byte);
        digitalWrite(13, HIGH);
        delay(1000);
        digitalWrite(13, LOW);
      }
    }

body:
Try replacing the line `char rx_byte;` with `int rx_byte=0;`. Use `Serial.println(rx_byte,DEC);`

    int rx_byte=0;

    void setup() {
      Serial.begin(115200);
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
    }

    void loop() {
      if(Serial.available() > 0){
        rx_byte = Serial.read();
        Serial.print("You typed: ");
        Serial.println(rx_byte,DEC);
        digitalWrite(13, HIGH);
        delay(1000);
        digitalWrite(13, LOW);
      }
    }


body:
You have to change the baud rate at the right bottom corner of the serial monitor to 115200 which you have assigned initially.
I have tested it  and
It doesn't matter if its int/char


body:
> Which one are you using?
>
> The one closest to the reset button, I believe its the native...

This is more confusing than I realized. The Due has two ports:

[![Due ports][1]][1]

---

## Programming port

For programming, the programming port is easiest to use. **And** you can "talk" to the serial port using `Serial`, like this:

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ("Hello, world!");
      }  // end of setup

    void loop ()
      {
      }  // end of loop

---

## Native USB port

This lets you emulate USB devices (eg. keyboard, mice). However if you want to use it for Serial communications you need to use a different class `SerialUSB` like this:

    void setup ()
      {
      SerialUSB.begin(115200);
      while (!SerialUSB) ; // wait for it to become ready
      SerialUSB.println ("Starting ...");
      }  // end of setup

    unsigned long i;

    void loop ()
      {
      SerialUSB.print ("Hello, world! Count = ");
      SerialUSB.println (++i);
      delay (1000);
      }  // end of loop

It also helps to wait for the serial port to become ready, as I did in `setup`. Otherwise you may miss the first 10 lines or so of serial output.

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


message:
MATLAB - Read from 2 SPI inputs synchronously

I am using the MATLAB Arduino Support Package to create a setup where I can read force data from a load cell and positional data from an incremental encoder - then plot them on MATLAB. It must be done at the same time in order to produce a material stress-strain curve.

I am thinking of using the [SPI Device functions to do this][1].

Can the data from the load cell and encoder be read synchronously?

  [1]: http://uk.mathworks.com/help/supportpkg/arduinoio/spi-sensors.html

body:
 Yes and No.
 Synchronously in development slang means step-by-step execution. Asyncronously mean by some event.

 Arduino has only one core. Even if you use interrupt, Arduino can only execute one command at once.

 Best way for you I guess would be read both on Arduino and combine into single value to read at once. Just reading both with [readDigitalPin][1]  would give huge latency.

  [1]: http://www.mathworks.com/help/supportpkg/arduinoio/ref/readdigitalpin.html


body:
Truly parallel sampling is rarely needed.  Especially if you can separate the triggering (latching) of a reading in the peripheral from the act of subsequently transferring the latched value over SPI, it is likely you can merely trigger both in quick turn and then read them out in slightly slower turn.

But if you *truly* need simultaneous reading, then you will need a workaround.  The ATmega used in classic Arduinos only has one hardware SPI engine.  But you can also implement a software or "bit bang" SPI master using arbitrary digital I/O pins.

Typically this is done with single-bit GPIO operations, but if you place the critical SPI signals for both chips (probably SCLK, the others are usually only sampled at changes in that) on distinct pins of the same GPIO port, then you can use whole port operations at raw AVR level (below the Arduino API level) to drive them at effectively the same time.

To make this work, you would do the following:

1) For each SPI peripheral, figure out exactly at what transition of what part of what access sampling occurs. Make sure to include any internal setup or latency within the chip in the determination.

2) Start the access to whichever peripheral takes longer using port-wide operations which preserve the status of bits not related to this peripheral.

3) Add the access to the peripheral which takes less setup before the sampling instant by starting to include the bits connected to that in the values to be changed in the port wide GPIO operation.

4) Use a similar port-wide operation to trigger the critical sampling operation for both devices at the same time

5) Continue with whatever followup each device needs, and stop updating its pins when no more operations are needed by that device.

Do be aware that some SPI devices, particularly those which are ADC's or having ADC type behavior internally, can be quite sensitive to jitter or timing variation in the clock edges.  You may want to look at using an interrupt or even a hardware counter/time or the SPI peripheral to generate the SCLK edges, and operate the other signals with interrupt driven software slaved to that.

Again, in most cases true parallelism will not be needed.  But if it is needed methods such as this can achieve it at the cost of intricate software.