text:
strcmp() returns 0 when chars are different
I am trying to build a sketch that reads a single number from the Serial Monitor and uses it to light a 7 segment display with this number.
I need to compare the input with the known values, stored in a char array, to know which character was typed in and associate the matching binary combination to light the 7 segment display.
I have made a sample code extracted from the sketch, just to test if I am able to pass a char and get the correct result back:
char nums[] = "0123456789."; // The characters we will check against

/* Tried also these, same results
      char nums[12] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '\0'};
      char nums[] = "456789.0123";
*/

void setup() {
  Serial.begin(9600);
  Serial.println("Write a single character"); Serial.println(" ");
}

void loop() {
  if (Serial.available() > 0) {
    char text = Serial.read(); // Read a single char from serial
    Serial.print("Character provided is: "); Serial.println(text);
    char c = parseChar(text); // Evaluate the char
    Serial.print("Character returned is: "); Serial.println (c);
    if (strcmp(c, text) == 0) { // Check if the returned char is the same
      Serial.print("      CORRECT character returned");
    } else {
      Serial.print("      WRONG character returned");
    }
    Serial.println(" ");
  }
}

char parseChar(char c) {
  int comp = 0;
  Serial.println("----- parseChar() START-----");
  Serial.print("  Parameter 'c' is: "); Serial.println(c);
  for (int i = 0; i < sizeof(nums) ; i++) { // Check the values of the array one by one
    comp = strcmp(c, nums[i]); // Compare the chars
    Serial.print("  Compare to nums["); Serial.print(i); Serial.print("] = "); Serial.print(nums[i]); Serial.print(" --> Result: "); Serial.println(comp);

    /* If the check matches, return the character at that index.
       For simplicity, it just returns the matching char of the array,
       that should be the same as the one sent in to the function.
    */
    if (comp == 0) {
      Serial.println("----- parseChar() END (found) -----");
      return nums[i];
    }
  }
  Serial.println("----- parseChar() END (not found)-----");
  return 0;
}

The function works well for all numbers from 0 to 6. However, for any number over 6, or any other character, the strcmp() function returns always 0, so the returned character is the index 0 of the array, regardless of the character typed.
This is the Serial Monitor output for different characters:
Write a single character

Character provided is: 3
----- parseChar() START-----
  Parameter 'c' is: 3
  Compare to nums[0] = 0 --> Result: 1
  Compare to nums[1] = 1 --> Result: 1
  Compare to nums[2] = 2 --> Result: 1
  Compare to nums[3] = 3 --> Result: 0
----- parseChar() END (found) -----
Character returned is: 3
      CORRECT character returned

Character provided is: 6
----- parseChar() START-----
  Parameter 'c' is: 6
  Compare to nums[0] = 0 --> Result: -6
  Compare to nums[1] = 1 --> Result: 1
  Compare to nums[2] = 2 --> Result: 1
  Compare to nums[3] = 3 --> Result: 1
  Compare to nums[4] = 4 --> Result: 1
  Compare to nums[5] = 5 --> Result: 1
  Compare to nums[6] = 6 --> Result: 0
----- parseChar() END (found) -----
Character returned is: 6
      CORRECT character returned

Character provided is: 7
----- parseChar() START-----
  Parameter 'c' is: 7
  Compare to nums[0] = 0 --> Result: 0
----- parseChar() END (found) -----
Character returned is: 0
      WRONG character returned

Character provided is: g
----- parseChar() START-----
  Parameter 'c' is: g
  Compare to nums[0] = 0 --> Result: 0
----- parseChar() END (found) -----
Character returned is: 0
      WRONG character returned

As you can see, the parseChar() function never returns a "not found" result, even for chars that are not in the array. In fact, it never loops through the array, as the first comparison returns 0 always.
I can't figure out why the strcmp() function returns 0 when the chars are different. Am I missing something?

Change "comp = strcmp(c, nums[i]);" to "comp = (c - nums[i]);" might do the trick. Nick explains why.

strcmp is not for comparing a single character like your c parameter. It is for comparing a null-terminated string. I'm a little surprised you didn't get a compiler error, but there it is.
If you want to compare individual characters, just compare them with ==.

Thanks @nick, seems to work. Just to clarify, == should be used when comparing char,and strcmp() when comparing char[]?

Generally speaking, you use == to compare two simple things of the same type (like numbers, characters, floats, etc.) strcmp is specifically for comparing a null-terminated string of characters.


text:
Why does my LED turn off automatically after about 18 seconds on its own?
I am using the Arduino Due and I am programming it with Atmel Studio 6.2. I have had a HUGE learning curve using this IDE and the Atmel ASF. Nothing is straightforward as it is in the Arduino IDE. Nonetheless, I want to toggle an LED on and off with a simple interrupt on a pull-up configured tactile button. This is my code:
#include <asf.h>
#include "pio.h"

// Define the LED pins
#define BLUE_LED2 PIO_PC28 // Arduino Due pin 3
#define BLUE_LED3 PIO_PC26 // Arduino Due pin 4
#define BLUE_LED4 PIO_PC25 // Arduino Due pin 5
#define BLUE_LED5 PIO_PC24 // Arduino Due pin 6
#define BLUE_LED6 PIO_PC23 // Arduino Due pin 7

// Define the button pins
#define BUTTON_1 PIO_PC22
#define BUTTON_2 PIO_PC21

// Define function prototype for button interrupt
void button_press_handler(uint32_t, uint32_t);
void toggle_LED(uint32_t);

int main (void)
{
    /* Initialize the SAM system. */
    sysclk_init();

    // Initialize input/out
    ioport_init();
    pmc_enable_periph_clk(ID_PIOC);
    pmc_enable_periph_clk(ID_PIOB);

    // Set LED pins as outputs and set there default values (off)
    pio_set_output(PIOC, BLUE_LED2, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED3, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED4, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED5, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED6, LOW, DISABLE, ENABLE);

    // Set button pins as pull-up inputs
    pio_set_input(PIOC, BUTTON_1, PIO_PULLUP);
    pio_set_input(PIOC, BUTTON_2, PIO_PULLUP);

    // Configure button input pin interrupt mode and handler (Falling Edge)
    pio_handler_set(PIOC, ID_PIOC, BUTTON_1,  PIO_IT_RISE_EDGE, button_press_handler);
    pio_handler_set(PIOC, ID_PIOC, BUTTON_2,  PIO_IT_RISE_EDGE, button_press_handler);

    // Enable the interrupts
    pio_enable_interrupt(PIOC, BUTTON_1);
    pio_enable_interrupt(PIOC, BUTTON_2);
    NVIC_EnableIRQ(PIOC_IRQn);

    while(1){
         // Doing stuff in here...
    }
}

Then this is my interrupt routine:
// Interrupt handler for button press
void button_press_handler(uint32_t a, uint32_t b)
{
    // Turn the LED's on or off
    toggle_LED(BLUE_LED2);
    toggle_LED(BLUE_LED3);
    toggle_LED(BLUE_LED4);
    toggle_LED(BLUE_LED5);
    toggle_LED(BLUE_LED6);
}

// Function to toggle LED on/off
void toggle_LED(uint32_t LED){

    if (pio_get(PIOC, PIO_TYPE_PIO_OUTPUT_0, LED))
    pio_clear(PIOC, LED);
    else
    pio_set(PIOC, LED);
}

Things work normal and as expected up until about 18 seconds in. After 18 seconds, the LED turns off if it is on. I tested this by setting LED 2 HIGH by default and removing the interrupt all together:
pio_set_output(PIOC, BLUE_LED2, HIGH, DISABLE, ENABLE);

In this case, the LED will stay on forever, but about every 18 seconds, the LED will flash off then back on once quickly. Why is this happening?

I realized that the problem was occurring due to the fact that I was not initializing the board. All I needed to do was add "board_init();" underneath my system clock initialization code in main(void) and now it works.

You should answer yourself and mark that as the answer so that other people will realize the question has a solution.  This is expected behavior http://arduino.stackexchange.com/help/self-answer

Again, figured this out. I simply forgot to put in board_init(); Also, since board_init() already calls ioport_init(), I had to disable that.
Now I have this:
int main (void)
{
    /* Initialize the SAM system. */
    sysclk_init(); // Initialize the System Clock
    board_init();  // Initialize the board

....

The symptoms you describe are consistent with your program crashing after 18 seconds.  I expect you will find something in this that is the problem:
while(1){
     // Doing stuff in here...
}

To debug this, add something to the startup that is unique or clearly identifiable:

a print "reset" to a serial port if you have one
in your case, blink the led's in sequence 2,3,4,5,6

Once you confirm that your program is resetting, strip out everything in the
// Doing stuff in here...

With the program stripped down, it should keep the LED's lit.
If the LED's still do not stay lit, but you see your reset indicator, consider power.  Microcontrollers will reset when the voltage droops too low.  The LED's might be consuming enough power to reduce the voltage below the trip point.  Connect a voltmeter to the supply voltage to see if it is stable.
The time delay can be associated with the power supply heating at higher current.  The LM2734 chip on the Due has a thermal shutdown, same as most voltage regulators.  If your hardware draws enough current to overheat, the chip will shutoff, cool down and turn back on.

About drawing too much current, I don't think that is the case because all the LED's work perfectly in Arduino IDE. I made absolutely no hardware changes on the board. It works in Arduino, but not in Atmel Studio so I think this must be a software issue.

Also, as for the while loop, I literally have nothing in there. I simply have the comment to remind me to do stuff once I sort this issue out.

Improper handling of interrupts will cause a reset.

@JohnAugust It would be best to add what you have already tried in the question.

I fixed the issue, it was because I did not include "board_init();"

This may be because the ATSAM3X8E chip has a watchdog: from the datasheet section 15.1,

The Watchdog Timer can be used to prevent system lock-up if the software becomes trapped in a deadlock. It
  features a 12-bit down counter that allows a watchdog period of up to 16 seconds (slow clock at 32.768 kHz). It
  can generate a general reset or a processor reset only. In addition, it can be stopped while the processor is in
  debug mode or idle mode.

board_init() almost certainly disables the watchdog.

source: Stack Exchange

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

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

sort: votes


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Are you sure that dmpReady is being set?

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

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

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

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


text:
Powering Down Arduino MKR1000
The MKR1000 is still pretty new and I'm having a hard time getting good information on it. I'm using the Arduino IDE but don't find any functions to sleep the MKR1000. Most libraries I encounter are for AVR chips while the MKR1000 has an ARM chip. I want to put it to sleep until an external interrupt is called. I also use the millis() function, will this function be rendered useless if it goes to sleep?
In the data sheet for the ATSAMD21 it talks about the Wait for Interrupt instruction which puts the machine to sleep but it doesn't say how to call the instruction. How can I do this in the Arduino IDE?

The rocketscream low power library looks like it supports the ATSAMD21.


text:
Universal remote control with bluetooth emitter
I am creating a universal remote control to replace multiple devices I have at home. The IR part was quite easy to implement.
I realised then that the Chromecast with Google TV remote uses Bluetooth, and only Bluetooth, instead of IR.
I have another remote (Foxtel, Australia) that is also Bluetooth, but it accepts IR, so I can just use IR.
I tried to connect the remote to my mobile but, although it shows on the mobile as a possible device to connect, it doesn't complete the connection process.
Is it possible at all to clone the remote into an Arduino and make the Arduino connect to Chromecast to send the commands?
Kind Regards,
Eduardo

The first question to find the answer to would be, what communication profile is advertised by the remote. Bluetooth can carry many different profiles (for example HID, Serial, audio, ...). Without knowing that you cannot reproduce it. On your mobile you would need a fitting app, that controls the bluetooth interface. Don't know, if such an app exists.

Now you are on... Why just not build from scratch your new Remote? Just a sugestion ofc

@k.Cyborg, that is what I am doing. The problem with Chromecast is that it doesn't accept anything else but Bluetooth. For all the IR remotes I have a prototype working. I need to understand and clone the Bluetooth one. Any suggestions?

Oh, that's a nice project then. I suggest you use the usual HC-05 (or the HC-06) modules if you are a newbie into the electronics, do not buy clone modules from China because they are harder to use and understand. And... Read how the Bluethooth protocol works, so you can easilly work with it. Greetings mate, and good luck

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


text:
Issues with AltSoftSerial
I have my arduino connected to my PC and another serial device.
This serial device sends a 3 line piece of info on bootup then if I trip a zone it will send information regarding the radio transmission.
When I first power up the device I see the information from the device in the serial monitor (SELFTEST-PASS) however that is the last information I receive from it until I powercycle the device.
I have connected it directly to my PC comport and verified information is being sent via Serial however the arduino seems to quit after the first bit of info... any idea where to proceed from here?
PS I have tried both SoftwareSerial and NewSoftSerial
Here is an example of the data sent from the serial device as viewed by hyperterminal:
<1234 #3F->0000 1234->FFFF D_ALARM>
<FFFF #3F->1234 FFFF->1234 P_ACK>
<1234 #40->0000 1234->FFFF D_ZREST>

Code that is currently not working:
 #include <AltSoftSerial.h>
 AltSoftSerial portOne;

void setup() {

                Serial.begin(4800);
                while (!Serial) {; // wait for serial port to connect. Needed for native USB port only
                }
                // Start each software serial port
                portOne.begin(4800);

              }

// the loop function runs over and over again forever
void loop()
{
  if (portOne.available())
  {
    Serial.write(portOne.read());
  }

  if (Serial.available())
  {
    portOne.write(Serial.read());
  }
}

What pin do you have the device connected to on the Arduino? What Arduino do you have? What baud rate do you have set in the Serial Monitor?

8,9 - uno 4800.   When I first power up unit is see the self test but nothing further. I have connected directly to a pic and verified the radio I'm connecting to does indeed continue to send data.

Which is Rx and which is Tx?

One way displayed junk when I booted up the device so I swapped the pins and that showed me the bootup message. 9=tx 8=rx

Device connected to arduino had DTR/DSR. I had to jumper one to the other to convince it to flow data to the arduino.

Try SoftwareSerial rather than AltSoftSerial.
I don't see the point in these lines, I think you can remove them:
 if (Serial.available())
  {
    portOne.write(Serial.read());
  }

I have connected directly to a pic and verified the radio I'm connecting to does indeed continue to send data.

If that is the case, that it sends data anyway, then you could just use HardwareSerial. Connect the radio to Rx (D0 on the Uno) and leave Tx unconnected. Then just read from Serial, and write to Serial. You should see the results on the Serial Monitor. (Disconnect this wire when uploading new versions of the sketch).

Thank you for the information Nick, in my original post I stated I had tried both SoftwareSerial and AltSoftSerial.  Also I believe the snippet of code you specified allows me to send a character from the serial monitor to the serial device hooked up to the software serial port... Yes?

Yes, but does the device need to receive data?

I can trigger a response from the radio but sending a character to it. However I am not seeing anything after the initial boot up message. I can connect directly to of serial and interact np, but the arguing only gives me the initial power up message.

See amended answer.

Now I'm totally stumped.

This works the same way, I put in code as you stated, I still see the power on message but no following messages. I've plugged in another serial monitor and verified the serial data is being sent and it is but when I plug in the device to the arduino I get the bootup and nothing else.  Serial parameters are 4800 8-N-1 Flow: Off

Seems like there must be something different about the arduino serial compared to the PC serial.... I can't figure it out. I can unplug it from the arduino and directly into my computer and see the data flow but then hook it into the arduino and nothing.

Serial input is "passive". The sending device doesn't know if you are receiving or not (ie. the Rx pin is high impedance). So either it stops sending (for some reason) or you are receiving but somehow ignoring it. I can trigger a response from the radio but sending a character to it. - well, send a character to it then. Try going back to AltSoftwareSerial, and send a newline or something every few seconds.

I went back on looked at the Device, it has 6 pins, GND, RX, TX, DTR DSR +12v (supplied from device)
I put a jumper between DTR and DSR and suddenly I see the information streaming. I'm guessing i need to hook that to the arduino somehow so I can interupt the DTR and then send my character then turn the DSR back on... Thank you for persevering on this with me.

Can't you leave them jumpered? In the olden days we used to just jumper stuff together until it worked. It's not as if you are looking at DTR/DSR anyway.

Nick, After more research yes your right it appears I can just leave it jumpered. I can now see all the information from the information. The next step is I need to pass the letter d to the arduino. When I have the device connected to hyperterminal I press 'd' and nothing else and it gives me a status report... I've tried a hundred different things but can't seem to get this part going. should I open a new question so I can post the code? I'm pretty new here.

Yes, this sounds like a different question. Can you please take steps to let the Stack Exchange system know this question is answered? Either accept my answer, or post your own answer to your question along the lines of: Problem solved by jumpering together DTR/DSR - that way the next person with this problem will find a solution here.


text:
Send multiple int values from Python to Arduino using pySerial
I'm trying to send 3 ints in the range of 0-180 from Python to the Arduino Uno device using pySerial (py3K). I have managed to send 1 int by using python's struct lib (not sure if it's the best or fastest way but it works).
However I'm failing to send more than 1 and every example online seems to stop at 1.
Here's the simplified code. The task is to send servo0-servo4 to the Arduino and apply those values to the corresponding servos.
Python Code
import serial
import struct
import time

bge.arduino = serial.Serial('/dev/ttyACM0', 9600)

# let it initialize
time.sleep(2)

# send the first int in binary format
bge.arduino.write(struct.pack('>B', 45))

Arduino code
#include <Servo.h>
Servo servo0;
Servo servo1;
Servo servo2;

void setup(){
  Serial.begin(9600);
  servo0.attach(3);
  servo1.attach(5);
  servo2.attach(6);
}

void loop(){
  if(Serial.available()){
    int message = Serial.read();
    // control the servo
    servo0.write(message);
  }
}

I guess I'll answer my own question for anyone else having this issue. What I did was:
Python:
# write to arduino as raw binary
bge.arduino.write(struct.pack('>BBB',45,90,180))

Arduino:
#include <Servo.h>

Servo servo0;
Servo servo1;
Servo servo2;

// create array
int incoming[2];

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

  servo0.attach(3);
  servo1.attach(5);
  servo2.attach(6);
}

void loop(){
  while(Serial.available() >= 3){
    // fill array
    for (int i = 0; i < 3; i++){
      incoming[i] = Serial.read();
    }
    // use the values
    servo0.write(incoming[0]);
    servo1.write(incoming[1]);
    servo2.write(incoming[2]);
  }
}

You're not verifying if Serial.available() has 3 values available.  So it's going to get filled with -1's if there aren't.  Check to see how many bytes are in the receive buffer.

void loop(){
  if(Serial.available() >= 3){
    // fill array
    for (int i = 0; i < 3; i++){
      incoming[i] = Serial.read();
    }
    // use the values
    servo0.write(incoming[0]);
    servo1.write(incoming[1]);
    servo2.write(incoming[2]);
  }
}

Thank you @baldengineer. I'm now verifying like you proposed. However after a little while of playing with the program it completely messes up and I have to reboot the Arduino for it to work again. I suspect the ordering of the bytes might be shuffling?

Holly cow, I think I solved the problem by replacing if(Serial.available().. with while(Serial.available().. Does that make sense to you?


text:
How to increment and decrement an output voltage by using two buttons?

I'm trying to create a code using an Arduino Uno board to increment and decrement the output voltage of the Arduino Uno which is 5 volts and I need to step it up to 10 volts which I have done below.
The things that are missing on the schematic are two buttons. I want to be able to increment 0.5 volts with each press of Button-A until the Arduino is at 5 volts. With Button-B I want to be able to lower the voltage by 0.5 volts with each press of the button till value is 0.
I can do the calculations and the circuit design but I'm not much of a programmer. I just want to know if anyone can point me in a good direction of where I can get the right code. I have already looked at all the tutorials on the Arduino Website. I do know I have to work with the PWM functions as well as attachinterrupt() and Debounce() functions. Also, how do I set the increments so that I don't go over, say it takes 10 presses to get to 5 volts on the 11th press have it not do anything so I don't break anything. So can anyone please help me with any suggestions?
I have a low pass filter on the circuit for noise handling and like I said I need to add in the buttons to my schematic.

simulate this circuit – Schematic created using CircuitLab
Here is my code I have made. I'm using an LED to test the Vout aspect. So far I can only get my LED to flicker from 2 to 4 volts and my buttons A and B don't work. Can someone look over my code and see how bad I made this?
int PWMPin = 6; // output pin supporting PWM
int buttonApin = 9; // buttonA to pin 9 PWM
int buttonBpin = 10; // buttonB to pin 10 PWM
float value = 0; // read the value at 0
int fadeValue = value;

void setup()
{
  Serial.begin(9600); //initialize serial communication at 9600 baud
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
  pinMode(PWMPin, OUTPUT);
}
void loop()
{
  {
    int port = analogRead(0);
    port = map(port, 0, 10, 0, 255);
    analogWrite(6, port);
  }

  {
  if (digitalRead(buttonApin) == LOW, fadeValue)
  {
  // fade from min to max in increments of 25.5 points: basically (0.5 volts)
  for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=25.5)

    digitalWrite(PWMPin, fadeValue);

    // sets the value (range from 0 to 255):
   Serial.println(PWMPin);
   analogWrite(PWMPin, fadeValue);
  }
  }

  {
    if (digitalRead(buttonBpin) == LOW, fadeValue)
  {
  // fade from max to min in increments of 25.5 points:
  for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=25.5)

    digitalWrite(PWMPin, fadeValue);

  // sets the value (range from 0 to 255): basically (0.5 volts)
  analogWrite(PWMPin, fadeValue);
  }
  }
}

I think you need to add a pull-down resistor to the + side of the opamp. Since the input of the opamp is high impedance, the voltage on the + is always 5v even at a low pwm duty cycle.

I suggest you to use debounce to detect if a pin has been definitely pressed. You could also test using interrupts (hint: interrupts can happen multiple times even if you "only" pressed once). So either use Arduino's example of debounce or take a look at the Bounce2 library found on their website.
Now that you can check whether or not either button A or B has been pressed, how do you keep track of the voltage to be output? You should use a counter variable that will be incremented when button A is pressed and decremented when button B is pressed. Here is a pseudocode:
if(ButtonA == pressed)
  counter++;
else if(ButtonB == pressed)
  counter--;

This counter variable can be used to control the output voltage. Remember that the argument for analogWrite() function on the Arduino Uno is the duty cycle which takes in values from 0 to 255. So analogWrite(0) ≣ 0 Volt and analogWrite(255) ≣ 5 Volt. So at the moment, you couldn't just do analogWrite(counter) because you would need to press 255 times button A!
Instead, you would need a way to convert your counter to reflect the increment you need. You mentioned that it should require 10 presses to reach 5 Volt at the Arduino output, and the easiest way to accomplish this is to use Arduino's Map function. The pseudocode would look like this:
Output = map(counter, 0, 10, 0, 255);
analogWrite(Output);

Now there is one last step! The map function will limit the output voltage from 0 to 5 Volt so everything will be safe; however, the counter is not limited to 0 to 10. This means that even if the counter is at 15 (because you pressed button A too many times) the voltage will be 5 Volt and you would need to press button B at least 6 times to see the voltage go down! So to limit the counter you could easily implement your own function:
if(counter >= 10)
  counter = 10;
else if (counter<= 0)
  counter = 0;

You could also use Arduino's constrain() function which more information can be found on their website.
Hopefully this points you in the right direction.

If all you have to do is to read those 2 buttons, you could just forgo the interrupts and simply poll in the main loop.
The Bounce2 library does basically the same.
Also, about the PWM, why not an R-2R?
10V/0.5V + 1 => 21 steps < 32 => 5 bits => 6 resistors.
But it could be more precise, as you would not depend on the oscillator, rather on the precision of the resistors.

Agreed with Igor. Resistor ladders are much more accurate and noise resistant. I would go for an I2C potentiometer such as AD5248.


text:
Code will not run when Serial Monitor is not open
My code runs perfectly as long as the serial port is open. However if I connect it to external power, or even if I just try to run it plugged into my computer with the Serial Monitor not open, nothing happens. My project doesn't need any serial interaction, it will operate on its own far from any computers. I have it in here to help me debug.
The sticking point appears to be with if (morseInput.available()) on line 63.
Here is everything, including the libraries I am using:
Morse EnDecoder.h
#ifndef MorseEnDecoder_H
#define MorseEnDecoder_H

#if (ARDUINO <  100)
#include <WProgram.h>
#else
#include <Arduino.h>
#endif

#define MORSE_AUDIO true
#define MORSE_KEYER false
#define MORSE_ACTIVE_LOW true
#define MORSE_ACTIVE_HIGH false

class morseDecoder
{
public:
morseDecoder(int decodePin, boolean listenAudio, boolean morsePullup);
void decode();
void setspeed(int value);
char read();
boolean available();
int AudioThreshold;
long debounceDelay;     // the debounce time. Keep well below dotTime!!
boolean morseSignalState;
private:
int morseInPin;         // The Morse input pin
int audioSignal;
int morseTablePointer;
int wpm;                // Word-per-minute speed
long dotTime;           // morse dot time length in ms
long dashTime;
long wordSpace;
boolean morseSpace;     // Flag to prevent multiple received spaces
boolean gotLastSig;     // Flag that the last received morse signal is decoded as dot or dash
boolean morseKeyer;
boolean lastKeyerState;
boolean morseAudio;
boolean activeLow;
long markTime;          // timers for mark and space in morse signal
long spaceTime;         // E=MC^2 ;p
long lastDebounceTime;  // the last time the input pin was toggled
long currentTime;       // The current (signed) time
char decodedMorseChar;  // The last decoded Morse character
};

class morseEncoder
{
public:
morseEncoder(int encodePin);
void encode();
void setspeed(int value);
void write(char temp);
boolean available();
int morseSignals;       // nr of morse signals to send in one morse character
char morseSignalString[7];// Morse signal for one character as temporary ASCII string of dots and dashes
private:
char encodeMorseChar;   // ASCII character to encode
boolean sendingMorse;
int wpm;                // Word-per-minute speed
long dotTime;           // morse dot time length in ms
long dashTime;
long wordSpace;
int morseSignalPos;
int sendingMorseSignalNr;
long sendMorseTimer;
long lastDebounceTime;
long currentTime;
protected:
int morseOutPin;
virtual void setup_signal();
virtual void start_signal(bool startOfChar, char signalType);
virtual void stop_signal(bool endOfChar, char signalType);
};

#endif

Morse EnDecoder.cpp
/*          MORSE ENDECODER

- Morse encoder / decoder classes for the Arduino.

Copyright (C) 2010-2012 raron

GNU GPLv3 license:

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Details: http://raronoff.wordpress.com/2010/12/16/morse-endecoder/

#include "MorseEnDecoder.h"

// Morse code binary tree table (dichotomic search table)

// ITU with most punctuation (but without non-english characters - for now)
const int morseTreeLevels = 6; // Minus top level, also the max nr. of morse signals
const int morseTableLength = pow(2,morseTreeLevels+1);
const char morseTable[] PROGMEM =
" ETIANMSURWDKGOHVF*L*PJBXCYZQ!*54*3***2&*+****16=/***(*7***8*90*"
"***********?_****\"**.****@***'**-********;!*)*****,****:*******\0";

morseDecoder::morseDecoder(int decodePin, boolean listenAudio, boolean morsePullup)
{
morseInPin = decodePin;
morseAudio = listenAudio;
activeLow = morsePullup;

if (morseAudio == false)
{
pinMode(morseInPin, INPUT);
if (activeLow) digitalWrite (morseInPin, HIGH);
}

// Some initial values
wpm = 13;
AudioThreshold = 700;
debounceDelay = 20;
dotTime = 1200 / wpm;       // morse dot time length in ms
dashTime = 3 * 1200 / wpm;
wordSpace = 7 * 1200 / wpm;

morseTablePointer = 0;

morseKeyer = LOW;
morseSignalState = LOW;
lastKeyerState = LOW;

gotLastSig = true;
morseSpace = true;
decodedMorseChar = '\0';

lastDebounceTime = 0;
markTime = 0;
spaceTime = 0;
}

void morseDecoder::setspeed(int value)
{
wpm = value;
if (wpm <= 0) wpm = 1;
dotTime = 1200 / wpm;
dashTime = 3 * 1200 / wpm;
wordSpace = 7 * 1200 / wpm;
}

boolean morseDecoder::available()
{
if (decodedMorseChar) return true; else return false;
}

char morseDecoder::read()
{
char temp = decodedMorseChar;
decodedMorseChar = '\0';
return temp;
}

void morseDecoder::decode()
{
currentTime = millis();

// Read Morse signals
if (morseAudio == false)
{
// Read the Morse keyer (digital)
morseKeyer = digitalRead(morseInPin);
if (activeLow) morseKeyer = !morseKeyer;

// If the switch changed, due to noise or pressing:
if (morseKeyer != lastKeyerState) lastDebounceTime = currentTime; // reset timer

// debounce the morse keyer
if ((currentTime - lastDebounceTime) > debounceDelay)
{
  // whatever the reading is at, it's been there for longer
  // than the debounce delay, so take it as the actual current state:
  morseSignalState = morseKeyer;

  // differentiante mark and space times
  if (morseSignalState) markTime = lastDebounceTime;
  else spaceTime = lastDebounceTime;
}
} else {
// Read Morse audio signal
audioSignal = analogRead(morseInPin);
if (audioSignal > AudioThreshold)
{
  // If this is a new morse signal, reset morse signal timer
  if (currentTime - lastDebounceTime > dotTime/2)
  {
    markTime = currentTime;
    morseSignalState = true; // there is currently a Morse signal
  }
  lastDebounceTime = currentTime;
} else {
  // if this is a new pause, reset space time
  if (currentTime - lastDebounceTime > dotTime/2 && morseSignalState == true)
  {
    spaceTime = lastDebounceTime; // not too far off from last received audio
    morseSignalState = false;     // No more signal
   }
 }
}

// Decode morse code
if (!morseSignalState)
{
  if (!gotLastSig)
  {
    if (morseTablePointer < morseTableLength/2-1)
    {
    // if pause for more than half a dot, get what kind of signal pulse (dot/dash) received last
    if (currentTime - spaceTime > dotTime/2)
    {
      // if signal for more than 1/4 dotTime, take it as a morse pulse
      if (spaceTime-markTime > dotTime/4)
      {
        morseTablePointer *= 2;  // go one level down the tree
        // if signal for less than half a dash, take it as a dot
        if (spaceTime-markTime < dashTime/2)
        {
           morseTablePointer++; // point to node for a dot
           gotLastSig = true;
        }
        // else if signal for between half a dash and a dash + one dot (1.33 dashes), take as a dash
        else if (spaceTime-markTime < dashTime + dotTime)
        {
           morseTablePointer += 2; // point to node for a dash
           gotLastSig = true;
        }
      }
    }
  } else { // error if too many pulses in one morse character
    //Serial.println("<ERROR: unrecognized signal!>");
    decodedMorseChar = '#'; // error mark
    gotLastSig = true;
    morseTablePointer = 0;
  }
}
// Write out the character if pause is longer than 2/3 dash time (2 dots) and a character received
if ((currentTime-spaceTime >= (dotTime*2)) && (morseTablePointer > 0))
{
  decodedMorseChar = pgm_read_byte_near(morseTable + morseTablePointer);
  morseTablePointer = 0;
}
// Write a space if pause is longer than 2/3rd wordspace
if (currentTime-spaceTime > (wordSpace*2/3) && morseSpace == false)
{
  decodedMorseChar = ' ';
  morseSpace = true ; // space written-flag
}

} else {
// while there is a signal, reset some flags
gotLastSig = false;
morseSpace = false;
}

// Save the morse keyer state for next round
lastKeyerState = morseKeyer;
}

morseEncoder::morseEncoder(int encodePin)
{
  morseOutPin = encodePin;
  this->setup_signal();

// some initial values
sendingMorse = false;
encodeMorseChar = '\0';

wpm = 13;
dotTime = 1200 / wpm;       // morse dot time length in ms
dashTime = 3 * 1200 / wpm;
wordSpace = 7 * 1200 / wpm;
}

void morseEncoder::setspeed(int value)
{
wpm = value;
if (wpm <= 0) wpm = 1;
dotTime = 1200 / wpm;
dashTime = 3 * 1200 / wpm;
wordSpace = 7 * 1200 / wpm;
}

boolean morseEncoder::available()
{
if (sendingMorse) return false; else return true;
}

void morseEncoder::write(char temp)
{
if (!sendingMorse && temp != '*') encodeMorseChar = temp;
}

void morseEncoder::setup_signal()
{
pinMode(morseOutPin, OUTPUT);
digitalWrite(morseOutPin, LOW);
}

void morseEncoder::start_signal(bool startOfChar, char signalType)
{
digitalWrite(morseOutPin, HIGH);
}

void morseEncoder::stop_signal(bool endOfChar, char signalType)
{
digitalWrite(morseOutPin, LOW);
}

void morseEncoder::encode()
{
currentTime = millis();

if (!sendingMorse && encodeMorseChar)
{
// change to capital letter if not
if (encodeMorseChar > 96) encodeMorseChar -= 32;

// Scan for the character to send in the Morse table
int p;
for (p=0; p<morseTableLength+1; p++) if (pgm_read_byte_near(morseTable + p) == encodeMorseChar) break;

if (p >= morseTableLength) p = 0; // not found, but send a space instead

// Reverse binary tree path tracing
int pNode; // parent node
morseSignals = 0;

// Travel the reverse path from position p to the top of the morse table
if (p > 0)
{
  // build the morse signal (backwards morse signal string from last signal to first)
  pNode = p;
  while (pNode > 0)
  {
    if ( (pNode & 0x0001) == 1)
    {
      // It is a dot
      morseSignalString[morseSignals++] = '.';
    } else {
      // It is a dash
      morseSignalString[morseSignals++] = '-';
    }
    // Find parent node
    pNode = int((pNode-1)/2);
  }
} else { // Top of Morse tree - Add the top space character
  // cheating a little; a wordspace for a "morse signal"
  morseSignalString[morseSignals++] = ' ';
}

morseSignalString[morseSignals] = '\0';

// start sending the the character
sendingMorse = true;
sendingMorseSignalNr = morseSignals; // Sending signal string backwards
sendMorseTimer = currentTime;
if (morseSignalString[0] != ' ') this->start_signal(true, morseSignalString[morseSignals-1]);
}

// Send Morse signals to output
if (sendingMorse)
{
char& currSignalType = morseSignalString[sendingMorseSignalNr-1];
bool endOfChar = sendingMorseSignalNr <= 1;
switch (currSignalType)
{
  case '.': // Send a dot (actually, stop sending a signal after a "dot time")
    if (currentTime - sendMorseTimer >= dotTime)
    {
      this->stop_signal(endOfChar, currSignalType);
      sendMorseTimer = currentTime;
      currSignalType = 'x'; // Mark the signal as sent
    }
    break;
  case '-': // Send a dash (same here, stop sending after a dash worth of time)
    if (currentTime - sendMorseTimer >= dashTime)
    {
      this->stop_signal(endOfChar, currSignalType);
      sendMorseTimer = currentTime;
      currSignalType = 'x'; // Mark the signal as sent
    }
    break;
  case 'x': // To make sure there is a pause between signals
    if (sendingMorseSignalNr > 1)
    {
      // Pause between signals in the same letter
      if (currentTime - sendMorseTimer >= dotTime)
      {
        sendingMorseSignalNr--;
        this->start_signal(false, morseSignalString[sendingMorseSignalNr-1]); // Start sending the next signal
        sendMorseTimer = currentTime;       // reset the timer
      }
    } else {
      // Pause between letters
      if (currentTime - sendMorseTimer >= dashTime)
      {
        sendingMorseSignalNr--;
        sendMorseTimer = currentTime;       // reset the timer
      }
    }
    break;
  case ' ': // Pause between words (minus pause between letters - already sent)
  default:  // Just in case its something else
    if (currentTime - sendMorseTimer > wordSpace - dashTime) sendingMorseSignalNr--;
}
if (sendingMorseSignalNr <= 0 )
{
  // Ready to encode more letters
  sendingMorse = false;
  encodeMorseChar = '\0';
}
}
}

Morse.h
#pragma once
/**
* Generate and send Morse Code on an LED or a speaker. Allow sending
* in a non-blocking manner (by calling a 'continue sending' method
* every so often to turn an LED on/off, or to call tone/noTone appropriately).
*
* All input should be lowercase. Prosigns (SK, KN, etc) have special
* character values #defined.
*/

// for malloc and free, for the new/delete operators
#include <stdlib.h>

// Arduino language types
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif

#define WPM_DEFAULT 12.0
// PARIS WPM measurement: 50; CODEX WPM measurement: 60 (Wikipedia:Morse_code)
#define DITS_PER_WORD   50
// Pass to SpeakerMorseSender as carrierFrequency to suppress the carrier.
#define CARRIER_FREQUENCY_NONE  -1

// Bitmasks are 1 for dah and 0 for dit, in left-to-right order;
//  the sequence proper begins after the first 1 (a sentinel).
//  Credit for this scheme to Mark VandeWettering K6HX ( brainwagon.org ).
typedef int             morseTiming_t;
typedef unsigned char   morseBitmask_t; // see also MAX_TIMINGS
#define MORSE_BITMASK_HIGH_BIT  B10000000

// sentinel
#define END             0

// the most timing numbers any unit will need; ex: k = on,off,on,off,on,end = 5
#define MAX_TIMINGS     15

// Punctuation and Prosigns
#define PROSIGN_SK  'S'
#define PROSIGN_KN  'K'
#define PROSIGN_BT  'B'
typedef struct {
char c;
morseBitmask_t timing;
} specialTiming;
const specialTiming MORSE_PUNCT_ETC[] = {
{'.',       B1010101},
{'?',       B1001100},
{PROSIGN_SK,    B1000101},
{PROSIGN_KN,    B110110},
{PROSIGN_BT,    B110001},
{END,       B1},
};

// Morse Code (explicit declaration of letter timings)
const morseBitmask_t MORSE_LETTERS[26] = {
/* a */ B101,
/* b */ B11000,
/* c */ B11010,
/* d */ B1100,
/* e */ B10,
/* f */ B10010,
/* g */ B1110,
/* h */ B10000,
/* i */ B100,
/* j */ B10111,
/* k */ B1101,
/* l */ B10100,
/* m */ B111,
/* n */ B110,
/* o */ B1111,
/* p */ B10110,
/* q */ B11101,
/* r */ B1010,
/* s */ B1000,
/* t */ B11,
/* u */ B1001,
/* v */ B10001,
/* w */ B1011,
/* x */ B11001,
/* y */ B11011,
/* z */ B11100,
};

/**
* Define the logic of converting characters to on/off timing,
* and encapsulate the state of one sending-in-progress Morse message.
*
* Subclasses define setOn and setOff for (for example) LED and speaker output.
*/
class MorseSender {
protected:
const unsigned int pin;
// The setOn and setOff methods would be pure virtual,
// but that has compiler issues.
// See: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1167672075 .

/**
 * Called to set put the output in 'on' state, during a dit or dah.
 */
virtual void setOn();
virtual void setOff();

/**
 * Called before sending a message. Used for example to enable a
 * carrier. (Noop in the base class.)
 */
virtual void setReady();
virtual void setComplete();

private:
morseTiming_t DIT, DAH;
String message;

// on,off,...,wait,0 list, millis
morseTiming_t timingBuffer[MAX_TIMINGS+1];

// index of the character currently being sent
unsigned int messageIndex;
// timing unit currently being sent
unsigned int timingIndex;

// when this timing unit was started
unsigned long lastChangedMillis;

/**
 * Copy definition timings (on only) to raw timings (on/off).
 * @return the number of 'on' timings copied
 */
int copyTimings(morseTiming_t *rawOut,
    morseBitmask_t definition);

/**
 * Fill a buffer with on,off,..,END timings (millis)
 * @return the index at which to start within the new timing sequence
 */
unsigned int fillTimings(char c);

public:
/**
 * Create a sender which will output to the given pin.
 */
MorseSender(unsigned int outputPin, float wpm=WPM_DEFAULT);

/**
 * To be called during the Arduino setup(); set the pin as OUTPUT.
 */
void setup();

/**
 * Set the words per minute (based on PARIS timing).
 */
void setWPM(float wpm);

/**
 * Set the duration, in milliseconds, of a DIT.
 */
void setSpeed(morseTiming_t duration);

/**
 * Set the message to be sent.
 * This halts any sending in progress.
 */
void setMessage(const String newMessage);

/**
 * Send the entirety of the current message before returning. See the "simple"
 * example, which uses sendBlocking to send one message.
 */
void sendBlocking();

/**
 * Prepare to send and begin sending the current message. After calling this,
 * call continueSending repeatedly until it returns false to finish sending
 * the message. See the "speeds" example, which calls startSending and
 * continueSending on two different senders.
 */
void startSending();

/**
 * Switch outputs on and off (and refill the internal timing buffer)
 * as necessary to continue with the sending of the current message.
 * This should be called every few milliseconds (at a significantly
 * smaller interval than a DIT) to produce a legible fist.
 *
 * @see startSending, which must be called first
 * @return false if sending is complete, otherwise true (keep sending)
 */
boolean continueSending();

void *operator new(size_t size);
void operator delete(void* ptr);
};

/**
* Adapt Morse sending to use the Arduino language tone() and noTone()
* functions, for use with a speaker.
*
* If a carrierFrequency is given, instead of calling noTone, call tone
* with a low frequency. This is useful ex. for maintaining radio links.
*/
class SpeakerMorseSender: public MorseSender {
private:
    unsigned int frequency;
    unsigned int carrFrequency;
protected:
    virtual void setOn();
    virtual void setOff();
    virtual void setReady();
    virtual void setComplete();
public:
    // concert A = 440
    // middle C = 261.626; higher octaves = 523.251, 1046.502
    SpeakerMorseSender(
        int outputPin,
        unsigned int toneFrequency=1046,
        unsigned int carrierFrequency=CARRIER_FREQUENCY_NONE,
        float wpm=WPM_DEFAULT);
};

/**
* Sends Morse on a digital output pin.
*/
class LEDMorseSender: public MorseSender {
protected:
    virtual void setOn();
    virtual void setOff();
public:
    LEDMorseSender(int outputPin, float wpm=WPM_DEFAULT);
};

/**
* Sends Morse on an analog output pin (using PWM). The brightness value is
* between 0 and 255 and is passed directly to analogWrite.
*/
class PWMMorseSender: public MorseSender {
private:
    byte brightness;
protected:
    virtual void setOn();
    virtual void setOff();
public:
    PWMMorseSender(int outputPin, float wpm=WPM_DEFAULT, byte brightness=255);
    void setBrightness(byte brightness);
};

morse.cpp
// Morse Code sending library

#include <morse.h>

// MorseSender
int MorseSender::copyTimings(
morseTiming_t *rawOut,
morseBitmask_t definition)
{
int t = 0;
boolean foundSentinel = false;
for(morseBitmask_t mask = MORSE_BITMASK_HIGH_BIT;
    mask > 0; mask = mask >> 1)
{
    boolean isDah = (mask & definition) > 0;
    if(!foundSentinel)
    {
        if (isDah) { foundSentinel = true; }
        continue;
    }
    rawOut[2*t] = isDah ? DAH : DIT;
    rawOut[2*t + 1] = DIT;
    t++;
}
return t;
}
unsigned int MorseSender::fillTimings(char c)
{
int t = 0;
unsigned int start = 0;
if (c >= 'a' && c <= 'z')
{
    t = copyTimings(timingBuffer, MORSE_LETTERS[c-'a']);
}
else if (c >= '0' && c <= '9')
{
    int n = c - '0';
    boolean ditsFirst = (n <= 5);
    if (!ditsFirst)
    {
        n -= 5;
    }
    while(t < 5)
    {
        timingBuffer[2*t] = ((t < n) == ditsFirst) ? DIT : DAH;
        timingBuffer[2*t + 1] = DIT;
        t++;
    }
}
else
{
    int s = 0;
    while(MORSE_PUNCT_ETC[s].c != END)
    {
        if(MORSE_PUNCT_ETC[s].c == c)
        {
            t = copyTimings(timingBuffer,
                MORSE_PUNCT_ETC[s].timing);
            break;
        }
        s++;
    }
    if (MORSE_PUNCT_ETC[s].c == END)
    {
        start = t = 1; // start on a space
    }
}

timingBuffer[2*t - 1] = DAH;
timingBuffer[2*t] = END;

return start;
}

// see note in header about pure-virtual-ness
void MorseSender::setOn() {};
void MorseSender::setOff() {};

// noop defaults
void MorseSender::setReady() {};
void MorseSender::setComplete() {};

MorseSender::MorseSender(unsigned int outputPin, float wpm) :
pin(outputPin)
{
setWPM(wpm);
}

void MorseSender::setup() { pinMode(pin, OUTPUT); }

void MorseSender::setWPM(float wpm)
{
setSpeed((morseTiming_t)(1000.0*60.0/(max(1.0, wpm)*DITS_PER_WORD)));
}

void MorseSender::setSpeed(morseTiming_t duration)
{
DIT = max(1, duration);
DAH = 3*DIT;
}

void MorseSender::setMessage(const String newMessage)
{
message = newMessage;

// Force startSending() before continueSending().
messageIndex = message.length();

// If a different message was in progress, make sure it stops cleanly.
if (timingIndex % 2 == 0) {
    setOff();
}
}

void MorseSender::sendBlocking()
{
//Serial.println("Sending blocking: ");
//Serial.println(message);
startSending();
while(continueSending());
}

void MorseSender::startSending()
{
messageIndex = 0;
if (message.length() == 0) { return; }
timingIndex = fillTimings(message[0]);
setReady();
if (timingIndex % 2 == 0) {
    setOn();
    //Serial.print("Starting with on, duration=");
} else {
    //Serial.print("Starting with off, duration=");
}
lastChangedMillis = millis();
//Serial.println((int)timingBuffer[timingIndex]);
}

boolean MorseSender::continueSending()
{
if(messageIndex >= message.length()) { return false; }

unsigned long elapsedMillis = millis() - lastChangedMillis;
if (elapsedMillis < timingBuffer[timingIndex]) { return true; }

timingIndex++;
if (timingBuffer[timingIndex] == END)
{
    messageIndex++;
    if(messageIndex >= message.length()) {
        setOff();
        setComplete();
        return false;
    }
    timingIndex = fillTimings(message[messageIndex]);
}

lastChangedMillis += elapsedMillis;
//Serial.print("Next is       ");
if (timingIndex % 2 == 0) {
    //Serial.print("(on) ");
    setOn();
} else {
    //Serial.print("(off) ");
    setOff();
}
//Serial.println((int)timingBuffer[timingIndex]);

return true;
}

void *MorseSender::operator new(size_t size) { return malloc(size); }
void MorseSender::operator delete(void* ptr) { if (ptr) free(ptr); }

// SpeakerMorseSender

void SpeakerMorseSender::setOn() { tone(pin, frequency); }
void SpeakerMorseSender::setOff() {
if (carrFrequency == CARRIER_FREQUENCY_NONE) {
    noTone(pin);
} else {
    tone(pin, carrFrequency);
}
}
void SpeakerMorseSender::setReady() { setOff(); }
void SpeakerMorseSender::setComplete() { noTone(pin); }
SpeakerMorseSender::SpeakerMorseSender(
int outputPin,
unsigned int toneFrequency,
unsigned int carrierFrequency,
float wpm)
: MorseSender(outputPin, wpm),
frequency(toneFrequency),
carrFrequency(carrierFrequency) {};

// LEDMorseSender

void LEDMorseSender::setOn() { digitalWrite(pin, HIGH); }
void LEDMorseSender::setOff() { digitalWrite(pin, LOW); }
LEDMorseSender::LEDMorseSender(int outputPin, float wpm)
: MorseSender(outputPin, wpm) {};

// PWMMorseSender

void PWMMorseSender::setOn() { analogWrite(pin, brightness); }
void PWMMorseSender::setOff() { analogWrite(pin, 0); }
void PWMMorseSender::setBrightness(byte bright) {
brightness = bright;
}
PWMMorseSender::PWMMorseSender(
    int outputPin,
    float wpm,
    byte bright)
: MorseSender(outputPin, wpm), brightness(bright) {};

And finally, here is my code:
#include <avr/pgmspace.h>
#include <MorseEnDecoder.h>
#include <stdio.h>
#include <morse.h>
#define PIN_STATUS  13
#define CPU_RESTART_ADDR (uint32_t *)0xE000ED0C
#define CPU_RESTART_VAL 0x5FA0004
#define CPU_RESTART (*CPU_RESTART_ADDR = CPU_RESTART_VAL);

// Pin mapping
const byte morseInPin = 7;
const byte morseOutPin = 13;
String check = "";
String origin = "SOS";
const int maxItems = 3;
int x;
char myArray[maxItems], curChar;
char nextChar;
int i;
int y;

// Instantiate Morse objects
morseDecoder morseInput(morseInPin, MORSE_KEYER, MORSE_ACTIVE_LOW);
morseEncoder morseOutput(morseOutPin);

// Variables dealing with formatting the output somewhat
// by inserting CR's (carriage returns)
long lastTransmissionTime;
long currentTime;
boolean transmissionEnded = true; // Flag to mark old transmission is finished

// Minimum transmission pause time to insert carriage returns (CR)
// Adjust depending on Morse speed. IE 13 wpm = 646 ms between words (no CR).
const long transmissionPaused   = 1000; // Suitable for 13 wpm?

LEDMorseSender sender(PIN_STATUS);

void setup()
{
  Serial.begin(9600);
  Serial.println("Morse EnDecoder Geocache");

  // Setting Morse speed in wpm - words per minute
  // If not set, 13 wpm is default anyway
  morseInput.setspeed(5);
  morseOutput.setspeed(5);

  lastTransmissionTime = (long)millis();
}

void(* resetFunc) (void) = 0; //declare reset function @ address 0

void loop()
{
  currentTime = (long)millis();

  // Need to call these once per loop
  morseInput.decode();
  morseOutput.encode();

  // RECEIVE MORSE (INPUT)
  // If a character is decoded from the input, write it to serial port
  if (morseInput.available())
  {
    char receivedMorse = morseInput.read();
    Serial.print(receivedMorse);
    // A little error checking
    if (receivedMorse == '#') Serial.println("< ERROR:too many morse signals! >");
    morseOutput.write('#');
    morseOutput.encode();

    //Create Array out of receivedMorse Chars

    curChar = 0;
    nextChar = receivedMorse;
    curChar += nextChar;
    myArray[i] = curChar;
    check.concat(myArray[i]);
    Serial.println(check);

    //Check input and respond
    if (check == origin)      //GOOD JOB!!  Your reward is as follows
    {
      Serial.println("check = origin");
      Serial.println(check);
      sender.setup();
      sender.setWPM(5);
      sender.setMessage(String("help is coming"));
      sender.startSending();
    }
    else if (check == "S") {}
    else if (check == "SO") {}
    else if (check == " SOS") {}
    else if (check.length() > 4)
    {
      delay(100);
      Serial.println("resetting");
      delay(500);
      resetFunc();  //call reset
      delay(100);
    }
    else {}
  }
  sender.continueSending();
}

I'm not keen on resetFunc();  //call reset - that doesn't actually reset the chip, you know. It just jumps to the reset vector, that is something else (the hardware is not reset).

if I just try to run it plugged into my computer with the serial monitor not open, nothing happens - without trying to understand all your code, what are you expecting to happen, that doesn't happen, if you don't see the serial output?

I want it to run the code, I'm not trying to sound  facetious, but it literally will not run anything unless serial monitor is open.  It is supposed to read in and decode morse code input from a button on digital pin 7 then it is supposed to compare this string of morse code with another string and if they match it is supposed to output morse code to the LED.

An idea occurred to me that could be the culprit.  The code may be sending the character to the serial monitor after it decodes it (turns button pushes into a character).  If this is the case it would not run without the serial monitor, but I have no idea about how to fix this.

Can you please specify the exact board you are using?
As a side note, you might want to use a non invasive approach to system debug, like https://github.com/rlogiacco/MicroDebug.

On both the Mega and the Nano, if you use the serial port for output only, the board does not care, and does even know, whether anyone (serial monitor or other program) is listening.

I am using Mega currently because it is larger and easier to test circuits on, however I plan to transition this project onto a nano, this is why I tagged both boards.

I have used your debug LED library, and have determined that without serial monitor open, it skips lines 71-116, the main if statement which essentially contains all the important bits of code.  I believe this may have something to do with morseInput.available, but I don't know how to fix it.

It is supposed to read in and decode morse code input from a button on digital pin 7 then it is supposed to compare this string of morse code with another string and if they match it is supposed to output morse code to the LED. - you mean it is reading switch presses via an input pin, and then echoing those same patterns to an output pin, via a decode/encode lot of code? Why? What does it achieve to do that?

It would appear that with this code, the serial.print commands were interfering with the code running as strange as that seems.  I was able to delete the offending serial commands and now the code works.  With a few tweaks, it should be flawless.


text:
Connecting Arduino Wifi shield to Arduino Uno based Mcore board
I am trying to connect this mBot board to an external network, that's why I bought the arduino wifi shield.
I am connecting the wifi shield to the 6pins (5V MOSI GND RST SCK MISO) of the mCore.
Though when uploading any of the Wifi program example, the shield isn't even recognized.
(I've succesfully upgraded the firmware of the shield)
The thing is that I don't really understand how should I plug in the wifi shield on the mCore since I'm struggling to understand the datasheet of the mBot board.
Any advices ?
Regards,
Alex


text:
ESP8266-12 is showing garbage when RST is given
I use ESP8266-12 with an Arduino Uno as a USB-serial adapter.
When I upload any sketch to the ESP8266 it works fine until I reset the ESP8266.
uint32_t realSize = ESP.getFlashChipRealSize();
uint32_t ideSize = ESP.getFlashChipSize();
FlashMode_t ideMode = ESP.getFlashChipMode();

Serial.printf("Flash real id:   %08X\n", ESP.getFlashChipId());
Serial.printf("Flash real size: %u\n\n", realSize);

Serial.printf("Flash ide  size: %u\n", ideSize);
Serial.printf("Flash ide speed: %u\n", ESP.getFlashChipSpeed());
Serial.printf("Flash ide mode:  %s\n", (ideMode == FM_QIO ? "QIO" : ideMode == FM_QOUT ? "QOUT" : ideMode == FM_DIO ? "DIO" : ideMode == FM_DOUT ? "DOUT" : "UNKNOWN"));

if(ideSize != realSize) {
    Serial.println("Flash Chip configuration wrong!\n");
} else {
    Serial.println("Flash Chip configuration ok.\n");
}

delay(5000);

If I ground reset button, garbage values are being shown.
Connections details:
EN  - 3.3V of Uno
VCC - 3.3V of Uno
RST - GND Of Uno(If needed)
TX - TX of Uno
RX - RX of Uno
GPO15 - GND of Uno
GPO01 - GND of Uno
GND - GND of Uno

Possible duplicate of ESP8266 + Arduino Uno: Can't send AT Commands

Espressif says it can not be disabled.
Ref.: https://github.com/esp8266/Arduino/issues/3047


text:
Electric meter pulse counting using LLC
I am trying to create an electric meter reading setup for Arduino, and I have been searching for it and almost every posts available is using LDR sensor.
http://www.reuk.co.uk/wordpress/solar/flashing-led-on-electricity-meter/
https://jonarcher.info/2014/03/arduino-based-electricity-monitor/
And since it is using LDR, the system should be kept in a dark area, or that the LDR is taped to the flashing LED so that no other light source will interfere the sensor.
But I wanted to have a different setup, and what I am thinking is:

inside the electric meter, tap into the blinking LED
From the LED, connect it to an LLC (https://www.sparkfun.com/products/12009)
From the LLC, connect it to the Arduino
Arduino will sense/detect the pulse of the LED.

Is this a possible setup? Will it not fry the Arduino or the LLC? Will Arduino be able to detect the pulse?
If not, are there any other options? can I use discrete components instead? (I will be the one creating the circuit connection for the LED and Arduino, using resistor, diodes, etc.)

You know you aren't allowed to open you electricity meter, right? If the company finds out, you're screwed.

Yes, I am quite aware of that. But this is for a project only. :)

Relieved to hear that. Then an opto-coupler is the most ideal solution.

for a project only ... is this for a school project? ... if i was teaching your course, i would give you lower marks because of the use of an illegal hack

When you aren't using the same power supply as the product you are interfacing with, it's usually a good idea of have some form of electrical isolation, which is what the LDR+LED was doing -- there was no way for a voltage spike to reach the Arduino, nor was there any way that different "ground" potentials could cause problems. (Imagine if the ground reference for the meter was floating at a high voltage with respect to earth-ground, but your Arduino power supply's negative line was referenced to earth ground.)
A good way to get electrical isolation is with an opto-coupler, also called an opto-isolator, which is essentially an LED and a photo-transistor inside the same package. The LED side is completely electrically isolated from the photo-transistor side, but light can pass from the LED to the phototransistor.
You would connect the opto-coupler so that current passes through the LED side when the pulse happens, and with a pull-up or pull-down resistor on the phototransistor side, which gets pulled down or up (depending on the circuit) when the LED is on.

simulate this circuit – Schematic created using CircuitLab

so this means the LED side of the opto-coupler will be the one tapped into the electric meter's LED?

Correct. Depending on the particular model of opto-coupler, you can put it's LED in series with the meter's LED and hope the voltage drop will not be too much, or you can just replace the meter's LED with the opto-coupler's LED if you are allowed to make that kind of modification.

Oh okay. How about the connection for the Arduino side? Is it okay if the 5V will come from Arduino Uno's 5V and then the "Arudino input" will be connected to Arduino's Pin 10?

5V would come from the Arduino 5V supply, yes. The input would be any digital input pin -- if your code wants to check pin 10, no problem.

If you plan to put the opto, instead of the led, you may have to add an additional resistor in series with the led. Depending on what value they used in the meter. As the opto uses a IR led, which has a lower forward voltage that the visible led you'd replace.

Thanks! Any optocoupler you can recommend?

I won't recommend any particular, except to say that the easiest to set up are the 4-pin. Search the usual vendors, read the datasheets. In the datasheet examine the LED side forward voltage (Input Forward Voltage) and the CTR (Current Transfer Ratio), which tells you the current that will flow through the output side compared to the current flowing through the input side. It all depends on your circuit.

Alright! Last thing, according to the electric meter I'll be testing, it is 1600 imp/kWh. In getting an optocoupler, is there someting related to this which I need to check on the datasheet of the optocoupler I'll be buying?

Unless you’re pulling megawatts of power, you don’t have anything to worry about with that pulse rate and any opto.


text:
How to connect DRV-8835 to arduino
I try to connect arduino with motor using DRV-8835. The problem I have - simply nothing happens. I used tutorial from http://www.instructables.com/id/The-SnapMobile-Start-Your-Physical-Computing-Engin/step6/Building-the-Prototype-Wiring-Up-the-Arduino-the-D/
Code for arduino:
void setup() {
    pinMode(7, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(8, OUTPUT);
}

void loop() {
  digitalWrite(8, HIGH);
  digitalWrite(7, HIGH);
  analogWrite(5, 255);
}

Maybe someone has scheme how to connect wires to motor. Now I'm not sure if I made a mistake or motor driver is broken.

You might try wiring the enable and direction pins active (high?) to skip the arduino.  But check the motor wiring, too.  Do the motors spin when directly connected to your motor power supply without the PCB?  (The motor supply voltage is appropriate for the motors, right?  And you aren't running them off the Arduino or USB power?  And these are DC motors, not steppers or something more exotic?)

I use http://www.dagurobot.com/goods.php?id=86 . In fact I didn't try to connect battery(4x 1.5V) to motor. I'm newbie and little afraid of destroy motor

Ok. I tried without arduino and motor driver and motor works so it's not motor fault

Do you have any LEDs and resistors you could use to check the Arduino outputs in place of the motor driver?  Or you could use a voltmeter to measure them.

Yes. I checked it and there is no output - at least using LED and resistor

Try disconnecting the motor driver from the arduino and building and running the blink sketch.  If that works, try changing it to blink each pin you had used for the motor driver.

All arduino pins works fine.

Could you post a picture of the wiring? Also, just a shot in the dark, try adding a delay(100) at the end of the loop function.

I've added delay to loop method and connected led instead of motor. I guess it should be on

Try this code:
void setup() {
    pinMode(8, OUTPUT);//MODE
    pinMode(5, OUTPUT);//AENBL
    pinMode(7, OUTPUT);//APHASE
}

void loop() {
  pinMode(7, HIGH);//APHASE
  pinMode(8, HIGH);//MODE
  pinMode(5, HIGH);//AENBL
  delay(200);
  pinMode(5, LOW);//AENBL
}

Here is a description of the breakout board, this shows a requirement of PWM on AENBL for speed control. Try different  delays.

Setting AENBL HIGH should drive the motor at full speed - it has the same effect as analogWrite(5, 255). Dropping it from high to low should stop the motor.
Are you sure the DRV8835 is working properly? You can in theory diagnose it with a logic analyzer, but a scope will work better as the motor outputs aren't really logic. My test setup (yeah, I had one die on me) watched PHASE (just make sure it would toggle), MODE (should be HIGH), and AENBL (should show a square wave for the PWM duty cycle) as logic inputs, then watched the motor outputs on the scope to verify that one of them is the inverse of AENBL and the other is HIGH. Which follows AENBL and which is HIGH depends on PHASE, so you can toggle it if you can only check one output.


text:
Flame Sensors Problems
I am making a fire fighting robot and I need a sensor. I want the sensor detection range to be about 6m or 7m (about 18ft to 20ft).
The question is which sensor should I choose to get that detection range? I've found that some small IR sensors are not suitable for my range required.
I'm making a simulated one. It might be confused if there are non-fire distractions so I'm asking for a technique that can improve the sensor range and determination very very effective... or which sensor should I choose??
I don't want the IR sensor to be more directional. If I need it to be more directional I can use 2 or 3 or more. It is no problem. I want the IR sensors to improve their detection range. I can only get 2m now. I want it to be about 4m or 5m.

Are you fighting real fires or simulated ones such as a candle in a maze?  What possible non-fire distractions exist in the environment which might confuse it?

You'd probably want the IR sensor to be more directional. Try putting some heat-shrink around the sensor, so it can only see light from straight ahead.


text:
Grove temperature sensor with Arduino Yun
I try to test Grove - Infrared Temperature Sensor on Arduino Yun with the sample code but it does not work. In the console it shows that the object temperature is out of range all the time. However, when I try to test it on Arduino Uno, it works fine.
My sketch:
#include <math.h>
#include<Console.h>
//#include <NewSoftSerial.h>       //if display in LCD(seeed serial LCD driver)
//#include <SerialLCD.h>           //if display in LCD(seeed serial LCD driver)
//#include "temp.h"

const int temp_analog_in = A0;  // Analog input pin connect to temperature sensor SUR pin
const int objt_analog_in = A1;  // Analog input pin connect to temperature sensor OBJ pin
float temp_calibration = 0;     //this parameter was used to calibrate the temperature
//float objt_calibration=0.000; //this parameter was used to calibrate the object temperature
float temperature_range = 10;  //we make a map of temperature-voltage according to sensor datasheet. 10 is the temperature step when sensor and
//object distance is 9CM.
float offset_vol = 0.014;      //this parameter was used to set the mid level voltage,when put the sensor in normal environment after 10 min,
//the sensor output 0.For example,the surrounding temperature is 29℃，but the result is 27℃ via the sensor,
//you should set the reerence to 0.520 or more,according to your sensor to change.
//the unit is V

//SerialLCD slcd(11,12);
float tempValue = 0;
float objtValue = 0;
float current_temp = 0;
float temp = 0;
float temp1 = 0;
float temp2 = 0;
unsigned int temp3 = 0;
const float reference_vol = 0.500;
unsigned char clear_num = 0; //when use lcd to display
float R = 0;
float voltage = 0;

long res[100] = {
  318300, 302903, 288329, 274533, 261471, 249100, 237381, 226276, 215750, 205768,
  196300, 187316, 178788, 170691, 163002, 155700, 148766, 142183, 135936, 130012,
  124400, 119038, 113928, 109059, 104420, 100000, 95788, 91775, 87950, 84305,
  80830, 77517, 74357, 71342, 68466, 65720, 63098, 60595, 58202, 55916,
  53730, 51645, 49652, 47746, 45924, 44180, 42511, 40912, 39380, 37910,
  36500, 35155, 33866, 32631, 31446, 30311, 29222, 28177, 27175, 26213,
  25290, 24403, 23554, 22738, 21955, 21202, 20479, 19783, 19115, 18472,
  17260, 16688, 16138, 15608, 15098, 14608, 14135, 13680, 13242, 12819,
  12412, 12020, 11642, 11278, 10926, 10587, 10260, 9945, 9641, 9347,
  9063, 8789, 8525, 8270, 8023, 7785, 7555, 7333, 7118, 6911
};

float obj [13][12] = {
  /*0*/             { 0, -0.274, -0.58, -0.922, -1.301, -1.721, -2.183, -2.691, -3.247, -3.854, -4.516, -5.236}, //
  /*1*/             { 0.271, 0, -0.303, -0.642, -1.018, -1.434, -1.894, -2.398, -2.951, -3.556, -4.215, -4.931}, //→surrounding temperature,from -10,0,10,...100
  /*2*/             { 0.567, 0.3, 0, -0.335, -0.708, -1.121, -1.577, -2.078, -2.628, -3.229, -3.884, -4.597}, //↓object temperature,from -10,0,10,...110
  /*3*/             { 0.891, 0.628, 0.331, 0, -0.369, -0.778, -1.23, -1.728, -2.274, -2.871, -3.523, -4.232},
  /*4*/             { 1.244, 0.985, 0.692, 0.365, 0, -0.405, -0.853, -1.347, -1.889, -2.482, -3.13, -3.835},
  /*5*/             { 1.628, 1.372, 1.084, 0.761, 0.401, 0, -0.444, -0.933, -1.47, -2.059, -2.702, -3.403},
  /*6*/             { 2.043, 1.792, 1.509, 1.191, 0.835, 0.439, 0, -0.484, -1.017, -1.601, -2.24, -2.936},
  /*7*/             { 2.491, 2.246, 1.968, 1.655, 1.304, 0.913, 0.479, 0, -0.528, -1.107, -1.74, -2.431},
  /*8*/             { 2.975, 2.735, 2.462, 2.155, 1.809, 1.424, 0.996, 0.522, 0, -0.573, -1.201, -1.887},
  /*9*/             { 3.495, 3.261, 2.994, 2.692, 2.353, 1.974, 1.552, 1.084, 0.568, 0, -0.622, -1.301},
  /*10*/            { 4.053, 3.825, 3.565, 3.27, 2.937, 2.564, 2.148, 1.687, 1.177, 0.616, 0, -0.673},
  /*11*/            { 4.651, 4.43, 4.177, 3.888, 3.562, 3.196, 2.787, 2.332, 1.829, 1.275, 0.666, 0},
  /*12*/            { 5.29, 5.076, 4.83, 4.549, 4.231, 3.872, 3.47, 3.023, 2.527, 1.98, 1.379, 0.72}
};

float binsearch(long x)// this function used for measure the surrounding temperature
{
  int low, mid, high;
  low = 0;
  //mid=0;
  high = 100;
  while (low <= high)
  {
    mid = (low + high) / 2;
    if (x < res[mid])
      low = mid + 1;
    else//(x>res[mid])
      high = mid - 1;
  }
  return mid;
}

float arraysearch(float x, float y) //x is the surrounding temperature,y is the object temperature
{
  int i = 0;
  float tem_coefficient = 100;
  i = (x / 10) + 1;
  voltage = (float)y / tem_coefficient;
  //Serial.print("sensor voltage:\t");
  //Serial.print(voltage,5);
  //Serial.print("V");
  for (temp3 = 0; temp3 < 13; temp3++)
  {
    if ((voltage > obj[temp3][i]) && (voltage < obj[temp3 + 1][i]))
    {
      return temp3;
    }
  }
}

float temp_measure()
{
  unsigned char i = 0;
  float current_temp1 = 0;
  int signal = 0;
  tempValue = 0;

  for (i = 0; i < 10; i++) //
  {
    tempValue += analogRead(temp_analog_in);
    delay(10);
  }
  tempValue = tempValue / 10;
  temp = tempValue * 1.1 / 1023;
  R = 2000000 * temp / (2.50 - temp);
  signal = binsearch(R);
  current_temp = signal - 1 + temp_calibration + (res[signal - 1] - R) / (res[signal - 1] - res[signal]);
  //current_temp1=current_temp;
  //slcd.setCursor(0,1);
  //slcd.print("sur T:");
  //slcd.print((int)current_temp1,DEC);
  Console.print("Surrounding temperature:");
  Console.print(current_temp);
  return current_temp;
}

float objt_measure()
{
  unsigned char i = 0;
  unsigned char j = 0;
  float sur_temp = 0;
  unsigned int array_temp = 0;
  float temp1, temp2;
  float final_temp = 0;
  objtValue = 0;
  for (i = 0; i < 10; i++)
  {
    objtValue += analogRead(objt_analog_in);
    delay(10);
  }
  objtValue = objtValue / 10;
  temp1 = objtValue * 1.1 / 1023; //+objt_calibration;
  sur_temp = temp1 - (reference_vol + offset_vol);
  Console.print("\t Sensor voltage:");
  Console.print(sur_temp, 3);
  Console.print("V");
  //slcd.setCursor(11,1);
  //slcd.print((int)(temp1*10000),DEC);
  array_temp = arraysearch(current_temp, sur_temp * 1000);
  temp2 = current_temp;
  temp1 = (temperature_range * voltage) / (obj[array_temp + 1][(int)(temp2 / 10) + 1] - obj[array_temp][(int)(temp2 / 10) + 1]);
  final_temp = temp2 + temp1;
  if ((final_temp > 100) || (final_temp <= -10))
  {
    Console.println ("\t out of range!");
  }
  else
  {
    Console.print("\t object temperature:");
    Console.println(final_temp, 2);
    //Serial.println("℃");
  }
  ////////////////////////////////////////////////////
  //The fllowing code is used for display by serialLCD
  /*
    slcd.setCursor(0,0);
    slcd.print("obj T:");
    if((final_temp>=0)&&(final_temp<=100))
    {
      slcd.print(final_temp,DEC);
    }
    else if((final_temp<0)&&(final_temp>=-10))
    {
      slcd.setCursor(10,0);
      slcd.print('-');
      slcd.print(abs(final_temp),DEC);
    }
    else
      {
        slcd.setCursor(5,0);
        slcd.print("out of range");
        }*/
  //////////////////////////////////////////
}

void setup()
{
  Bridge.begin();
  Console.begin();
  while (!Console);
  Console.println("Hi, what's your name?");// initialize serial communications at 9600 bps:
  //slcd.begin();//Add while using LCD to display
  //slcd.backlight();//Turn on the backlight of LCD while using LCD to display
  analogReference(INTERNAL);//set the refenrence voltage 1.1V,the distinguishability can up to 1mV.
  //analogReference(INTERNAL1V1);//(mega only)set the refenrence voltage 1.1V,the distinguishability can up to 1mV.
}
//If use LCD to display, adding below code to clear the screen in time
void loop()
{
  temp_measure();
  objt_measure();

  /*
    if(clear_num==10)
      {
        slcd.clear();
        clear_num=0;
        }
    else
      clear_num++;
  */
}

I am sure that I connected the wires properly. The exact same wiring configuration is used with Arduino Uno.

What's the current output?

The current out put is 5V.

Sorry, I meant "what does the sketch print right now?"


text:
Cannot communicate with Serial Monitor - Arduino Yun
I connect Arduino Yun to my Computer with WiFi. I was able to get the IP address of my Arduino Yun. However, when I try to print something. It seems to not work at all. The following code is the one that I try:
void setup() {
 Serial.begin(9600);
}

void loop() {
 // print labels
 Serial.print("NO FORMAT");
 delay(100);
}

I did not get any kind of error. However, when I open the Serial Monitor, it shows nothing at all. I try to use the same code with Arduino Uno. It works fine.

double check the port, also check in Device Manager if there is the Yun in Ports. It might be the missing driver

When using the Yun over wifi, you cannot user Serial, you need to use Bridge Console object. Serial is bound to the usb cable.
Give a spin to ConsoleRead example.

Moreover, can you take a look at my other question with Arduino Yun?http://arduino.stackexchange.com/questions/5239/grove-temperature-with-arduino-yun


text:
External access to Yun - request not recognised as HTML
I am trying to access my Yun externally.
My router recognises traffic on Port XXXXX and forwards it to my Arduino Yun.
I have the below code working internally and now trying to adapt this to work for external (adapted from http://arduino.cc/en/Tutorial/TemperatureWebPanel).
To access the Arduino Yun over the network I type:
http://XXX.XXX.XXX.XXX:XXXXX/arduino/on

When using this script locally, i.e. myArduinoName.local/arduino/on, the onboard light turns on (and off if URL changed accordingly).
Adapting this working code, I have changed to "noListenOnLocalhost" and put in my port number (XXXXX).
The code is reached (see below for the response).
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

// Listen on default port 5555, the webserver on the Yun
// will forward there all the HTTP requests for us.
YunServer server(XXXXX);
String startString;
long hits = 0;

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

  // Bridge startup
  pinMode(13,OUTPUT);
  digitalWrite(13, LOW);
  digitalWrite(13, HIGH);

  Bridge.begin();
  Console.begin();

  // Listen for incoming connection only from localhost
  // (no one from the external network could connect)
  //server.listenOnLocalhost();
  server.noListenOnLocalhost();
  server.begin();

}

void loop() {
  // Get clients coming from server
  YunClient client = server.accept();

  client.println("hello");

  // There is a new client?
  if (client) {
    // read the command
    String command = client.readString();

    command.trim();        //kill whitespace

    client.println(command); // why does this return a full GET request instead of "on"?

    if (command == "on") {
      digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);
    }

    if (command == "off") {
      digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);              // wait for a second
    }

    // Close connection and free resources.
    client.stop();
    hits++;
  }

  delay(50); // Poll every 50ms
}

The response I get is (I have replaced my IP and port with X's):

hello
GET /arduino/off HTTP/1.1 Host: XXX.XXX.XXX.XXX:XXXXX
  Connection: keep-alive Pragma: no-cache Cache-Control: no-cache
  Accept:
  text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
  User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36
  (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
  Accept-Encoding: gzip, deflate, sdch Accept-Language:
  en-GB,en-US;q=0.8,en;q=0.6

I expected

hello
on

So it would seem that because I'm using a different port (other than 80 or 5555) the response is no longer being interpreted as an HTTP request.
I have also tried to edit the uhttpd file via SSH to provide a specific address and port for both my external IP address and my fixed internal IP address.
Then tried to restart the device and also a uhttpd restart i.e.:
/etc/init.d/uhttpd restart

I have attempted to access the URL using my mobile phone (i.e. not on the same network).
Any ideas why my request is not being treated as HTTP?

It works!
The changes to the uhttpd must have done the trick to listen for http traffic on a given IP/port (other than 0.0.0.0:80).
Instead of supplying a port number for the server in the code, I would surmise that the change to the config takes care of it so this, so the port number in code is no longer needed:
YunServer server(XXXXX);
should be changed back to
YunServer server;


text:
Mosfet controlled motor runs while LOW
I am using a mosfet (IRFZ44N) to control a dc motor, and a separate one to control a led strip. Both are using the same circuit running to different pwm pins on the arduino.
The light strip is working fine (can be turned on an off as expected), but the motor runs at a low level when the pin sends a LOW state, and revs up when it is sent a HIGH state.
They are both receiving power from the VIN pin of the arduino which in turn in plugged into a 12v 6a dc adaptor.
Any ideas what could cause this behavior?
(Apologies if this is a messy schematic, I am a beginner)

Please include a schematic of ypur circuit. Generally, this transistor is a bad choice due to its high gate-source-saturation voltage of 2-4V. For switching applications you want to choose one with a Vgs,sat several times lower than your logic level. There are dedicated "logic-level mosfets"

Just added a schematic, hope it represents what I have here.
I'm finding that the mosfet gets very hot, maybe it can't handle the current going through it.

There are some mistakes in the provided schematic:

the nmos has to be connected to motor-
the freewheeling diode has to be the other way around
the resistor doesn't make sense. If it's meant to be a pulldown is has to connect the gate with ground and have a much higher value (~10kOhm). If it's meant to be an inrush limiter it has to be in series with the gate

Actually I don't trust you schematic at all, because I wonder why the motor runs at all without damaging your arduino. Have a look at the low-side transistor configuration here to see how it is done.
As I mentioned in a comment, this mosfet is a bad choice because it has a too high gate-source threshold voltage Vgs,th (that's the gate voltage at which the transistor starts to conduct. The voltage at which it has the specified on-resistance Rds,on is several times higher than this. Choose a device with a Vgs,th below 1V or go for a logic-level mosfet.

Thanks, I will try to replicate the circuit in the article


text:
MQTT on nano with Ethernet shield not working
I'm using an arduino nano with an ethernet shield (ENC28J60), and  ethernet eem to be working (I can create a webserver with Ethercard library).However, i'm stuck when i try to connect to a MQTT server.
I tried NanodeMQTT (stuck at waitforlink), Adafruit MQTT Library + Ethernet.h ( MQTT_connect() : Connection failed, endlessly retrying), PubSubClient + Ethernet.h (client.connect return 0) and some others.
At this point i am wondering if i am doing the right configuration each time:

when asked an ip, i set the static one i want for my arduino : 192.168.1.50
when asked an gwip, i set one of wy internet router : 192.168.1.254
when asked for a server, i set it to my mqtt server ipv4 : 192.168.1.185 (and port is 1883)
when asked for a mac adress, i keep the one in the example, or just write a random one

Do you know what can cause the ethernet.h or mqtt library to fail, but still ethercard is working fine ?

Try simple then add features.  For example, try to get the Ethernet working first.  Then add the MQTT.  Who is asking for IP addresses?  Are you saying these are the IP addresses you have added to your program / sketch?  If your program / sketch is not long maybe you can include it in your question.

try UIPEthernet library instead of Ethernet, which is for a different chip

i'm using the basic bluit-in examples for theese libraries, and did not include them since i tried 3 and none worked. But since Ethercard work on my end, i will try to fiddle with it and a MQTT library then. Also tried UIPEthernet with no success, but did not even realise it was a standard library designed for ENC28J60, thanks for pointing that out, maybe i can just adapt some Ethernet.h code by replacing it with UIPEthernet

Thanks to Juraj pointing me that UIPEthernet is just a replacement for the Ethernet library, I finnally found this article Which works just fine.