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.


sender: user

message:
Arduino code not working

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);
    }

sender: assistant

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


message:
Speeding up Arduino DC Motors

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!

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


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

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

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.


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

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

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.


message:
multiple relays not triggering correctly

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");
      };

    }

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`.


message:
where I can find ground?

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)

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


message:
Problem while writing sketch for GSM module sim800

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

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();
      }
    }


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

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.

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.


message:
Programming many Arduinos simultaneously with a wireless broadcast

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/

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


message:
HC-SR505 PIR Sensor only outputting HIGH

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

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 :)


message:
Arduino motor control using digital pins

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

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


message:
Arduino Mega connect to 2.1 speakers

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.

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!


message:
It seems my Arduino doesn't work

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

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


message:
Use large variables without using much memory

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.

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


message:
Generating digital positive (+5 V) and negative (-5 V) signal?

Problem in getting -5 V with Arduino.

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

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

    void loop() {
      digitalWrite(13, HIGH);
      delay(20);
      digitalWrite(13, LOW);
      delay(20);
    }

Above code is generating below digital signal:

[![puredigi][1]][1]

I want this type of digital signal output:

[![digiwithn][2]][2]

I read this for generating negative -5 V signal:

https://electronics.stackexchange.com/questions/10322/what-is-negative-voltage

but not able to understand very well WRT Arduino.

Also read this:

https://arduino.stackexchange.com/questions/19435/negative-voltage-how-do-i-scale-a-0-to-5-v-signal-to-10-v-to-10-v

seems to much complicated circuit diagram with TL802.

**My questions:**

1. How do I get above digital signal?
2. I was wondering if we can use some 1 microF capacitor or transistor to generate negative signal? (simplest way)

  [1]: https://i.stack.imgur.com/GGNoF.png
  [2]: https://i.stack.imgur.com/sruN8.png

body:
It is not so easy to create a -5v power supply using a capacitor or transistor.

 A very easy way is to use an additional Wall wart power supply to create -5 volts (while still using your original +5 volt power supply).

For the additional (new -5 volts power supply), use the two wires (positive and negative to create your -5 volts).   The positive lead goes to your board ground, and the negative lead becomes your -5 volts.

EDIT 1  :   Make certain that the Wall wart that you use is isolated from the mains voltage (line voltage you plug it into).  Most Wall warts are isolated,  but check to be sure.

Then you need level translation, which can be done with an op-amp and a couple of resistors  :

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

You have not mentioned what frequency (data rate) you need.  This circuit is not fast, so for high frequency or high data rates, the circuit could be improved.

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


message:
Error when using USART with Arduino Mega 2560

I use the Arduino IDE 1.6.9

What I want is a DMX Receiver which receives 1 channel and displays it on the serial monitor. When I try to compile the code, I get the following error:

    C:\Users\Helyx\AppData\Local\Temp\build25a76891c667e0896ec10beb77bd0478.tmp/core\core.a(HardwareSerial0.cpp.o): In function `__vector_25':

    D:\Programme\Arduino\hardware\arduino\avr\cores\arduino/HardwareSerial0.cpp:48: multiple definition of `__vector_25'

    sketch\DmxReceive.ino.cpp.o:C:\Users\Helyx\Documents\Arduino\DmxReceive/DmxReceive.ino:26: first defined here

    d:/programme/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.8.1/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Fehler beim Kompilieren.

Any ideas?
Here is my code:

    #include <avr/interrupt.h>
    #include <avr/io.h>
    #include <stdio.h>

    #define F_CPU 16000000

    #define DMX_BAUD 250000
    #define DMX_LOST_TIMEOUT 8000

    volatile unsigned char dmx_buffer[10];
    volatile unsigned int dmx_lost = DMX_LOST_TIMEOUT;

    volatile unsigned int dmx_adresse = 1;

    ISR (USART0_RX_vect)

    {
    static unsigned int dmx_channel_rx_count = 0;
    static unsigned char dmx_valid = 0;
    unsigned char tmp = 0;

    tmp =  UDR0;

    if(UCSR0A&(1<<FE0))
    {
     if(dmx_channel_rx_count > 1)
     {
       dmx_lost = 0;
     }
     dmx_channel_rx_count = 0;
     dmx_buffer[0] = tmp;
     if(dmx_buffer[0] == 0)
     {
       dmx_valid = 1;
       dmx_channel_rx_count++;
     }
     else
     {
       dmx_valid = 0;
     }
     return;
    }

    if(dmx_valid)
    {
     dmx_buffer[dmx_channel_rx_count] = tmp;
     if(dmx_channel_rx_count < 514)
     {
       dmx_channel_rx_count++;
     }
     return;
    }
    }

    ISR (TIMER2_COMPA_vect)

    {
     if(dmx_lost<DMX_LOST_TIMEOUT)
     {
       dmx_lost++;
     }
    }

    void setup()
    {

    EICRA |= (1<<ISC11)|(1<<ISC10); //The rising edge of INT1 generates an interrupt request
    EIMSK |= (1<<INT1); //External interrupt request 1 enable

    //Init usart DMX-BUS
    UBRR0   = (F_CPU / (DMX_BAUD * 16L) - 1);
    UCSR0B|=(1 << RXEN0 | 1<< RXCIE0);
    UCSR0C|=(1<<USBS0); //USBS0 2 Stop bits
    sei();//Globale Interrupts Enable

    TCCR2A |= (1<<WGM21);
    TCCR2B |= (1<<CS22|1<<CS21|1<<CS20);
    TIMSK2 |= (1<<OCIE2A);
    OCR2A = F_CPU/1024/1000 - 1; //Tick 1ms
    Serial.begin(57600);

    DDRC = (1<<PE3);
    PORTB |= 0x3F;
    PORTC |= 0xFF;
    PORTC &=~(1<<PE3);

    }

    void loop()
    {

    if(dmx_lost==DMX_LOST_TIMEOUT)
    {
      dmx_buffer[dmx_adresse] = 0;

    }
    Serial.print(dmx_buffer[dmx_adresse]);
    }

body: The compiler/linker is providing the answer. There are at least two definitions of the ISR for UART0 RX. One in your code and one in HardwareSerial.


body:
If I understand you correctly, you want to receive serial data (in DMX format) on one serial port, and then display that data on the serial monitor (using a different serial port).

The Arduino Mega 2560 is an excellent choice, because it has [4 hardware UARTs][1].

Alas, there is really only 3 hardware UARTs that you can actually connect to external hardware. USART0 (the Mega pins labeled "TX0" and "RX0") are *already* connected to the USB interface; the Arduino calls that USART "Serial." (without a number).

I avoid connecting anything to the "TX0" or "RX0" pins on the Mega, so I can use "Serial." (USART0) for sending debugging messages to the serial terminal over the USB cable.

    // doesn't compile
    ISR (USART0_RX_vect)
    {
        // ...
    }
    // ...
    void loop()
    {
        // ...
        Serial.print(dmx_buffer[dmx_adresse]);
    }

This looks inconsistent to me.
One part of your program is trying to use USART0 ("Serial.") for sending and receiving messages to the serial monitor on the PC.
Another part of your program is trying to use the same USART0 ("Serial.") for sending and receiving messages on the DMX network.

Have you tried connecting the DMX interface to the other available hardware USARTs -- perhaps USART1 ("Serial1.", the pins labeled TX1 and RX1), or USART2 ("Serial2.", the pins labeled TX2 and RX2), or USART3 ("Serial3.", the pins labeled TX3 and RX3)?
Then your code would look more like other people recieving DMX on an Arduino Mega -- [(a)][2], [(b)][3], [(c)][4], etc.:

    // the ISR setup that the other DMX-on-Arduino-Mega people use:
    ISR( USART3_RX_vect ){
        // ...
    }
    // ...
    void loop(){
        // ...
        Serial.print(dmx_buffer[dmx_adresse]);
    }

  [1]: http://www.arduino.cc/en/Reference/Serial
  [2]: http://forum.arduino.cc/index.php?topic=50696.0
  [3]: http://github.com/phoeve/NPCC_DMX/blob/master/npcc_dmx_servo_mega
  [4]: http://github.com/rad1o/l0unge-sender/blob/master/arduino_dmx/libraries/Conceptinetics/Conceptinetics.cpp


message:
Can an a Arduino make music or speech without a speaker?

I have an Arduino Leonardo that can turn a relay off and on and the click is audible on the relay -this is simply done by making one of the control wires HIGH in the program code to turn the relay on and make the same control wire LOW to turn the relay off. In this way it can turn a set of relays on and off. By varying the patterns of on and off timings to the relay it make distinct sounds-it reminded me of a piezoelectric speaker for some of the programmed values. At fast on or off puling this 6V relay makes a buzzing noise. I was wondering if the sound emitted from the relay could be used as a crude speaker- I'm not talking about a quality speaker- just good enough to recognise a melody or speech. So my question
I was thinking the problem maybe be simplified if a set of relays is used buzzing at a certain frequency-corresponding to tones heard in the human voice to make it sound like speech. Im no expert in acoustics.

My questions are

1) is  it theoretically possible to use the clicking noise from a set of relays only to act as a a crude speaker (so hear a crude known melody or a crude speech)?

2) Is there such a circuit (if so what is it exactly and the theory of how it works) that can be built with an arduino?-so it only used the noise from a relay to act as a crude speaker.

I personally think it possible it would be an interesting circuit to build as I have not seen a relay used like this before. I just think it sounds interesting that music or speech can possible be made by a circuit without using a speaker type component. Maybe there's another non-speaker component (i.e. a component that was not originally designed to make a sound) that can be used instead of a relay.

I'd love to know the answers.

Update
I started on this. And the relays do make different tones-thats as far as I got.
So music seems to be possible; something like a famous melody of a song. I havent got any ideas yet for a another component instead of a relay.

body:
Sound happens because of a disturbance in the air (or other conducting medium). So the short answer is an unqualified "yes." To start making a recognizable "tune" or "voice" you would need to vary the frequency at which you create the disturbance. In the case of a relay, you'd be varying the rate at which you activate it. This would be very possible on the Arduino.

To get recognizable sounds out of a relay you'd need one that can respond in the range of a few hundred Hz (which would give notes around middle C (roughly 260 Hz) up to a few KHz. From what is posted in @CharlieHanson's comments and answers, it doesn't seem like common relays can do that.

A function that takes agreements of pitch and duration, something like:

     note(hz, ms)

would give you a fairly easy way to describe the music you wanted to play.

Just for fun, here are a few examples of "speakerless devices" making music:

* [Floppy disc drive music][1]
* [Lotus F1 car plays Happy Birthday][2]

[1]: https://youtu.be/OUzDwCX1sKY
[2]: https://youtu.be/Tr4zb-HHZs4?t=30s


body:
The operate/release time for a [typical relay](http://www.omron.com/ecb/products/pdf/en-g5v_2.pdf) is 10ms/4ms - that means it takes 14ms for the contacts to close and open again. 14ms equates to a maximum 'click' frequency of 71Hz.

Typical rates of cycles-before-failure are in the region of 100,000  minimum - but at a rate of 5 cycles per second. This will rapidly decrease as you increase the switching rate.

Furthermore, as alluded to in the above datasheet, must-operate and must-release voltages increase as the number of completed cycles moves into the tens-of-thousands. Thus, if you were to find a relay that switched fast enough you will eventually (and maybe only after a 100 seconds of non-continuous operation) run its operating voltage above a level that can be achieved.

----------

Due to the maximum switching frequency of a relay you **cannot** use one, or many, to synthesise speech. Speech is an incredibly complex mixture of frequencies, the majority of which are well above those that can be produced by switching a relay on and off.

----------

*Music* is a loose term. Simply switching the relay on and off once per second is technically a rythym, and therefore music. Different relay models will have different 'clicks' - the smaller the contacts the higher the click will be in pitch (logically speaking, that is). A collection of *different* relays could definitely create music, akin to percussion, but by their *individual clicks* and **not by the rapid switching thereof**.


message:
Funduino Joystick Shield with Bluetooth

I have a Funduino Joystick Shield (See here [Funduino on Gearbeast store][1]) which has some Bluetooth pins.

Does anyone know what pins they are connected to, and has anyone successfully connected to a BT HC-05 device using SoftwareSerial?

  [1]: http://www.gearbest.com/boards-shields/pp_236610.html?currency=GBP&gclid=CKvOx76k0soCFUieGwodKTcD-w

body:
Well, it turns out that the tx/rx for the board are connected to the standard pins 0 and 1 on the Arduino.
To use this, you can simply use Serial.write.
Of course, remember to take of the module when trying to upload your code.....


message:
Reprogram CH341A chips VID PID etc

I know it's possible (in theory) to reprogram the VID PID details back into a chip. It is however way beyond me.

Recently I learned that Microsoft distributed a piece of malicious software as part of their Windows update service. This virus was written by the FTDI chip makers to brick any chips such as the CH341's found in many cheaper Arduinos et al.

The virus attacked my CH341A serial to USB chip by writing 0's to the VID PIC and probably other locations. This makes the hardware 'Unknown' and even if you have the correct driver software, the device is never associated with it.

Does anyone know a solution to get the zeroed information back into the CH341A?

body:
What you call a “virus” is, more properly, malware.  FTDI's driver that bricked fake FT232R chips was withdrawn from Windows Update in October of 2014.  (See, for example, discussion at [epanorama.net](http://www.epanorama.net/newepa/2014/10/23/on-counterfeit-usb-serial-chips/), [sparkfun](https://www.sparkfun.com/news/1629), and [hackaday](http://hackaday.com/2015/02/08/unbricking-a-counterfeit-ftdi-chip/).  The hackaday article, “Unbricking a counterfeit FTDI chip”, has links to an article about unbricking counterfeits.)

The CH341A is not a fake FT232; it is a cheaper alternative that requires a different driver.  The driver is not automatically installed by Windows. Several web pages I've seen about it suggest downloading from Chinese-language web pages, which is a gamble if you don't understand what the page says.  [However, English-language [driverscape.com](http://www.driverscape.com/download/usb-serial-ch341a) seems to have a CH341A driver at the moment.  I don't know if it works or whether it is free, and anyway have no Windows machine to test it on.]


body:
Here's the guide I used to correct the problem :-

## HOW TO FIX THE USB-FTDI PROBLEM

(on arduino nano, usb ttl, ft232, ...)

There must have been a production of faulty ftdi drivers (version 2.12.0.0 or later) on august 2014 that makes some arduino boards and other usb devices not readable from the computer. The problem is random, meaning that it is possible to program the arduino a couple of times and then it comes out the ftdi problem, at that point the board isn't accessible anymore.

Once you come up with this problem, upgrading/downgrading the drivers, the IDE or the bootloader is just a waste of time, as the ftdi driver installed leaves some wrong data. This guide followed step by step will completely fix the driver problem thus making your board working again.

### Step 1: check if you have a faulty ftdi chip driver

Not every ftdi chip has faulty drivers, so the first step is to check the chip's driver version. In order to check the version you need a software like usbview or usbdeview (both freeware and don't need any installation). Run the software and look for the "USB serial converter" device which is the one related to the ftdi driver, then read the vendor-id and the Product-id whose values should be 0x0403 for the vendor and 0x6001 for the product. The goal is to modify that 0x6001 value with 0x0000, and to do that we need some other software.

### Step 2: modify values

Unplug your arduino nano or usb device. In order to modify the driver values you need CDMUninstaller (no installation needed). Fill the vendor and product fields with the values found with usbview (0403 and 6001) and click 'add', finally click 'remove devices'.

### Step 3: download the 2.10.0.0 ftdi driver

Go to the ftdi website and download the 2.10.0.0 virtual driver choosing between 32 or 64 bit version, voiding the 'setup executable' file: just download the folder. After downloading the folder, we have to overwrite some files inside of it. Click [FTDI.rar][1] to download the files already modified, and place them inside the 2.10.0.0 folder overwriting the old ones.

### Step 4: connect your arduino board

connect your arduino board, and stop windows from looking for new drivers. Go to device manager and look for FT232 USB device, then right click on it, select Properties and click on update drivers. Manually select the place in which scan for the new drivers and choose the 2.10.0.0 driver folder with the modified files. Now windows will prompt you saying that it can't certificate the new drivers. Ignore the alert and proceed with the installation. Once installation has finished, windows should recognize the connected board as 'USB recuperacion'.

Close the window and go to device manager, and look for the COM ports device. The connected device is now showing up like USB recuperation by ElectroHobby.es

### Step 5: modify the chip eeprom

This is the last step and you need to restore the initial vendor and product values inside the ftdi chip eeprom. In order to do that you need to download and install Ftprog, click on the magnifing glass icon, select 'USB device descriptor' and again select 'custom pid'. Finally click on 'ftdi default'.

A new window shows up and you just need to check flag the device list and then click on 'program'.

  [1]: http://www.electrohobby.es/Archivos/ModificadosFTDI.rar


message:
Switching LED on and off using microcontroller

I am new to microcontrollers and just become confused trying to solve the following problem:

An ATmega32 chip is connected to four on/off switches (SW0-SW3) and 4 LEDs (LED0-LED3). SWi is connected to PAi.  LEDi is connected to PA(4+i).

How will I code in such a way that turning a switch on, turns the corresponding LED on? For example, turning SW1 on will turn LED1 on. **I am confused in the part that after taking input what will I send to port A**? Multiple switches can be switched on at the same time.

**For clarification:**

    switch0 is connected to PA0
    switch1 is connected to PA1
    switch2 is connected to PA2
    switch3 is connected to PA3

    LED0 is connected to PA4
    LED1 is connected to PA5
    LED2 is connected to PA6
    LED3 is connected to PA7

body:
A common approach is, to read the input pin, check the read value and then write to the output pin.
As the events on the input pin are generally asynchronous to your code, you have to check it more than once, which means in fact you have to check it regularily.

So in your arduino sketch you could write:

    loop()
    {
      uint8_t pin1=digitalRead(PA0);
      if (pin1==HIGH)
      {
         digitalWrite(PA4, HIGH);
      }
      uint8_t pin2=digitalRead(PA1);
      if (pin2==HIGH)
      {
         digitalWrite(PA5, HIGH);
      }
      // and so on
    }

I assume you have already done the prerequisites in your setup() routine.


message:
Use MOSFET to Change Voltage With PWM

Ok so forgive me for being an amateur but I'm having a situation that's driving me nuts.

I have a sensor that I have to cycle between +5VDC and +1.4VDC every 60 seconds. I'm using an ATTiny85 with the 8Mhz internal clock fuse set.

What I was hoping was to use a 2N7000 N-Channel MOSFET to control the cycling of the voltage. So my thought is to have +5VDC on the Drain and a PWM signal on the Gate with the + side of the sensor connected to the Source. I am thinking that using PWM and adjusting the duty cycle on the Gate will allow me to adjust the voltage that is seen at the Source but what I'm seeing is a variation of +1.4VDC @28% duty cycle and +3.6VDC at 100% duty cycle.

I can't figure out why +3.6VDC is the best I can do. The PWM is coming from PB1 on the ATTiny85 and the +5VDC is coming from the main voltage source that also feeds the ATTiny85. The current draw of the sensor is 140mA max.

[![Schematic][1]][1]

Ok so I haven't had any luck using a BJT or a single component to perform this voltage change so I started on a different approach using two 1N7000, with one being in an inverter configuration.  My though is the pin from the MCU will go high, which will turn on both FET's, with one supplying 5V and the other sinking to ground.  When the MCU pin goes low, both FET's turn off, which stops the 5V flow and the sink to ground, which then will allow the path through a voltage divider into my sensor at 1.4V.  The issue I am having is the second FET is smoking, and by that I mean the sucker heats up like crazy and one even let the smoke out!  I cannot for the life of me figure out WTF I am missing in this configuration.  Here is the new schematic and Q1 is the FET that is smokin.

[![Version 2][2]][2]

  [1]: https://i.stack.imgur.com/Iv3Px.png
  [2]: https://i.stack.imgur.com/bzTeI.png

body:
Using a N-type transistor as a high-side switch is inefficient unless you have some way of driving the gate above the positive rail. The most you can reasonably expect at the source is the gate voltage minus the gate threshold voltage, VGS(th). The typical threshold voltage of the 2N7000 as given in the datasheet is 2.1V, which means that it is a bit remarkable that you are able to get a voltage as high as you have (5V - 2.1V = 2.9V).

The way to fix this is to switch to a P-type transistor (and flip it around) since its threshold voltage is negative.


message:
Arduino sending data over MAX485

I would like to introduce myself as a student from Czech Republic. I'm currently I'm working on a Meteostation project.

I've got Arduino set up, with plenty of weather sensors, as well as WH1080 sensors connected.

Right now, I'm only able to read the data via serial port on computer with Arduino IDE or show it on my 20*4 display.

Because of the distance between source of data and recipient of data, wireless data transfer is unsuitable for my application.

I found these MAX 485 modules on eBay for cheap:

[![max485 module][1]][1]

I quickly got 2 pieces, as well as 5v-3.3v logic level shifter, as I was concerned about different logics on Raspi. I don't know much about Raspi and their pins, as the only thing I ever used with them was DS3231 real time clock module.

Now, the thing I'm trying to achieve is this - I want to be running a bunch of sensors at roof of our house, and have the Arduino send the data to Raspi over the rs485 (on request? as the sensor loop would be like 10-15min so maybe communicate on interrupt?)

What I'm planning to do with the data on the raspi would be running a software like WeeWx or wfrog to process them and possibly render a local website, that I could make public as port forwarding (I have public IP).

However, there are few questions I have, hopefully its not too much to ask

1. How would the wiring look like? I was unable to find any dumb-proof tutorial online, as I don't know whether or how to use the logic level shifter.

2. If I can read the data over serial port, would it be just a plain text (as shown on PC in Arduino ide serial monitor), or has each value its address that I could then easily accessing to a variable then being used to process the weather data?

3. If I'm completely wrong in something, or there's some completely different way how these things are being done by more experienced people, I'd love to hear some suggestions.

Thanks in advance for any kind of response, as this is at the moment causing me headaches, as I'm unable to do this on my own. I don't expect anyone to do all the work for me, maybe just point me in the right direction.

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

body:
Ok, one simple step which might help you to get going.

**The no-brainer**

There is an RS232 link between your Arduino and the PC. (Of course, it might not be a real RS232, it can be the USB, and over the USB the PC sees the arduino as a serial port what you can write from Arduino. So far so good.

You can easily extend the USB with passive expansion cords, as well as with active USB expansion cords, easily getting an extra 30m. Of course it is not an RS485, but comes at no further thinking.

**The RS485**

RS485 is basically a clever variant of a serial port, which allows you sending your data over up to 1.5km twisted wire pair.

 * get an USB-RS485 adapter for your PC or Raspberry side. These are widely available, e.g. http://usb-rs485.eu/?cms=eu85xl&gclid=CjwKEAjwq6m3BRCP7IfMq6Oo9gESJACRc0bNkhzTSQU3wUW_5tebRZDD-zAqflcvcFOq9V8nmZIlRhoCvyPw_wcB
 * get an RS485 driver chip such as MAX485 (I prefer LTC485, that works straight from 5V, costs like 1 EUR) for your Arduino side.
 * you'll need two ardino pins - serial read and write, therefore you may prefer an Arduio supporting also Serial1 - so a TxD and RxD wire from the board. When you write to this serial port instead of Serial, the data comes out from the TxD pin of the Ardino panel, instead of going to the PC via the USB.
 * now, if you can have a simplex system - i.e. only Arduino talks to the PC or Raspberry - then it makes your life a lot easier. Then you only need the TxD from the Arduino, and connect it to the DI of the RS485 driver chip. Connect RE and DE and connect both of them to 5V. That's all.
 * if you want a two direction communication between the Arduino and PC, that makes things a bit more complicated. RS485 is a half-duplex thing, so your Arduino needs to control when it wants to talk to the line or listen. For that you need a separate pin to be connected to RE and DE together. Put it to 1 to write, 0 to read from the RS485 lines. Note that Arduino is having write buffers, so it will be a little tricky to know exactly when to switch back to listening after writing. Solving this properly worths of a separate question :)
 * connect A of the MAX485/LTC485 to the A of the USB RS485 interface. Connect B to B. Now you're almost there... Connect also GND of the Arduino to the GND of the RS485 interface. (Although you can see many examples on the net of using only two wires, A and B, in the real life you either need a common GND, or an additional overvoltage protection circuit made of four zener diodes to have it running well forever.)
* you're advised of using a twisted pair wire for A and B. This is not a requirement though, you can go well with any wires. One of my friend used a garden fence made of metal as A, and the soil as B, which worked well for 50 meters :) However for 1.5Mbit, 1km you definitely need a twisted pair
* Note that if you go with long wires (over 50 meter) and higher speed (over 9600 bps), you need to have line-terminator resistors. This means a simple 120 ohm resistor connected between A and B on the PC side. Another 120 ohm resistor to be connected at A and B on the MAX 485 side - so the two farthest end of the long communication wire.

Now the software side:

* The USB RS485 interface will look like just a regular serial port for the PC (e.g. COM9) or Raspberry. So you can read and write the RS485 bus just like a standard com port.
* On the Arduino side, you can use the Serial1 (or equal) to write data out to the MAX485, which drives the wires.
* I suggest again to start with a simplex system, i.e. Arduino only writes data, the PC just reads data.
* Note that you have to use exactly the same bit rate on Arduino as well as on the PC side. Watch out when you open up the terminal.


body:
> How would the wiring look like? I was unable to find any dumb-proof
> tutorial online.

I found [this][1] tutorial to be pretty usefull.

There really isn't much to it, I suggest trying a short range before going full range.
It's a "half duplex bus system" the ends of the bus should have a "end termination resistor", usually 120Ohms, between the A and B signal.
Since it's half duplex, the Pi and Arduino can't talk at the same time.
You'll have to pull the DE and RE pins high when you want to transmit (and keep them low for receiving).

Basic sketch would be something like:

    #define TXEnablePin 13

    void setup(){
      Serial.setup(9600);
      pinMode(TXEnablePin,OUTPUT);
    }

    void loop(){
      String data = "";
      Unsigned int sensorValue1 = Sensor.getValue();
      Unsigned int sensorValue2 = Sensor.getValue();
      data += str(sensorValue1) + ":" + str(sensorValue2) + ";\r\n";
      send(data);
      delay(10000);
    }

    void send(String data){
      digitalWrite(TXEnablePin,HIGH);
      delay(1);
      Serial.send(data);
      Serial.flush();//Wait for everything to be transmitted, before disabling transmitter.
      digitalWrite(TXEnablePin,LOW);
    }

> I don't know whether or how to use the logic level shifter.

These things are pretty straight forward. You should actually be able to figure it out yourself (given you have the power of the internet).

LV to 3.3V of Pi
GND to GND of Pi
GND to GND of Arduino
HV to 5V of Arduino

Then, whatever 5V signal you want to connect to HVx and whatever 3.3V signal you want to connect to LVx

    Example:
    Arduino-TX -> HV1
    Arduino-RX -> HV2
    Pi-TX -> LV2
    Pi-RX -> LV1

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

> If I can read the data over serial port, would it be just a plain text
> (as shown on PC in Arduino ide serial monitor), or has each value its
> address that I could then easily accessing to a variable then being
> used to process the weather data?

It would be ASCII (plain text) if you send strings.
You could make different types of requests.

Like; If you send: "Temperature" to the Arduino, it will respond with: "TEMP:10" or something.

But the easiest thing would be to send all values of all sensors in a combined string every 10 seconds or so. And let the Raspberry Pi unpack that string.

> If I'm completely wrong in something, or there's some completely
> different way how these things are being done by more experienced
> people, I'd love to hear some suggestions.

I think it's pretty good that you actually already know of the existence of RS485 and why you'd want to use it.

But I also feel that you feel a little uncomfortable with the project as it is.
It's important to handle problems one by one, to avoid getting overrun by problems.
Try to make it working over (short) USB first. Then try a short RS485 link and eventually try a long RS485 link. You can then more easily spot where the problem is. Use facts from multiple tutorials, to boost the confidence you have in the system ;). It may just work if you wire it as said. If it doesn't work, you can always post a question.

If possible, it may also be worthwhile to follow some tutorials on Arduino (get a starter kit and book with tutorial projects?). Within these tutorials they give examples of problems and show what there is to solve them. Without throwing yourself into a dark pit of a project.

  [1]: http://arduino-info.wikispaces.com/SoftwareSerialRS485Example
  [2]: https://i.stack.imgur.com/GUmhB.png


message:
Arduino potentiometer example: what limits the current?

I have a question regarding _potentiometer example_:

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

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

If I turn the potentiometer to the marginal position and have 5V at A0 (and almost zero resistance at the pot), what limits the current flowing through the circuit?

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

body:
A0 input is high impedance, so very little current is flowing into A0. The value is so small that you can simplify that it flows only from +5V through the potentiometer to GND.

For some applications, when you are measuring high-impedance sources (a source that can deliver very little current) this simplification may not be correct.

You can find more detailed explaination in Atmel application note:

http://www.atmel.com/images/atmel-8456-8-and-32-bit-avr-microcontrollers-avr127-understanding-adc-parameters_application-note.pdf


body: Assuming A0 is set to **input** then it is a high-impedance input. That is, the input has a high resistance, and only consumes enough current to "sample" the voltage.


message:
Replicating Tx and Rx LEDs

In my application all of the Arduino Uno LEDs will be invisible inside an enclosure, so I wish to provide panel-mounted Tx and Rx LEDS just replicating their on-board counterparts. Is there a way to drive any of the digital outputs to replicate those LEDs? I seem to recall that the Tx and Rx LEDs are driven directly from the FTDI logic, does this preclude hacking their states and sending them to two digital outputs? How could this be done? I could de-solder the LEDs and hardwire the panel LEDS to their pads, but I think this should be a last resort.

body: The easiest thing to do would likely be to use an Arduino that does not have an on-board serial connection such as the Pro Mini and then add a separate USB-UART bridge with either bare pads you can solder panel-mount LEDs to or mounting holes that will allow you to mount it with the LEDs aligned to holes on the enclosure.


body:
The USB to serial and LEDs are done with the ATmega16U2 (the chip near the USB socket).

If you look closely you'll see there are 4 pad near the chip, JP2 in the [schematic](https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf). You could solder some wire to it to connect your leds. You could then slightly modify the [firmware running on the ATMega16u2](https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/firmwares/atmegaxxu2), and [upload it using DFU](https://www.arduino.cc/en/Hacking/DFUProgramming8U2).

I did this on my arduino uno to break out the reset signal, so I could use my UNO to program an separate ATMega328 over serial.

In your case you could use the pads connected to PB4 and PB5 (as the original code uses PD4 and PD5), so the you only have to change `DDRD` and `PORTD`, to `DDRB` and `PORTB` in [LED.h](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/firmwares/atmegaxxu2/arduino-usbserial/Board/LEDs.h).


body:
Personally I would wrap all serial reading and writing in my own functions which, as well as doing the reading and writing, turn on an LED on any chosen GPIO and set a timer variable which is then used in the main loop to turn the LEDs off after a short period (otherwise they flicker too fast to be properly seen).  Something like:

    uint32_t readLedTimer = 0;

    // Call instead of Serial.read();
    int mySerialRead() {
        if (Serial.available()) {
            digitalWrite(13, HIGH);
            readLedTimer = millis();
            return Serial.read();
        }
        return -1;
    }

    // Call from loop();
    void cancelLeds() {
        if ((readLedTimer > 0) && (millis() - readLedTimer > 20)) {
            readLedTimer = 0;
            digitalWrite(13, LOW);
        }
    }

Of course, replicate (with a different LED) for the any Serial.write or Serial.print functions you may want to do (use may use *overloading* to pass different variable types to similar functions).

Another option is to directly modify the serial reading and writing routines within the Arduino AVR core to do the same thing, but that gets rather tricky when you update the IDE or want other people to use your code to build these widgets of yours.


message:
Arduino subtracting chars from strings

Hello I have an Arduino programme that has a string with the words hello in it.
I can add characters and other strings to the end of that one using:

       String test = "hello";
       test+=" jack";

it would then say "hello jack"
The problem is I want to get rid of the last character of the string every 2 seconds so it would be "hello jac" then "hello ja" and so on. How can I do this?

body:
You may use [remove()][1] method to remove last character.

  [1]: https://www.arduino.cc/en/Reference/StringRemove

    String s = "1234567890";
    while(s.length() > 0) {
        int lastIndex = s.length() - 1;
        s.remove(lastIndex);
        Serial.println(s);
    }


body:
> I want to get rid of the last character of the string every 2 seconds so it would be "hello jac" then "hello ja" and so on. How can I do this?

This is how you could do that. Avoid using String and putting the string constants in program memory.

    // A buffer for the message
    const size_t MSG_MAX = 16;
    char msg[MSG_MAX];

    void setup()
    {
      Serial.begin(9600);
      while (!Serial);
    }

    void loop()
    {
      static int len = 0;
      // Check if it is time to create the initial message
      if (len == 0) {
        strcpy_P(msg, (const char*) F("hello"));
        strcat_P(msg, (const char*) F(" jack"));
        len = strlen(msg) - 1;
      }
      // Otherwise shorten the message
      else {
        msg[len--] = 0;
      }
      // And print current message
      Serial.println(msg);
      delay(2000);
    }


body:
You are best of learning about C-style strings rather than the String class. The String class can eventually fragment dynamic memory.

To shorten a string a simple method is to move the "string terminator" inwards by overwriting the last byte of the message with zero, like this:

    const size_t MSG_MAX = 20;
    char msg [MSG_MAX];

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();

      strcpy (msg, "hello");  // initial message
      strcat (msg, " jack");  // concatenate more stuff
      }  // end of setup

      void loop ()
        {
        if (strlen (msg) > 0)
          {
          Serial.println (msg);  // display current message
          msg [strlen (msg) - 1] = 0;  // move null-terminator in
          delay (1000);
          }  // end of any message left

        }  // end of loop

Results:

    hello jack
    hello jac
    hello ja
    hello j
    hello
    hello
    hell
    hel
    he
    h


message:
Problem with sending DMX

I want to send DMX with my Arduino Mega 2560. I'm using the IDE 1.6.7

I tried the [AVR -> DMX source code from Ulrich Radig][1] and also the layout for the RS-485 transmission.

I modified the code to fit the ATMega2560 but when I upload the code nothing happens.

The only thing I didn't do is to use the 22 Ohm resistors, is that a problem?

Any idea?

Here is my circuit:

[![Photo of breadboarded RS-485 circuit][2]][2]

Here is the source

    #include <avr/interrupt.h>
    #include <avr/io.h>
    #include <stdio.h>

    #define F_CPU 16000000
    #include <util/delay.h>

    #define DMX_BAUD 250000
    #define DMX_BAUD_BREAK 80000
    #define DMX_BAUD_BREAK_UBBR ((F_CPU+DMX_BAUD_BREAK*8)/(DMX_BAUD_BREAK*16)-1)
    #define DMX_BAUD_UBBR ((F_CPU+DMX_BAUD*8)/(DMX_BAUD*16)-1)

    volatile unsigned char dmx_buffer[512];

    //############################################################################
    //DMX Senderoutine
    ISR (USART_TX_vect)
    //############################################################################
    {
      static unsigned int  dmx_channel_tx_count = 0;
      static unsigned char dmx_tx_state = 0;

      switch (dmx_tx_state)
      {
        case (0):
          UBRR0   = DMX_BAUD_BREAK_UBBR;
          UDR0 = 0; //RESET Frame
          dmx_tx_state = 1;
          break;

        case (1):
          UBRR0   = DMX_BAUD_UBBR;
          UDR0 = 0; //Start Byte
          dmx_tx_state = 2;
          break;

        case (2):
          _delay_us(10);
          //Ausgabe des Zeichens
          UDR0 = dmx_buffer[dmx_channel_tx_count];
          dmx_channel_tx_count++;

          if(dmx_channel_tx_count == 512)
          {
            dmx_channel_tx_count = 0;
            dmx_tx_state = 0;
          }
          break;
      }
    }

    void setup() {
     //Init usart DMX-BUS
     UBRR0   = DMX_BAUD_UBBR;
      DDRE |= (1<<PE1); //Output TXD Pin ATmega2560
      UCSR0B|=(1<<TXEN0)|(1<<TXCIE0); // TXEN0 Transmitter enable / TXCIE0 TX complete interrupt enable
      UCSR0C|=(1<<USBS0); //USBS0 2 Stop bits
      sei();//Globale Interrupts Enable
      UDR0 = 0;//Start DMX

    }

    void loop() {
      // put your main code here, to run repeatedly:
        dmx_buffer[4]=255;
        _delay_ms(1000);
        dmx_buffer[5]=255;
         _delay_ms(1000);
        dmx_buffer[6]=255;
        _delay_ms(1000);
        dmx_buffer[4]=0;
        _delay_ms(1000);
        dmx_buffer[5]=0;
         _delay_ms(1000);
        dmx_buffer[6]=0;
         _delay_ms(1000);

    }

  [1]: http://www.ulrichradig.de/home/index.php/avr/atmega8-experimentierboard/avr---dmx
  [2]: https://i.stack.imgur.com/AA6Cx.jpg

body:
> The only thing I didnt do is to use the 22 Ohm resitors, is that a problem?

Yes, that's a *huge* problem. The resistors are there to prevent reflections from distorting the signal. Without them the best you can hope for is a garbled mess.


message:
SPISettings was not declared in this scope

I'm trying to compile a simple I2C example to read data from an MPU-6050 accel/gyro sensor, but I'm getting the compilation error:

    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:27:8: error: 'SPISettings' does not name a type
     static SPISettings settings;
            ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'void Sd2Card::chipSelectHigh()':
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:167:9: error: 'class SPIClass' has no member named 'endTransaction'
         SPI.endTransaction();
             ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'void Sd2Card::chipSelectLow()':
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:176:9: error: 'class SPIClass' has no member named 'beginTransaction'
         SPI.beginTransaction(settings);
             ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:176:26: error: 'settings' was not declared in this scope
         SPI.beginTransaction(settings);
                              ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'uint8_t Sd2Card::init(uint8_t, uint8_t)':
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:269:3: error: 'settings' was not declared in this scope
       settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
       ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:269:53: error: 'SPISettings' was not declared in this scope
       settings = SPISettings(250000, MSBFIRST, SPI_MODE0);
                                                         ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:275:7: error: 'class SPIClass' has no member named 'beginTransaction'
       SPI.beginTransaction(settings);
           ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:279:7: error: 'class SPIClass' has no member named 'endTransaction'
       SPI.endTransaction();
           ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp: In member function 'uint8_t Sd2Card::setSckRate(uint8_t)':
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:518:14: error: 'settings' was not declared in this scope
         case 0:  settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break;
                  ^
    /usr/share/arduino/libraries/SD/src/utility/Sd2Card.cpp:518:66: error: 'SPISettings' was not declared in this scope
         case 0:  settings = SPISettings(25000000, MSBFIRST, SPI_MODE0); break;
                                                                      ^
    make: *** [.build_ano/uno/SD/src/utility/Sd2Card.o] Error 1
    Make failed with code 2

I've commented-out all code until it compiled without error, and I found that the error is caused by the line:

    #include <Wire.h>

So my minimal code to reproduce the error is:

    #include <Wire.h>

    void setup(){
    }

    void loop(){
    }

Why is this include throwing this error? Why is it trying to compile code for accessing an SD card when I have no code that uses that?

I'm using Arduino 1.6.1 and targeting the Uno. I found I can fix this error by copying version 1.0 of the Wire library into my local sketch folder.

body:
If fixed this by deleting this built-in library

    /usr/share/arduino/libraries/SD

but then I received the error:

    /usr/share/arduino/libraries/Robot_Control/ArduinoRobot.cpp:25:2: error: 'Serial1' was not declared in this scope
      Serial1.begin(9600);

so I deleted these libraries as well:

    /usr/share/arduino/libraries/Robot_Control
    /usr/share/arduino/libraries/Robot_Motor

which appear to be buggy in the 1.6 Arduino release. It's still unclear why any of these libraries were being used, since I wasn't including any of their files.


message:
Multiple MPU9250 using Multiplexer

[![enter image description here][1]][1]Anybody here have tried connecting multiple MPU9250 into multiplexer. Anyway, I've used the HD74LS151 as the substitute for the 74HC4051 multiplexer. I already tried running the program and just followed how it is connected as it is connected like in the picture. Please see the attached image in here.

Right after running the code I just only got zeros on the output. I hope someone could help me figure out what's going on with my program or  the connections of my pins.

And here is the code I used:

        #include <I2Cdev.h>
        #include <MPU6050.h>

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

        // class default I2C address is 0x68
        // specific I2C addresses may be passed as a parameter here
        // AD0 low = 0x68 (default for InvenSense evaluation board)
        // AD0 high = 0x69
        MPU6050 mpu_0(0x68);
        MPU6050 mpu_1(0x68);
        MPU6050 mpu_2(0x68);
        MPU6050 mpu_3(0x68);
        //MPU6050 accelgyro(0x69); // <-- use for AD0 high

        int16_t ax_0, ay_0, az_0, ax_1, ay_1, az_1, ax_2, ay_2, az_2, ax_3, ay_3, az_3;
        int16_t gx_0, gy_0, gz_0, gx_1, gy_1, gz_1, gx_2, gy_2, gz_2, gx_3, gy_3, gz_3;

       // uncomment "OUTPUT_READABLE_ACCELGYRO" if you want to see a tab-separated
      // list of the accel X/Y/Z and then gyro X/Y/Z values in decimal. Easy to read,
     // not so easy to parse, and slow(er) over UART.
     #define OUTPUT_READABLE_ACCELGYRO

     // uncomment "OUTPUT_BINARY_ACCELGYRO" to send all 6 axes of data as 16-bit
     // binary, one right after the other. This is very fast (as fast as possible
    // without compression or data loss), and easy to parse, but impossible to read
    // for a human.
    //#define OUTPUT_BINARY_ACCELGYRO

     #define LED_PIN 13
     bool blinkState = false;

     //Mux control pins
     int s0 = 5;
     int s1 = 6;
     int s2 = 7;

     //Mux in "SIG" pin
     int SIG_pin = 0;

     const int MPU=0x68;

     void setup() {

      pinMode(s0, OUTPUT);
      pinMode(s1, OUTPUT);
      pinMode(s2, OUTPUT);

      //    delay(5);
      //    Wire.begin();
      //    Wire.beginTransmission(MPU);
      //    Wire.write(0x6B);  // PWR_MGMT_1 register
      //    Wire.write(0);     // set to zero (wakes up the MPU-6050)
      //    Wire.endTransmission(true);
      //    delay(15);
     //
     //    digitalWrite(s0, HIGH);
     //    digitalWrite(s1, LOW);
     //    digitalWrite(s2, LOW);
    //    delay(5);
    //
    //    Wire.begin();
    //    Wire.beginTransmission(MPU);
    //    Wire.write(0x6B);  // PWR_MGMT_1 register
    //    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    //    Wire.endTransmission(true);
    //    delay(15);

    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
    // it's really up to you depending on your project)
    Serial.begin(38400);

    // ================= MPU: 0 =================
    digitalWrite(s0, LOW);
    digitalWrite(s1, LOW);
    digitalWrite(s2, LOW);
    delay(5);
    Wire.begin();
    Wire.beginTransmission(MPU);
    Wire.write(0x6B);  // PWR_MGMT_1 register
    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    Wire.endTransmission(true);
    delay(15);
    mpu_0.initialize();
    Serial.println("Testing device connections #0 ...");
    Serial.println(mpu_0.testConnection() ? "MPU6050 connection #0 successful" :      "MPU6050 connection #0 failed");
    delay(5);

    // ================= MPU: 1 =================
    digitalWrite(s0, HIGH);
    digitalWrite(s1, LOW);
    digitalWrite(s2, LOW);
    delay(5);
    Wire.begin();
    Wire.beginTransmission(MPU);
    Wire.write(0x6B);  // PWR_MGMT_1 register
    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    Wire.endTransmission(true);
    delay(15);
    mpu_1.initialize();
    Serial.println("Testing device connections #1 ...");
    Serial.println(mpu_1.testConnection() ? "MPU6050 connection #1 successful" :  "MPU6050 connection #1 failed");
    delay(5);

    // ================= MPU: 2 =================
    digitalWrite(s0, LOW);
    digitalWrite(s1, HIGH);
    digitalWrite(s2, LOW);
    delay(5);
    Wire.begin();
    Wire.beginTransmission(MPU);
    Wire.write(0x6B);  // PWR_MGMT_1 register
    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    Wire.endTransmission(true);
    delay(15);
    mpu_2.initialize();
    Serial.println("Testing device connections #2 ...");
    Serial.println(mpu_2.testConnection() ? "MPU6050 connection #2 successful" : "MPU6050 connection #2 failed");
    delay(5);

    // ================= MPU: 3 =================
    digitalWrite(s0, HIGH);
    digitalWrite(s1, HIGH);
    digitalWrite(s2, LOW);
    delay(5);
    Wire.begin();
    Wire.beginTransmission(MPU);
    Wire.write(0x6B);  // PWR_MGMT_1 register
    Wire.write(0);     // set to zero (wakes up the MPU-6050)
    Wire.endTransmission(true);
    delay(15);
    mpu_3.initialize();
    Serial.println("Testing device connections #3 ...");
    Serial.println(mpu_3.testConnection() ? "MPU6050 connection #3 successful" : "MPU6050 connection #3 failed");
    delay(5);

    // use the code below to change accel/gyro offset values
    /*
    Serial.println("Updating internal sensor offsets...");
    // -76 -2359 1688 0 0 0
    Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
    Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
    Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
    Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
    Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
    Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
    Serial.print("\n");
    accelgyro.setXGyroOffset(220);
    accelgyro.setYGyroOffset(76);
    accelgyro.setZGyroOffset(-85);
    Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t"); // -76
    Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t"); // -2359
    Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t"); // 1688
    Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t"); // 0
    Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t"); // 0
    Serial.print(accelgyro.getZGyroOffset()); Serial.print("\t"); // 0
    Serial.print("\n");
    */

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

    void loop() {
    // read raw accel/gyro measurements from device
    //    accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

    // these methods (and a few others) are also available
    //accelgyro.getAcceleration(&ax, &ay, &az);
    //accelgyro.getRotation(&gx, &gy, &gz);

    // ================= MPU: 0 =================
    digitalWrite(s0, LOW);
    digitalWrite(s1, LOW);
    digitalWrite(s2, LOW);
    delay(5);
    mpu_0.getMotion6(&ax_0, &ay_0, &az_0, &gx_0, &gy_0, &gz_0);
    #ifdef OUTPUT_READABLE_ACCELGYRO
        Serial.print("#0\ta/g:\t");
        Serial.print(ax_0); Serial.print("\t");
        Serial.print(ay_0); Serial.print("\t");
        Serial.print(az_0); Serial.print("\t");
        Serial.print(gx_0); Serial.print("\t");
        Serial.print(gy_0); Serial.print("\t");
        Serial.println(gz_0);
      #endif
      delay(5);

    // ================= MPU: 1 =================
    digitalWrite(s0, HIGH);
    digitalWrite(s1, LOW);
    digitalWrite(s2, LOW);
    delay(5);
    mpu_1.getMotion6(&ax_1, &ay_1, &az_1, &gx_1, &gy_1, &gz_1);
    #ifdef OUTPUT_READABLE_ACCELGYRO
        Serial.print("#1\ta/g:\t");
        Serial.print(ax_1); Serial.print("\t");
        Serial.print(ay_1); Serial.print("\t");
        Serial.print(az_1); Serial.print("\t");
        Serial.print(gx_1); Serial.print("\t");
        Serial.print(gy_1); Serial.print("\t");
        Serial.println(gz_1);
    #endif
    delay(5);

    // ================= MPU: 2 =================
    digitalWrite(s0, LOW);
    digitalWrite(s1, HIGH);
    digitalWrite(s2, LOW);
    delay(5);
    mpu_2.getMotion6(&ax_2, &ay_2, &az_2, &gx_2, &gy_2, &gz_2);
    #ifdef OUTPUT_READABLE_ACCELGYRO
        Serial.print("#2\ta/g:\t");
        Serial.print(ax_2); Serial.print("\t");
        Serial.print(ay_2); Serial.print("\t");
        Serial.print(az_2); Serial.print("\t");
        Serial.print(gx_2); Serial.print("\t");
        Serial.print(gy_2); Serial.print("\t");
        Serial.println(gz_2);
       #endif
       delay(5);

       // ================= MPU: 3 =================
       digitalWrite(s0, HIGH);
       digitalWrite(s1, HIGH);
       digitalWrite(s2, LOW);
       delay(5);
       mpu_3.getMotion6(&ax_3, &ay_3, &az_3, &gx_3, &gy_3, &gz_3);
       #ifdef OUTPUT_READABLE_ACCELGYRO
        Serial.print("#3\ta/g:\t");
        Serial.print(ax_3); Serial.print("\t");
        Serial.print(ay_3); Serial.print("\t");
        Serial.print(az_3); Serial.print("\t");
        Serial.print(gx_3); Serial.print("\t");
        Serial.print(gy_3); Serial.print("\t");
        Serial.println(gz_3);
        #endif
        delay(5);

       //    #ifdef OUTPUT_BINARY_ACCELGYRO
         //        Serial.write((uint8_t)(ax >> 8)); Serial.write((uint8_t)(ax &    0xFF));
         //        Serial.write((uint8_t)(ay >> 8)); Serial.write((uint8_t)(ay & 0xFF));
         //        Serial.write((uint8_t)(az >> 8)); Serial.write((uint8_t)(az & 0xFF));
          //        Serial.write((uint8_t)(gx >> 8)); Serial.write((uint8_t)(gx & 0xFF));
          //        Serial.write((uint8_t)(gy >> 8)); Serial.write((uint8_t)(gy & 0xFF));
         //        Serial.write((uint8_t)(gz >> 8)); Serial.write((uint8_t)(gz & 0xFF));
         //    #endif

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

Cheers!

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

body:
Your concept sounded sensible enough so I gave it a try-out.

[![Multiplexed I2C][1]][1]

First point is: The master always generates the clock so we don't need to multiplex that. We only need to multiplex the data (SDA).

Code snippet:

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

    // the multiplexer address select lines (A/B/C)
    const byte addressA = 6; // low-order bit
    const byte addressB = 5;
    const byte addressC = 4; // high-order bit

    int selectTarget (const byte which)
      {
      // select correct MUX channel
      digitalWrite (addressA, (which & 1) ? HIGH : LOW);  // low-order bit
      digitalWrite (addressB, (which & 2) ? HIGH : LOW);
      digitalWrite (addressC, (which & 4) ? HIGH : LOW);  // high-order bit
      }  // end of readSensor

All you have to do is call `selectTarget(n)` where `n` is 0 to 7, and you redirect SDA to the desired chip. I suggest a 4.7k pull-up on the target side so that the line is pulled high when not selected.

I tested it out and it seems to work OK.

---

The beauty of this setup is that you can multiplex 8 devices (eg. sensors) which happen to have the same I2C address, with only one additional chip. And, you can get 16-channel multiplexers if you want to take this further. Of course, in the code you still have to select the correct I2C address for the chip.

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


message:
Can I do parallel processing in Arduino?

I recently got to work with Arduino and I want to get parallel input from 5 LDRs and at the same instance I need to light a LED corresponding to that LDR if the resistance got high.

I read about a finite state machine, but I couldn't understand how it works.

Is it the only way for this type of problem or are there any other way?

body:
You do not need parallel processing or finite-state machines for that:

    // Vector with digital pin numbers for LEDs (with resistor to ground)
    const int LED_MAX = 5;
    const int LED[LED_MAX] = { 2, 3, 4, 5, 6 };

    // Vector with analog pin numbers for LDR (with pullup resistor)
    const int LDR_MAX = 5;
    const int LDR[LDR_MAX] = { A0, A1, A2, A3, A4 };

    // Analog value or lower when to light the LED
    const int THRESHOLD = 200;

    void setup()
    {
       // All LED pins should be digital output pins
       for (int i = 0; i < LED_MAX; i++)
         pinMode(LED[i], OUTPUT);
    }

    void loop()
    {
       // Read all LDRs and set LED pins according to threshold
       for (int i = 0; i < LDR_MAX; i++)
         digitalWrite(LED[i], analogRead(LDR[i]) < THRESHOLD);
    }

But if you really want to describe this as multiple tasks you could use the [Simple Scheduler library][1]:

    #include <Scheduler.h>

    const int THRESHOLD = 200;

    template<int LED> void setup()
    {
       pinMode(LED, OUTPUT);
    }

    template<int LED, int LDR> void loop()
    {
       digitalWrite(LED, analogRead(LDR) < THRESHOLD);
       yield();
    }

    void setup()
    {
       Scheduler.start(setup<2>, loop<2, A0>);
       Scheduler.start(setup<3>, loop<3, A1>);
       Scheduler.start(setup<4>, loop<4, A2>);
       Scheduler.start(setup<5>, loop<5, A3>);
       Scheduler.start(setup<6>, loop<6, A4>);
    }

    void loop()
    {
       yield();
    }

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


message:
Understanding global variables on Arduino

I am rewriting a set of LED manipulation functions to be more object oriented, and I have found that, mysteriously, my global variable memory space has been over consumed, despite a reduction of the use of global variables.

I played around with a number of things, and found something curious.

Here is a fragment of a function that does not live in an object, and is called directly from `loop()`:

    Animation *getNewAnim(int index)
    {
        switch(index)
        {
            case 0:
                return new RedClouds();
            case 1:
                return new TwoLayerClouds();
            case 2:
                return new LavaLamp1();
            case 3:
                return new Bubbles1();

            ...  (20 or so more cases)
         }

This is a function that lets me switch between display modes based on the value of `index`.  Only one of these objects is ever created at a given time; I delete the old one before calling this, so there will never be multiple instances in use simultaneously.

Now the curious thing is that if I remove a few of these return statements, collapsing the block into something like this:

    Animation *getNewAnim(int index)
    {
        switch(index)
        {
            case 0:
            case 1:
            case 2:
            case 3:
                return new Bubbles1();
    }

The amount of global memory space used falls considerably.

My hypothesis is that the Arduino build environment is pre-allocating space for each of these objects in the global memory space before the program is even run, rather than doing so dynamically as needed.

Is my hypothesis correct?  And if so, is there any way to tell the build environment not to do this, as I'd rather use the same memory for my new object that was used by the old one.

To clarify: When I build I see this sort of output:

    Sketch uses 6,550 bytes (21.3%) of program storage space. Maximum is 30,720 bytes.
    Global variables use 1,167 bytes (57.0%) of dynamic memory, leaving 881 bytes for local variables. Maximum is 2,048 bytes.

When I refer to "global memory" I am referring to the Global variables number on that output.  I'll also note that when I compile with the second example, the program storage space reported also falls dramatically.

**NEW HYPOTHESIS**

Here is what I think may be going on.  When I omit the classes from the switch statement, the compiler seems to optimize them out of the codebase, which is what I expect, and is consistent with seeing the program storage space shrink.  Each class has a method that returns it's name.  This method contains an embedded string, and I now believe that this string is stored in the global variable space.  Therefore, if the class is included, more global variable space is consumed to hold the name, and if it is optimized out, less is consumed.  This theory is consistent with all the facts I have, and makes more sense than my previous hypothesis.

body: I suggest you take a look at https://stackoverflow.com/questions/16274451/operator-new-for-arduino the new operator is not coming from the c++ libraries, it is coming from the Arduino libraries.  It's a wrapper for malloc https://arduino.stackexchange.com/questions/682/is-using-malloc-and-free-a-really-bad-idea-on-arduino


message:
Using Rx and Tx pins(0 and 1) on Arduino Uno for GSM

I am using a GSM module sim800. My module responds to the output given by my PIR sensor and sends sms according to it. My module has got +5V, GND, Rx and Tx pins. What are the pin connections that I have to make?

body:
You have a choice.

Always:

* GND => GND
* +5V => +5V

Then, either:

* TX => RX (0)
* RX => TX (1)

and use the hardware UART "Serial", but that then means that uploading new code to your Arduino becomes an arduous task since the usage pins 0 and 1 will interfere with that.  So the other option:

* TX => Any pin
* RX => Any pin

And then use [SoftwareSerial](https://www.arduino.cc/en/Reference/SoftwareSerial) to set up a secondary "bit banged" serial port on the two pins you choose.


body:
> My module has got +5V, GND, Rx and Tx pins. What are the pin connections that I have to make?

TX => RX, RX => TX, that is Arduino TX to module RX, and TX to module RX. If you want to use [Serial][1] the pins are 0 for Arduino RX, and 1 for Arduino TX.

If you want to use [SoftwareSerial][2] you decide which pins to use (check the documentation for valid pins on your board).

    // Use software serial with pin 2 for rx and pin 3 for tx
    SoftwareSerial gsm(2,3);

Cheers!

  [1]: https://www.arduino.cc/en/Reference/Serial
  [2]: https://www.arduino.cc/en/Reference/SoftwareSerialConstructor


message:
LCD is not printing strings, only integers with Arduino

As mentioned in the title I'm facing a problem in printing strings in the LCD. It's printing actually weird characters.

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
    void setup() {
      lcd.begin(16, 2);
      Serial.begin(9600);

      lcd.print("hello, world!");
    }
    void loop() {

     lcd.setCursor(0, 1);
      lcd.print(millis()/500);
    }

You can find the output of the LCD in the picture below:

[![LCD error !!][1]][1]

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

body:
Whenever I use an LCD display I make sure to use the I2C backpack.  It takes actual effort to hook it up wrong if you use them.  So if this were me, I would desolder all those pins and get one.

Here is a good description of how they work:
https://learn.adafruit.com/i2c-spi-lcd-backpack/overview