message:
PIR sensor issues

**The code works but there was a problem on the output. When the PIR detect the presence of motion the output (pin 12) would not give an instant HIGH state on the output, it has more than 10 sec delay to provide a HIGH state on PIN 12. HOw can I lessen the time that once the PIR sensors detected motion it would give a HIGH state to the output (pin 12)? please help me regarding this problem! Thanks**

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

    void loop()
    {
        pinMode(13,OUTPUT);//output 1
        pinMode(12,OUTPUT);//output 2
        int pirOuts=11;pinMode(pirOuts,INPUT); /*PIR sensor 1*/
        int pirOut = 10;pinMode(pirOut,INPUT); /*PIR sensor 2*/

        if (digitalRead(pirOut) || digitalRead(pirOuts) == HIGH){
            digitalWrite(12,HIGH);
            tone(13, 50132); delay(100); noTone(13); delay(10);
            tone(13,54621);  delay(50);  noTone(13); delay(50);
            tone(13,35689);  delay(60);  noTone(13);
        }
        else if (digitalRead(pirOut)||digitalRead(pirOuts)==LOW){
            digitalWrite(12,LOW);
            tone(13,50132); delay(100); noTone(13); delay(10);
            tone(13,54621);  delay(50);  noTone(13); delay(50);
            tone(13,35689);  delay(60);  noTone(13);
        }
        else
        {}
    }

body:
Check to make sure your PIR sensor reads high when triggered. Most of them will trigger high, but I've seen a few that will trigger low. Also, some PIR sensors have potentiometers to control delay. Some delay the trigger, some delay the reset between triggers.

The delay may not be coming from the Arduino, but from the sensor itself.

Note, the first if statement is formatted incorrectly:

    if (digitalRead(pirOut) || digitalRead(pirOuts) == HIGH)

should probably be:

    if (digitalRead(pirOut) == HIGH || digitalRead(pirOuts) == HIGH)

It works the way you coded it because you're doing a logical OR of the two input values (which will be 0 or 1) then comparing the result to HIGH. As I said it will work, but probably not best practice.

Also, in your code, I don't understand why you're using else if instead of just else.

    else if (digitalRead(pirOut)||digitalRead(pirOuts)==LOW){

Basically, your first if statement has to be false (so both pirOut and pirOuts must both be low) so your if statement as written will always be true.

If your intent was to execute that code when either pirOut or pirOuts goes LOW, then it should be a separate if statement, not an else if.


sender: user

message:
Cat motion detector that can tell the difference from humans

I'm trying to build a cat motion detector but, to avoid getting false alarms when a person walks by, I was thinking of using RFID. i.e. the cat has a collar and the detector senses the collar when they get within a couple of feet and makes a noise.

The problem there seems to be with RFID is that the range is so short - e.g. 4".

Anyone have a better solution?

sender: assistant

body: Place an additional motion sensor such that it can only detect motion from things significantly taller than cats, and use that as an inhibitor/classifier of the cat motion signal.


body:
What about a transmitter on the collar - Bluetooth, or a coded infra red pulse, that could be detected by fixed stations?

Battery life and safety (swallowing batteries!) would be serious considerations though...


message:
Arduino uno + cnc shield v3 + Stepper Motor Driver A4988 + AccelStepper?

I successfully run the [AccelStepper examples][1] on an [Arduino Mega][2] with a [RAMPS 1.4][3] shield, two [A4988 stepper motor drivers][4] and two [17HS16-0284S stepper motors][5].

I used 3 jumpers on the RAMPS to set the microstep resolution to 1/16.

I used this code inspired by the [Polargraph Server][6] for [Polargraph][7]:

    #include <AccelStepper.h>

    /*
    // for the Arduino Uno + CNC shield V3

    #define MOTOR_A_ENABLE_PIN 8
    #define MOTOR_A_STEP_PIN 2
    #define MOTOR_A_DIR_PIN 5

    #define MOTOR_B_ENABLE_PIN 8
    #define MOTOR_B_STEP_PIN 3
    #define MOTOR_B_DIR_PIN 6
    */

    // for the Arduino Mega + RAMPS 1.4
    #define MOTOR_A_ENABLE_PIN 30
    #define MOTOR_A_STEP_PIN 36
    #define MOTOR_A_DIR_PIN 34

    #define MOTOR_B_ENABLE_PIN 56
    #define MOTOR_B_STEP_PIN 60
    #define MOTOR_B_DIR_PIN 61

    AccelStepper motorA(1, MOTOR_A_STEP_PIN, MOTOR_A_DIR_PIN);
    AccelStepper motorB(1, MOTOR_B_STEP_PIN, MOTOR_B_DIR_PIN);

    void setup()
    {
      motorA.setEnablePin(MOTOR_A_ENABLE_PIN);
      motorA.setPinsInverted(false, false, true);
      motorB.setEnablePin(MOTOR_B_ENABLE_PIN);
      motorB.setPinsInverted(false, false, true);

      motorA.setAcceleration(100);
      motorA.move(1000);
      //motorA.setMaxSpeed(100);
      //motorA.setSpeed(100);

      motorB.setAcceleration(100);
      motorB.move(1000);
      //motorB.setMaxSpeed(100);
      //motorB.setSpeed(100);

      motorA.enableOutputs();
      motorB.enableOutputs();
    }

    void loop()
    {

      motorA.run();
      motorB.run();

    }

I tried to use the same code with the same stepper motor drivers and motors on a [Arduino Uno](https://www.arduino.cc/en/Main/ArduinoBoardUno) and a [CNC shield v3](http://blog.protoneer.co.nz/arduino-cnc-shield-v3-00-assembly-guide/) without success (I also used the 3 jumpers to set the microstep resolution to 1/16). The motors do not work and jitter.

What is wrong with my code?

**Bonus questions**:
I have taken this setup and code from the Polargraph server but I didn't get how I'm suppose to know how to use `setEnablePin()` and `setPinsInverted()` methods. In fact, I have troubles finding documentation about the CNC shield V3 and the A4988 drivers (I only found [this page][8]) to work with AccelStepper.

  [1]: http://www.airspayce.com/mikem/arduino/AccelStepper/examples.html
  [2]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560
  [3]: http://reprap.org/wiki/RAMPS_1.4
  [4]: https://www.pololu.com/product/1182
  [5]: http://www.omc-stepperonline.com/nema-17-bipolar-stepper-motor-028a-36ncm51ozin-17hs160284s-p-80.html
  [6]: https://github.com/euphy/polargraph_server_polarshield
  [7]: http://www.polargraph.co.uk/
  [8]: http://blog.protoneer.co.nz/arduino-cnc-shield-v3-00-assembly-guide/

body:
Manually set the ENABLE pins as OUTPUTs, i.e. add in the `setup()` function:

    pinMode(MOTOR_A_ENABLE_PIN, OUTPUT);
    pinMode(MOTOR_B_ENABLE_PIN, OUTPUT);


message:
Override #define statements in libraries

I'm using a library that, by default, wants to use Serial2 as the interface to a display, however, I'm working with an UNO which only has one serial interface, so the compile fails. I'm trying to use a SoftwareSerial instead, but I can't figure out how to override the #define statement in the library without editing the library.

I'm guessing since the software serial port isn't generated at compile time, I can't.

    #include <SoftwareSerial.h>
    #define nexSerial HMI
    #include <Nextion.h>

    SoftwareSerial HMI(8,9);

    void setup() {
      // put your setup code here, to run once:

    }

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

    }

I haven't started writing code yet, can't get past the attempt to redirect the serial interface to a software serial.

body:
You can't.

All you are doing in your code is providing a #define to the instance of the header file that is included in your sketch file. You have no way of modifying the instance that is included in the library's source files.


body:
You're allowed to modify the header file.  The [version I looked at](https://github.com/bborncr/nextion/blob/master/Nextion.h#L47) says

    #define USE_SOFTWARE_SERIAL //Comment this line for use  HardwareSerial

...but I think he meant "comment this line out to use HardwareSerial".  Or conversely, "uncomment this line to use SoftwareSerial."

Then you just pass your `SoftwareSerial` instance into the `Nextion` constructor:

    SoftwareSerial HMI( 8,9 );
    Nextion nextion( HMI );

    void setup()
    {
       HMI.begin( 9600 ); // or whatever speed...

However, because you are using pins 8 & 9, I would **strongly** recommend using [AltSoftSerial](https://github.com/PaulStoffregen/AltSoftSerial) instead.  It is much more reliable and efficient.  MUCH.

You would have to modify the Nextion files to either (1) search and replace all occurrences of `SoftwareSerial` with `AltSoftSerial`, or (2) add a third choice to the author's `#ifdef/#endif` sections.  For example:

    #define USE_SOFTWARE_SERIAL // uncomment this line to use SoftwareSerial
    #define USE_ALTSOFT_SERIAL  // uncomment this line to use AltSoftSerial
                                // comment both above  to use HardwareSerial

    #if defined(USE_SOFTWARE_SERIAL)
    #include <SoftwareSerial.h>
    #elsif definied(USE_ALT_SOFTSERIAL)
    #include <AltSoftSerial.h>
    #endif

    class Nextion{
     private:
      void flushSerial();
    #if defined(USE_SOFTWARE_SERIAL)
      SoftwareSerial *nextion;
    #elsif defined(USE_ALTSOFT_SERIAL)
      AltSoftSerial *nextion;
    #else
      HardwareSerial *nextion;
    #endif

Do either one of those things in all files that refer to the `Nextion` serial member; Nextion.CPP certainly needs it.


message:
Error on Uploading Program to ESP8266 via Foca v2.2 (USB to TTL Adapter)

BACKGROUND
----------

To test the capability of uploading program to ESP8266,  I use an empty program with only a blank setup function and a blank loop function. The result showed me that there are a **espcomm_sync error** and a **espcomm_open error**. Any idea to solve this problem?

----------

HARDWARE
--------

[![Foca v2.2][1]][1] [![ESP8266][2]][2]
----------

----------

PIN CONNECTION
--------------

      Foca v2.2 <-> ESP8266
            TXD <-> RXD
            RXD <-> TXD
            DTR <-> RST

    Arduino UNO <-> ESP8266
            GND <-> GND
           3.3V <-> Vcc

----------

PIN DIAGRAMS
------------
Foca v2.2

[![enter image description here][3]][3]

ESP8266

[![enter image description here][4]][4]

----------

ON LINUX UBUNTU 15.04
---------------------

[![enter image description here][5]][5]

----------

ON WINDOWS 10
---------------------

[![enter image description here][6]][6]

REFERENCE
---------

----------

Bring IoT to Arduino, together [Getting Started] - [http://www.arduinesp.com/getting-started][7]

  [1]: https://i.stack.imgur.com/jHQP2.jpg
  [2]: https://i.stack.imgur.com/6Z1PO.jpg
  [3]: https://i.stack.imgur.com/8s6D0.jpg
  [4]: https://i.stack.imgur.com/1Ksvu.jpg
  [5]: https://i.stack.imgur.com/R8SPR.jpg
  [6]: https://i.stack.imgur.com/eq5MJ.png
  [7]: http://www.arduinesp.com/getting-started

body:
by the comments I think you are not understanding correctly how to connect Reset and GPIO_0 of ESP. To set esp-01 into flash mode (to program) you need to set GPIO_0 Low (GND) and then also apply Low on RST ESP pin.
To debug the things and be certain that there is no hardware problem let just start by doing these connections:

    Foca v2.2 <-> ESP =1
          TXD <-> RXD
          RXD <-> TXD
          GND <-> GND
      Arduino <-> ESP 01
         3.3V <-> 3.3V
         3.3V <-> CH_PD
         GND  <-> GND

Now, with a wire, **connect GPIO_0 to ground**. With another wire, **briefly** connect **RST of the ground** to make ESP reset. You should be now in flash mode. Remove the connection on GPIO_0 and make it float. Now upload the code.

**Note:** this is basically the option C on the link you provide. If you have some buttons you can make it too:
[![Manually Flash][1]][1]
(source: [arduinesp.com](http://www.arduinesp.com/arduinesp/wp-content/uploads/2015/04/TTL-to-ESP01-blink-upload-and-reset-button.jpg))

**Now, does the code upload in Arduino IDE?**

If the answer is still no, try to add a small capacitor between 3.3v and ground.

If the answer is yes, now you can move on and try the other options described in the link you provide. I recommend using the option A:

[![Automatic Upload][2]][2]
(source: [arduinesp.com](http://www.arduinesp.com/arduinesp/wp-content/uploads/2015/07/TTL-to-ESP01-blink-NPN.png))

Any generic npn transistor should work

 [1]: https://i.stack.imgur.com/9SBe2.jpg
 [2]: https://i.stack.imgur.com/bE5r0.png


message:
Control brightness of 20 watt street LED light using Arduino

I have searched google and I now know that if we change the resistance, we can change the brightness of an LED, but I was wondering how to change resistance by using a micro controller.

body:
Did you do a web search? "[arduino pwm high power led driver][1]" gives all the info you may need to answer this.

Here is a nice youtube clip, by [Julian Ilett][2] that explains how to do this: [60W High Power LED Driver with PWM #2 - Brightness Control][3].

  [1]: https://www.google.co.th/search?q=arduino pwm high power led driver
  [2]: https://www.youtube.com/channel/UCmHvGf00GDuPYG9DZqQKd9A
  [3]: https://www.youtube.com/watch?v=V7CA1brVXDA


message:
Arduino mega R17 led blink continuously

I have bought 10 Arduino Mega 2560 clones and all of them have the same problem. When I connect the to my PC I get a message that windows cannot recognize that device and the LED at the board in R17 blinks non stop. normally this led stops when the arduino is ready. Also in the Arduino IDE I don't see the port option enable.

body:
You need CH340G drivers. CH340G is a chip that basically replaces the usual ATMega 8U2/16U2 that is used for USB to serial interface. As CH340 cannot be reprogrammed it means that you can't emulate other USB devices with your arduino for example a keyboard.

----

You can download the drivers [here][1].

  [1]: http://www.5v.ru/ch340g.htm


message:
How should I use an optocoupler to control a 12Vcc load with Arduino?

I am developing a project to operate a load of about 12Vdc.  I considered the use of an optocoupler to avoid mechanical wear of a relay.  The design I have tried is [this][1]:

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

This configuration seems to work OK, but I am a biologist and this is my first attempt with an opto of any kind!!!!  I had a lot of trouble with the transistor until I changed to a PNP.  Is this right?  Can it be done with an NPN or even without any transistor at all?

  [1]: http://123d.circuits.io/circuits/1573080-optoacoplador-con-arduino
  [2]: https://i.stack.imgur.com/W3OtZ.png

body:
If your load draws a small amount of current (less than about 30 mA current), your 4N35 optocoupler could drive the load directly on 12 volts.

Ignore my use of 4N28 (similar to 4N35). It is the symbol that I had.

It appears that your PNP transistor circuit is something like this :

[![enter image description here][1]][1]

The PNP transistor circuit can work well depending upon your load current.  The PNP circuit has some problems with the transistor not turning on fully (and won't be described here).  You may not get the full 12 volts to your Load. But, if it works for your load, then be happy with the PNP circuit.

The circuit below is for a NPN transistor circuit  :

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

Using the NPN circuit allows (in this case) for the transistor to turn on fully, leaving almost the full 12 volts for your Load.

Important Note :  The NPN transistor circuit produces an output that is the LOGIC opposite of the PNP circuit.   Notice that for the PNP circuit, a logic 1 to the input of the optocoupler (LED on) turns on power to your Load.

On the NPN circuit, a logic zero (0) to the optocoupler LED is required to turn on your Load.

Another variation of the circuit is below, and does NOT have the reverse logic situation.  In other words, it will behave like the PNP circuit. When LED is on, the Load will be on  :

[![enter image description here][3]][3]

You can experiment with the value of R1 in the NPN circuits. You could experiment with lower value, down to 1K (1000 ohms) if you are using a power transistor to drive high current loads.

  [1]: https://i.stack.imgur.com/2kUIv.jpg
  [2]: https://i.stack.imgur.com/h6eMQ.jpg
  [3]: https://i.stack.imgur.com/WkbZy.jpg


message:
Data changes when working with classes

When I pass an array, and it's len to the constructor of a class. I store the length, and access it later, it's value changes, seemingly at random.

    #include "Arduino.h"

    #define NUMSENSORS 2
    const byte dataPins[] = {A5, A4};

    class B {
        public:
            B(byte pin) { _pin = pin; }
            byte getPin() { return _pin; }
        private:
            byte _pin;
    };

    class A {
        public:
            A(const byte sensorPins[], int len) {
                Serial.print("provided len is: ");
                Serial.println(len);
                _len = len;
                Serial.print("Stored len is: ");
                Serial.println(_len);
                for (int i=0; i<len; i++) { myBarray[i] = new B(sensorPins[i]); }
            }
            B* myBarray[];
            int _len;
            void printLen() {
                Serial.print("Length is: ");
                Serial.println(_len);
            }
    };

    void setup() {
        Serial.begin(115200);
        A test(dataPins, NUMSENSORS);
        for (uint8_t i=0; i<10; i++) {
            test.printLen();
            delay(100);
        }
    }

    void loop() {
    }

The value of len is fine in the constructor,  but is different when I call it in the function "getLen".

I feel as though it has something to do with pointers. Because if I comment out the for loop in the constructor of A, the value is correct.

Any help would be greatly appreciated, thanks in advance.

body:
Let us do this with a template class and avoid malloc, etc.

    #define membersof(x) (sizeof(x) / sizeof(x[0]))

    const byte dataPins[] = { A5, A4 };

    class B {
    public:
      byte getPin() { return (_pin); }
      void setPin(byte pin) { _pin = pin; }
    private:
      byte _pin;
    };

    template<unsigned len>
    class A {
    public:
      A(const byte sensorPins[]) {
        for (unsigned i = 0; i < len; i++)
          _vec[i].setPin(sensorPins[i]);
      }
      unsigned getLen() { return (len); }
      B* getB(unsigned ix) { return (ix < len ? &_vec[ix] : NULL); }

    private:
      B _vec[len];
    };

    void setup() {
      Serial.begin(115200);
      A<membersof(dataPins)> test(dataPins);
      unsigned len = test.getLen();
      Serial.print(F("test.getLen()="));
      Serial.println(len);
      for (unsigned i = 0; i < len; i++) {
        B* bp = test.getB(i);
        Serial.print(F("test::B["));
        Serial.print(i);
        Serial.print(F("].getPin()="));
        Serial.println(bp->getPin());
      }
    }

    void loop() {
    }

Cheers!


message:
How can I pass a char array as the parameter to a function?

I am creating a menu for adjusting system variables.

The menu is made up of pointers like so:

    char* options4[] = {"hMin1", "hMax1", "refr1", "fSpeed1"};

I want to pass the selected string as the parameter for an 'adjust' function for use in some conditional logic and for display on a HCMAX7219 7 segment display. Here's what I've got:

    int option = 0;
    float variable = 82.0;

    if(Serial.available() > 0) {
      key = Serial.read();
      if(key == back) {
        return;
      } else if(key == fwd) {
        float newVar = adjust(String(options4[option%4]), variable);
      } else if(key == down) {
        option++;
      } else if(key == up) {
        option--;
      }
    }

    float adjust(char* str, float var) {
      ...do some stuff...
      display.print7Seg(str, 8);
      EDIT: forgot this call..
      display.print7Seg(var, 1, 4);
      ...do stuff to var...
      return var;
    }

The library function takes `(char[] TextString, unsigned int Offset)` as it's parameters.

EDIT: the library also has functions `print7Seg(long number, byte decimalPlace, unsigned int Offset)` and `print7Seg(long number, unsigned int Offset)`

Now I'm new to pointers, but I can see that I am passing a pointer to my adjust function, and expecting it to dig out a char array from memory. I can't see any problems with that, though I may be missing something. When I try to compile, the IDE just crashes with exit status 84; so no debug info.

Am I going about this the wrong way?

body:
There are one or two things missing in your code. Where is setup() and loop()? Or is it just a snippet?

But answer to the question first. This is not right:

    newVar = adjust(String(options4[option%4]), variable);

Should be:

    newVar = adjust(options4[option%4], variable);

You want to index the vector of strings and pass one of the elements to the function.

Cheers!


body:
Ah .. ok I've just figured it out..

This *is* a legitimate way to pass char arrays to functions.

The original `char* options4[]` array is just an array of pointers to char arrays in memory, so passing one of these pointers to a function works fine.

The culprite was actually my float parameter, I was trying to make a library function call with a float to this function: `print7Seg(long number, byte decimalPlace, unsigned int Offset)`.

This is what was causing the IDE to crash.

I got around it by having an int version of each of the variables I need to set. Then typecasting and dividing by a float to get variables that will be used in the main program. like so:

    int hMin1Int = 820;
    float hMin1 = (float)hMin1Int / 10.0;
    int hMax1Int = 880;
    float hMax1 = (float)hMax1Int / 10.0;
    int refr1 = 30; //minutes
    int fSpeed1 = 128;

I was then able to change my function to accept an `int`, the library function, so far, seems to be ok treating an int as a long, but if not I can just make all my ints longs:

    int adjust(char* str, int var) {
      ...do some stuff...
      display.print7Seg(str, 8);
      display.print7Seg(var, 1, 4);
      ...do stuff to var...
      return var;
    }

I was asking the wrong question!

Still I hope this will be useful to someone, so I will leave it up. Thanks for the response Mikael Patel.

Moral of the story, know your library.


message:
Setup J-K Flip-flop for logging on Arduino RESET

There are two events I plan to log; using no switches or requiring manual input of some kind.  One of the events is whenever the Arduino Serial Monitor is opened; the other, is when external event occurs that causes a Arduino RESET.  Second event produces a LOW pulse used to CLK the J-K Flip-flop.  digitalRead of J-K Flip-flop Q; using a conditional statement, if Q = HIGH log to SD Card as event1 date/time stamp else log to SD Card as event2 date/time stamp.  I need the J-K Output Q to be STORED thru the Arduino RESET, so Q can be read.

After reading Q, will need to clear Q; plan to do this from running sketch with a DigitalWrite

74HC73 is the chip I plan to use; it is triggered with a negative going CLK.

What needs to happen with the J and K inputs?  Will this work in toggle mode; with both J and K tried to +5 volts?

body:
Rather than having events that set 1Q or 2Q, consider having the external events take 1R\ or 2R\ low, to reset 1Q or 2Q.  When your sketch starts up, it would read 1Q and 2Q.  If one or the other is low, its event occurred and you can log it.  Then the sketch sets both Q's by dropping the CP lines with J's wired high and K's wired low.  You'd use three I/O pins: two for reading 1Q and 2Q, one for strobing the CP lines to set the Q's after reading them.

Arduino AVR pins default to inputs on Reset so the Arduino can reset without affecting the 74HC73's state.  A 10 to 20KΩ resistor to passively pull the CP lines high is reasonable.

*Edit:* Note, 1R\ and 2R\ operate asynchronously, and are independent of clock inputs.  This leads to simpler interface requirements for your external events.  However, it may also increase sensitivity to electrical noise; if your system is in a noisy environment a different approach might be needed.


body:
My resolution:
[![Status Bit Memory][1]][1]

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

This is the code for logging Arduino RESET and WDT RESET.  Plus the code for resetting the J-K Flip-Flop.

     /////////////// J-K Flip-Flop 74HC73,  Status of Q Monitor ///////////////////////////////////////

     delay(10);

     getDateTime();

     if(value == 1)
     {

          //Creates an entry in "Server.txt" for every RESET cause by "Dual Watchdog Timer"
          SdFile serverFile;
          serverFile.open("Server.txt", O_RDWR | O_CREAT | O_APPEND);

          if (!serverFile.isOpen()) error("Watchdog Start Server");

          serverFile.println("Watchdog RESET:  " + dtStamp);
          serverFile.close();
          Serial.print("Watchdog RESET  ");
          Serial.println(dtStamp + "  ");
          Serial.println("Listening for connections...  ");
          //Serial.println(value);

     }
     else
     {

          //Creates an entry in "Server.txt" for every RESET; caused by opening Serial Monitor
          SdFile serverFile;
          serverFile.open("Server.txt", O_RDWR | O_CREAT | O_APPEND);

          if (!serverFile.isOpen()) error("Manual Start Server");

          serverFile.println("Manual RESET:  " + dtStamp);
          serverFile.close();
          Serial.print("Manual RESET  ");
          Serial.println(dtStamp + "  ");
          Serial.println("Listening for connections...  ");
          //Serial.println(value);

     }
     //Sends LOW to RESET the 74HCT73, JK Flip-flop
     digitalWrite(RESET, LOW);
     delay(10);
     digitalWrite(RESET, HIGH);
     delay(10);
     digitalWrite(RESET, LOW);

///////////////////////////////////////////////////////////////////////////////////////////////

William Lucid 12/22/2016


message:
Playing music with an Arduino

Good evening!

I am quite new with Arduino but not in programming. Still, I have already done some programs with few leds.

I was just wandering how to create a circuit and a program that would play the "happy birthday" song with the following materials:

[![enter image description here][1]][1]

I have a breadbord and some wires.

Else, do you have some links where I could start learning how to play music with it?

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

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

Thanks to Mikael Patel for suggesting [that link](http://forum.arduino.cc/index.php?topic=178460.0) (your Google-Fu must be strong!).

I am pasting the code below so that this answer survives any possible future deletion of the read-only part of the Arduino Forum.

    //ONG LIT YIT 2013-07-20
    //This following code plays happy birthday melody on Arduino
    //Put Piezo Buzzer on GDN and 9 (Positive and negative are reversible)
    //this project requires a Piezo Buzzer and

    // an Arduino board and
    //jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

    const int speakerPin = 9;
    const int LENGTH = 28; // the number of notes
    const char notes[LENGTH + 1] = "GGAGcB GGAGdc GGxecBA yyecdc";
    const int beats[LENGTH] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 16 };
    const int tempo = 150;

    void playTone(int tone, int duration)
      {
      for (long i = 0; i < duration * 1000L; i += tone * 2)
        {
        digitalWrite(speakerPin, HIGH);
        delayMicroseconds(tone);
        digitalWrite(speakerPin, LOW);
        delayMicroseconds(tone);
        }
      } // end of playTone

    void playNote(const char note, const int duration)
      {
      char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',
                      'c', 'd', 'e', 'f', 'g', 'a', 'b',
                      'x', 'y'
                     };
      const int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,
                      956,  834,  765,  593,  468,  346,  224,
                      655 , 715
                    };
      const int SPEE = 5;

      // play the tone corresponding to the note name
      for (int i = 0; i < 17; i++)
        {
        if (names[i] == note) {
          int newduration = duration / SPEE;
          playTone(tones[i], newduration);
        }
      }
    } // end of playNote

    void setup()
      {
      pinMode(speakerPin, OUTPUT);
      } // end of setup

    void loop()
      {
      for (int i = 0; i < LENGTH; i++)
        {
        if (notes[i] == ' ')
          {
          delay(beats[i] * tempo); // rest
          }
        else
        {
          playNote(notes[i], beats[i] * tempo);
        }

        // pause between notes
        delay(tempo);
      }
    } // end of loop

I also cleaned up the code a bit.


message:
Maintaining Arduino on Ubuntu 14.04

I used to use Arduino on Windows but I changed to Linux last week and I was wondering how to have a maintained version of the Arduino terminal:

Indeed, I'm not sure my version is quite recent:

[![Screenshot of Arduino IDE on Ubuntu][1]][1]

The icon seems to have lived ages without a little lifting...

Maybe I'm wrong but it seems so when I open the "Tools" option for instance...

Furthermore I tried to copy and paste this code:

<!-- language: c -->

    //ONG LIT YIT 2013-07-20
    //This following code plays happy birthday melody on Arduino
    //Put Piezo Buzzer on GDN and 9 (Positive and negative are reversible)
    //this project requires a Piezo Buzzer and

    // an Arduino board and

    //jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

    //HAVE FUN

    //this project requires a Piezo Buzzer and

    // an Arduino board and

    //jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

    //HAVE FUN

    int speakerPin = 9;

    int length = 28; // the number of notes

    char notes[] = "GGAGcB GGAGdc GGxecBA yyecdc";

    int beats[] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8,8, 16, 1, 2,2,8,8,8,8,16, 1,2,2,8,8,8,16 };

    int tempo = 150;

    void playTone(int tone, int duration) {

    for (long i = 0; i < duration * 1000L; i += tone * 2) {

       digitalWrite(speakerPin, HIGH);

       delayMicroseconds(tone);

       digitalWrite(speakerPin, LOW);

       delayMicroseconds(tone);

    }

    }

    void playNote(char note, int duration) {

    char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',

                     'c', 'd', 'e', 'f', 'g', 'a', 'b',

                     'x', 'y' };

    int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,

                     956,  834,  765,  593,  468,  346,  224,

                     655 , 715 };

    int SPEE = 5;

    // play the tone corresponding to the note name

    for (int i = 0; i < 17; i++) {

       if (names[i] == note) {
        int newduration = duration/SPEE;
         playTone(tones[i], newduration);

       }

    }

    }

    void setup() {

    pinMode(speakerPin, OUTPUT);

    }

    void loop() {

    for (int i = 0; i < length; i++) {

       if (notes[i] == ' ') {

         delay(beats[i] * tempo); // rest

       } else {

         playNote(notes[i], beats[i] * tempo);

       }

       // pause between notes

       delay(tempo);

    }

    }

And not all of it appeared in the Arduino terminal.

[![Screenshot of Arduino IDE with badly pasted code][2]][2]

  [1]: https://i.stack.imgur.com/vcyLD.png
  [2]: https://i.stack.imgur.com/hIwAn.png

body:
If you want to get maintained (automatically updated) version of Arduino IDE then you install if from a package repository with its dependencies e.g. using `apt-get`:

    sudo apt-get update
    sudo apt-get install arduino arduino-core

However, this way you get a very old version (currently *1.0.5*). Obviously, it is not updated too often if at all.

If you already installed from the package repository via apt-get you can uninstall the package and its dependencies like this:

    sudo apt-get remove arduino arduino-core
    sudo apt-get autoremove

**Better way is to download and install Arduino IDE yourself.** This way Arduino software won't automatically be updated, so you should check Arduino website every now and then and download a new version if one is available.

Open a terminal window (e.g. by pressing *CTRL-ALT-T*), and run `uname -m` to check if you are running 32 bit or 64 bit platform:

    uname -m

See output:

    x86_64 ==> 64-bit kernel
    i686   ==> 32-bit kernel

Go to Arduino Download page on [Download the Arduino Software][1] and download the 32 bit or 64 bit version, depending on the Ubuntu version installed on your computer.

In a terminal window extract the package and move it to your preferred location, e.g. `/opt`. You need sudo rights to move it to `/opt`. Finally, run the install script if you want to start the IDE graphically (adds desktop icon, MIME type, default application for `.ino`). See the example commands below for installing the latest 32 bit version as of the time of writing to `/opt`.

    cd ~/Downloads
    tar xf arduino-1.6.7-linux32.tar.xz
    sudo mv arduino-1.6.7 /opt
    /opt/arduino-1.6.7/install.sh

You can also start the IDE from the terminal:

    /opt/arduino-1.6.7/arduino

  [1]: https://www.arduino.cc/en/Main/Software


message:
Arduino Audio Shield Problems

I recently bought a Velleman KA02 Arduino Audio Shield (http://www.velleman.co.uk/contents/en-uk/p579_ka02.html), which uses an ISD1760PY audio chip and soldered it together. The first time I fired it up, it worked fine, I had freshly soldered it together. But from the next time up to now, if I press any button but the reset button, the onboard LED blinks 7 times and it doesn't record or do anything. I checked the solder joints and nothing fell out and I also checked the ISD1760PY datasheet but found nothing about my problem. Is there a way to fix this and why it it happening? Please note that I am not controlling the shield with SPI or with the Arduino.

This question was put on hold in the EE section so I an posting it here because the reason was that it has something to do with Arduino.

body:
Look at page 35 of winbond datasheet.
If the LED is blinking 7 times either the chip is in isp mode or in an unstated mode. This can happen after power off during erase function.
I held erase button for about 20 seconds and after that I was able to record messages.


message:
Daikin Remote ARC

I started off attempting to use the  IRRemote    Library and a VS1838B Sensor to capture the Daikin air condition signal.  I’ve read about the timing and in all honesty, I don’t think I can do it on my own so I looked to find the code others had created and adapt it to my own, trying their remote controls first thinking Daikin may only have a few sets.

I can’t confirm that will work as yet because I’ve only been able to find the code below but I’m not quite sure what is the best practice for ripping (stripping out the parts I don’t need) it apart.

When I attempted to capture the IR codes, most of the time I get nothing at all.  My stereo remote is immediate displayed though.

Now the good news,  based on Harizanov’s work, he’s mapped the ARC533 Remote,  which is the same model that I have.

 - My Model : FTM18NV2S
 - Remote:  ARC533A55
 - [Daikin - Smash][1]

NV2S  (On the Inverter)

 - Remote:  Doesn’t say anything of use
 - [15-Series Wall Mount][2]

Code Here: [Control Daikin air conditioner over the Internet][3]

Code here: [Github: mharizanov/Daikin-AC-remote-control-over-the-Internet][4]

Can anyone provide a recommendation on how I could trim up this code to try it?

  [1]: http://www.daikin.co.th/en/product/smash/
  [2]: http://www.daikinac.com/content/residential/single-zone/15-series/
  [3]: http://harizanov.com/2012/02/control-daikin-air-conditioner-over-the-internet/
  [4]: https://github.com/mharizanov/Daikin-AC-remote-control-over-the-Internet

body: I had a problem with my daikin A/C. After spending lot of time trying to fix this problem, i found out that is is using long ir codes which is hard to simulate using the IRSenderBitBang (38 kHz). After lot of fustation I used irdevkit.com. It has a ir decoder built in and I can control it using ESP8266. Works well


message:
Are there flexible pressure sensors for Arduino that can measure forces of at least 600 lbs?

I'm in need of flexible pressure sensors that can read how much force is exerted on someone's foot while running (these sensors would be placed inside the shoe). Since pressure can often be three times the weight of the person, I need something fairly strong. Are there fairly cheap sensors that are available or hacks that could do the same thing?

Thanks!

body:
Sensors such as you describe are usually called "Load Cell".

At the 600 pound weight, I haven't found any "flexible" load cells. A sensor would have to be quite robust.

Flexible might not be the best answer.

[This load cell page](http://www.futek.com/product.aspx?t=load) has quite a range of load cells, several thousand pounds, also not very inexpensive.

This might be difficult to install in running shoes :

[![enter image description here][1]][1]

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


body:
As you are presumably measuring changing (dynamic) loads, you could consider a piezo electric sensor.

At the simplest, use a piezo element usually sold as a buzzer (make sure you get the plain element with no electronics included, some 'buzzers' also have drive circuitry).
[![Piezo element][1]][1]

That will give you a voltage pulse proportional to applied pressure, which might give you the precision that you need, and is very small and light to insert in a shoe.

See [this question][2] for a similar solution (and the above image!)

  [1]: https://i.stack.imgur.com/fqvSV.jpg
  [2]: https://electronics.stackexchange.com/questions/18048/glowing-pressure-plate


message:
Detect how long a push button is being pressed?

I would like to detect how long the state on/off is going on for. Is there a way to do that? I would like to do that for two reasons:

 1. I would be able to make a very simple toggle button. (I know about the other way with the old value and new value).
 2. I can make the button being pressed for a long time be like a return button.

Anyone got any ideas?

body:
1. Note the time the switch is pressed (with `millis()`)
2. Note the time the switch was released.
3. When the switch is released calculate the difference. If it is a "long" time do one thing, otherwise do something else.


body:
This needs a combination of patterns.

First, the button pin needs to be debounced. This can be done with the "blink-without-delay"-pattern where the button pin is sampled with a low period (40 ms in the example code below).

Second, a simple state-machine is needed to keep track of the button state but also if the return button action function, doReturnButton(), has already been called.

The button is assumed to be connected from GND to pin4. The button action function, doButton(), is called when the button is pushed (goes LOW).

    const int buttonPin = 4;
    const unsigned long debounceInterval = 40;
    const unsigned long returnInverval = 400;
    bool buttonState = true;
    bool returnButtonState = false;
    unsigned long buttonDownMillis = 0L;

    void doButton()
    {
      Serial.print(buttonDownMillis);
      Serial.println(F(":doButton"));
    }

    void doReturnButton()
    {
      Serial.print(buttonDownMillis);
      Serial.println(F(":doReturnButton"));
    }

    void setup()
    {
      Serial.begin(57600);
      while (!Serial);
      pinMode(buttonPin, INPUT_PULLUP);
    }

    void loop()
    {
      unsigned long currentMillis = millis();
      static unsigned long previousMillis = 0L;

      // Check if it is time to sample the button pin
      if (currentMillis - previousMillis >= debounceInterval) {
        previousMillis = currentMillis;

        // Did the button change
        if (digitalRead(buttonPin) != buttonState) {
          buttonState = !buttonState;

          // Was the button released
          if (buttonState) {
         returnButtonState = false;
          }

          // Was the button pushed
          else {
         buttonDownMillis = currentMillis;
         returnButtonState = true;
         doButton();
          }
        }

        // Check if button was pushed and time for return action
        else if (returnButtonState) {
          if (currentMillis - buttonDownMillis >= returnInverval) {
         returnButtonState = false;
         doReturnButton();
          }
        }
      }
    }

What does the code do?

1. It samples the button pin with a debounce interval.
2. If the button state changes:
a. High to Low it calls the doButton() function and captures a timestamp. It also allows detect of return time interval.
b. Low to High. Return time interval is not allowed any more.
3. It checks if the return time interval has elapsed and if so calls the doReturnButton() function. The detect is then not allowed any more.

The doButton() function is called when the button is pushed (transition high to low), only once. The doReturnButton() function is called if the return time limit exceeds and the button is still low. Both are only called once per push (transition high to low).

To avoid the multiple transitions that occur when a button is pushed a debounce time period is used. The can also be done in hardware with a RC-circuit.

With some abstraction it could be rewritten as:

    #include <Timemark.h>

    Timemark debounce(40);
    Timemark buttonHold(400);

    const int buttonPin = 4;
    bool buttonState;

    void doButton()
    {
      Serial.println(F("doButton"));
    }

    void doReturnButton()
    {
      Serial.println(F("doReturnButton"));
    }

    void setup()
    {
      Serial.begin(9600);
      while (!Serial);
      Serial.println(F("started"));
      pinMode(buttonPin, INPUT_PULLUP);
      buttonState = digitalRead(buttonPin);
      debounce.start();
    }

    void loop()
    {
      if (debounce.expired()) {
        bool currentState = digitalRead(buttonPin);
        if (currentState != buttonState) {
          buttonState = currentState;
          if (buttonState) {
         if (buttonHold.expired())
           doReturnButton();
         else
           doButton();
         buttonHold.stop();
          }
          else {
         buttonHold.start();
          }
        }
      }
    }

This also demonstrates the callback on the release of the button. The [Timemark][1] class hides all the time intervals, expire calculations, etc.

Cheers!

  [1]: https://github.com/mikaelpatel/Arduino-Timemark


message:
Should millis() be stored in a variable once each loop, or called for every reference?

When comparing the value of millis() numerous times per loop(), are there reasons for/against storing it in a variable once at the top of loop(), v.s.  calling millis() each time?

The most basic example code "Blink Without Delay" is written as such:

    void loop() {
      //...
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // Do stuff
      }
    }

I don't really she why the example code above bothers storing millis() in a variable "currentMillis" at all. (I realize that in such a simple program, there would be no noticeable difference.)

I imagine that if I use a variable, the longer the duration of loop(), and the further down my use of the "currentMillis" variable, the more deviated the stored value will be.
*I'm wondering the other ramifications of either method as well.*

Does calling millis() directly hog resources of any sort? If not, I imagine it would be better to not use a variable, so as to get a more accurate time value and save a bit of memory.

body:
The primary downside to calling a function each time is that it may take more CPU cycles to complete the overall loop. The difference in CPU cycles, if any, depends on the actual implementation of the function and how the compiler optimises the call. For low-CPU sketches, this difference is probably unnoticeable.

Generally speaking, it is good programming practice to avoid calling a function more times than is necessary. Really the function should be called directly only if you have reasons to believe, based on desired timing and procedure order, that using the same return value in multiple places could create problems. In the example sketch given, there would be almost no functional difference between using a variable or calling the function inline.

Another advantage to using a variable is that you can give it a name that makes the code clearer to understand. In the example given, the relationship between `currentMillis` and `previousMillis` is very clear. In the case where a function returns a more complex object, such as a class or structure instance, using a variable (of the appropriate type) can be really useful since this would allow multiple members of the returned data to be accessed without calling the function multiple times. In fact, even in the given example, the function would have to be called twice since `currentMillis` appears twice in the loop.

As far as memory goes, an unsigned long uses very little.


message:
21 Servo on Mega?

I want to use 21 servo ([SG5010][1]) motors using Mega board. Is it possible to do this?

A possibility is all the servos will be operating at the same time, with average load of ~3.5 KG, and each using 1A, so 21 servos will use 21A.

Will be able to supply power? If yes then how do I go about it?

  [1]: https://www.adafruit.com/product/155

body:
The Mega board will not be able to supply that much current, no. If you consult the schematic, you will see that the 5V regulator is rated for a maximum current of 800mA.

A computer PSU would be an appropriate power supply (a typical 350W PSU will happily supply >30A on the 5V rail). Be aware that some PSUs have a minimum load; you may need to add a power resistor or other load.

Also note that if you want individual control of all the servos, the ATmega1280 only has 16 PWM outputs (IIRC), so you would need software PWM or an external PWM IC.


body:
There is a [servo/sensor shield for the Arduino Mega][1] that can control up to 54 servos. This shield will only fit the Mega, unlike the usual 14 servo Arduino shield, which is shaped to fit most Arduino boards.

[![Photo of Arduino Mega servo shield][2]][2]

Here is an easier to view diagram:

[![Diagram of Arduino Mega servo shield][3]][3]

It is possible, and **advisable**, to supply power via the screw terminals from an external power source, rather than use the Arduino's own power. Even just one servo can have difficulty in working from the Arduino's on board power supply, especially if just using USB to power the Arduino. However, even with the use of an external power source powering the shield, I have my doubts as to whether the shield could support 21A without burning out. Someone may be able to clarify this.

You may find this page, [Servo Shield][4], useful:

> **MEGA Sensor Shield**
>
> The Arduino MEGA has many more I/O pins (54 Digital pins and 16 Analog
> pins)than a standard Arduino. This shield also has connectors
> specifically for some external devices like an SD Card, Radio
> communications (Bluetooth and others). It also has an option to power
> the "V" pins on all the Digital I/O 3-pin groups from an external
> power supply instead of the Arduino +5V. This is good for large
> numbers of servos etc. The "Analog" 3-pin groups still use the Arduino
> +5V which is better from an electrical noise perspective.
>
>This version has two options of +5V supply to all the "V" pins:
>
> - Jumper on: +5 comes
> from the Arduino. Should be limited to about 300 ma
> - Jumper off: +5 (or
> other appropriate voltage) comes from an external supply connected to
> the blue terminal strip. External power Ground must also be connected
> to the blue terminal strip.
>
> Using an external supply allows more current than the Arduino or Mega
> can supply, such as current for control of many servos or relays, and
> other attached devices. Usually this is +5V because most external
> devices require it. It is possible to use +6 volts if ALL the attached
> devices are the same such as Servos with that rating.

  [1]: http://www.ebay.co.uk/itm/Mega-Sensor-Shield-V2-0-V2-Arduino-ATMEGA-2560-R3-1280-ATmega8U2-ATMEL-AVR-/391374794831
  [2]: https://i.stack.imgur.com/l5Kz7.jpg
  [3]: https://i.stack.imgur.com/J3aAn.jpg
  [4]: https://arduino-info.wikispaces.com/SensorShield


message:
ATmega32U4 (Leonardo/Pro Micro) bootloader, 8K rather than 4K?

Recently hit the dreaded 0x7000 / 28k~ AVRDUDE+LUFA limit.  It states everywhere this is because the bootloader uses 4KB, thus reducing the 32KB to 28KB.  Makes sense, except...

Blank sketches on the 32U4 take nearly 4KB from the get go, which I thought was attributed to the bootloader?  So now I'm confused.  If I'm losing 4KB off the top, and 4KB off the bottom - is the bootloader 8KB?

EDIT:  In case the above is unclear, it appears my sketches only have ~24k of the 32k available to them.  Is this expected behavior?

body: The bootloader needs a USB stack to work. It is possible to run the main sketch without a bootloader. So yes, I suppose you must have two of them. Looking at the assembler output for a blank sketch, it appears that you get the USB code in it by default. As I said, they have to assume you may not have the bootloader around, so they can't just execute the stack from the bootloader.


message:
SendSMS example sketch hangs at PINMUNBER if statement

I'm using an Arduino shield connected to an Arduino Uno for sending text messages. I'm using one of the in built examples from the Arduino IDE for sending SMS by name - `sendsms` in the GSM examples. However, the code doesnt work at all... it keeps hanging at the line

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

and never goes beyond it.

I didn't keep any pincode for my SIM card. please help

[![Screenshot of code][1]][1]

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

body:
Try this sketch:

    #include <SoftwareSerial.h>

    SoftwareSerial gsm(2,3);
    void setup() {
      Serial.begin(9600);
      gsm.begin(9600);
      delay(1000);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      while (gsm.available() > 0)
        Serial.write(gsm.read());
      while (Serial.available() > 0)
        gsm.write(Serial.read());
    }

This sketch will help troubleshoot exactly what's wrong with your setup, without the clutter of a library.

Connect the shield's TX pin to Arduino pin 2 and the shield's RX pin to Arduino pin 3. Ensure that all GNDs are connected. Upload the sketch. Set your serial monitor to `BOTH NL & CR` and the baud rate to 9600. Enter `AT` from the serial monitor. If you recieve `OK`, it means comms have been established with the shield. If you receive gibberish, change the SoftwareSerial baud rate to values from 19200, 57600, etc. until you get a legible response.

Then send the command `AT+CREG?` to check the SIM's registration status. If you get something like `+CREG: *, 1` or `+CREG: *, 5` (* means 'dont care'), then your SIM has been registered on the network. Report your results here.


message:
MQTT broker and Arduino + Sensors NRF24L01

I am newbie, I have never used MQTT before, so I have some questions.
Here is my topology.

I have several sensors (Arduino Pro Mini + NRF24L01) and main server/handler(Arduino Mega + Ethernet Shield or ESP module) to receive/send messages to/from sensor nodes, so all network is build on NRF24L01 (NRF24 Mesh library). But I need to be able to communicate with all these sensors from outside over the internet. Previously I implemented simple socket communication.
I have recently discovered MQTT protocol and it is awesome. I want to implement communication between main server and outside world using it.

1. What part of my topology should implement broker in? I think it should be on the main server (Arduino Mega) but again communication between main server/master server is implemented via NRF24L01 modules and custom protocol.

2. Or in my case is better to use HTTP communication with master server?

Please explain this topic and suggest how to implement this correctly in my case.

body:
The normal topology is sensor nodes publishing topic-data on a MQTT broker. And the broker distributing updates to subscribing clients. The MQTT broker is responsible for several levels of QoS (Quality of Service) such as storing attribute/topic-values (persistence), checking that messages are delivered, etc. Typically the broker runs on a server with disk, multiple network connections, etc.

A possible solution is to send sensor messages to a bridge that translates and publishes the message on the MQTT broker. The sensors may use a simple cheap local wireless network (such as based on NRF24L01) and the bridge would publish over IP (Ethernet, WiFi, etc) to the MQTT broker.

Some sensors/actuators might need configuration/control (alarm thresholds, resolution, etc). In this case they need to subscribe to messages (topic updates) from the MQTT broker. Again the bridge needs to provide the subscription and message translation/routing back to the sensor.

Last, topics naming is a challenge as the bridge should be transparent in the naming structure but still configurable. The bridge configuration (e.g. network address/topic translation) could also be handled as a bridge topic.

Cheers!


message:
Power converting - up or down?

Sorry if there is an obvious answer to this - I'm pretty new at Arduino and electronics. I've searched a bunch, but I think I'm too vague - and don't know what terms to look for.

I have a pretty simple project using a 3.3v Arduino Pro Mini (https://www.adafruit.com/products/2377) and a 12v button/LED (https://www.adafruit.com/products/1185).

I'd like to give the LED the full 12v so the light is a bright as possible. The system will be battery operated.

**The question is**: Do I *need* a 12v power supply or can I use a 3.7v power supply and upgrade it somehow? I know I can power the LED with 3.7v but then it's really dim. Is there a way to "upgrade" the 3.7v to 12v? I would assume this would draw more power and drain the battery faster, but I think that would be ok.

I'm hoping to get away with a 3.7v power supply because I want to use a lithium ion polymer battery (https://www.adafruit.com/products/328) - since it's small and rechargeable.

Seems like if I go with 12v source then I need a much bigger battery pack, and I'm hoping to keep the project small. Not sure if it would help to know, but I only need the device to run for 4+ hours between charges.

I'm guessing people will say to go with 12v since the Pro Mini can downgrade the 12v supply so there'd be less parts I have to deal with (I can already make this work). But, again, I was hoping to get away with a small rechargeable power supply. Or, are there good, small 12v batteries - I can't seem to find any on Adafruit or SparkFun.

Any recommendations? Thanks!

body:
Basically you have two choices. There is a third, but you don't wan to take that route.

The third route is to directly power the system with 12V and rely on the Arduino's regulator to drop it to the right voltage for the Arduino. That is very very inefficient and wasteful, and your battery won't last very long - plus the regulator will get hot. So don't even consider that option.

So the two sensible options - start with 3.7V and step it up to 12V using a *boost regulator*, or start at 12V and step it down using a *buck regulator*.

Which of those will be the easiest and most efficient?  Well, there's not much to choose between them.

With either of those solutions you are converting voltage and current. With a buck regulator you are converting voltage into current, and with a boost regulator you are converting current into voltage.

If you start at 12V and step it down yes you need more cells, but each cell can be smaller since each one will have to supply less current.  With 3.7V and stepping up you will have just one cell, but it will need to be bigger since it will have to supply more current.

From a charging perspective it is easier to charge a single cell since you don't have to worry about cell balancing.

From a price and availability point of view, buck (step-down) regulators are cheaper and easier to get hold of on places like eBay than boost (step-up) regulators as pre-built circuits.

So really the choice is yours - 12V (well, 11.4V it would really be - 3S LiIon / Li-Poly) and buck regulator, or 3.7V and boost regulator. Both will work, both will be about as efficient as each other.

Incidentally there are boost regulators specifically designed for driving LEDs from battery sources - you might like to look around to see what is available in that way.


body:
Since your project is to be battery powered, you want to make your system as efficient as is reasonable.

So I am going to take an approach that ends up improving the efficiency of your project.

The button you describe in your link states :

> This button has a domed red plastic cover with a black retaining ring around it. There's an optional LED included

Further, the LED included has a "built in resistor", so that the LED can operate from 12 volts.

Since you would have to install the "optional LED",  why not purchase a Red LED that operates from lower voltage. You will still need a resistor but you won't need to have a voltage converter.

Example  :  Their LED probably has a 2 volt LED (approximate) that operates at perhaps 20 mA).  This would require a 500 ohm resistor (which they incorporate into the LED).  The power loss (wasted) in the resistor is 0.2 watts (200 mW).

Improved Example :  With LED of about 2 volts operating from 3.3 volt power source.  This would require a 68 ohm resistor.  The power loss in the resistor would be 0.027 watts (27 mW).  A substantial improvement in efficiency.

The manufacturer of the button does not give specifications for the LED (the one with the resistor included).  You should connect their LED to a 12 volt power supply and measure the current drawn.  It is possible their LED draws more current than I have shown in the examples.  This would require a re-calculation of the resistor values.

But in any case, the improvement in efficiency will still exist.


message:
Does a moisture sensor need warm-up time?

I am trying to use a moisture sensor to identify the moisture value of my plants. (As every one does.)

The sensor was connected to VCC all the time and my battery goes empty after a short time. So I decided to connect power only at the time I read from the sensor (on the arduino with `digitalWrite(moisture_vcc, HIGH)`.

To problem is that the values were too high.

So I'm wondering if these kind of sensors need a "warm-up time"? And If so, how long is it?

Any experience with it?

body:
Photograph of the YL-69 Sensor  :

[![enter image description here][1]][1]

**Most of this content was generated by :  Conner Wolf**

Basically, that sensor works by measuring the resistance between the two "pins" of the PCB stake. It does this by applying a voltage across the pins, and measuring the current flow. So, the intention is that more water means less resistance, means less voltage, and a fall in the voltage sent to the ADC of the processor.

However, this is also going to lead to the metal from one of the pins being eaten away by galvanic action (electrolysis).

The other pin is likely to have accumulation of materials rather than being eaten away.

This electrolysis and coating of the pins results in a change in surface area of the pins and causes resistance measured to change (for the same given moisture content).

If you want to squeeze as much life out of the thing as possible, there are a few things you can do.

1. DO NOT leave the sensor powered. When you want to take a reading, power the sensor for maybe a few seconds, and take your readings. Then power it off again. Don't take readings too often.
2. Periodically reverse the pins of the electrical connection between the readout board and the "stake" board. Since only one terminal will be eaten away at a time, this should spread the decay out a bit.
3. Be aware that ANY mechanical disturbance of the "stake" board will probably cause a large shift in readout value. Your "jiggling the wires" causing a shift in values probably came from the mechanical force transmitted to the PCB through the wiring.

An improved version for this sort of thing use a AC bias on the sensor, which minimizes galvanic corrosion. AC bias reverses the voltage applied to the sensor, attempting to eliminate electrolysis on the sensor.

Higher Quality soil moisture sensors use capacitive sensor, and therefore make the sensor immune to the corrosion issue, but are much more complex and expensive.

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


message:
Do I use 3,3V or 5V, when device supports both?

I have a general question regarding the power-supply of the electronic components, that are attached to an Arduino.

If I have a device that operates at voltages between 3,3V and 5V ([e.g. this RS232 to ttl converter][1]), what is the best way to connect it with the Arduino?

> Connect 3.3V or 5V power supply between VCC and GND

I know, that you can not draw as much current out of the 3,3V Pin like on the 5V Pin. But what if I don't need much current anyways (like in the linked example)?

What ware the advantages / disadvantages of connecting it to 3.3V and 5V?

  [1]: http://www.emartee.com/product/41777/RS232 TTL Converter MAX3232 Module

body:
Using the [MAX3232 data sheet](http://www.ti.com/lit/ds/symlink/max3232.pdf) , which is what the TTL Converter has on it's board :

The main difference between using 3.3v or 5v is on the receiver data line "R" (or Rout as it is called on the MAX3232).

Simply put, you want to power the TTL converter from the same voltage as your Arduino is using (3.3v or 5v). Meaning the voltage that your I/O pins will put out and accept.

The received data line R will go between 0 volts and Vcc.

You would NOT want to power the TTL converter at 5 volts if you are using the converter for a 3.3v Arduino, as the received data line would go to 5 volts when high. Actually Vcc - 0.1 volts (typ.)  (5 - .1 = 4.9)  as per this specification :

[![enter image description here][1]][1]

If you power the TTL converter from 3.3 volts, the received data line (Rout) switches between 0v and 3.3v   as shown here :

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

  [1]: https://i.stack.imgur.com/ARWv9.jpg
  [2]: https://i.stack.imgur.com/lVVRi.jpg


message:
What is preventing my code from checking the number of pushbutton values for a correct/wrong answer?

My code is supposed to generate a random number and then display it in binary using four LEDs. After you press it, it waits for two seconds before checking your number of pushbutton presses to see if they equal the random number, and it turns the green/red LED on accordingly and restarts the loop.

It doesn't do that, and also it counts multiple pushes if you keep the button pressed in, since it reads the pushbutton as being "on".

Code:

    //VARIABLES:
    const int ledPin1 = 2;
    const int ledPin2 = 3;
    const int ledPin3 = 4;
    const int ledPin4 = 5;
    const int buttonPin = 6;        //push button
    const int ledPincorrect = 8;   //green LED that switches on for correct answer
    const int ledPinfalse = 9;    //red LED that switches on for wrong answer

    int randomNumber = 0;
    int buttonState = HIGH;
    int buttonPushCounter = 0;             //counter for button presses
    int lastButtonState = HIGH;             //previous state of the button
    int getal;
    int i;                              //for the ConvertBinary function, i serves as a variable for the LED's
    unsigned long Timer;               //Timer, switches on after buttonstate = LOW, and after 2 seconds the game restarts
    long lastDebounceTime = 0;         // the last time the output pin was toggled
    long debounceDelay = 50;    // the debounce time; increase if the output flickers
    int ledState = HIGH;
    int remember;

    void setup()
    {
      pinMode(ledPin1, OUTPUT);
      pinMode(ledPin2, OUTPUT);
      pinMode(ledPin3, OUTPUT);
      pinMode(ledPin4, OUTPUT);
      pinMode(buttonPin, INPUT);
      pinMode(ledPincorrect, OUTPUT);
      pinMode(ledPinfalse, OUTPUT);
      Serial.begin(9600);
      randomSeed(analogRead(0));
      buttonState = digitalRead(buttonPin);
      Timer = millis(); // unsigned long Timer = millis();

    }
    void loop()
    {
      if (randomNumber == 0) {
        Serial.print("lets start with random");
        getal = random(1, 16);
        Serial.print("random is: ");
        Serial.println(getal);
        randomNumber = 1;
      }

       int remember = getal;
       for (int i = 2; i < 6; i++) {
       remember = remember / 2;
          if (remember % 2 == 1){
           digitalWrite (i, HIGH);
          }
         else ((digitalWrite(i, LOW)));
        }

        // reading the button state

        // read the state of the switch into a local variable:
        int reading = digitalRead(buttonPin);

        if (reading != lastButtonState) {
          lastDebounceTime = millis();
          if (reading == LOW) {                    // if (reading == LOW) ????
            buttonPushCounter++;
            Serial.println("on");
            Serial.print("number of button pushes:  ");
            Serial.println(buttonPushCounter);
            Timer = millis();
            lastButtonState = buttonState;

          } else {
          // if the current state is LOW then the button wend from on to off:
          Serial.println("off");
        }

          if ((millis() - lastDebounceTime) > debounceDelay) {
        if (reading != buttonState) {
          buttonState = reading;
          lastButtonState = reading;
        }

        if (Timer >= 2000UL) {
          if (buttonPushCounter == getal) {
            digitalWrite(ledPincorrect, HIGH);
            digitalWrite(ledPinfalse, LOW);
            digitalWrite(ledPin1, LOW);
          digitalWrite(ledPin2, LOW);
          digitalWrite(ledPin3, LOW);
          digitalWrite(ledPin4, LOW);
          randomNumber = 0;
          buttonPushCounter = 0;
          }
          else {
            digitalWrite(ledPinfalse, HIGH);
            digitalWrite(ledPincorrect, LOW);
            digitalWrite(ledPin1, LOW);
          digitalWrite(ledPin2, LOW);
          digitalWrite(ledPin3, LOW);
          digitalWrite(ledPin4, LOW);
          randomNumber = 0;
          buttonPushCounter = 0;
          }
    }

        }
    }

    }

body:
Let us start with the simplest issue in your code:

    Timer = millis();
    ...
    if (Timer >= 2000UL) {
    ...
    }

After 2000 ms this is always true (for about 49 days)?

Cheers!

Please format your code if you expect anybody to take the time to read it and help.


message:
Are there sensors that can detect the color of an LED?

I am working on an Arduino project that needs to detect the color of an LED on an external device. I am trying to identify a light sensor that can be connected to the Arduino's input that can tell me the color of light the LED is currently emitting. The LED is capable of displaying red, green and yellow.

body:
You can use an LED as a light sensor - http://www.instructables.com/id/LEDs-as-light-sensors/

In theory, LEDs should be most sensitive to the frequency it emits - if this is true, the same type of red/green/yellow LED would be best.

I don't know how sensitive this will be.

If you control the "external device", then you could get much better accuracy by blinking the LED at very high rates (not visible to the human eye). Or, if you can get at the legs of the LED, you can tap into the signal directly (you should use an opto-isolator - even if powered at a few volts, the ground of your project may be different from the ground of the external device, causing 100s of volts to run through your Arduino - not good!).


body:
There are a few different things you can do to detect a color.

The Arduino starter kit that I got when I first got into Arduino had some photoresistors plus some colored films. One of the projects in the project book had you put a different color film over each photoresistor, so that only that color of light would hit the sensor. You could do something like that if you only need to check for a small number of distinct colors.

There are also a wide array of color sensors and sensor modules available (just search your favorite online store for "color sensor" or "arduino color sensor"), which will allow for far more detailed and precise color readings, but at a higher price point.


body:
You mean like this one?

[Adafruit RGB Color Sensor][1]

They have similar products in different form factors.

  [1]: https://www.adafruit.com/products/1334?gclid=CM-al4jZ8MoCFQtFaQoddHEFxg


message:
Can an L293D motor driver shield do microstepping?

I bought a [L293D motor driver shield](http://www.ebay.com/itm/L293D-Motor-Drive-Shield-Expansion-Board-For-Arduino-Duemilanove-Mega-UNO-/221798329172) and have used it with a pre-made sketch for driving a pair of stepper motors, but I'm not familiar with its capabilities.

The [sketch](https://github.com/MarginallyClever/Makelangelo-firmware/releases/tag/1.0.2) I've used so far doesn't use microstepping when it's set up for this shield (though it does use it with the Adafruit shield).

I've done some searching, and it's not clear if the L293D chips on the shield can do microstepping, and if so, how.

Are L293D chips (and thus the motor driver shield that uses them) capable of microstepping? If so, how can I add this capability into my sketch?

body:
Not directly. The L293D is a digital H-bridge chip. L293 series devices allow you to supply enough power for small motors, and the "D" model has internal protection diodes. There are other ICs and breakout boards that are designed specifically for microstepping. Here are a few options...

- The [SparkFun EasyDriver](https://www.sparkfun.com/products/12779) ($14.95) will probably be the quickest solution.
- There are a variety of [stepper driver ICs](http://www.mouser.com/Semiconductors/Power-Management-ICs/Motor-Motion-Ignition-Controllers-Drivers/_/N-41dum?P=1z0vpfyZ1z0z63xZ1z0yyznZ1z0y0t6Z1z0y325Z1yzbn3rZ1z0z44dZ1z0y33tZ1z0y33vZ1z0y22tZ1z0y33rZ1yzua75) on the market with a wide range of power ratings. For instance, ST makes the [L6219](http://www.mouser.com/ProductDetail/STMicroelectronics/E-L6219/?qs=sGAEpiMZZMtKB4wrjsn3lSPJ0ZpNBlDPTInlIKiwZOA=) ($4.86) and ON also makes several versions of the [LB1847](http://www.mouser.com/Semiconductors/Power-Management-ICs/Motor-Motion-Ignition-Controllers-Drivers/_/N-41dum?P=1z0vpfyZ1z0z63xZ1yzr60o) ($4.19-$6.90). TI also makes a few.

Datasheets will typically say whether a driver is capable of microstepping at the beginning. Just make sure the driver you choose is capable of handling the stall current of your stepper.

Are your steppers unipolar (6+ wires) or bipolar (4 wires)? That may make a difference in how you wire them, although some unipolar motors can be driven as if they were bipolar.


body:
It would be more accurate to say that it can be used as part of a microstepping system, though it's probably not a good choice for *any use* today.

The L293D is merely an (effectively obsolete implementation of an) H-bridge, not a stepper motor *sequencer*, hence it is no more capable of autonomously driving a motor in full or half step mode than it is of microstepping - it can only do any of these when it is controlled by a sequencer, such as an L297 chip, or software running on an Arduino's processor.

Microstepping requires partially actuating the coils to interpolate between the angular positions which would be achieved by activating each in turn fully.  It can be thought of as a proportional extension of how half-stepping uses actuating both coils at the same power to achieve a halfway in between position, only now the coils are actuated at different power levels to achieve finer gradations of position, though achieving accurate interpolation requires care as the relationship is not linear.

Modern power electronics no longer use variable analog drivers, as these convert the unused power to heat.  Instead, the goal is to use switches which come as close as possible to only ever being fully on or fully off.  Reduced driver power is achieved by pulse width modulating the switch, varying the average amount of power delivered to the load over a short period of time.  In a stepper motor setting, this on-off modulation can be done to achieve microstepping and or also to achieve current regulation when a many-times-rated-voltage supply is used to allow overcoming winding inductance at high step rates.

The L293D (and its larger cousin the L298) are quite inefficient bipolar transistor bridges (they aren't very good switches compared to MOSFETs), and should probably not be chosen for new designs today.  They are, however, capable of being used to microstep a motor when actuated by a sequencer which pulse width modulates the phase signals.
Adafruit, who appear to be the original creators of this shield design, have in fact published microstepping driver code for their L293D board on github.

[https://github.com/adafruit/Adafruit-Motor-Shield-library][1]

Given that the ebay seller you link to as the source of the board is using Adafruit's own schematic on their product page, it's a bit unclear why your software is differentiating between this board vs an Adafruit one, unless by the the Adafruit board you mean their V2 shield.  The V2 design uses a more efficient TB6612FNG FET bridge, but of more relevance to microstepping offloads the sequencing task from Arduino software to a PCA9685 chip which is apparently capable of microstepping (as well as simpler modes) by itself.  Depending on the computational load and/or your  level of determination, you may be able to get the ATmega microstepping the L293D in the context of your overall project.

  [1]: https://github.com/adafruit/Adafruit-Motor-Shield-library


message:
Cannot disable interrupts

I am new to arduino.

Why does this not work the way it's supposed to?
<br>Shouldn't it block all interrupts for 3secs after it received one from digi pin 2?

How would I accomplish this:
Running a method whenever the value on this pin changes, execute it and then listen for more interrupts from that pin?

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
    }

    int i = 0;

    void loop(){}

    void test(){
      noInterrupts();
      Serial.println("Interrupt registered - waiting " + i);
      delay(3000);
      Serial.println("done waiting!" + i);
      i++;
      interrupts();
    }

body:
You could achieve that by this simple rewrite:

    void setup() {
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
    }

    volatile bool changed = false;
    int i = 0;

    void loop() {
      if (!changed) return;
      Serial.print(F("Interrupt registered - waiting "));
      Serial.println(i);
      delay(3000);
      Serial.print(F("done waiting "));
      Serial.println(i);
      i += 1;
      changed = false;
      clearInterrupt(digitalPinToInterrupt(2));
      attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
    }

    void test() {
      changed = true;
      detachInterrupt(digitalPinToInterrupt(2));
    }

The interrupt service routine (ISR), test(), is really short and does not call functions that actually need interrupts to work (e.g. delay(), Serial). Please see Nick Gammon's comment below on clearInterrupt(), i.e. EIFR = bit (INTF0);

An alternative rewrite is to use the BlinkWithDelay-pattern and a somewhat more complex state-machine:

    volatile bool changed = false;
    bool waiting = false;

    const unsigned long waitIntervalMillis = 3000UL;
    unsigned long waitStartMillis = 0L;

    int i = 0;

    void setup() {
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(2), test, CHANGE);
    }

    void loop() {

      // Check for change
      if (!changed) return;

      // Check for change before wait interval
      if (!waiting) {
        Serial.print(F("Interrupt registered - waiting "));
        Serial.println(i);
        waiting = true;
        waitStartMillis = millis();
      }

      // Check if wait interval has expired
      else {
        unsigned long currentMillis = millis();
        if ((currentMillis - waitStartMillis) >= waitIntervalMillis) {
          Serial.print(F("done waiting "));
          Serial.println(i);
          i += 1;
          changed = false;
          waiting = false;
        }
      }
    }

    void test() {
      changed = true;
    }

A third rewrite is possible. Assuming that the pin is connected to a push button, the interrupt handler can be replaced by simply reading the pin with a low frequency (for debouncing).

Cheers!


body:
Probably your biggest problem is that `delay()` cannot be used inside interrupt service routines (ISR's) and it doesn't work if interrupts are turned off because it uses interrupts to function.

ISR's should be as short as possible, because they stop normal operation of the device while they execute. A good ISR will set a few variables, and then return, while the main program loop checks the state of those variables and actually does stuff. [Mikael Patel's answer](https://arduino.stackexchange.com/a/20507/3720) shows how you can rewrite your sketch to do this.


message:
Calibrate motors using arduino

I'm trying to create a car that's being controlled by an Arduino.
I'm using the following chasis:
http://www.aliexpress.com/item-img/New-2WD-car-chassis-DC-gear-motor-wheels-easy-assembly-and-expansion-car-toys-robot-toys/32310649967.html

And L298N motor driver.

The problem is it's hard to make the car go straight. Giving the same PWM value to the motors still makes them spin in different speeds, trying to calibrate the value is hard and every time I recharge my batteries the value changes.

What are my options on making the car go straight when I want (well, sometimes I'll want to turn it around of course)?

I've thought about using an encoder but I wish to avoid that since it will complicate the whole project, is there any other viable option? and even when using an encoder, Does it means I will need to keep track all the time and always adjust the motors value continuously? is there some built-in library for that?

Thanks in advance!

body:
Modern tiny $20 toy quadcopters use a magnetometer to maintain a steady heading.    Duplicating that effect could be cheaper and more reliable than dual encoders.  On certain surfaces, like carpet, even perfect encoding with perfect voltage and wheels can't guarantee maintaining the heading.

One viable option might be to drive one wheel with your control system, drive the other wheel to maintain the magnetometer heading, and then steer by adjusting the target heading.


body:
I used a simple optical encoder and the little disks that came with my kit.  The encoders cost < £1 for 2 of them.

Failing that use an accelerometer and measure the lateral motion, should also cost about £1.


message:
Arduino error when compiling

When this code is uploaded I get an "Error Compiling". Any help is very much appreciated.

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

    #include <MeetAndroid.h>
    #define supplyVolts 6
    #define motorVolts 5
    #define baudRate 57600
    // If you are using a General Bluetooth adapter (available on buildcircuit.net), then, it works with 9600bps baud rate
    MeetAndroid phone;
    int left = 255; // midpoint
    int right = 255;
    int pwmLeftPin = 3;  1 int pwmRightPin = 11;
    int directionLeftPin = 12;
    int directionRightPin = 13;
    void setup() {
      pinMode(pwmLeftPin, OUTPUT);
      pinMode(pwmRightPin, OUTPUT);
      pinMode(directionLeftPin, OUTPUT);
      pinMode(directionRightPin, OUTPUT);
      setMotors();
      // use the baud rate your bluetooth module is configured to
      Serial.begin(baudRate);
      phone.registerFunction(setLeft, 'l');
      phone.registerFunction(setRight, 'r');
    }

    void loop() {
      phone.receive();
    }

    void setLeft(byte ignore, byte count) {
      int value = phone.getInt();
      left = value;
      setMotors();
    }

    void setRight(byte ignore, byte count) {
      int value = phone.getInt();
      right = value;
      setMotors();
    }

    void setMotors() {
      int vLeft = abs(left - 255) * motorVolts / supplyVolts;
      int vRight = abs(right - 255) * motorVolts / supplyVolts;
      int dLeft = (left > 255);
      int dRight = (right > 255);
      if (vLeft < 50) {
        vLeft = 0;
      }
      if (vRight < 50) {
        vRight = 0;
      }
      analogWrite(pwmLeftPin, vLeft);
      analogWrite(pwmRightPin, vRight);
      digitalWrite(directionLeftPin, dLeft);
      digitalWrite(directionRightPin, dRight);
    }

body:
Take a close look at this line. The compiler will not like that as it does not have the right syntax.

    int pwmLeftPin = 3;  1 int pwmRightPin = 11;

Change it to:

    int pwmLeftPin = 3;
    int pwmRightPin = 11;

This should at least remove the first issue with your code.

Cheers!


message:
Arduino Ping sensor with NewPing library

I was trying out the [NewPing library][1] (the main example sketch) and when I compile it and check the serial monitor, it seems like it works for about 10 seconds, then instead of giving distance values it just writes out random characters. The only thing I can think of is that my sensor is bad. Any suggestions before I get another Ping sensor? I'm unsure if the same thing will happen.

[![Screenshot of NewPing output on serial monitor showing 10 seconds of output and then random characters][2]][2]

  [1]: http://playground.arduino.cc/Code/NewPing
  [2]: https://i.stack.imgur.com/PEHid.png

body:
The main example sketch has this:

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

      Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.

Your serial monitor is set to 9600 baud (bottom RH corner). Change that to match the setting in the sketch.


message:
Serial.println for pointers to the byte datatype behaves unexpectedly

byte subkeys[16][48/8];

    for (size_t address = 0; address < 16*6; address++)
        Serial.println( (byte) *(subkeys + address) );

Why won't the compiler handle this? It tells me

> cast from 'byte* {aka unsigned char*}' to 'byte {aka unsigned char}' loses precision [-fpermissive]

If I omit the `(byte)` part, it tells me

> call of overloaded 'println(byte [6])' is ambiguous

I have no idea what's happening.

body:
A `byte` is to small to store a pointer value. Instead to casting to
byte, you should cast to `uintptr_t`, which is guaranteed to be large
enough. On an AVR-based device like the Uno, this is the same as
`uint16_t` or `unsigned int`, but `uintptr_t` is more general.

**Edit**: From your comment it would seem you want to print the contents
of the array instead of the addresses of the rows. The obvious way is to
loop with two indices:

<!-- language-all: lang-cpp -->

    for (size_t i = 0; i < 16; i++) for (size_t j = 0; j < 6; j++)
        Serial.println(subkeys[i][j]);

If you really want to use `subkeys` as a 1D array, then cast it to a
`byte *`, which is the type a 1D array would naturally decay to:

    for (size_t address = 0; address < 16*6; address++)
        Serial.println(((byte *) subkeys)[address]);


message:
Problem receiving CAN messages using arduino, MCP2515 CAN module and multiprotocol radio shield

I am using an arduino UNO and a Cooking Hacks CAN BUS module through a Cooking Hacks Multiprotocol radio shield. I plan to read the CAN messages through the car's OBD-II port. I have connected the components according to the tutorial and though there is no LED to indicate that the shield and CAN bus module are ON, I verified that they are indeed ON by using a multimeter. Also, when the reset button is pressed on either the shield or the CAN module, the arduino resets so I guess they are powered up. Coming to my problem, I uploaded the code and connected the setup to the OBD-II port and turned the ignition ON. I expected to see the CAN messages on the arduino serial monitor but I didn't see anything. I also took up this issue with the cooking hacks support team who told me that the libraries were updated and that I should use the updated ones. So I downloaded the revised libraries to use with my code but I am unable to upload the code itself to the arduino because of an error during compilation.

C:\Users\user\Documents\Arduino\libraries\arduinoCANBUS\arduinoCAN.cpp:26:49: fatal error: ../arduino-api/arduinoMultiprotocol.h: No such file or directory

The major difference as far as I can tell between the old and the new libraries is the addition of two lines in the arduinocan.cpp file :
# include "../arduino-api/arduinoMultiprotocol.h"
# include "../arduino-api/arduinoUtils.h"
Both of these are header files in another library that was included as part of the whole library that you can download from their website.

I realise I might have confused whoever's reading but please have a look at the arduino code. Hopefully, that should clear things up. Any help would be highly appreciated. Thanks.

Code:

        #include <arduinoCAN.h>
        #include <arduinoClasses.h>
        #include <arduinoMultiprotocol.h>
        #include <arduinoUART.h>
        #include <arduinoUtils.h>
        #include <Wire.h>
        #include <SPI.h>

        // Create an instance of the object
        CAN myCAN = CAN();

        // Setting up our devices and I/Os
        void setup() {
        // Using the Socket 0 onto which Can bus module is plugged in
        Utils.setONSocket0();
        Utils.setMUXSocket0();
        // Initializes the UART
        Serial.begin(115200);
        delay(100);

        myCAN.begin(500); // Start talking to the BUS. Speed= 500 Kbps
        }

        void loop() {
        // 1. Receive data

        if (myCAN.messageAvailable()) {
        // Read the last message received.
        myCAN.getMessage(&myCAN.messageRx);
        // Print in the serial monitor the received message
        myCAN.printMessage(&myCAN.messageRx);
         }
        }
EDIT: PROBLEM SOLVED!

Putting the header file's full path in the sketch did not solve it. The compiler still displayed the same error. I then made a backup copy of all the files containing the #include "arduinoMultiprotocol.h" statement and edited them to contain the full path. Initially, the error didn't change and I moved onto the next suggestions, all of which did not change the error. However, I went back to the edited files and replaced the backslash(\) with the slash(/). This time, the compiler did not throw the same error, instead saying it cannot find arduinoUtils.h.
So I proceeded to do the same thing with arduinoUtils.h, editing all the files containing it to mention the full path. And this time it worked and the sketch works as well. Thanks for your help!

body:
The compiler is saying it can't find the header files. The part of the path `../arduino-api/` is suspicious.

It may be because the header files are expected to be somewhere else, or their is a small error which has had a knock on effect.

1 - Find arduinoMultiprotocol.h
Put its full path into the include statement, e.g.

        #include "C:\Users\user\Documents\Arduino\libraries\arduinoCANBUS\wibble\arduinoMultiprotocol.h"

If that is still broken, but a new error is printed, copy the error. If the error doesn't change, then make a backup copy of every file you can find containing ` #include <arduinoMultiprotocol.h>` and edit it to contain the full path. It looks like starting with arduinocan.cpp is a good place to start.

2 - If that doesn't fix the error, create an empty sketch, including all those headers, e.g.

        #include <arduinoCAN.h>
        #include <arduinoClasses.h>
        #include <arduinoMultiprotocol.h>
        #include <arduinoUART.h>
        #include <arduinoUtils.h>
        #include <Wire.h>
        #include <SPI.h>

        void setup() { }

        void loop() { }

Compile and copy the error message.
Move the `#include <arduinoMultiprotocol.h>` a bit later in the sequence of #includes. If the error changes copy that for later, and record which sequence changed it.

3 - Change `#include <arduinoMultiprotocol.h>` in that empty sketch
to the full path (as in step 1). If that doesn't fix it, copy that error message.

If you still need help, please update your question with the results of those tests.


message:
text to 2D array on Arduino

I am trying to read a text file and send the info to 2D array, but after loading the array, it reads all zeroes. What can I do to stop the Arduino from doing this and get the array with my required data?

<!-- language: c -->

    /* This program was created by ScottC on 8/5/2012 to receive serial signals from a computer to turn on/off 1-9 LEDs */

    int** ptr;

    void setup() {
      // initialize the digital pins as an output.
      pinMode(13, OUTPUT);
      // Turn the Serial Protocol ON
      Serial.begin(9600);
    }

    void loop() {
      byte byteRead;

      if (Serial.available()) {

        /* read the most recent byte */
        byteRead = Serial.read();
        //You have to subtract '0' from the read Byte to convert from text to a number.
        byteRead = byteRead - '0';
        ptr = new int* [byteRead];

        int i,j;
        for ( i = 0; i < byteRead; i++) {
          ptr[i] = new int[3];
          for ( j = 0; j < 3; j++) {
            if (Serial.available()) {

                /* read the most recent byte */
                byteRead = Serial.read();
                //You have to subtract '0' from the read Byte to convert from text to a number.
                byteRead = byteRead - '0';
                ptr[i][j] = byteRead;
                Serial.print(ptr[i][j]);
            }
          }
        }
      }
    }

body:
There are several issues with your code but instead of correcting I recommend that you start by checking that your assumptions about the format is correct. Send your data to this "reduced" variant of your sketch. Does it work? Did you receive what you expected?

    void setup() {
      // initialize the digital pins as an output.
      pinMode(13, OUTPUT);
      // Turn the Serial Protocol ON
      Serial.begin(9600);
    }

    void loop() {
      byte byteRead;

      if (Serial.available()) {

        /* read the most recent byte */
        byteRead = Serial.read();
        //You have to subtract '0' from the read Byte to convert from text to a number.
        byteRead = byteRead - '0';
        Serial.print(F("byteRead = "));
        Serial.println(byteRead);

        int i,j;
        for ( i = 0; i < byteRead; i++) {
          for ( j = 0; j < 3; j++) {
            if (Serial.available()) {

                /* read the most recent byte */
                byteRead = Serial.read();
                //You have to subtract '0' from the read Byte to convert from text to a number.
                byteRead = byteRead - '0';
                Serial.print(i);
                Serial.print(':');
                Serial.print(j);
                Serial.print(F(":byteRead = "));
                Serial.println(byteRead);
            }
          }
        }
      }
    }

Did you see the issue with:

        for ( i = 0; i < byteRead; i++) {
        ...
        }

Cheers!


message:
Is it possible to control a 12v led matrix with an arduino?

This is a bit home automation but if I want to control my 12v LEDs and I have 8 free pins would it be possible to drive 16 lights as a matrix. I was looking into running 8 LEDs with an 8 channel relay but the I got to thinking if I wire up 16 LEDs in a matrix I could still control them all with those 8 channels. Problem is I was looking at mechanical relays that would burn out very quickly with that kind of switching. Are there any other solutions?

body:
You can use [ULN2803][1] driver IC on sink side (cathode), P channel MOSFET on anode/source side of common anode LED matrix. Since you need only 4 sinks you can pair every 2 i/o of ULN2803 so you can drive/sink 1A max load per row. This IC is cheap and widely available.

MOSFET current and speed should match those of ULN2803. You can use BJT instead of MOSFET, but voltage drop on BJT will be higher.

Similar design is here: [8x8 LED matrix][2]

  [1]: http://www.ti.com/lit/ds/symlink/uln2803a.pdf
  [2]: http://www.avrfreaks.net/sites/default/files/Matrix_display2.png


body:
I think the best solution would be to use WS2812 LEDS. I already implemented this many times also for my home illumination.
WS2812 is a RGB LED with an integrated chip (1m strip with 60 LED will cost about 10$).
One advantage is that you need only 1 output from your Arduino and the library works very well.
Another one is that you don't need power! 5mA is enough to drive 1000 LEDS! So you don't need MOSFETS and you don't need any Relais.


message:
Why is my SRAM so quickly filled? There are not more than 60 bytes

I have just gone through all my code. At max I use 60 bytes. I have done everything in order to minimize its usage - I even store booleans as bits, not bytes! What could be happening here?

The only thing that comes to my mind are extremely large arrays, like this:

    const uint8_t SBoxes[8][4][16] PROGMEM;

However, these are stored in the program memory as you can see. How can I check they are really there and my memory usage? My code is too large to post it here.

EDIT:

IDE tells me (even though I believe it's very inaccurate):

> Sketch uses 7,898 bytes (24%) of program storage space. Maximum is 32,256 bytes.
Global variables use 1,023 bytes (49%) of dynamic memory, leaving 1,025 bytes for local variables. Maximum is 2,048 bytes.

All my literal strings use F() and there are not many of them.

EDIT2:

[Code on pastebin.][1] Just for a quick glance, it is really large.

  [1]: http://pastebin.com/0ZduU2JJ

EDIT3:

My `Serial` prints

    ready
    some numbers (that's ok I ask it to print out an array)
    ENready
    again numburs
    Enready
    ...

I ask it to print `ready` at the very beginning of my program. I ask it to println `End of encr` near the end of my `setup` funciton, but as you see it never finishes the printing.

It always behaves like that when I run out of SRAM.

body:
When you are asking yourself what is eating so much RAM, the first step
is to look at the symbol table in the ELF file. If you use a makefile, you
probably know where to find the ELF file. If you are using the Arduino
IDE, go to File / Preferences, check “Show verbose output during
compilation”, compile and look at the output: you will see the temporary
directory where the compiler puts your ELF file.

Now run the command `avr-nm -Crtd --size-sort your_elf_file` and look
for symbols of type 'D' (data), 'V' (vtable) and 'B' (BSS), in either
upper or lower case. On a Unix-style OS you would pipe through
`grep -i ' [dbv] '`. Running this on your program gives:

    00000068 B tx_buffer
    00000068 B rx_buffer
    00000034 B Serial
    00000021 B lcd
    00000016 V vtable for HardwareSerial
    00000008 V vtable for LiquidCrystal
    00000004 B timer0_overflow_count
    00000004 B timer0_millis
    00000002 D __malloc_margin
    00000002 D __malloc_heap_start
    00000002 D __malloc_heap_end
    00000002 B __flp
    00000002 B __brkval
    00000001 b timer0_fract
    00000001 D encr
    00000001 B debug
    00000001 B EEPROM

Obviously, this cannot account for the 1,023 bytes of static RAM your
program is using. What this command misses is the literal arrays and
strings. These can be seen with the command
`avr-objdump -j .data -s your_elf_file`. The literal strings are quite
obvious in the output, the literal arrays less so. Running this on your
program gives a long listing starting with

    Contents of section .data:
    800100 00000005 2000010e 040d0102 0f0b0803  .... ...........
    800110 0a060c05 09000700 0f07040e 020d010a  ................

Now, on the source code we see:

<!-- language: lang-cpp -->

    const uint8_t SBoxes[8][4][16] PROGMEM = {
    {{14,  4,  13,  1,   2, 15,  11,  8,   3, 10,   6, 12,   5,  9,   0,  7},
     { 0, 15,   7,  4,  14,  2,  13,  1,  10,  6,  12, 11,   9,  5,   3,  8},
     { 4,  1,  14,  8,  13,  6,   2, 11,  15, 12,   9,  7,   3, 10,   5,  0},
     {15, 12,   8,  2,   4,  9,   1,  7,   5, 11,   3, 14,  10,  0,   6, 13} },
     ...

If you translate this to hexadecimal, you get `0e 04 0d 01 02 0f...`,
which appears also by the end of the first line of previous listing. So
there is your culprit: all the big PROGMEM arrays. The compiler does not
honor the PROGMEM attribute on local variables.

My first thought was to make the arrays global, and this does solve the
problem. However, as pointed out by Mikael Patel in a comment, the
documentation on PROGMEM states that “variables must be either globally
defined, OR defined with the static keyword, in order to work with
PROGMEM.” Then, making the arrays `static const PROGMEM` is a cleaner
solution.