body:
I'm using the Adafruit Motor Shield v2.3. I'm powering the Arduino with a USB cable and I'm powering the motor shield with a 9 volt battery.

I removed the vin pin, and I'm using [this](https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/install-software) tutorial/code to make the DC motor spin.

I've tried 3 different kinds of DC motors, but none of them will do anything. The Arduino works for normal sketches, like lighting up LEDs, but I can't get the motors to work.

Any ideas?

Edit: I'm using Adafruit's "Motor Test" code from the Motor Shield v2 library, as shown below. The motor is on port 1.

    // Adafruit Motor shield library
    // copyright Adafruit Industries LLC, 2009
    // this code is public domain, enjoy!

    #include <AFMotor.h>

    AF_DCMotor motor(4);

    void setup() {
      Serial.begin(9600);           // set up Serial library at 9600 bps
      Serial.println("Motor test!");

      // turn on motor
      motor.setSpeed(200);

      motor.run(RELEASE);
    }

    void loop() {
      uint8_t i;

      Serial.print("tick");

      motor.run(FORWARD);
      for (i=0; i<255; i++) {
        motor.setSpeed(i);
        delay(10);
     }

      for (i=255; i!=0; i--) {
        motor.setSpeed(i);
        delay(10);
     }

      Serial.print("tock");

      motor.run(BACKWARD);
      for (i=0; i<255; i++) {
        motor.setSpeed(i);
        delay(10);
     }

      for (i=255; i!=0; i--) {
        motor.setSpeed(i);
        delay(10);
     }

      Serial.print("tech");
      motor.run(RELEASE);
      delay(1000);
    }

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

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

title: Why is my Adafruit motor shield not spinning my motors?

Answers: 3

body:
Per the comments above, and the [documentation from Adafruit][1], a 9V battery is insufficient for use with motors as they do not provide enough current.

  [1]: https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/faq#faq-14

body:
A couple of things I see...

**1.)** Your motor leads may be shorting out of the housing of the motor. make sure they are not.

**2.)** You may have the motor on the wrong port for the given code:

On line 7 of the code it reads: `AF_DCMotor motor(4);`

So try switching physically your motor to port 4.

**3.)** Also, this board has an I2C address and I dont see that addressed anywhere in the code. You can check to see what the I2C address is with this code. It will also show you that the motor control board is indeed responding.

    // --------------------------------------
    // i2c_scanner
    //
    // Version 1
    //    This program (or code that looks like it)
    //    can be found in many places.
    //    For example on the Arduino.cc forum.
    //    The original author is not know.
    // Version 2, Juni 2012, Using Arduino 1.0.1
    //     Adapted to be as simple as possible by Arduino.cc user Krodal
    // Version 3, Feb 26  2013
    //    V3 by louarnold
    // Version 4, March 3, 2013, Using Arduino 1.0.3
    //    by Arduino.cc user Krodal.
    //    Changes by louarnold removed.
    //    Scanning addresses changed from 0...127 to 1...119,
    //    according to the i2c scanner by Nick Gammon
    //    http://www.gammon.com.au/forum/?id=10896
    // Version 5, March 28, 2013
    //    As version 4, but address scans now to 127.
    //    A sensor seems to use address 120.
    // Version 6, November 27, 2015.
    //    Added waiting for the Leonardo serial communication.
    //
    //
    // This sketch tests the standard 7-bit addresses
    // Devices with higher bit address might not be seen properly.
    //

    #include <Wire.h>

    void setup()
    {
      Wire.begin();

      Serial.begin(9600);
      while (!Serial);             // Leonardo: wait for serial monitor
      Serial.println("\nI2C Scanner");
    }

    void loop()
    {
      byte error, address;
      int nDevices;

      Serial.println("Scanning...");

      nDevices = 0;
      for(address = 1; address < 127; address++ )
      {
        // The i2c_scanner uses the return value of
        // the Write.endTransmisstion to see if
        // a device did acknowledge to the address.
        Wire.beginTransmission(address);
        error = Wire.endTransmission();

        if (error == 0)
        {
          Serial.print("I2C device found at address 0x");
          if (address<16)
            Serial.print("0");
          Serial.print(address,HEX);
          Serial.println("  !");

          nDevices++;
        }
        else if (error==4)
        {
          Serial.print("Unknow error at address 0x");
          if (address<16)
            Serial.print("0");
          Serial.println(address,HEX);
        }
      }
      if (nDevices == 0)
        Serial.println("No I2C devices found\n");
      else
        Serial.println("done\n");

      delay(5000);           // wait 5 seconds for next scan
    }

body:
I see that this is still not working even with a proper battery. My next best guess is you need to update your library:

>     // Adafruit Motor shield library
>     // copyright Adafruit Industries LLC, 2009
>     // this code is public domain, enjoy!
>
    #include <AFMotor.h>

Judging by `2009` and `AFMotor.h` you have a copy of an old version of the library. I recommend getting the [latest version][2] and following the [official tutorial][3].

  [1]: https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/faq#faq-14
  [2]: https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library
  [3]: https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/using-dc-motors


body:
I'm using mthreads (https://github.com/jlamothe/mthread) for my arduino. But now as the project is getting bigger, it would make sense to break it up in several files.

I successfully outsourced already a part which is not threaded. But somehow I cannot make up my mind how to use mthread in conjunction with several header files.

here is what I got:

main: call header:

    #include "tcan.h"

tcan.h:

    #ifndef tcan_h
    #define tcan_h

    #include "Arduino.h"

    class tcan : public Thread {
      public: tcan();
      protected: bool loop();
      private:
    };
    #endif

tcan.cpp

    #include "Arduino.h"
    #include "tcan.h"
    #include <mcp_can.h>

    bool tcan::loop() {
      // lala
      return true;
    }

but I get an error when compiling:

> tcan.h:6:28: error: expected class-name before '{' token  class tcan :
> public Thread {

Thanks in advance

title: mthread and multiple header files

Answers: 1

body:
The compiler error is due to that the compiler does not know what Thread is.
> tcan.h:6:28: error: expected class-name before '{' token class tcan : public Thread {

The issue is that the header file is not complete. **A good practice is to include all header files that are needed to read the header file.** As *Thread* is defined in *mthread.h* the *tcan.h* file should be:

    #ifndef tcan_h
    #define tcan_h

    #include <mthread.h>

    class tcan : public Thread {
    public: tcan();
    protected: bool loop();
    private:
    };
    #endif

Cheers!


body: I purchased the arduino pro mini atmega328 and equipped it with FTDI breakout board with USB, a battery charging board, Wireless transmitter and a wireless receiver.  I'm assuming they can all be connected.  My question is, how do I download programs to the arduino board?  And where might I find specific programs to download?

title: arduino pro mini downloading?

Answers: 1

body:
The Arduino Pro Mini has a row of connections at the small end that align with the connections on the USB-to-Serial board you have.  They are marked GND - VCC - RXI - TXI and should be in the same order as the connector on the FTDI board. I think that the pin marked GRN on the Arduino will align with the connector marked DTR on the USB-to-Serial board, but please make sure that VCC aligns with 5V!

With the FTDI board plugged into the Arduino, you can plug your computer into the FTDI board's USB port and when you run the Arduino IDE programming tool, that USB port should say that it's connected to a serial port.  Pick the "Arduino Pro or Pro Mini" as your board, then pick your processor (most likely the "ATmega328 (5V, 16MHz)" and finally your port (that serial port you found).

Now when you upload your Arduino program to the Arduino, it will know the board your have and the port to use.

As for programs to use, start simple and get the onboard LED to blink.  From there, you'll have the basics down for creating a program and getting it to the Arduino.  You'll find tons of example programs (called sketches in Arduino land) that will help you connect all your fun wireless gizmos!

As noted above - Google is your friend.  There are many places to go for examples and help.  Start with some of the commercial sites like Adafruit and SparkFun. Their staff really supports the Arduino community with how-to videos, libraries, examples, etc.


body:
I am Android application developer and I want to modify regular toy RC car which can be controlled by Android phone. I want to use 2 Android phones: 1 as remote controller, 1 as controller in RC car. I want to use sensors like GPS, Mobile network, Wifi in RC car in RC car side. I want to know: can I use Android phone as controller in RC car. I am thinking about 2 options:

 1. phone as controller (without arduino) - this option would be the
    best
 2. if phone cannot give commands maybe with arduino, while
    using phone's sensors like gps, mobile network, wifi, bluetooth

Is this possible? If yes, what tools I should use to connect?

title: Can Android phone can be used instead of( or with) Arduino as controller?

Answers: 1

body:
You cannot directly control your RC car using and Android phone if you are talking about a normal RC car. If you have an RC car that can be already connected via bluetooth this is another story.

So for normal RC car you would need to have:

AndroidPhone -> Network -> AndroidPhone -> SerialInterface -> Arduino -> RC


body:
I have an air conditioner switch rated at 32A/240V AC - how do I turn this on using Arduino and Relay.

I'm based in India and I am unable to find a relay switch rated higher than [this][1].

I don't want to try anything that results in a fire hazard. My aim is to switch on the AC with my mobile phone. I'm using Arduino Uno with a 2.4GHz transceiver for communication.

  [1]: http://www.amazon.in/Channel-Module-Shield-Arduino-Electronic/dp/B00C59NOHK/ref=pd_sim_sbs_147_6?ie=UTF8&dpID=51amkYDfw4L&dpSrc=sims&preST=_AC_UL160_SR160,160_&refRID=1DYV10685X37A49WG5NV

title: How to switch on 32A/240VAC with Arduino?

Answers: 4

body:
The simple answer is: you need to find a relay rated high enough for the voltage and current. There's no way you can make a small relay handle a large current, and relays cannot be joined together to share the load.

If a relay is not available in your country (and I seriously doubt that - you're probably just looking in the wrong places - instead of looking for things on Amazon or eBay try looking at proper industrial electronics suppliers) then you would have to come up with something more creative.

How about designing and building a small electro-mechanical system that physically changes the position of the existing switch for you? Solenoids to press the right bits of the switch, or motors to turn the right bit round, etc.

body:
> I don't want to try anything that results in a fire hazard.

That's a good idea.

Besides those toy relays there are real ones:
[440 V AC * 63 A][1] (Around there, you can find smaller ones too)

BTW: Don't rely on what's printed on the relay itself, with cheap Arduino relay modules. 230V and some current need proper handling by the PCB board as well (size and distance of the copper tracks on the scondary side)

If you want a solution that could be certified (or certifiable) as "safe" there probably won't be an Arduino involved or being built by anyone asking questions like you do  ;(   (sorry)

  [1]: http://uk.rs-online.com/web/p/non-latching-relays/8002896/

body: What about staying with small relay and just add a contactor? The relay will deal with the low current 230v to drive the contactor and the contactor would deal with the high current.

body:
Just go with a solid state relay: you can search on ebay for SSR-40DA (240V, 40A, from China around 4$) or, better, SSR-100DA (240V, 100A, from China around 6$). For 32A you should definitely mount it on an heatsink (they sell quite a lot of them on ebay).

The main advantage of that kind of SSR is that you can command them directly from the arduino. No transistors, no limiting resistors, just connect the ground and the pin and you are done.

With a relay my arduino halted often (probably because of the 5V-12V boost, but it was necessary to drive the 12V relay). In the end I switched to an SSR and... Works like a charm. And since it is quite cheap I suggest you to use it.


body:
Is it possible to emulate an RFID tag with the [RC522](http://playground.arduino.cc/Learning/MFRC522)? (Spec sheet: [nxp MFRC522.pdf](http://www.nxp.com/documents/data_sheet/MFRC522.pdf))
I want the RC522 to act like a NTAG213 nxp.com/documents/data_sheet/NTAG213_215_216.pdf and to be read/write by other readers/writers.
Are there libraries for that purpose?

title: How to emulate an RFID tag with the RC522

Answers: 1

body:
No. Looking at the datasheet, card emulation is not a feature provided by the RC522.

Another popular chip, the [PN532][1], does seem to indicate support for that feature, however, looking at the most popular [library for this chip][2] from Adafruit, it does not implement this feature. Another [library][3] from Seeed, does seem to implement it, but it looks rather limited as to which cards can be emulated, and the library itself hasn't been updated in a while.

  [1]: https://www.adafruit.com/datasheets/pn532ds.pdf
  [2]: https://github.com/adafruit/Adafruit-PN532
  [3]: https://github.com/Seeed-Studio/PN532


body:
So I recently bought an Arduino along with an LCD module and two extra ATmega328P-PU ICs. Yesterday it was working just fine then I disconnected everything and reconnected it and this happened.

What could possibly go wrong?

Setup:

[![Photo of Arduino and 16 x 2 LCD display][2]][2]

with microcontroller that came with the board:

[1]: https://i.stack.imgur.com/x3e7P.jpg
[2]: https://i.stack.imgur.com/mhd5m.jpg

title: Bad LCD? Bad microcontroller? Or what?

Answers: 2

body:
> So i recently bought an arduino along with lcd module and 2 extra atmega328p-pu ,yesterday it was working just fine then i disconnect everything and reconnect it and this happen, what could possibly go wrong ?

I hope you understand how difficult it is for anyone to help with this type of question.

My quick answer is "follow the schematics and reconnect the wires correctly" and "double check all wires".

From the picture it looks like you need to adjust the LCD contrast and reduce the back-light. Please see typical schematics for this.

Another rule-of-thumb is to use wire colors in a meaningful way. For instance, black for GND, red for VCC, yellow for data, blue for control, green for clock, etc.

Cheers!

body:
These 16x2 LCDs are fairly sensitive about their power requirements.

As a first step, I would check the VCC and GND wires are well connected, and closely connected on the breadboard near the LCD.

If your LCD display shows rubbish characters, check the 4 data lines are connected in the correct order.

Also it looks like the contrast is at minimum (or LED backlight at maximum).  It could just be the photo, but best check both of these.


body:
I have a question with the topic *variables*.

So, a variable is a place where you can store data.

And when you make a variable with datatype int (`int ledpin=13;`) then you store a value 10 in a variable named `ledpin`.

BUT how can the Arduino know it's a pin number 13 from Arduino or a random number 13 that we are storing there?

title: How can Arduino know that the number in a variable is a pin number and not something else?

Answers: 3

body:
Yes, a variable is just somewhere to store some data.

It's what you *do* with the variable that is important.

For instance:

    int ledpin = 13;
    pinMode(ledpin, OUTPUT);
    digitalWrite(ledpin, HIGH);

That will set the variable `ledpin` to 13, then the next line will query the `ledpin` variable to find out what number it is, then pass that number to the `pinMode` function to set the mode of the pin to `OUTPUT`. The line after then does the same thing but passes the number 13 that it read from `ledpin` to the `digitalWrite` function to turn the LED on.

However, if you do this:

    int ledpin = 13;
    pinMode(ledpin, OUTPUT);
    ledpin = 10
    digitalWrite(ledpin, HIGH);

then it will act just the same at first, but the `digitalWrite` function will get the number 10 not the number 13 since the value in `ledpin` has been changed to 10 in the third line.

Remember: an integer is just a number - it's only when you do something with that number that it has any meaning.

body:
You need to put the correct number into the pinMode() function.

You could put the number into a variable like:

    int ledPin = 13;
    pinMode(ledPin, OUTPUT);

or you can put a number straight into pinMode() like this:

    pinMode(13, OUTPUT);

Whatever number you put in will be the pin that you start using.

Here's an example to blink the onboard LED:

    int ledPin = 13;                 // LED connected to digital pin 13

    void setup()
    {
      pinMode(ledPin, OUTPUT);      // Whatever number is in ledPin is made an output.
    }

    void loop()
    {
      digitalWrite(ledPin, HIGH);   // sets the LED on
      delay(1000);                  // waits for a second
      digitalWrite(ledPin, LOW);    // sets the LED off
      delay(1000);                  // waits for a second
    }

body:
> BUT how can the Arduino know it's a pin number 13 from Arduino or a random number 13 that we are storing there?

The Arduino does not "know" the intention of a variable. The variable "becomes" a pin number when passed as an argument to pinMode() or digitalRead().

The use of a variable to "name" a pin is part of a programming style. There are a lot of examples sketches that try to convey programming style. One of these is to reduce the amount of ripple effects of change; reduce the number of line to change for a logical change.

Continuing the LED pin number example above. The "baseline" code is:

    void setup()
    {
      pinMode(13, OUTPUT);
      ...
    }
    void loop()
    {
       digitalWrite(13, HIGH);
       ...
       digitalWrite(13, LOW);
       ...
     }

This works just fine BUT what is the ripple effect if we change the pin "13". The example uses symbols OUTPUT, HIGH and LOW which are also just numbers.

Typically in C the tradition is to use the preprocessor and define a macro.

     #define LED 13

The preprocessor will replace LED in the source code with 13 and the compiler sees the same code as above.

An alternative is using a variable.

     int LED = 13;

The drawback is that memory is allocated and it is possible to change the value at run-time which is often a very bad idea especially for a pin. The definition should actually be:

     const int LED = 13;

The drawback with the macro is that it is just a value. In C++ it is best to use a constant variable. This tells the compiler both what data type and value it is. A constant variable cannot be assigned (again).

The next level to strength code quality and reduce ripple effects is to use lexical scope. A lexical scope such as a function body, class or namespace defines "when" a symbol is available.

An example; first global scope where definitions are available across the source code (just as for a macro):

    const size_t BUF_MAX = 32;
    static char buf[BUF_MAX];

    const char* read()
    {
       ...
       for (int i = 0; i < BUF_MAX; i++) buf[i] = ...
       ...
    }

Local lexical scope; definitions within a function:

    const char* read()
    {
       const size_t BUF_MAX = 32;
       static char buf[BUF_MAX];
       ...
       for (int i = 0; i < BUF_MAX; i++) m_buf[i] = ...
    }

The symbols buffer *buf* and the buffer size *BUF_MAX* are only available in the function.

    class Reader {
    public:
      void read()
      {
        ...
        for (int i = 0; i < BUF_MAX; i++) m_buf[i] = ...
      }
    protected:
      const size_t BUF_MAX = 32;
      char m_buf[BUF_MAX];
      ...
    };

Again the symbols are only available within the class and member function. Here is also another example of programming style. The prefix *m_* is used to show that it is member data.

Last, the same example using a namespace:

    namespace Reader {
      const size_t BUF_MAX = 32;
      char buf[BUF_MAX];
      ...
      void read()
      {
        ...
        for (int i = 0; i < BUF_MAX; i++) buf[i] = ...
      }
    };
    ...
    for (int i = 0; i < Reader::BUF_MAX; i++) Reader::buf[i] = ...;

All symbols must have the prefix Reader when used outside the namespace.

These techniques have been developed to allow writing larger programs with reuse. It is important to use them when writing a library for Arduino and especially when sharing. Ripple effects and symbol redefinition/collisions are reduced.


body:
I am building a little car project, and I have come across an issue that has made me go mental.
I have a single motor (3V-5V), that on direct 3.3V & 5V output works fine. However, when I connect this to a digital port, it for some reason doesn't power. Of course, I first thought it was not supplying correct power, so I got myself a voltage meter and tried that. 3.3V outputs, well 3.3V, all fine. The digital port outputs 4-5V (when it is coded to). So here is my question: Why aren't my motors powering/turning?

title: Powering Motor doesnt work from Digital Pin, but works on 5V power

Answers: 1

body:
Power is made up of two values, not one. Besides the voltage there is the current (P=VI), and it's the current you are lacking.

A motor needs a large amount of current to start turning (called the *stall current*) and a digital I/O pin can only supply a relatively small amount (absolute maximum 40mA, recommended maximum 25mA). The power pins though can supply many hundreds of mA.

You should never try and power a motor directly from an I/O pin since you risk damaging the I/O pin.  Instead you should use the I/O pin to control an NPN transistor or N-channel FET, which is then used to switch the power (actually the ground connection) to the motor from one of the power pins.

Here is a good tutorial: http://www.circuitstoday.com/pwm-generation-and-control-using-arduino


body:
vI have this functions in my loop() and it publishes temperature reading to Ubidots(an IoT cloud service) using the #include <Ubidots.h> library but it seems it returns a boolean and so the loop is delayed until a true or false value is return and this takes a while there by slowing  down my loop() function and other functions in it.
Is there a way I can call this function without it having to slow the loop?

    #include <math.h>
    #include <Wire.h>
    #include <Servo.h>
    #include <WiFi.h>
    #include <Ubidots.h>
    #include "rgb_lcd.h"
    #include "Timer.h"
    //#include <SoftwareSerial.h>

    //SoftwareSerial mySerial(11, 10); // RX, TX

    char ssid[] = "ROSTALECOM_6916";                                                 //your network SSID (name)
    char pass[] = "6PTDFYJD";                                                         //your network password (use for WPA, or use as key for WEP)
    String api = "875c4a17d995ce4977bdfc1ace55233fd0591c7ce";                             //your API Key number
    String idvari = "567d623a762542205cbc517f";                                          //the number of the Ubidots variable
    String ctext = "{\"color\":\"blue\",\"status\":\"active\"}";
    Ubidots ubiclient(api);                                                             //with that you call the api with the prefix ubiclient

    byte p5[8] = {
      0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F
      };

    int a;
    int temperature;
    int B=3975;                  //B value of the thermistor
    float resistance;

    String readString;
    int val;
    int hum = 70.35;
    unsigned char base = 10;

    //Temperature Limits
    int maxTemp = 29;
    int minTemp = 28.5;

    //Declarations
    rgb_lcd lcd;
    Servo winServo;

    //Ubidots timer
    Timer t;

    void setup()
    {
        //Loading character
        lcd.createChar(0, p5);

    Serial1.begin(9600);
    Serial.begin(9600);
    winServo.attach(3);
    lcd.begin(16, 2);
    //mySerial.begin(9600);

    //Start Screen
    lcd.print("--SmartGarden--");
    for (int i = 0; i < 16; i++)
    {
            // scroll one position left:
            lcd.setCursor(i, 1);
            lcd.write((uint8_t)0);
            delay(400);
     }
    lcd.clear();
    lcd.print("Connecting...");
    //connect to  wifi network
    boolean response;
    int status = WL_IDLE_STATUS;
    response = ubiclient.WifiCon(ssid, pass, status, api);
    Serial.println(response);

    //
    t.every(1000, sendToUbi);

    }

    void readTemp()
    {
       a=analogRead(0);
       resistance=(float)(1023-a)*10000/a;
       temperature=1/(log(resistance/10000)/B+1/298.15)-273.15;

       //Send temperature via Bluetooth
       Serial.print(temperature);

       //print temperature to LCD
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("Tmp:");
       lcd.print(temperature);
       //print humidity to LCD
       lcd.setCursor(8,0);
       lcd.print("Hm:");
       lcd.print("50");

       delay(1000);

    }
    void writeServo()
     {
      if (val != 0)
      {
      //val = map(val, 0, 1023, 0, 180);
      winServo.write(val);
      delay(100);
      }
     }

     void sendToUbi()
     {
     ubiclient.save_value(idvari, String(temperature));                                                  //this function is to post to ubidots and return True or False depending on the connection status
     Serial.println("The sensor value " + String(temperature) + " was sent to Ubidots");                //print the sensor value
     }

    void timerMax()
    {
      for (int i = 0; i < 60; i++)
      {

       }
       winServo.write(180);
     }

    void loop()
    {
      //read temperature
      readTemp();

      //Update ubidots timer
       t.update();

      while (Serial1.available()) {
        delay(3);
        char c = Serial1.read();
        readString += c;
      }
      if (readString.length() >0)
        {
          Serial.println(readString);
          delay(15);

           val = readString.toInt();
           if (val != 0)
           {
           //val = map(val, 0, 1023, 0, 180);
            winServo.write(val);
           delay(100);
           readString = "";
           }
           //writeServo();

        if (readString == "1")
           {
            digitalWrite(13, HIGH);
           }
         if (readString == "0")
           {
            digitalWrite(13, LOW);
           }
         readString = "";
      }

      if (temperature >= maxTemp)
      {
        timerMax();

      }

    }

title: How to avoid delays in the loop() function?

Answers: 2

body:
> How to avoid delays in the loop() function?

The question is why all the delays? Is there some logic missing? What are you trying to design?

Using delays is often a sign of an attempt to synchronize with external events. Wait for additional input, etc.

Let us walk through some of them:

    void readTemp()
    {
       ...
      delay(1000);
    }

What is this about? The function does read an analog input BUT then there is a lot of output to Serial and LCD and last this delay. Why?

    void writeServo()
    {
      ...
     delay(100);
    }

Again the same pattern. Now for your question "delays in the loop()".

    void loop()
    {
       readTemp(); // hidden 1000 ms delay

      while (Serial1.available()) {
        delay(3);
        ...
      }
      if (readString.length() >0)
      {
         ...
         delay(15);
         ...
         if (val != 0)
         {
           winServo.write(val);  // Possible hidden 100 ms delay
           delay(100);
           ...
         }
         ...
    }

Consider using some logic instead of the delays. There seem to be a common pattern you are using.

body:
As short reply and a general note, there is the [millis() function][1] that will be faster than a `delay()`. It returns the number of milliseconds since the Arduino board began running the current program. You use maths to check if you've waited long enough.

Like [this][2]:

      // check to see if it's time to do something; that is, if the
      // difference between the current time and last time you blinked
      // the LED is bigger than the interval at which you want to
      // blink the LED.
      unsigned long currentMillis = millis();

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

        // do something after the waiting interval here

       }

Edit: One should also be aware of [Interrupts][3], but be warned they must be used correctly.

  [1]: https://www.arduino.cc/en/Reference/Millis
  [2]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
  [3]: http://playground.arduino.cc/Code/Interrupts


body:
<!-- language: c -->

       /*
     * --------------------------------------------------------------------------------------------------------------------
     * Example sketch/program showing how to read data from a PICC to serial.
     * --------------------------------------------------------------------------------------------------------------------
     * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
     *
     * Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
     * Reader on the Arduino SPI interface.
     *
     * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
     * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
     * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
     * will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
     * when removing the PICC from reading distance too early.
     *
     * If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
     * So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
     * details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
     * keep the PICCs at reading distance until complete.
     *
     * @license Released into the public domain.
     *
     * Typical pin layout used:
     * -----------------------------------------------------------------------------------------
     *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
     *             Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
     * Signal      Pin          Pin           Pin       Pin        Pin              Pin
     * -----------------------------------------------------------------------------------------
     * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
     * SPI SS      SDA(SS)      10            53        D10        10               10
     * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
     * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
     * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
     */

    #include <SPI.h>
    #include <MFRC522.h>

    #define RST_PIN         9          // Configurable, see typical pin layout above
    #define SS_PIN          10       // Configurable, see typical pin layout above

    MFRC522 MFRC522(SS_PIN, RST_PIN);  // Create MFRC522 instance

    void setup() {
     Serial.begin(9600);  // Initialize serial communications with the PC
     while (!Serial);  // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
     SPI.begin();   // Init SPI bus
     MFRC522.PCD_Init();  // Init MFRC522
     MFRC522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
     Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
      Serial.print("...");
    }

    void loop() {
     // Look for new cards
     if ( ! MFRC522.PICC_IsNewCardPresent()) {
        Serial.print("IsNewCardPresent");
      return;
     }

     // Select one of the cards
     if ( ! MFRC522.PICC_ReadCardSerial()) {
        Serial.print("ReadCardSerial");
      return;
     }

     // Dump debug info about the card; PICC_HaltA() is automatically called
     MFRC522.PICC_DumpToSerial(&(MFRC522.uid));
    }

I have recently purchased a RC522 RFID Module for my Arduino UNO. I connected everything, and started the IDE, downloaded the correct library, and ran the DumpInfo example program. The first time that I ran it, all went well, and when I swiped a card in fro, I recieved the correct data dump.

However, I started it up today, and reset everything, ran a new program to clear the Arduino, restarted my PC, and it still did not work. In the serial monitor it says that all is well, no error messages or anything. But, when I put a card in front of it, absolutely nothing happens.

Any help would be great!

title: MFRC522 Only working sometimes

Answers: 3

body:
Check your power supply. I've seen so many weird results from inconsistent/under powered circuits. It's worth a look.

What does your circuit look like?
Are you powering the RFID reader from the Arduino or it's own source?
Are the grounds coupled?

body:
If I am right then you have soldered the pins of the module yourself and I recommend you to desolder the pins and soldered them again.

I also used RC522 RFID Module with an Arduino and I faced same type of problem with the module. This way worked for me.

body:
The first thing you could try is to increase the baud rate to 115200. I'm using a different library, and in the `auth_read_write.ino` sketch the `Serial.begin()` comments says "Read a fast as possible. There is a limit for how long we are allowed to read from the tags".

If changing the baud rate doesn't work, then have a look at this answer: [RFID-RC522 not working, red led is on][1]. It has a link to a different library which worked for me.

  [1]: https://arduino.stackexchange.com/questions/44099/rfid-rc522-not-working-red-led-is-on/44109#44109


body:
I am creating an electronic device that has a 4 position rotator switch and a SPST Momentary ON push button. For the knob, I plan for position 0 to be low (OFF). Position 1-3 are high (ON). But I want these positions to equate to a different signal so they each have different values. When push button is pressed, it sends a high (ON) signal.

Can someone point me into slightly setting up the circuit to accomplish this?
And how can I create a remapper program (preferably in C++) that detects the HID device and allows the end-user to remap the pushbutton signal to any QWERTY key? I want replicate this process for each input of my device.

title: How are HIDs (keyboard,joypad) created and mapped?

Answers: 1

body:
When the Arduino sends data to the computer using the HID protocol it sends what is called a *HID Report*. That is basically an array of numbers in a pre-defined format that correspond to what the computer is expecting.

In the case of keyboard events it sends a *HID Keyboard Report*

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

It can send events for up to 6 keys at once along with up to 8 *meta* keys.  How those key events are interpreted are down to the *Keyboard Mapping* used on the computer.  This is the setting (usually in the *Language* or *Regional* settings of the computer) that defines the layout of your keyboard - UK, US, French "AZERTY", etc.

While it is possible to create custom key mappings in many operating systems it is usually a very difficult and involved task. Also the mapping takes effect for every keyboard attached to the system, including the one you type on. So changing the mapping at will is probably not a good idea since it could break your normal keyboard usage.

So how would you go about doing what you want to do?  Well, my recommendation is not to do it on the computer, but to do it on the Arduino.  The Arduino has multiple interfaces available at once. As well as the HID interface for keyboard and mouse it also has the CDC/ACM interface for emulating serial. You can use both of these at once quite happily.  So you can use that USB serial interface to configure the way the Arduino works - including what key code to send for any particular event.  You could even write an easy-to-use GUI in Visual Basic or something that communicates with the Arduino over serial to adjust the settings.  How you do that communication (what protocol you come up with) is entirely up to you.

----

As for the hardware side of things - all you really need is just the switches / buttons and wire.  Just follow the on-line tutorials (there's millions of them) for connecting switches and buttons to the Arduino. Enable the internal pullups, and connect the switch between the I/O pin and ground.  For the rotary switch you will have 4 inputs and 1 output, so connect the 4 inputs to I/O pins and the 1 output to ground.

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


body:
I'm just confused about the supply that I should use in driving my arduino. Is it okay to use a 3.7V with a 1000mAh to supply it?

I will be using a Lilypad Arduino.

Your replies would be a big help to me.

Cheers!

title: What is the Proper Voltage to supply an enough Current to the Arduino

Answers: 1

body:
The [Technical Specs][1] say that 2.7-5.5V DC is ok so you should be good at 3.7V DC.

Remember though:  Power consumption = Current  x  Voltage

So check that your power supply has enough current available. The current amount used will depend on how many pins you are using. The maximum each digital pin may use is 40mA. 1A (1000mA) will be plenty but mAh (milliampere hours) sounds like a battery specification.

Also, a word from the wise is that some cheap power supplies can be bad (little spikes and dips). If you are having trouble with strange issues it can be a good idea to check the power is ok.

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


body:
I'm an Arduino beginner and I recently bought a cheap starter kit on eBay. One of the lessons in the starter kit is an [RGB LED controlled by 3 PWM output pins][1]. However, the arrangement of the connections seems a bit funny to me:
[![Strange LED PWM setup][2]][2]

To my surprise, it worked. I could see the three LEDs inside the plastic change colors. Why does this work? Do the PWM pins accept current whilst low? Is this a common arrangement? See the above link for the code provided in the lesson.

  [1]: http://wiki.epalsite.com/index.php?title=Starter_Kit_for_Arduino#Lesson_6_RGB_LED_various_color_display
  [2]: https://i.stack.imgur.com/Qupku.jpg

title: Why does an RGB LED between VCC and PWM work?

Answers: 3

body:
This is a common arrangement and is known as *Common Anode*, and the I/O pin is said to be *sinking* current.

To better understand what is happening here it's best to think of an I/O pin as a two-position switch:

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

When the I/O pin is HIGH point 1 is connected to point 2. When the I/O pin is LOW point 1 is connected to point 3.

So when HIGH the circuit is Vcc -> D1 -> R1 -> Vcc (or the other way around - I have done it that way because of the polarity of the LED), and no current can flow since it has nowhere that isn't at a lower potential than Vcc to flow to.

But when the I/O pin is LOW the circuit is now Vcc -> D1 -> R1 -> GND and so current can flow through it all to ground.  As a result the LED now lights up.

One thing you may have noticed now is that the operation is backwards.  Set the IO pin to LOW to turn the LED ON. That has the effect, as well, that PWM duty cycles are reversed.  `analogWrite(ledPin, 0)` will be full brightness and `analogWrite(ledPin, 255)` will be off.

  [1]: https://i.stack.imgur.com/WJFVn.png

body:
The RGB LED is common anode. This is why it is connected to VCC and the PWM pins pulls down to light resp LED.

A common cathode RGB LED would be connect to GND and the PWM pins would pull up to light

Cheers!

body:
> Do the PWM pins accept current whilst low?

The pins **sink** current when low. And yes, that is commonly done. The pins are **not** "do nothing" at LOW, and "put 5V there" at HIGH. They are specifically designed to try to source (drive high) current when HIGH and sink (drive low) current when LOW.

To have pins (more or less) do nothing, you have to set them to INPUT mode. Then they try to neither source nor sink.

*Caveat:* if you enable the internal pull-ups they will try to weakly source current.

---

> Is this a common arrangement?

It is quite common, depending on whether the device you are controlling is active high, or active low.


body:
So, I have bought this USB programmer with CH340G chip on it, but it seems, that I cannot program arduino mini clone.

So, this programmer has pinout of 5V|GND|TX|RX|3V3.

I have connected TX to TX and RX to RX (and also switched, because these programmers sometimes have marked where certain pins supposed to go, not what they represent).

I have also wired the DSR leg from the chip and connected it to the RESET on arduino mini clone.

There's still no connection between them.

Now I'm wondering, if I just connect the power supply and TX and RX connectors, when am I supposed to press reset for the succesfull programming?

title: Arduino mini being programmed with CH340G

Answers: 1

body:
First of all you should connect the DTR (not the DSR) pin to the reset terminal WITH a 100nF capacitor. See [this page][1] or [the arduino uno schematics][2] to see how to put the capacitor (it's simply in series with the signal.

However I suggest you to start programming WITHOUT the autoreset; once you are sure that you can program it then try soldering that capacitor to program the arduino without having to hit the reset button.

As for when, watch the IDE status: when it stops compiling and shows the "Uploading" string, press the reset button on the board. You will usually have a couple of seconds to press it.

  [1]: http://playground.arduino.cc/Learning/AutoResetRetrofit
  [2]: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf


body:
I'm programming C++ for arduino and today I have seen an example like this

    void loop() {
        byte variable = 0; // << This variable is the question.
        //more stuff here
    }

Is the same as this?:

    byte variable = 0;

    void loop() {
        //stuff here
    }

If the answer is "no", my question is "why?".

Thanks for your time!

title: What's the difference between setting a variable outside a function and setting a variable inside a function?

Answers: 2

body: No, it's not the same. Instructions within the loop() repeat every time the program gets to the end. If you set your variable at the start of the loop, it will automatically get reset to the default when you might not want it to be reset. The author of the example wants to reset to default every time the loop completes.

body:
The difference is not only about where you set the variable, but about where you defined it as well.

Defined outside the function, it will have global scope and lifetime, meaning it is visible everywhere and it exists for the entire duration of the program.  If you then place an initializer inside the function, whatever value it had just before function-entry will be replaced by the initializer value.

If you define it inside the function (and without a "static" specifier) it only exists while that function is executing, and is only visible to code inside the function. Because it only comes into existence when the function is entered, you must initialize it within the function, somehow.

If you define it inside the function, but _with_ a static specifier,

    static byte variable = 0;

then it will exist for the entire execution of the program but will only be visible to code within the function. In addition, an initializer on its definition (as opposed to other assignments to the variable) will only be executed once, just before the program begins executing, and *will not* be executed within function.

Using local and static (as opposed to global) variables is considered good program-variable hygiene because it hides those variables (to a greater or lesser degree) from code that needn't and shouldn't be able see or alter them.


body:
I have an Arduino UNO with Atmega 328 SMD, and I am trying to use PWM, but by setting registers, not using analogWrite(). My code is:

    DDRD |= (1 << PORTD6); //Setting pin D6 as output
    OCR0A = 128; //50% duty cycle
    TCCR0A |= (1 << COM0A1)|(1 << WGM01)|(1 << WGM00); //setting mode and fast pwm
    TCCR0B |= (1 << CS01); //setting the prescaler to 8, which should yield PWM with frequency of 8 kHz

The problem is with the last line. No matter what I do, it results in PWM with frequency of 1 kHz. Setting different prescaler bits just yield 1 kHz PWM again. I was thinking that maybe its because I am programming this in Arduino IDE, and I kHz is Arduinos default frequency?
Or where am I making the mistake? Thanks for any answers.

title: Atmega328 PWM frequency setting not working

Answers: 1

body:
Your code assumes that TCCR0n are zero. But what if they are not. What if there is some hidden [initialization][1]?

Timer0 is used by the Arduino micro/millis counter and the prescale (TCCR0B) is initiated by setting bits CS00 and CS01 in init() before setup() is called.

If you really want to use Timer0 you will need to set/clear all the prescale bits. Alternatively clear the register before setting any bit.

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring.c#L263


body:
Sorry in advance for the length of my question; I want to provide proper context. I wrote an audio visualization program in Java that (in addition to making "pretty pictures" based off of the amplitudes of different frequencies being sent from the computer) sends a color to an Arduino Uno based off the sound it is "hearing."

I know the algorithm for generating this color is functional (in addition to sending that color to the Arduino, it also changes the color of an item on the DrawingCanvas). When the color is sent to the Arduino (as 3 bytes representing red, green, and blue), though, the physical LEDs don't respond correctly (they become a random color for a few seconds then switch to another random color for a bit – the behavior is hard to describe, but certainly not desired!).

I have been able to send colors to the Arduino using the same client program, but when the audio visualizer sends colors by the same method, this odd behavior occurs. My thought is that, because the audio visualizer sends color profiles dozens of times per second, the Arduino might be getting overloaded with data. Is that possible?

Here are the relevant pieces of code from the client, the audio visualizer, and the Arduino:

**Client:**

    public class Client extends WindowController{
      //USB is a class I wrote that extends PApplet. Unless baud rates are the issue, I don't think we need to worry about this.
      static USB port = new USB("COM3", 9600);
      byte[] code = new byte[LENGTH];
      static byte killTerm = -100;
      private AudioVisualizer vis;

    public void begin() {
      resize(1500,900);
      for (int k=0;k<LENGTH;k++){
        code[k]=killTerm;
      }
      vis = new AudioVisualizer(10,30,1200,300,canvas);
    }

    public void onMouseClick(Location point) {
      runVis = !runVis;
      if(runVis) {
        vis.start();
        code[0]=-22;
        sendCodeUSB(code);
      } else
        vis.stop();
 }

    public static void sendCodeUSB(byte[] code) {
      for (int k=0; k<code.length; k++) {
        port.writeProfile(code[k]);
      }
    }

AudioVisualizer

    public class AudioVisualizer implements Runnable {
      Thread thread = null;
      DrawingCanvas canvas;
      byte[] code = new byte[3];
      private int xPos;
      private int yPos;
      private int width;
      private int height;
      private int scale;
      private Location topLeft;
      private Location bottomRight;
      private FilledRect background;
      private int brightness=0;
      private boolean needOff = false;

      public AudioVisualizer(int x, int y, int w, int h, DrawingCanvas myCanvas) {
        canvas=myCanvas;
  xPos=x;
  yPos=y;
  topLeft = new Location (xPos,yPos);
  bottomRight = new Location (xPos+width, yPos+height);
  width=w;
  height=h;
  background = new FilledRect(topLeft,width,height,canvas);
  background.setColor(Color.BLACK);
  initiateMonitor();
  scale = height/30;
      }

      public void start() {
        if (thread == null) {
          thread = new Thread(this);
       thread.start();
     }
      }

      public void stop() {
        thread=null;
      }

      public void run() {
        while (thread != null) {
          try {
            Thread.sleep(40);
          } catch (InterruptedException e) {
          }
          graphAmps();
        }
        thread = null;
      }

      public void graphAmps() {
        //there is a whole bunch of stuff here that is unrelated that I removed.
        //basically, just know that graphAmps() calls avgColors()
        avgColors();
      }

      public void avgColors(){
        //there is stuff here that generates avgRed,avgGreen,and avgBlue (known to be working)
        Color c = new Color (avgRed,avgGreen,avgBlue);
        background.setColor(c);
        //so we don't spam the Arduino more than we need to
        if(avgRed>10 || avgGreen>10 || avgBlue>10) {
          sendArduinoColor(c);
          needOff = true;
        } else if (!(avgRed>10 || avgGreen>10 || avgBlue>10) && needOff) {
          sendArduinoColor(c);
        }
      }

      public void sendArduinoColor(Color c) {
        //takes the color and sets code = an array of 3 bytes with values from 0-100 (100 is the highest brightness I ever want the LEDs to be)
        //I am sure this is done correctly so I've left it out.
        constrainArduinoColor(c);
        //calls the static method from the client and passes in the byte array with the rgb values
        Client.sendCodeUSB(code);
      }
    }

Arduino

    #include <EEPROM.h>

    int redPin = 11;
    int bluePin = 10;
    int greenPin = 9;
    //declared here for debugging ease of access
    int r;
    int g;
    int b;
    //are we going through the Spectrum Cycle loop for the first time?
    boolean sclFirstTime = true;
    //temporary initialization
    boolean waiting = true;
    int index = 0;
    const int LENGTH = 20;
    byte profile[LENGTH];
    byte avProfile[3];
    byte killTerm = -100;
    byte audioVisualizationCode = -22;

    void setup() {
      //start the serial communication
      Serial.begin(9600);
      //initialize the profile to all -1 values
      clearProfile();
    }

    void loop() {
      //if there is nothing over serial and nothing is in the EPROM, we are waiting
      if (!eepromProfileAvailable() && Serial.available()==0){
        waiting = true;
      } else if (eepromProfileAvailable() && Serial.available()==0) {
        //if there is something in EEPROM and nothing over Serial, we aren't waiting and load the EEPROM profile
        waiting = false;
        loadEEPROMProfile();
        //load the EPROM color profile into the array
      } else if (Serial.available()>0) {
        //if something enters over Serial, we aren't waiting, clear the profile, and load the new profile with the serial info
        waiting = false;
        clearProfile();
        while (Serial.available()<LENGTH) {}
        // Wait until there are LENGTH number of Bytes waiting
        for(int n=0; n<LENGTH; n++) {
          profile[n] = Serial.read(); // place them in the profile.
        }
        Serial.flush();
        //clear out the serial to prep for next time
      }
      //if we have a profile (either from EEPROM or Serial), save it, check for special codes (if found, apply the effect),
      //and if there are no special codes, the profile is a static color profile, and set LEDS to that.
      if(!waiting) {
        saveEEPROMProfile(); //omitted but working
        if (profile[0]==101) {
          while (Serial.available()==0)
            spectrumCycle(); //omitted but working
        } else if (profile[0]==-22) {
          audioVis();
        } else {
          anodeSafteyOut(redPin,profile[0]);
          anodeSafteyOut(greenPin,profile[1]);
          anodeSafteyOut(bluePin,profile[2]);
        }
      }
    }

    //a bunch of preset color effects omitted
    //we are using a common Anode LED, so low value is 255 instead of 0
    void anodeSafteyOut(int pin, int c) {
      if(c>=0) {
        c = 255 - c;
        //as a safety measure because there are no resistors (yes, I know im breaking an intergalactic law by not using any), make sure we aren't writing something too bright
        if (c>=155) {
          analogWrite(pin,c);
        }
      }
    }

    //wait for 3 bytes to come in, assign them to the avProfile, set the colors to that, do it again
    //THIS IS PROBABLY WHERE THE PROBLEM IS
    void audioVis() {
      while (Serial.available()<3);
      for (int k=0;k<3;k++)
        avProfile[k]=Serial.read();
      anodeSafteyOut(redPin,avProfile[0]);
      anodeSafteyOut(greenPin,avProfile[1]);
      anodeSafteyOut(bluePin,avProfile[2]);
      audioVis();
    }

So that's a lot, and I've left a lot out that I didn't think was necessary, though I'm happy to provide the full programs if needed. Thanks for your help!

Here is `constrainColorArduino`:

    public void constrainArduinoColor(Color c) {
      int r = c.getRed();
      int b = c.getBlue();
      int g = c.getGreen();
      int r1 = (int)(r*0.4);
      int b1 = (int)(b*0.4);
      int g1 = (int)(g*0.4);
      byte r2=0;
      byte b2=0;
      byte g2=0;
      for (int k=0; k<r1; k++)
        r2++;
      for (int k=0; k<b1; k++)
        b2++;
      for (int k=0; k<g1; k++)
        g2++;
      System.out.println(r+" "+g+" "+b);
      System.out.println(r1+" "+g1+" "+b1);
      if (r2>100) r2=100;
      if (b2>100) b2=100;
      if (g2>100) g2=100;
      if (r2<0) r2=0;
      if (b2<0) b2=0;
      if (g2<0) g2=0;
      System.out.println(r2+" "+g2+" "+b2);
      code[0]=r2;
      code[1]=g2;
      code[2]=b2;
    }

title: Problem sending colors from an audio visualizer to Arduino

Answers: 2

body:
Your idea that there's a synchronization issue seems plausible.  Whenever any byte gets skipped, color assignments shift from RGB to GBR or BRG, etc.

While sending a start code before the color profile is a possible approach to fixing the problem, it may be that occasionally one of the RGB values matches the start code, which could result in temporary desynchronization.

For an alternative method that doesn't require a start code, consider encoding the data into four bytes.  In the first byte, send the high two bits for RGB; in the second, the next two bits of each color; etc.  Set the low two bits of each byte to 11, 10, 01, 00 for first, second, third, fourth.

That is, each byte you send would be encoded BBGGRRdd where the capital letters are appropriate bits from RGB brightness levels and dd indicates which pairs of bits are being sent.

Here's some (untested) code that implements the decode:

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

    byte code = Serial.read();
    byte shif = 2*(code & 3);
    byte mask = ~(3<<shif);
    code >>= 2;
    for (byte i=0; i<3; ++i) {
      profile[i] = (profile[i] & mask) | ((code & 3)<<shif);
      code >>= 2;
    }

The following shows a function `sendData3()` that encodes three bytes from an array of RGB data into four bytes to be sent to the Arduino.  It also shows a convenience function `sendDataRGB()`.  A call like `sendDataRGB(100, 0, 42);` puts three R, G, B values into a three-byte array and calls `sendData3()` to send it off.  [Substitute as appropriate in place of `Serial.write`]

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

    void sendData3 (byte *dataIn) { // dataIn[] has R,G,B levels
      byte code;
      byte mask=3;   // mask for low 2 bits of a byte
      for (int b=4; b; ) {
        --b;
        byte shif = 2*b; // For moving bits to align with mask
        code = 0;
        for (int k=3; k; ) { // Loop to handle dIn[2], dIn[1], dIn[0]
          --k;
          code |= (dataIn[k]>>shif) & 3; // Pick off 2 color bits
          code <<= 2;       // Roll up
        }
        Serial.write (code | b); // Send encoded bits
      }
    }

    void sendDataRGB (byte R, byte G, byte B) {
      byte dataEg[] = { R, G, B };
      sendData3(dataEg);
    }

body:
>My thought is that, because the audio visualizer sends color profiles dozens of times per second, the Arduino might be getting overloaded with data. Is that possible?

Close, but the source of the problem is probably this line

      Serial.flush(); //clear out the serial to prep for next time

Because your audio visualizer keeps sending data, it's quite likely that by the time you get around to claiming a record, at least some part of another one (or more) has also arrived.   When you discard that with flush(), you are probably most of the time *not* going to be discarding exactly a record's worth of bytes, but rather some arbitrary number more or less.  This introduces a synchronization problem.

You've already had some advice on solving synchronization problems.  There are a variety of workable methods, binary and otherwise.  One simple one that works in a lot of situations is to encode bytes textually in hex and terminate the record with a newline.  It does have just over a factor of two overhead, but it has the debug/test advantage of being human readable, and you can basically cover the overhead by switching from 9600 to 19200 baud.


body:
I am totally new to Arduino and I'm a real beginner with electronics and robotics. I would like to know where to start, knowing that my ultimate goal is to build an autonomous robot (I know that I will not be able to do this project before learning a lot of things). I am a developer so I have no problem with C and C++, actually I am using C++ at work.

Thanks

title: Where to start?

Answers: 3

body:
Personally I think the best way to start is hands on with a small robot. I mean the kind that have a couple of wheels, are circular and only a few inches in diameter. You can add many kinds of sensors or actuators as you learn. You get to see it move and hold it and pick it up.

The idea is to start with basic LED control and then get motors turning, sensors on, and then improvements and upgrades.

If you're ok at coding then electronics may be the bottle neck. Get a good book is my advice. As far has hardware the EEVBLOG guy Dave gives a good run down on what he recommends [here][1].

Just start.

  [1]: https://www.youtube.com/watch?v=R_PbjbRaO2E

body:
I would start with a lot of small projects, each designed to give you confidence over one small aspect. For example:

* Detect variations in light with an LDR
* Operate a motor (there are various types of motors) - including controlling one with a MOSFET or BJT transistor
* Blink LEDs
* Connect something with a fancier interface (eg. I2C or SPI) and get the hang of "talking" to a more sophisticated interface chip (you'll probably need this for things like balancing)
* Try distance detection. Eg. with bouncing light or sound off an obstacle
* Communicate between two Arduinos - get used to communications protocols, reliability, packet loss, etc.
* Get used to detecting switch presses, either individual ones, or a keypad (or both)
* Look into reverse polarity protection
* Look into detecting low voltages on your batteries
* Try radio communications (probably need to send your robot instructions) - there are various different ways of doing that
* Possibly experiment with motor-driver boards (eg. H-bridges) which you may need for driving wheels
* Investigate reading continuous values (eg. potentiometers, rotary encoders)
* Investigate read-outs (eg. 7-segment LED displays, or LCD displays)
* Investigate generating sounds (beeps, tunes)

You could take a look at my [radio controlled car](http://www.gammon.com.au/forum/?id=11506) project. I look into some of those things there, and describe how I handled them.

[![Radio controlled car][1]][1]

I would do these things initially on the bench. Don't try to assemble something fancy until you have some experience with how the individual parts work.

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

body:
It's sounds silly, but just get an UNO, a breadboard, wires, 1 resistor (220 ohm) and an LED.

Wire up a LED circuit, and program the Arduino to flash the LED.
(There's a million examples of this all over the internet).

Without getting into any sort of heavy circuits or complex programming, you'll have a quick stress-free introduction to Arduino.

This will teach you:

 - using a breadboard
 - wiring digital ports on the Arduino
 - polarity of components (LED yes, Resistor no)
 - using the Arduino IDE
 - uploading to the board

This is a great jumping-in point because it's reasonably fool-proof.

Sure you can eventually be PID-controlling the balance of a 2-wheel robot.  But build yourself a working foundation of good knowledge first.


body:
Basically its an arduino project in which i am using an analog temperature sensor ky 013. The sensor is reading the temperatures correctly but what i want is to print the temperatures showed on the serial monitor to a lcd screen. I did the wiring and everything correctly  but there is something wrong with the code which i couldnt figure out.
Here is the code.

    #include <math.h>

    #include <LiquidCrystal.h>
    LiquidCrystal lcd = LiquidCrystal(12, 11, 5, 4, 3, 2);

    const int sensorPin = A0;
    int switchState=0;

    double Thermistor(int RawADC)
    {
        double Temp;
        Temp = log(((10240000/RawADC) - 10000));
        Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
        Temp = Temp - 273.15;
        return Temp;
    }

    void setup()
    {
        Serial.begin(9600);
        lcd.begin(16, 2);
        pinMode(sensorPin,INPUT);
    }

    void loop()
    {

     switchState=digitalRead(sensorPin);
     int readVal=analogRead(sensorPin);
     double temp =  Thermistor(readVal);
     Serial.print("Temp. : ");
     Serial.print(temp);
     Serial.println(" Celsius");
     lcd.clear();
     lcd.setCursor(0,0);
     lcd.print("Temp: ");
     lcd.print(temp);
     lcd.print(" C");
     delay(500);
    }

title: Arduino code not working

Answers: 1

body:
Please format your code.  I know it takes longer, but the payoff is in readability and maintainability.  It's well worth the extra effort.

    LiquidCrystal lcd = LiquidCrystal(12, 11, 5, 4, 3, 2);

    const int sensorPin = A0;
    int switchState = 0;

    double Thermistor(int RawADC)
    {
        double Temp;
        Temp = log(((10240000 / RawADC) - 10000));
        Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp)) * Temp);
        Temp = Temp - 273.15;
        return Temp;
    }

    void setup()
    {
        Serial.begin(9600);
        lcd.begin(16, 2);
        pinMode(sensorPin, INPUT);
    }

    void loop()
    {
        switchState = digitalRead(sensorPin);
        int readVal = analogRead(sensorPin);
        double temp = Thermistor(readVal);
        Serial.print("Temp. : ");
        Serial.print(temp);
        Serial.println(" Celsius");
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Temp: ");
        lcd.print(temp);
        lcd.print(" C");
        delay(500);
    }

I think the problem is the

    lcd.print(temp);

Try casting it to a float from a double (and two decimal places).  Maybe you just need the decimal places.

    lcd.print((float)temp, 2);


body: I am using the Adafruit Motor Shield v2.3 for Arduino Uno. I am using the analogWrite() command to power my DC motor and have set the speed to 255. Is there any way to speed up the Arduino motor even further? Thanks!

title: Speeding up Arduino DC Motors

Answers: 1

body:
The speed of a motor is a function of the motor itself and the voltage applied to it. There is no programmatic way of increasing the speed of a motor. You would either need to increase the voltage being applied to the motor (as long as it is within the limits of your motor and speed controller) or find a different motor to use that is faster.

It appears the Adafruit motor shield accepts between 5-12 volts, if you are not already at the maximum of 12 volts, and your motor is rated to allow it, you can increase the voltage you are applying to the shield. All that `255` means in this case is give the motor all the power that is available, so if you are only giving the controller 5 volts, it is only going to give the motor 5 volts.

<del>Also I might recommend instead of using `analogWrite()` that you use the [official Adafruit library][1] to control your shield as it uses its own PWM library which is more performant for motor control than the built-in Arduino one.</del>

**EDIT**

Actually, with v2 of the shield, it has its own PWM driver controlled over I2C. In which case `analogWrite()` shouldn't work at all, or at least it doesn't do what you think it does. Instead use the [official Adafruit library][1] and I also recommend following the [official tutorial][2] as well.

  [1]: https://github.com/adafruit/Adafruit_Motor_Shield_V2_Library
  [2]: https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/overview


body:
I am doing a circuit for capturing light intensities.

I followed the [tutorial provided by Adil Moujahid][1]

Yet, when I plug the jumper wires on 5V the circuit stops working and when I plug on 3.3V the analog in A0 sent back only a series of zero...

What did I missed? I acknowledge that I tried to be the most economical on the jumper wires...

The sketches, program and circuit given by Adil Mouhajid

[![The program][2]][2]

[![The circuit provided by the site][3]][3]

My attempt

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

  [1]: http://adilmoujahid.com/posts/2015/07/practical-introduction-iot-arduino-nodejs-plotly/
  [2]: https://i.stack.imgur.com/GCBiL.png
  [3]: https://i.stack.imgur.com/xev9a.png
  [4]: https://i.stack.imgur.com/P6igk.jpg

title: Analogue input 0 staying at 0 when sensing light with Arduino and a photocell

Answers: 1

body: The two strips on either side of the bread board, color red and blue (typically) are power rails, and each strip is all connected. Your circuit connections that are on that strip are shorted together and will not work. I suggest following his layout exactly to begin with, and once you've learned the basics of breadboard connections, you can start doing your own layouts.


body:
I am looking for a compact solution to convert some 220V/20amp AC to something edible by our arduinos (like 5V/2amp DC). I would like to plug directly my arduino to the wall. I found many things like some Hi-link ([HLK-PM01][1]) chips ... But I also found this one :

- [LNK564DN - US $0.34 / piece][2]
- [LNK564DN - US $1.14 / piece][3]

That seems perfect, but unfortunatly, I can not find any tuto or example of use for this, shipping included, really cheap chip.

The datasheet [is here][4].

What do you think about it ?

  [1]: http://www.aliexpress.com/item/Free-Shipping-1pcs-lot-HLK-PM01-AC-DC-220V-to-5V-mini-power-supply-module-intelligent/32408565688.html
  [2]: http://www.aliexpress.com/item/PN8359-precision-CCCV-PSR-AC-DC-converter-PN8359-DIP-8-One-from-the-sale/32592989301.html
  [3]: http://www.aliexpress.com/item/LNK564DN-AC-DC-converter-switch-off-SMD-package/32518518757.html
  [4]: http://www.mouser.com/ds/2/328/lnk562-564-6129.pdf

title: Will this AC-DC converter chip really work with arduino?

Answers: 1

body:
> What do you think about it ?

If you have to ask, don't do it. Mains voltage can be **dangerous** and should only be done if you know what you are doing and how to be safe. The best choice is to just use pre-built adapters from reputable sources.


body:
quick description of the sketch: its a clap on/off relay that turns on only when it's dark.

Cannot seem to get the relays to stay off. What happens is they are off by default then when I do the double clap to turn them on that works, after this I double clap to turn them off and then go off then immediately go on again. I can get a single relay to work perfectly but when I uncomment the rest there seems to be a problem.

I am assuming it has something to do with the delay for the clap sensor, but I am not entirely sure-- I have tried quite a few things to try to resolve it but am really lost as to why this might be happening. ideas?

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

    //Light sensor
    int photocellPin = A1;
    int photocellReading;
    int LEDbrightness;

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

    void setup() {
      pinMode(soundSensor, INPUT);
      pinMode(relay, OUTPUT);
      pinMode(relay2, OUTPUT);
      pinMode(relay3, OUTPUT);
      pinMode(relay4, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {

      /////////////
      // photo sensor
      ////////////////////
      photocellReading = analogRead(photocellPin);
      photocellReading = 1023 - photocellReading;
      LEDbrightness = map(photocellReading, 0, 1023, 0, 255);

      if(photocellReading > 500){
          photoSensor = 0;
      }
      if(photocellReading < 500){
        photoSensor = 1;
      }

      /////////////
      // clap sensor
      /////////////////////
      int sensorState = digitalRead(soundSensor);
      //erial.println(sensorState);
      if (sensorState == 1)
      {
        if (claps == 0)
        {
          detectionSpanInitial = detectionSpan = millis();
          claps++;
        }
        else if (claps > 0 && millis()-detectionSpan >= 50)
        {
          detectionSpan = millis();
          claps++;
        }
      }

      if (millis()-detectionSpanInitial >= 500)
      {
        if (claps == 2)
        {
          if (doubleClap == 0)
            {
              doubleClap = 1;
            }
            else if (doubleClap == 1)
            {
              doubleClap = 0;
            }
        }
        claps = 0;
      }

      if(doubleClap == 1 && photoSensor == 0){
        digitalWrite(relay, LOW);
        digitalWrite(relay2, LOW);
        digitalWrite(relay3, LOW);
        digitalWrite(relay4, LOW);
        Serial.println("off");

      }
      else{
        digitalWrite(relay, HIGH);
        digitalWrite(relay2, HIGH);
        digitalWrite(relay3, HIGH);
        digitalWrite(relay4, HIGH);
        Serial.println("on");
      };

    }

title: multiple relays not triggering correctly

Answers: 1

body:
As it happens, you are debugging in the dark.  You have half a dozen devices attached to (presumably) some Arduino, driven by some hard-to-read code that might not work properly even if all the devices work ok, and definitely won't work properly if any of them fail or are incorrectly attached.

For example, you can't tell from that code whether your photoSensor works, whether your clap sensor works, or whether your relays work.  Before messing around further trying to test all at once, run some definitive tests on each device individually.  For example, run the following sketch and see if your system is able to turn on all of the relays at the same time.

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

    // Test if relays work ok: First individually for a second each,
    // then all together for 2.5 seconds
    enum {relay=A0, relay2=A3, relay3=A4, relay4=A5, nRelays=4};
    byte rePins[] = { relay, relay2, relay3, relay4};

    void setup() {
      for (int r=0; r<nRelays; ++r) {
        pinMode(rePins[r], OUTPUT);    // Set pin to outputs
        digitalWrite(rePins[r], LOW);  // Turn off relay
      }
      Serial.begin(115200);
    }

    void loop() {
      byte r;
      // Turn relays on individually for a second each, with half-second gaps
      for (r=0; r<nRelays; ++r) {
        delay(500);   // Wait half a second
        Serial.print("Turning on relay #");
        Serial.print(r+1);
        Serial.print(" at ");
        Serial.println(millis());
        digitalWrite(rePins[r], HIGH); // Turn on relay
        delay(1000);     // One on for a second
        digitalWrite(rePins[r], LOW);  // Turn off relay
      }

      // Turn all the relays on
      Serial.print("Turning all relays on at ");
      Serial.println(millis());
      for (r=0; r<nRelays; ++r)
        digitalWrite(rePins[r], HIGH); // Turn on relay

      delay(2500);   // Wait 2.5 seconds

      // Turn all the relays off
      Serial.print("Turning all relays off at ");
      Serial.println(millis());
      for (r=0; r<nRelays; ++r)
        digitalWrite(rePins[r], LOW); // Turn off relay
    }

Next, write a sketch to report results from photosensor and clap sensor readings.  Once you know if your hardware is working, try to get your double-clap logic to work without involving the photosensor, or vice versa.  Also, try to make the double-clap logic work just using a button in place of the clap sensor.

Note, to shorten your code and to get rid of some of the features that make it hard to read, do some of the following changes.  With the code slightly shorter, it may be easier to comprehend and debug.

(a) Instead of introducing program constants as integer variables, introduce them as program constants.  For example, instead of the verbose

    int relay = A0;
    int relay2 = A3;
    int relay3 = A4;
    int relay4 = A5;

say something like

    enum {relay=A0, relay2=A3, relay3=A4, relay4=A5};

which tells the compiler that `relay` is a constant with the value `A0`, etc.

(b) Since you don't use variable `LEDbrightness` for anything, take it out.  With that gone, change the verbose

    photocellReading = analogRead(photocellPin);
    photocellReading = 1023 - photocellReading;
    LEDbrightness = map(photocellReading, 0, 1023, 0, 255);

    if(photocellReading > 500){
        photoSensor = 0;
    }
    if(photocellReading < 500){
      photoSensor = 1;
    }

to

    photoSensor = analogRead(photocellPin) > 523;

which will set `photoSensor` to 0 or 1 much as before.  (It is slightly different: It handles a `photocellReading==500` case that your code ignores.)

(c) Change the verbose and badly formatted

      if (doubleClap == 0)
        {
          doubleClap = 1;
        }
        else if (doubleClap == 1)
        {
          doubleClap = 0;
        }

to

     doubleClap = 1 - doubleClap;

(d) Refactor to cut about half the code involving `detectionSpan`.


body:
Hello fellow Arduino enthusiasts,

I created an Arduino project for a Mega2560 board in Microsoft Visual Studio.
Before loading the code on the board I want to test it on my Windows desktop computer.

I'd like to automatically provide input (e.g. with a file containing some values) for the 4 hardware Serials as well as the I2C/Wire bus and check their output for validity.
How can one achieve that?

I read about mocking (e.g. "Arduino-mock") but this does not seem to be what I need since it is more a way of ignoring the absence of object implementations.
Are there maybe some simulators that can automatically generate input and create output logs or even check the output?

Thank you for any advice!

title: How to test Arduino behaviour on Windows?

Answers: 0


body:
there is AVR AVR ATmega32 and a board within.
there is outputs for all ports (A, B, C, D) on board, and Vcc.
the problem is - I have no external GND output.
to watch current - I should search for GND pin everytime.
and now I need ground on my solderless board for LEDs and temperature sensor.

let's guess that I have no idea what is current or electricity.
so the question is: where I can find ground to connect it to solderless board?
maybe I can use something else, except MCU? (like my hand or smth :D)
![board photo](https://pp.vk.me/c627928/v627928177/35713/n4HlnXV5PTo.jpg)

title: where I can find ground?

Answers: 2

body:
I've just sorted things out.
There is two interfaces - ISP and JTAG. ISP is busy with programmer everytime, but JTAG is free.
So, I have found pinout of JTAG interface and achieved GND.
There is pinout:
[![isp-and-jtag][1]][1]
<sub>(source: [digital-circuitry.com](http://www.digital-circuitry.com/IMAGES/webpage/MyLAB/Altera/JTAG_ISP.jpg))</sub>

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

body:
Pin 11 of the chip itself is GND (see below). In the photo it appears to have a decoupling capacitor between GND and VCC (pin 10). You could solder a wire onto pin 11 (on the chip socket, not the pin itself) - it might be easier on the back of the board. Also pin 31 would be an option.

[![Atmega32 pinouts][1]][1]

---

Also the reset switch is almost certainly wired (on one side) to GND. It looks to me like most of the board is "ground plane" (continuous copper) so find which part of the switch is wired to that, and solder a wire to it.

  [1]: https://i.stack.imgur.com/Wadpv.png


body:
I wanted to my GSM to recieve SMSs. I have written a sketch for it. But while verifying the sketch an error pops out in this part:

if (sms.available()) {
      sms.remoteNumber(senderNnumber, 20);
      if (senderNumber == "09432167015") {
        c = sms.read();
      if (c == "yes") {
          alarm_police();
          }
        }
      }

The error message:
>Arduino: 1.6.5 (Windows 8.1), Board: "Arduino/Genuino Uno"
>
>GuardDog_v2.5.ino: In function 'void loop()':
>GuardDog_v2.5:201: error: 'senderNnumber' was not declared in this scope
>GuardDog_v2.5:204: error: ISO C++ forbids comparison between pointer and >integer [-fpermissive]
>'senderNnumber' was not declared in this scope

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

I have checked the receiving sms example and have written the sketch according to the example.I need help regarding this error and how to fix it

title: Problem while writing sketch for GSM module sim800

Answers: 1

body:
You misspelled the variable `senderNumber`. Correct it. Also you aren't reading the SMS properly or comparing the phone numbers properly. Your code should be like this (using the examples):

    #define MAX_MSG 50

    char senderNumber[20];
    char sms_buf[MAX_MSG];   // a buffer for your sms, max len = 50

    if (sms.available()) {    // this part should be in loop()
      sms.remoteNumber(senderNumber, 20);
      if (strcmp(senderNumber, "09432167015") == 0) { // compare numbers
        while (sms.available() == 0);   // wait for a char
        char i = 0;
        while (i < MAX_MSG - 1){    // till max len is reached; 1 byte for null
          c = sms.read();
          if (c == '\0')  // assuming the modem terminates sms with null
            break;
          sms_buf[i++] = c;   // write char to the buffer
          while (sms.available() == 0);   //wait for a char
        }
        sms_buf[i] = 0;   // terminate the string, just in case
        if (strstr(sms_buf, "yes") != NULL)  // look for 'yes' in buffer
          alarm_police();
      }
    }


body:
I need some expert advice. I'm using an Arduino Leonardo, which I have got working with a Nokia 3310 monochrome screen. I wrote some code to draw any graphics to the screen.

What I want to know is, can I buy a chip from somewhere that will offload most of the CPU usage (for graphics from the Leonardo) that draws numbers and letters to the screen and basic graphics (different types of polygons and lines)? So I'm looking for a chip designed to do the graphical work and a data sheet reference for the chip.

title: Does a graphical driver chip exist for this project?

Answers: 1

body:
I have no idea if there is a chip or not, but I doubt it.

But then, why do you need one?

You already know how to communicate with the screen, so why not off-load those functions on to another Arduino (make your own small ATMega328P based board to do it) and then communicate with that through whatever means you like from your Leonardo?

You don't *need* a dedicated chip to do what you can quite easily program an Arduino to do.


body:
I will have many microcontroller-based devices which will be independent from each other, but all will run the same program.

I would like to upload a program to all of them at the same time with a wireless broadcast. Ideally the user would plug in a USB controller to his computer, and upload a program from the Arduino environment as if s/he were programming a single device.

To get a better idea of what I'm talking about, please take a look at [this video][1]. This was achieved with Atmel microcontrollers but a custom-made, non-Arduino bootloader.

From a Google search for "Arduino infrared programming" [this interesting project came up][2]. The main drawback is that the reset button still has to be pressed manually. Ideally I would like the devices to be in a low-power state by default, and wake up to receive a program when they sense a signal from the controller. Still, this may be a good starting point for me.

I just wanted to get some perspectives from people who are familiar with Arduinos as to whether they think this is feasible before I jump in.

  [1]: https://youtu.be/ISMwLCFwgK4?t=1m14s
  [2]: http://krazatchu.ca/2012/05/07/superduplex-an-infrared-bootloader-for-arduino/

title: Programming many Arduinos simultaneously with a wireless broadcast

Answers: 3

body:
### TL;DR -
You have the options of either BlueTooth or XBee (amongst others: IR, for example?) for wireless uploading. However, I believe that only one board can be uploaded to, at a time, so you will need to cycle through the boards one at a time, see [Programming multiple ATMegas/Arduinos at once][1].

>When uploading a sketch or using a programmer (for sketch or bootloader), the software does not just write the code, it actually communicates with the microcontroller.
>
>You can't program them all at once. But you can program them one by one in some automatic way.

-----
Your question is a very interesting one, and asks a question that I am sure that I would never have thought of, but would be extremely useful and labour saving, especially if one has, as I do, many Arduino controlled sensor points located around the house. Here is one rather inelegant solution that may be worth trying.

**Wireless upload hardware**

If you use **BlueTooth** to wirelessly upload your sketches, then this solution might be of use, [Wireless upload program to Arduino without USB cable][2]. Note that this solution ties up pins D0 and D1:

> But be careful that it maybe not compatible with some projects which need to use the D0 and D1 as hardware UART TX, RX. Because the wireless programmer needs to permanently occupy the two pins.

Looking at it, it employs a custom [Arduino Wireless Programmer][3], to which you may have been referring in your question. However, don't be fooled by the name, it is simply a Bluetooth shield. It is basically a BT HC-05 (or similar) device, bolted onto an Arduino, see also [Bluetooth Wireless Upload][4].

Alternatively, en lieu of BlueTooth, you could use **XBee** devices, see [Wireless Programming of Arduino][5]. The advantage of using XBees is that you would not have to go through the pairing new device loop (see below), that would be required when using BT. Instead you would merely have to cycle through the XBee network IDs.

However, in addition to that, you would need to automate the switching of BT devices, selecting the appropriate port and uploading to each Arduino in turn, as *you are not able to broadcast sketches*. (If am I wrong, then will someone please correct me).

**Selecting the port and uploading the sketch**

You could use a script along with the command line version of the Arduino IDE, to select the port that the BT device is connected to, before each upload. How you do this will vary for which ever platform you are compiling upon, see [Command line Arduino compiling and downloading?][6] This can be done using the environment variable `ARDUINO_COMPORT` (see the possibly out of date [Windows command line build][7]), or the arduino cmd line option `--port <portname>` ( see the [man page][8]). The sketch would then be uploaded using the option `--upload <filename>`. You could do this in one fell swoop:

    arduino --upload --port <portname> FILE.ino

Note that on Windows you should use `arduino_debug.exe`.

Or you could use [Ino][9], if you are *not* using a Windows PC... but that might make the next part, which deals with the looping more complex than it needs be.

**Selecting each of the Arduinos (i.e. the BT devices)**

Next, you would need to add a loop to the script, that pairs the PC to each BT device in turn and thereafter calls the Arduino IDE, for the port selection and uploading. Unfortunately, this would not be platform agnostic at all, and would require a different solution for what ever platform you are using. Take a look at [Bluetooth from the Command Line][10], but for Windows you would probably require the [Blue Tooth Command Line tools suite][11].

On OS X you may be best off resorting to using AppleScript, see [Connect to bluetooth device (iPhone) via command line on MacOSX][12], as the cmd line tools for controlling BT seem a little scant - there is [BlueUtil][13], see [How to control Bluetooth wireless radio from the command line?][14] but that only appears to turn the BT on of off. However, bolting AppleScript on to the rest of the Arduino IDE control script quickly makes things more complex, although you could just put the Arduino command within the AppleScript, I guess.

  [1]: http://forum.arduino.cc/index.php?topic=166451.0
  [2]: http://www.instructables.com/id/Wireless-upload-program-to-Arduino-without-USB-cab/
  [3]: https://www.itead.cc/arduino-wireless-programmer.html
  [4]: http://www.instructables.com/id/Bluetooth-Wireless-Upload/
  [5]: http://www.instructables.com/id/Wireless-Programming-of-Arduino/
  [6]: https://stackoverflow.com/questions/8189306/command-line-arduino-compiling-and-downloading
  [7]: http://playground.arduino.cc/Code/WindowsCommandLine
  [8]: https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc
  [9]: http://inotool.org/
  [10]: https://stackoverflow.com/questions/756555/bluetooth-from-the-command-line
  [11]: http://bluetoothinstaller.com/bluetooth-command-line-tools/
  [12]: https://stackoverflow.com/questions/17519804/connect-to-bluetooth-device-iphone-via-command-line-on-macosx
  [13]: http://www.frederikseiffert.de/blueutil/
  [14]: https://apple.stackexchange.com/questions/47503/how-to-control-bluetooth-wireless-radio-from-the-command-line#comment-54464

body:
You could use ESP-LINK to program the Arduino over WiFi.

The ESP8266 is simple cheap Wi-Fi MCU that can be programmed with Arduino IDE.

ESP-LINK is firmware for the ESP8266 that makes the ESP act like serial connection (USB) to Arduino.

The firmware can be found here at [ESP-LINK ESP8266][1].

  [1]: https://github.com/jeelabs/esp-link

body:
One can use something like [this][1]. It is a custom bootloader to update a Arduino's code via a NRF24L01+ radio module.*

*It only works under Linux machines.

  [1]: https://github.com/nekromant/rf24boot


body:
Friends Here is what i want to ask.

I have a midi keyboard that is casio cps7. Its an old model so its not a USB midi keyboard.
I use it with a cheap midi to usb cable.
I just wanted to use my arduino to act like a midi to USB adapter. So, i can use my midi keyboard with that too.
I found some tutorials that uses this arduino like usb serial device. And there is also a code for it. The code itself has a command to play midi notes.
We receive serial signals from arduino and convert them into midi (by using another software that is serial midi converter, there is also virtual midi port for it which is midi-yoke). Thats how i used my arduino board once but the program code for it (what i installed) plays its own notes. I just want to send my midi out (from my keyboard casio cps7) to pc as serial via arduino. Thanks

I hope you guys now understand what i wanted to say :)

title: sending midi to software using arduino

Answers: 0


body:
I recently bought an HC-SR505 Mini PIR sensor. I connected its positive to my Arduino UNO's 5v, output to digital pin 2, and ground to ground. I used Adafruit's [code][1] to test it, but all the serial monitor displayed was "Motion detected", which meant the PIR was always on a HIGH state. I then also tried powering it using 3V3 but the PIR kept on cycling on a HIGH and LOW state. Any help on getting my sensor to actually work would be greatly appreciated.

  [1]: https://learn.adafruit.com/pir-passive-infrared-proximity-motion-sensor/using-a-pir

title: HC-SR505 PIR Sensor only outputting HIGH

Answers: 5

body:
The PIR works at 5V but you need to tweak the amount of sensibility and the signal length.
Usually when a motion is detected, the PIR keeps sending HIGH until x seconds defined by a potentiometer on the board, when it goes down, the sensor is ready to capture another motion.

body:
I have similar problem with the HC-SR505 sensor. First few seconds it holds 0 on the output pin, and then always 1.
I think it was bad batch of sensors. Bad batch in chinese manufacturing means thousands (or hundreds of thousands) bad modules flooded the market.

Meanwhile I decided to choose one of options:

1. Stick with HC-SR501 sensor. It's bigger but works more or less.
2. Buy expensive ($5.90) [PIR sensor from seeed][1].
3. Build my own PIR module by my required dimensions and function (in progress).

**Update:**
From 5 sensors received 2 do the job. Supply voltage must be 5V or higher. First 20-60 seconds the output is not reliable and should be ignored. Then it works OK (if it works at all). Since the module has 3.3V LDO onboard the output signal is 3.3V.

  [1]: http://www.seeedstudio.com/depot/Mini-PIR-Motion-Sensor-Module-p-1729.html

body: Switch to use 5v for Vcc, the sensor will work correctly. I have the same trouble if I use 3.3v for Vcc. The output still 3.3v even your Vcc is higher than 5v.

body: The PIR sensor has delay of 8 seconds. So when you turn on arduino, take care that no movement is on the PIR, and then after 8 seconds it should detect no movement. And it has always this delay,every time when detects movement.

body:
I'm a noob. I had the same problem.

I connected the signal to pin 7 so I listened to gpio7 which always gave 1. But pin 7 is gpio4... Listening to gpio4 fixed the issue :)


body:
I am new to these Arduino things, and I am currently using an Uno board for my projects.

I don't know how to control the DC motor with the help of digital pins via L293D. But I cannot use the PWM pins of Arduino, since I have already used them for controlling servos and other things, which need higher accuracy.

I tried using the [SoftPWM library][1] to control motor, but it is conflicting with other things like ultrasonic sensor. I don't know what the problem is.

Could someone suggest me a solution?

  [1]: https://code.google.com/archive/p/rogue-code/wikis/SoftPWMLibraryDocumentation.wiki

title: Arduino motor control using digital pins

Answers: 1

body:
You can implement PWM using digital pins by turning the pin on and off with respect to your duty cycle, because PWM (Pulse Width Modulation) depends upon the duty cycle the % amount during which the pin is HIGH or LOW

Let say pin 13 of arduino is connected to your l293D enable pin

Sample Code:

void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  digitalWrite(13, HIGH);
  delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz
  digitalWrite(13, LOW);
  delayMicroseconds(1000 - 100);
}

Details are also on Arduino Help

https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM


body:
I am new to Arduino and I want to connect it to my 2.1 speakers and later to a 5.1 surround system.

The purpose is to play some wav sounds when a button is clicked or when a trip laser is cut. What should I do in order to play those wav around through the speakers? I also have an SD shield.

title: Arduino Mega connect to 2.1 speakers

Answers: 1

body:
First, you need to figure out the bandwidth requirements and if this is possible at all. You need to do some basic calculations and answer the question if the Arduino and the different components have the bandwidth (byte/second) that is required.

The Arduino MCU (AVR) is too "weak" to do this on it's own. A special shield is required. Such as https://www.adafruit.com/products/1788

The Arduino Due has more processing power but still not stereo quality; https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer

More info to be googled.

Cheers!


body:
I've got an Arduino Uno.

I was building a simple circuit with only one switch and it doesn't seem to work (I followed the Arduino project book from the Arduino starter kit).

This is my circuit :
[![Photo of circuit][1]][1]

Then I try again to move the switch and then it works (but I don't understand why).

[![Photo of circuit with active LED][2]][2]

So I tried to understand where the error is and I try to read digital input from the simple circuit with only one LED :

[![Simple LED circuit][3]][3]

And this is my code :

    int SWITCH = 13;

    void setup() {
        Serial.begin(9600);
        pinMode(SWITCH, INPUT);
    }

    // the loop routine runs over and over again forever:
    void loop() {
        int val;
        val = digitalRead(SWITCH);
        if(val == HIGH) {
            Serial.println("OKAY");
        }
    }

I expect to see on the Serial Monitor "OKAY OKAY" and so on... but nothing appears on the Serial monitor.

Then I try to change the condition :

    if(val == LOW)

And now I see "OKAY OKAY" and so on...

I think that there is something wrong with this Arduino... Can someone tell me something about what is happening? Am I stupid or there is really something wrong with this?

  [1]: https://i.stack.imgur.com/8fTTt.jpg
  [2]: https://i.stack.imgur.com/GFbIX.jpg
  [3]: https://i.stack.imgur.com/0dBpT.jpg

title: It seems my Arduino doesn't work

Answers: 1

body:
It looks to me like your arduino is working just fine.

In the first two images you use the arduino only to provide 5v power to the circuit on the breadboard. In the first image you haven't connected your button to properly function as a button. I don't know the exact pin layout of the button (which should be explained in a datasheet of that button), but it is also good to know exactly how to holes in a breadboard are connected. This picture shows why your button works on your second image but not your first:

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

This picture also shows how the breadboard holes are connected:

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

In your third image you have practically connected input pin 13 to GND, so it makes sense that digitalRead(13) in your code always returns LOW. Thus, the variable var is always LOW (or 0). Thus, the comparison (var == HIGH) is FALSE, which won't send "OKAY" to the serial monitor. And, the comparison (var == LOW) is TRUE, which will* send "OKAY" to the serial monitor.

I hope you can follow the logical steps and it is clear to you what is happening.

  [1]: https://i.stack.imgur.com/uhWCT.png
  [2]: https://i.stack.imgur.com/HtdSB.jpg


body:
I've wired up a dot matrix, and I display characters on the screen by using something like the example code below.

The `Char_B` variable is a global variable in a library used by the Arduino, and `displayPixels()` is called from inside the library.

    bool Char_B[8][8] = {
 {0,1,1,1,1,0,0,0},
 {0,1,0,0,0,1,0,0},
 {0,1,0,0,0,1,0,0},
 {0,1,1,1,1,0,0,0},
 {0,1,0,0,0,1,0,0},
 {0,1,0,0,0,1,0,0},
 {0,1,0,0,0,1,0,0},
 {0,1,1,1,1,0,0,0}
    };

    displayPixels(1000, Char_B);

However, each time I declare a new character like the array above, I use a relatively massive amount of memory. Is there any way to reduce memory usage? Keep in mind I am willing to change the structure of the array if necessary, since I'll need well over 100 characters loaded onto the Arduino to write text.

title: Use large variables without using much memory

Answers: 2

body:
Use a single byte to store a row of data. As a bool still takes a single byte.

Optionally you could flip the axis, and store column data, instead of row data in the array. Since letters like `i` use fewer columns that letters like `B`. Even in your example you can see you have 3 columns with only `0`s.

A final suggestion would be to use `PROGMEM` and use the `pgm_read_byte_near` function. That way the data will remain in the flash memory, and will not take any space in the program-memory.

body:
The data structure will take 64 bytes as sizeof bool is 1 byte not a bit. The first option is to pack each line (or column) in a byte (or bytes). The prefix 0b is for [binary constant value][1] (in gcc).

    uint8_t Char_B[8] = {
    0b01111000,
    ...
    0b01111000
    };

The second option is to move the data structure to program memory.

    const uint8_t Char_B[8] PROGMEM = { ... };

This will require reading each line with a special [function][2].

    for (int line = 0; line < sizeof(Char_B); line++) {
      uint8_t pixels = (uint8_t) pgm_read_byte(Char_B + line);
      ...
    }

  [1]: https://gcc.gnu.org/onlinedocs/gcc/Binary-constants.html
  [2]: http://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html#ga73084a8bbde259ffae72980354b3f027


body:
I would like to connect the DAC outputs of my arduino board to my pc sound card input so that I can use my sounds card as an osciloscope.

I have two questions:

1- if I don't use an amplifier,  how can I protect the arduino from being damaged?

2- if I use an amplifier with dual rails,  do i still need to protect the arduino somehow?

 Please note that I know little about analog circuitry so a direct solution would be most appreciated. In short how would I use components to make sure I don't end up nuking my dac outputs.

Thanks.

title: Connecting Arduino Due's DAC output to pc sound card with protection

Answers: 0