body:
You can use addressable LEDs that allow chaining from one LED to another using a serial protocol.

Like this :
![Fritzing, wiring][1]

This would alow you to set the first row blue, the second purple, each one can be controled independently.

Take a look at Ada Fruit's [neopixels][2] to start. These are basically skillfully branded WS2811 & WS2812 LEDs, but they are very well documented and well built. They feature 8 bit per channel RGB color (24 bit color) and take care of PWM internally. You could even chain the end of one strip to another, allowing all control to come from two pins of an arduino.

Assuming you go this route, consider the following:

1. You will need enough RAM to store the full array of pixels in memory, which is 3 bytes per pixel.  Alternatively, you can create a custom library with reduced bit depth, or one that stores pixels in clusters, because at the end of the day you are just operating a giant shift register.

2. You will need to supply enough **current** (60mA per led), and supply it at several points along longer strips.  You will likely need to use external power sources.  You can drive a decent amount of LEDs from Vin (before the power regulator), but not anything near 19 strips.

Now if you already have the strips, and they are analog strips, I think you can find similar drivers that output more power to drive strips, but still use a serial protocol.

You can use my example code here:

    // NeoPixel Demo minimum
    // By leo etchaas
    // released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library

    #include <Adafruit_NeoPixel.h>
    #include <avr/power.h>

    // Which pin on the Arduino is connected to the NeoPixels?
    // On a Trinket or Gemma we suggest changing this to 1
    #define PIN            6

    // How many NeoPixels are attached to the Arduino?
    #define NUMPIXELS      55

    // When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
    // Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
    // example for more information on possible values.
    Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

    int delayval = 500; // delay for half a second

    void setup() {
      // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
    #if defined (__AVR_ATtiny85__)
    if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
    #endif
    // End of trinket special code

    pixels.begin(); // This initializes the NeoPixel library.
    }

    void loop() {

    // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.

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

    // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
    pixels.setPixelColor(i, pixels.Color(25,255,255)); // Moderately bright green color.

    pixels.show(); // This sends the updated pixel color to the hardware.

    delay(delayval); // Delay for a period of time (in milliseconds).

    }for(int i;i>0;i-=1){

    // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
    pixels.setPixelColor(i, pixels.Color(255,5,255)); // Moderately bright green color.

    pixels.show(); // This sends the updated pixel color to the hardware.

    delay(delayval); // Delay for a period of time (in milliseconds).

    }
    }

  [1]: https://i.stack.imgur.com/Iq1on.png
  [2]: https://learn.adafruit.com/adafruit-neopixel-uberguide/overview


sender: user

message:
Arduino Ethernet and Uno R3 as a firewall

Is there a way to program the Ethernet Shield and Uno R3 to act as a firewall without using a huge chunk of the allowed bytes on the R3?  I plan on using a DC adapter to plug the R3 into a wall, and use the mini-SD card to keep logs while having the ethernet shield plugged into my router.

I know that it is possible to program it to do this but I want to know if there is a simple modification I can make to the web-client library or if I should use the web-server library and modify that?

sender: assistant

body:
As an entry level board, I wouldn't suggest trying this on the R3. You can do it to an extent on the Yun which comes with both a network port and wifi.

Now that said, your internet speed will be severely hampered by the lack of resources on the yun. In which case, you might want to steer closer to the Intel Edison, which you can use with the arduino IDE. It is considerably more powerful.


message:
modbus slave ID setting

I have small problem in setting device ID for Mosbus slave arduino. Here is simple example

In Modus library; device ID being configure hardcode while program. This code works for Me.

    Modbus slave(1,0,0);

Now I wanted to recognise 0-255 device ID , I am using 8:1 digital Multiplexer & DIP switch to select the port. I am reading status of digital pin & depend on status of 8 DIP pin i come to know whats device ID. Below function return device ID. I have checked Serial it returns value properly. If i assign the value to Device ID it wont work . Please let me know how can i solve this.

    unsigned int ID_Check() {
          unsigned   int ID_value;
          for(int row=0;row<8;row++)
          {
            digitalWrite(SO_enable,array[row][0]);
            digitalWrite(S1_enable,array[row][1]);
            digitalWrite(S2_enable,array[row][2]);
            Status_Out[row]=digitalRead(Output_Read);

          }

      ID_value = 1 * Status_Out[0] + 2 * Status_Out[1] + 4 * Status_Out[2] + 8 * Status_Out[3] + 16 * Status_Out[4] + 32 * Status_Out[5] + 64 * Status_Out[6] + 128 * Status_Out[7];
      return(ID_value);
    }

Below is complete code.I tried to call function loop But it wont work

    #include <ModbusRtu.h>
    int SO_enable=5;
    int S1_enable=4;
    int S2_enable=3;
    int Status_Out[8];
    int Output_Read=2;
    Modbus slave(ID_Check(),0,0); // this is slave @1 and RS-232 or USB-FTDI
    int array[8][3]={
      {
        0,0,0    }
      ,
      {
        0,0,1    }
      ,
      {
        0,1,0    }
      ,
      {
        0,1,1    }
      ,
      {
        1,0,0    }
      ,
      {
        1,0,1    }
      ,
      {
        1,1,0    }
      ,
      {
        1,1,1    }

    };

    unsigned int ID_Check() {
      unsigned   int ID_value;
      for(int row=0;row<8;row++)
      {
        digitalWrite(SO_enable,array[row][0]);
        digitalWrite(S1_enable,array[row][1]);
        digitalWrite(S2_enable,array[row][2]);
        Status_Out[row]=digitalRead(Output_Read);

      }

      ID_value = 1 * Status_Out[0] + 2 * Status_Out[1] + 4 * Status_Out[2] + 8 * Status_Out[3] + 16 * Status_Out[4] + 32 * Status_Out[5] + 64 * Status_Out[6] + 128 * Status_Out[7];
      return(ID_value);
    }

    uint16_t au16data[16] =
    {
      3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, -1
    };

    void setup() {
      slave.begin( 9600 ); // baud-rate at 19200
      pinMode(SO_enable, OUTPUT) ;// pin can enable/disable using digital IO 7 of arduino
      pinMode(S1_enable, OUTPUT) ;// pin can enable/disable using digital IO 6 of arduino
      pinMode(S2_enable, OUTPUT) ;// pin can enable/disable using digital IO 5 of arduino
      pinMode(Output_Read,INPUT);
    }

    void loop() {
      slave.poll( au16data, 16 );
    }

The other way i tried

    void Modbus_Setup()
    {
      Device_ID=ID_Check();
         delay(100);
        Modbus slave(Device_ID, 0, 0);
         slave.begin(9600);
      //slave.setID(Device_ID);

    }

body:
It looks like the problem may be initialisation order. In C/C++, global variables/objects are usually initialised in the order they are declared, and before any global functions run.

In your case, this means `ID_Check()` gets called before `array` is populated, and before `setup()` runs.

It looks like you need to make sure everything else is setup before your attempting to initialise the `Modbus` object. I'm not familiar with the library, but perhaps there's a way to set the device ID after it's been constructed (i.e. not in the constructor)?

If not, you could declare `slave` as a global pointer, and then instantiate it using `new` in `setup()`.

As a side note, I'm guessing your `Modbus_Setup()` function didn't work because the `slave` object in there is completely separate from the `slave` object that's declared globally and used in `loop()`.


message:
Will the 3.3V regulator on an Arduino Leonardo work when powered from USB?

Will the 3.3V regulator produce 3.3v when the Arduino is powered from the USB port?

body:
The 3.3V regulator is fed by the 5V, whatever that comes from. If you don't use a separate power supply like a wall-wart, the 5V switches automatically to the USB's 5V. That feeds the regulator for the 3.3V.
So yes, it will produce 3.3V.


body:
> Will the 3.3V regulator on an Arduino Leonardo work when powered from USB?

Yes, provided that

 - it is an "official" Leonardo or a competent clone and

 - as long as you do not load the power supply excessively with external loads.

[**Official circuit diagram here**](http://arduino.cc/en/uploads/Main/arduino-leonardo-schematic_3b.pdf)

The USB supply feeds the 3V3 regulator via MOSFET T1 at the bottom of the sheet and U3, an LP2985 LDO regulator. If your board has the same circuitry as this it should provide 3V3 from USB.

_____________________________

![enter image description here][1]

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


message:
Does the compiler generate intermediate assembler?

My source files are *.ino, but after compilation there aren't any other files placed in the folder. Does the compiler generate intermediate assembler, and if so, where does it leave them? Or is the machine code available somewhere?

body:
> My source files are *.ino, but after compilation there aren't any other files placed in the folder.

Correct. The Arduino IDE performs compilation in a separate temporary directory, whose location you can see if you enable verbose compilation in the IDE options.

> Does the compiler generate intermediate assembler, and if so, where does it leave them?

By default GCC (which the Arduino IDE uses) does not leave intermediate assembly language files on disk. You must pass the `--save-temps` argument to have it leave them in the current directory, or `--save-temps=obj` to save them in the output directory.

> Or is the machine code available somewhere?

The machine code is available in the .elf and .hex files generated in the temprary directory.


body:
Yes.

Arduino compilation is set up with link-time optimization (LTO), and the assembly files created during C compilation don't contain any assembly code - just the intermediate representation used later in the LTO stage to generate actual assembly code. We want the latter.

It so happens, rather nicely, that the very last time assembler is invoked in the entire compilation process, is to take the output from the LTO stage, and turn it into a whole-application object file.

To get at this assembly file, do the following (on Windows):

1. Open `%LOCALAPPDATA%\Arduino15\packages\arduino\hardware\avr\1.8.3\platform.local.txt` (create it if it doesn't exist). Add the following line

       compiler.c.elf.extra_flags=-save-temps=obj -fverbose-asm

   If there already is such a line there, just add the above options (to the right of `=`).

    **Note:** If you can't find the folder, look for the following files: `boards.txt`, `platform.txt`, `programmers.txt`. If you find these files in multiple locations, the one you want should be *inside your home directory* (i.e. not in `Program Files` or `/Applications` or `/usr`), and should be correlated at least partially to the version of Arduino you're using (should you have multiple versions installed).

2. Build the sketch again.

3. Look for a file named `%TEMP%\cc*.ltrans.s`. Each build will create a new such file. If you sort them by timestamp, the newest one is for the most recent build.

**Note:** The environment variables, enclosed by `%` signs, are valid in the Windows dialog boxes. You can directly paste such a path into e.g. an Open or Save As... dialog box, and it'll work. Paths with globs (`*`) will act as filters (IIRC).

To know which exact `cc*.s` file was generated, add the verbose option to the final binary generator pass:

    compiler.c.elf.extra_flags=-save-temps=obj -fverbose-asm -v

Rebuild, and copy-paste all the output from the compilation status window in Arduino to e.g. Notepad++, and search for `ar.exe`. The sole line that contains `ar.exe` ends with the name of this `cc` file:

     c:/users/[...omitted...]/avr/bin/as.exe -mmcu=avr6 -mno-skip-bug
        -o C:\Users\[...]\AppData\Local\Temp\cc3XhU2F.ltrans0.ltrans.o
        C:\Users\[...]\AppData\Local\Temp\cc3XhU2F.ltrans0.ltrans.s

How does the file look? This is a short extract, just to show that both the C source and the assembly are intermingled - and this represents exactly the binary embedded in the `.hex` file and sent to the target.

```
.LBE33:
.LBE32:
.LBB34:
.LBB35:
 ;  C:\Users\[...]\Documents\Arduino\sketch_jul01a\sketch_jul01a.ino:29:   pinMode(ledPin, OUTPUT);
 .file 4 "C:\\Users\\[...]\\Documents\\Arduino\\sketch_jul01a\\sketch_jul01a.ino"
 .loc 4 29 0
 ldi r22,lo8(1)  ; ,
 ldi r24,lo8(13)  ; ,
 call pinMode  ;
.LVL55:
 ;  C:\Users\[...]\Documents\Arduino\sketch_jul01a\sketch_jul01a.ino:30:   pinMode(relayPin, OUTPUT);
 .loc 4 30 0
 ldi r22,lo8(1)  ; ,
 ldi r24,lo8(12)  ; ,
 call pinMode  ;
.LVL56:
 ;  C:\Users\[...]\Documents\Arduino\sketch_jul01a\sketch_jul01a.ino:31:   pinMode(ldrPin, INPUT);
 .loc 4 31 0
 ldi r22,0  ;
 ldi r24,lo8(54)  ; ,
 call pinMode  ;
.LVL57:
.LBE35:
.LBE34:
.LBB36:
.LBB37:
```

This approach also works on Linux and MacOS, except that the paths are slightly different, and path expansion uses different syntax. The two files of concern still are `platform.local.txt` - a file you must create, since it doesn't exist at first, and the `${TEMP}/cc*.ltrans.s` files.


message:
Can I connect to WiFi with an Arduino, "wireless SD shield" and XBee

I want to create a growhouse sensor system. I have an Arduino UNO, wireless SD shield and I have just ordered a series 2 XBee XB24.

Any info I find seems to revolve around having 2 Arduinos and 2 XBee modules, why is that?

I am presuming that once I connect the XBee to the shield that I can then connect to my Arduino on the network and send and receive data, am I wrong?

I'm a developer and sysadmin but a noob to Arduino so any help is much appreciated.

body:
The xbee network and the wifi network are both wireless networks, but, they do not communicate with each other.

You have two options.

 1. Attach a second XBEE to your computer using one of these
    https://www.sparkfun.com/products/11812
 2. Get a WIFI shield http://arduino.cc/en/Main/ArduinoWiFiShield


body:
Do you remember the term mesh network? Xbee's create a mesh network or multipoint network using 802.15.4 (hurray for google) protocol. This is not compatible with 802.11, the wifi protocol.

If you want everything to talk, you are either going to need to get an Xbee for everything, or wi-fi for everything (or wi-fi + ethernet for that matter).


message:
project not working when switching to battery power

![enter image description here][1]

I have a project which involves a photocell, an led, a push button, and a small hobby servo ([tower pro sg5010][2]) - the project works as expected when the arduino is powered by usb, but when I switch to battery power (4 AA batteries) - it doesn't work.

When powered by batteries, the servo actually starts right up and moves to the correct angle, so I feel like it should be getting enough power, but when I push the push button, it doesn't move to the new angle. I can hear a clicking noise of the servo on a regular interval, like a clock, and my LED flickers on and off at about the same interval.

If I'm doing something wrong, can anyone point it out? If it's just that the servo is not getting enough power, is there a way to add a transistor or something so that I don't have to add a separate power supply for the servo (I'm not sure there's room in my project's enclosure).

I've attached a fritzing diagram as well as my project code.

CODE:

    #include <Servo.h>

    const int buttonPin = 2;     // the number of the pushbutton pin
    boolean buttonPushed = false;

    const int ledPin =  13;      // the number of the LED pin

    const int servoPin = 9;
    Servo servo;
    int angle = 0;
    int servoStartAngle = 90;
    int servoEndAngle = 10;

    boolean servoActivated = false;

    // variables will change:
    int buttonState = 0;         // variable for reading the pushbutton status

    int photoCellPin = 2;
    int photoCellThreshold = 500;
    int photoCellActivated = false;

    void setup() {
      Serial.begin(9600);
      // initialize the LED pin as an output:
      pinMode(ledPin, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);

      servo.attach(servoPin);
      servo.write(servoStartAngle);

    }

    void loop(){
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);

      int photoCellVal = analogRead(photoCellPin);

      if (photoCellVal > photoCellThreshold){
       photoCellActivated = true;
      } else {
       photoCellActivated = false;
      }

      // check if the pushbutton is pressed.
      // if it is, the buttonState is HIGH:
      if (buttonState == LOW && buttonPushed == false) {
        // turn LED on:
        buttonPushed = true;
        Serial.println("button pushed");
      } else if (buttonState == LOW && buttonPushed == true){
       buttonPushed = false;
       Serial.println('deactivate');
      }

      if (buttonPushed == true){
       digitalWrite(ledPin, HIGH);
      } else {
       digitalWrite(ledPin, LOW);
      }

      if (buttonPushed && servoActivated == false && photoCellActivated == true){
        servoActivated = true;
        Serial.println("activate motor");

        for(angle = servoStartAngle; angle > servoEndAngle; angle--){
          servo.write(angle);
          Serial.println(angle);
          delay(15);
        }
      } else if (buttonPushed == false && servoActivated == true){ //deactivate
        for(angle = servoEndAngle; angle < servoStartAngle; angle++){
          servo.write(angle);
          Serial.println(angle);
          delay(15);
        }
        delay(200);
        servoActivated = false;

      }

      delay(200);
    }

  [1]: https://i.stack.imgur.com/arOYe.png
  [2]: http://www.adafruit.com/product/155

body:
You may find that, with a high load on batteries, it's depleting the battery quickly; batteries often recover after a while, which may be confusing things further. Try using a multimeter to measure the voltage on the battery, when your program is running.

The Arduino (actually, the chip that runs the Arduino) has brown-out detection - if the voltage drops below a certain level, the Arduino will shut down; if the power comes back up, the Arduino will start up again - but reset. The chip has settings for 1.8v, 2.7v, and 4.3v brownout detection (or none at all!); something I read on the interweb (if you can trust that) said the default was 4.3v. It may be worth flashing an led on startup, so you can tell when the chip is reset.

Also, if you are powering the Arduino through the voltage regulator (using the power socket on the Arduino), then you need about 6-7 volt in just to get 5 volt at the Arduino - this causes further power loss. If using 4 AA batteries through the voltage regulator, you will get 6 volts (probably a little more when the batteries are fresh) going into the regulator - barely or not quite enough! - and the voltage on the Arduino is likely to be below the 5v it needs. Any load (in one of my projects, two large 7-segment displays) can cause the voltage to drop enough to trigger a reset. If you are using the voltage regulator, check the voltage between the 5V and GND pins.


body:
I had an even simpler project only involving a TMP sensor and 433 MHz RF module. On a 9V (150 mAh) block battery it lasted only about 2,5 hours.
The Arduino is great for prototyping this sort of stuff, but when you want to build something for battery operation I found  that it draws 56 mA just looping without RF or motor!

Counting 2 digital outputs, 1 digital input and 1 analog input in your project, you can run that of an ATTiny85 or ATTiny45. It's the same family and after setup can be programmed with the Arduino environment. You can also opt for a lower speed bootloader 1 MHz or 8 MHz instead of 16 MHz for the Arduino to save energy, you don't seem to calculate that much. The ATTiny will draw about 10 mA looping this way.

Next you'll find also that you can disable the brown out detection in the bootloader, so it just drains the battery until completion.

Saving space in you enclosure by swapping Arduino board for ATTiny chip will allow you to put in more batteries, say 8 AA in two parallel packs of 6V each.

When that doesn't help you'll discover about the sleep modes and disabling ADC when not in use, where you go to sleep for specific intervals and allow the chip to be woken up by interrupts. In sleep mode I found the ATTiny to consume only 0.03 mA.

**Some more information**

[Program an ATtiny with Arduino][2]

[ATTiny files for Arduino IDE][3]

 [2]: http://www.instructables.com/id/Program-an-ATtiny-with-Arduino/
  [3]: https://code.google.com/p/arduino-tiny/


message:
Eeprom write function does not seem to write in more than 100 locations

I am trying log my sensor data (1 byte each) on my Arduino Uno Eeprom. I have an ATmega328 on it, so it should allow me to write up to 1Kb on it, however I've tried the Eeprom write command and it does not seem to write to more than 100 locations on it (the first 100 bytes!)

I am using the Eepromex library.

Any thoughts on what's causing this?

Edit:

These are the excerpts from my code related to Eeprom logging:

    int addr1 = 0;
    int addr2 = 256;

      // Store Data in EEPROM

      EEPROM.write(addr1,FinalMoisture[0]);

        delay(5);

      EEPROM.write(addr2,FinalMoisture[1]);

        delay(5);
      // advance index pointer to the next location.  There are 256 bytes assigned for each sensor in the EEPROM, so go back to 0 when we hit 255/511.

      addr1 = addr1 + 1;

      if (addr1 == 255)
        addr1 = 0;

      //same for addr 2 :

       addr2 = addr2 + 1;

      if (addr2 == 511)
        addr2 = 256;

      // delay until next measurement (msec)
     Sleepy::loseSomeTime(30000);

PS: As mentioned earlier I've included the EepromEx library. Each sensor stores only first 50 locations. Also, I've noticed that if I run a single loop instead of storing data in two locations, I can write 100 straight entries. In any case it seems that the write function is limited to 100?

Could this be a setting in the library? How to disable/modify it? I tried looking at the info on the lib author's postings but didn't help.

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

Looking at the library at <https://github.com/thijse/Arduino-EEPROMEx/blob/master/EEPROMex.cpp> it seems they limit the number of writes to 100:

    EEPROMClassEx::EEPROMClassEx()
      :  _allowedWrites(100)
    {
    }

There seems to be a way of changing that:

    /**
     * Set global maximum of allowed writes
     */
    void EEPROMClassEx::setMaxAllowedWrites(int allowedWrites) {
    #ifdef _EEPROMEX_DEBUG
     _allowedWrites = allowedWrites;
    #endif
    }


message:
Serial communIcation from OS X app to Arduino Mega

I am new to stack overflow. I have a question regarding using the USB serial communication sending data from an OS X app to the Arduino Mega 2560.

What happens is, when I have the Arduino running with the Serial monitor open, then I run the OS X app to send data, the Arduino does receive the data for a few seconds, then it stops.

This is the simplified Object-C code on the Mac side:

    -(IBAction)sendData:(id)sender{
        NSString *toSend=[NSString stringWithFormat:@"echo %f > /dev/tty.usbmodem1a1341" ,vector.x];
        //vector is the continuous data generated by the Mac
        const char *toCSend =[toSend UTF8String];
        //converting to c string
        printf("%s", toCSend);
        popen(toCSend, "r");
    }

This is the code on the Arduino side:

    // Read Serial input:
    void setup() {
      // Open Serial commurial1.beginnications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        // wait for Serial port to connect. Needed for Leonardo only
      }
    }

    void loop() {
      // Read Serial input:
      while (Serial.available() > 0) {
        int inChar = Serial.read();
        if (inChar != '\n') {
          inString += (char)inChar;
          Serial.read();
        } else {
          // if you get a newline, print the string,
          // then the string's value as a float:
          Serial.println(inString.toFloat(), 6);
          // clear the string for new input:
          inString = "";
        }//end of if else
      }//end of while (Serial.available() > 0)
    }

I am not sure what the problem, could it be the OS X app send out too much data to quickly? Or could it be the Arduino serial buffer is overflowed?

I really don't know much about serial communication so I don't know what I am missing. Any help will be greatly appreciated.

body:
One problem is here:
<!-- language-all: lang-C++ -->

      // Read Serial input:
      while (Serial.available() > 0) {
        int inChar = Serial.read();

        if (inChar != '\n') {
          inString += (char)inChar;
          Serial.read();
        }

Your Serial.available() call guarantees that you have **one** byte of serial input, but you are attempting to read two of them if the first one is not a newline. This is not valid.

[How to process incoming serial data without blocking](http://www.gammon.com.au/serial)


message:
How does one use (specically the wiring) the OV7670 camera with the Arduino Uno?

If one could tell me where each of the pins on the back of the camera go to, that would be great. if someone added the code also that would be awesome.

body:
You need to connect A4 and A5 via pullup register to 3V and to I2C interface on Arduino Uno.
And you need to connect A7 to XCLK signal via 2 registers.

You can find schema and code in my blog: [How to connect Arduino Uno and OV7670][1]

  [1]: http://privateblog.info/arduino-uno-i-kamera-ov7670-primer-ispolzovaniya/


message:
unable to install usbserial driver for GPRS shield with mac air vs. 10.9

Despite all my efforts and web crawling I can not install the necessary driver to connect my Arduino uno R3 to the GPRS shield from seeedstudio. I have attempted downloading the VCP driver from [http://www.ftdichip.com/Drivers/VCP.htm][1]
I have tried the solution offered here [https://learn.sparkfun.com/tutorials/how-to-install-ftdi-drivers/mac][2] for Yosemite and beyond through the AppleUSBFTDI driver as well as the solution offered by FTDI's script. Any help will be greatly appreciated. Please let me know if I can provide any more information.

  [1]: http://www.ftdichip.com/Drivers/VCP.htm
  [2]: https://learn.sparkfun.com/tutorials/how-to-install-ftdi-drivers/mac

body:
The USB serial connection is provided by the Arduino, not the shield, and the naming pattern for an Uno on OSX will not be tty.usbserial### but rather something else (tty.usbmodem### perhaps?).

If I recall correctly, an Uno does not require a driver on OSX though older/unofficial FTDI based boards (as well as unofficial boards based on yet other fixed function chips) do require drivers.

(On Linux it is typically /dev/ttyUSB# for fixed function and /dev/ttyACM# for an Uno, both using kernel module drivers shipped with most distributions.  On Windows they are all COM# and drivers are typically required)


message:
Two Arduinos Send data via Analog Pin?

What I want to do is allow **Arduino A** to send some constant value to **Arduino B**.

I sense something inherently wrong with my approach, but I cant figure out what it is.

So in the diagram below you will see **Arduino A** setting its Analog Pin 0 as *OUTPUT* and write a value 2 every 500ms. On **Arduino B** we have Analog Pin 0 set as *INPUT* to receive and print data to Serial. The *GND* pins of both Arduinos are also connected.

When this setup is executed, **Arduino B** is constantly receiving data in the form of a 3 digit number starting with 3XX. I am starting to believe this is voltage value?

***What is inherently wrong with this idea?***

![enter image description here][1]

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

body: `analogWrite()` on the Uno doesn't actually output an analog value. It outputs a PWM wave whose *average* is equivalent to that value. If you want to turn it into a true analog value then you need to put it through a low-pass filter in order to remove the components that make it a PWM wave instead.


body:
This answer provides both Arduino specific knowledge and general electrical knowledge - both are necessary for a good solution (unfortunately).

_________________

Summary

To carry out Arduino analog to analog transfer:
-

 - Use analogWrite(pin, value) on a valid **digital** pin (see below)

 - Use analogRead(pin) on a valid analog input pin.

 - Connect a series resistor between the two pins - say 10k.
 Place a capacitor from the analog input to ground, say 100 nF to 10 uF.

The R & C act as a low pass filter to convert the PWM to DC.
Details below.

_____________

Arduino analog pins are ONLY for analog input, not for analog output.
So trying to do analog out on an analog pin dooms your attempt to failure.

Arduino analogWrite(pin, value) only works on DIGITAL pins and then only on the subset of digital pins that have PWM capability. This is typically digital pins 3 5 6 9 10 11.

"analogWrite(pin, value)  produces as others have said - a PWM signal - rail to rail square waves with mark space ratio that varies so the mean DC value changes. For a 5V system  =
V_DC_mean ~~= value/256 x 5V.
Where 'value' comes from analogWrite(pin, value)

To convert the PWM to good-enough DC a low pass filter with a cutoff somewhat below the PWM frame rate is needed. AFAIK Arduino PWM frame rate is about 800 Hz -  so components are usually higher than that. A simple RC filter where R x C is usefully more than about 0.001S will start to work . Larger RC is smoother but with secondary effects. Using a 10 uF ceramic cap and a 10k resistor is probably OK. 10 uF x 10k = 0.1S. 1uF and 1k = 0.001 s = marginal. An electrolytic cap can be used but leakage current may slightly affect accuracy. So -

_______________

From somewhere in Arduino land (unknown) I copied the material below.
This is NOT in the basic reference, but should be.

 - Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite() on the same pin). The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.

 On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.

 The Arduino Due supports analogWrite() on pins 2 through 13, plus pins DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs.


body:
As has been mentioned above, using analogWrite won't work. (I suppose you could sample the supposed analogue signal with a fast loop and measure the duty cycle...)

Why not use `SoftwareSerial` to send data between the two Arduinos?

It's a library which creates another serial port, entirely in software, so it's independent of the main UART on the USB port.

It's already part of the IDE and it's easy to use - in fact the demo code on the help page will already work for you, transferring any characters from the USB serial port to the software serial port.


body:
If your aim is to send a constant value from Arduino A to Arduino B, then a really easy way is to use SoftwareSerial.

Let's say you are using Arduino Uno - you can use pins 2 and 3 for SoftwareSerial (see which pins are supported for which device at http://arduino.cc/en/Reference/SoftwareSerial)

Cross connect pin 2 and 3 from Arduino A to pin 3 and 2 of Arduino B. You can send any random data between the two Arduinos by uploading a sketch like the following on to each. You can use a program like CoolTerm to have a "SerialMonitor" open to each Arduino (using the Arduino IDE, you can open only one monitor at a time)

The advantage of this approach over using AnalogWrite/AnalogRead is that with AnalogRead, you can only get 1024 values, which is based on the voltage. With SoftwareSerial, you can send any arbitrary data.

    // include the SoftwareSerial library so you can use its functions:
    #include <SoftwareSerial.h>

    #define rxPin 2
    #define txPin 3

    SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin);

    void setup() {
        pinMode(rxPin, INPUT);
        pinMode(txPin, OUTPUT);

        mySerial.begin(9600);

        Serial.begin(9600);
     }

    void loop() {

        if ( mySerial.available() )
        {
             while ( mySerial.available() )
                 Serial.write(mySerial.read());

             Serial.println();
        }

        if ( Serial.available() )
        {
            delay(5);

            while ( Serial.available() )
                mySerial.write( Serial.read() );
        }

    }


body:
As others have pointed out, your original suggestion will not work.

You could use PWM output and a filter which may work (you will need quite a large capacitor and/or resistor). The input at the other end would only be an approximation of the output (you could calculate based on detailed knowledge of component values and frequencies). Depending on the rate at which the value changes you may get different values on each read.

There are better ways. As suggested, serial will work (either hardware or software depending on other factors), and is probably easiest. You could use any of the common communication protocols (I²C or SPI) or even send values via IP.


body:
The Analog In does exactly what it says - it only reads (samples) analog voltage levels.

Using AnalogWrite(0,2) does not make pin A0 in Analog In to output the voltage of 2*AVCC/1024, but instead makes the pin D0 to do that instead. (Most D0 pins on Arduino boards do not have a PWM output associated with them, so the behaviour would be undefined.) In the mean time, your A0 is doing nothing.
(I suspect it's floating / not connected, hence the 3xx value. Could check the datasheet to be sure.)

So what should we do instead? For a start, connect Arduino B's A0 to Arduino A's pwm pin. If you're using Uno, you can connect to any of the pins 11,10,9,6,5,3. Then you can use the code:

int PWMPin = 11;
int SignalLvl = 2;
analogWrite(PWMPin,SignalLvl);

Give that a try. And you'll see that it works... sort of.

But then there's a problem. your readings will be close to what you want, but quite erratic. The reason is partly because analog signals are super unreliable and is filled with noise. But the main reason is really that Arduino's analogWrite is actually NOT designed as an analog signal output. It is a PWM, which outputs GND and AVcc levels at variable periods at a fast speed so that it approximates the voltage level you want when averaged.

If you want to experiment with this, you can connect a resistor and capacitor to the output, creating  a low pass filter. (Here's more info: http://provideyourown.com/2011/analogwrite-convert-pwm-to-voltage/)

---------------------

Having said all that, I guess the question most of us would like to ask is: is there a reason why you want to send data via analog? Analog signals are prone to noise. If data fidelity is critical, your best best is to use serial communication as highlighted by most answers here.

For simplicity, I suggest I2c which uses only 2 wires to communicate. If speed is of essence (like, writing to 10,000 bytes of data every second) you could try SPI or even parallel communication.

Hope this helps and good luck!


message:
Compiling is slow

Compilation of even the simplest program (like Blink) is extremely slow, the progress bar often hangs halfway for nearly half a minute.

![enter image description here][1]

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

Is this normal? I understand that not all computers are equally fast, but there's a huge difference between 3 seconds and 30 seconds

**edit**
It appears from the report that every time I switch programs they're built anew completely:

> Build options changed, rebuilding all

even when nothing has been changed. How can I avoid a complete rebuild?

body: I would download the non-install version and try compiling the blink sketch in it.  This will let you know if it is a computer specific issue or something related to your install.  I experienced something similar with a library that wasn't updated correctly between versions which caused all sorts of buggy behavior.


body:
The occurrence of “Build options changed, rebuilding all” (as mentioned in edited question and shown in screen shot) probably is causing the large delay.  My belief (correct or not) is that lots of libraries are being rebuilt when that message appears.  Ordinarily, libraries should be rebuilt only upon initial install or when changing target board type.

An [arduino.cc thread](http://forum.arduino.cc/index.php?topic=271617.0), “"Build options changed, rebuilding all" even when nothing changes ==> very slow”, from 2014 treats the issue superficially, merely pointing out that Arduino 1.5.8 Beta is suitable for Yún and Arduino Due boards, not “regular Arduino” boards.

A 2011 [Google code](https://code.google.com/p/arduino/issues/detail?id=638) thread probably is mostly irrelevant, but it's worth trying some steps mentioned in posts #14 and 15  ‒ eg, starting arduino via a path with no spaces in names ‒ if your platform is MS Windows.  If the Arduino IDE cannot find its options or preference files it probably assumes it is starting from scratch.

Note, please edit the question to specify how you started the Arduino IDE running, where the IDE is installed on your system, what your op system is, and what your computer is.


body:
I have found that this is a common issue across my development machines, however using Visual Micro for Visual Studio reduces this time by a significant factor.

I primarily use it for other Visual Studio features like Intellisense, refactoring, and solution management. Visual Micro has some compelling features of its own, like debugging tools, however I haven't used them.

 - [Visual Micro][1]
 - [Visual Studio Community Edition][2]

I haven't personally tried, but I would expect that you can avoid the rebuild using the project/solution options in Visual Studio - I found that the compile time is fast enough in most cases with this environment for it to not matter.

  [1]: http://www.visualmicro.com/
  [2]: https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx


body:
If you find compilation slow then yes, it is probably recompiling things that it doesn't really need to recompile.  This has always been a major failing of the Arduino environment, and is one of the major impetuses for the complete re-write of the whole compilation system in my IDE [UECIDE](http://uecide.org).

That includes very aggressive caching of compiled library and core files as proper ".a" files which are stored away separate from your board selection and kept until something really does need compiling.  That way the first time you compile something for a board it may take 30 seconds, 50 seconds, whatever.  All subsequent compilations for that same board, even for different sketches (not including the compilation time of "fresh" libraries) would be around 2 seconds, even less.

That caching is especially important when you're running on a very slow system, such as a Raspberry Pi, when compiling can take many minutes without the caches in place, but only a few seconds on all subsequent compilations.


body:
This thread, [Arduino IDE and ESET: Slow compilation][1], may be helpful if you use ESET (at least one user has reported that it helped), but it didn't help me since I'm using Comodo (and may be there are some other reasons).

Here's another thread, [SLOW ARDUINO IDE][2] regarding a solution which helped many users, since 2009 (the latest comment on the forum is dated year 2014).

Several useful posts here as well, [Unbelievable slow compilation of simple sketches][3]. Ok, I haven't tested all the solutions myself, but let me collect useful links here so that other guys can find them and I'll check them out, too.

  [1]: http://forum.arduino.cc/index.php?topic=215107.0
  [2]: http://www.johngineer.com/blog/?p=97
  [3]: http://forum.arduino.cc/index.php?topic=82527.15


body:
I had the same problem until today. Like many answers around the web, the problem seems to come from the anti-virus. My setup is Windows 10 x64 with a SSD and I use Windows Defender as the AV.

I tried by excluding the main arduino folder in "c:\program files (x86)\arduino", but it didn't improve the compilation time.

I checked the "verbose" option in the Arduino IDE and I've seen that it was calling the compiler from the AppData folder. So I add this folder to my AV exclusion list and it worked!

The compilation time improve by ten folds.

**TLDR;** In Windows 10, add the folder in %USERPROFILE%\AppData\Local\Arduino15 to the AV exclusion list.


message:
Arduino Uno with crystal

Are there Arduino UNO R3s which use a crystal instead of a ceramic resonator?

(Frankly, I don't understand this cheapness: if you really want to save on component cost you can run both AVRs on the same crystal. The 16U2 always has a crystal.)

body:
Some of the [Freeduino][1] boards use crystals although the newer ones now use a cheaper USB to serial chip (the CH340) instead of the Atmel chip used on the Arduino Uno.

The [diavolino][2] is another build-it-yourself board that has a crystal. I am sure there are many others. The [ruggeduino][3] is another that uses a crystal and also markets itself as being practically indestructible. Their ["How to Destroy an Arduino"][4] is well worth a read for things to avoid doing to your Uno.

  [1]: http://www.freeduino.org/about.html
  [2]: http://shop.evilmadscientist.com/productsmenu/tinykitlist/180
  [3]: http://www.ruggedcircuits.com/ruggeduino
  [4]: http://www.ruggedcircuits.com/10-ways-to-destroy-an-arduino/


body:
It appears that the Arduino Leonardo uses a crystal:

![enter image description here][1]

On the Sparkfun site it's the same price as the Uno R3, so I think I'll go for the Leonardo.

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


message:
Cannot program Arduino Micro in OSX without hard resetting the board every time

I am experiencing a problem when programming Arduino Micro in OSX Mavericks. I have tried to reproduce this problem in XCode and Arduino IDE and it is persistent. I need to make a hard-reset at the same time as a click the "program" button.

I have tried to use the new Leonardo bootloader to see if it solves my issue, but its still persistent.

I am running avrdude 6.1, what is the problem?

Stacktrace:

    ---- Size ----

    Binary sketch size:   24162 bytes (of a 28672 byte maximum)
    Estimated SRAM used:  733 bytes (of a 2560 byte maximum)
    Elapsed time: 5.2 s

    ---- Reset ----

    screen -X kill

    No screen session found.

    make: [reset] Error 1 (ignored)

    sleep 1

    9.2-RESET:  <   micro ./ ./

    stty -f /dev/tty.usbmodem1411 1200

    ---- Upload ----

    10.6-UPLOAD:  <   micro ./

    /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avrdude -patmega32u4 -C/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf -D -cavr109 -b57600 -P/dev/tty.usbmodem1411 -Uflash:w:Builds/embeddedcomputing.hex:i

    Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

body:
This [Arduino.cc article][1] describes the differences between Leonard & Micro vs. other Arduinos, including the fact that Micro does not have a separate USB processor on board but creates a virtual USB with the main processor. There is no (or a very different) auto-reset mechanism. There is apparently a way for the IDE to open the Mac's USB at 1200 baud to cause the Micro to reset; then the IDE can wait for the virtual USB to re-appear. But it also says you may need to use the reset button suggesting the 1200 baud dance doesn't work all that reliably.

  [1]: http://arduino.cc/en/Guide/ArduinoLeonardoMicro


message:
Unable to flash bootloader on ATmega32U4 with AVR dragon

I am flashing a _naked_ ATmega32U4, but the process fails in the end where it is verifying.

    avrdude -c dragon_isp -p m32u4 -P usb -U flash:w:Caterina-Micro.hex -U lfuse:w:0xff:m -U hfuse:w:0xd8:m -U efuse:w:0xcb:m -U lock:w:0x2f:m -v -B 100

    avrdude: Version 6.1, compiled on Mar 23 2014 at 04:42:55
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "/usr/local/Cellar/avrdude/6.1/etc/avrdude.conf"
             User configuration file is "/Users/SomeUser/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : usb
             Using Programmer              : dragon_isp
             Setting bit clk period        : 100.0
    avrdude: usbdev_open(): Found AVRDRAGON, serno: 00A200050468
    JTAG ICE mkII sign-on message:
    Communications protocol version: 1
    M_MCU:
      boot-loader FW version:        255
      firmware version:              7.38
      hardware version:              1
    S_MCU:
      boot-loader FW version:        255
      firmware version:              7.38
      hardware version:              7
    Serial number:                   00:a2:00:05:04:68
    Device ID:                       AVRDRAGON
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : DRAGON_ISP
             Description     : Atmel AVR Dragon in ISP mode
             Vtarget         : 5.0 V
             SCK period      : 100.37 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.16s

    avrdude: Device signature = 0x1e9587
    avrdude: safemode: lfuse reads as FF
    avrdude: safemode: hfuse reads as D8
    avrdude: safemode: efuse reads as CB
    avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
             To disable this feature, specify the -D option.
    avrdude: erasing chip
    avrdude: reading input file "Caterina-Micro.hex"
    avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
    avrdude: writing flash (32730 bytes):

    Writing | ################################################## | 100% 62.28s

    avrdude: 32730 bytes of flash written
    avrdude: verifying flash memory against Caterina-Micro.hex:
    avrdude: load data flash data from input file Caterina-Micro.hex:
    avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
    avrdude: input file Caterina-Micro.hex contains 32730 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 152.35s

    avrdude: verifying ...
    avrdude: verification error, first mismatch at byte 0x0002
             0x66 != 0x6e
    avrdude: verification error; content mismatch

    avrdude: safemode: lfuse reads as FF
    avrdude: safemode: Verify error - unable to read hfuse properly. Programmer may not be reliable.
    avrdude: safemode: lfuse reads as FF
    avrdude: safemode: Verify error - unable to read hfuse properly. Programmer may not be reliable.
    avrdude: safemode: Sorry, reading back fuses was unreliable. I have given up and exited programming mode

    avrdude done.  Thank you.

I get another verification error when i program without fuses:

    avrdude -c dragon_isp -p atmega32u4 -P usb -U flash:w:Caterina-Micro.hex -u

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.16s

    avrdude: Device signature = 0x1e9587
    avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
             To disable this feature, specify the -D option.
    avrdude: erasing chip
    avrdude: reading input file "Caterina-Micro.hex"
    avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
    avrdude: writing flash (32730 bytes):

    Writing | ################################################## | 100% 69.60s

    avrdude: 32730 bytes of flash written
    avrdude: verifying flash memory against Caterina-Micro.hex:
    avrdude: load data flash data from input file Caterina-Micro.hex:
    avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
    avrdude: input file Caterina-Micro.hex contains 32730 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 178.10s

    avrdude: verifying ...
    avrdude: verification error, first mismatch at byte 0x0000
             0x04 != 0x0c
    avrdude: verification error; content mismatch

    avrdude done.  Thank you.

body:
I think you need to pass the option `-u` to disable safe mode, see the [avrdude documentation](http://www.nongnu.org/avrdude/user-manual/avrdude_4.html#Option-Descriptions). Under the `-u` option the manual states:

>If you want to change fuses you will need to specify this option


body: I literally gave up and got myself a Atmel-ICE which solved all my problems.


message:
estimating battery run time

I have a project which runs a continuous loop and listens for the push of a button to light an led and activate a servo motor on an Arduino Uno (R2). The arduino is powered by 4 AA batteries, and the servo is powered by a 9V. I'm wondering how long I can leave this running off battery power. Does anyone know how to estimate this? As a side note, if anyone spots a way to improve battery life in my sketch / wiring, I'd love to know.

Below is my code and attached is the wiring diagram for the project (minus the batteries).

        #include <Servo.h>

    const int buttonPin = 2;     // the number of the pushbutton pin
    boolean buttonPushed = false;

    const int ledPin =  13;      // the number of the LED pin

    const int servoPin = 9;
    Servo servo;
    int angle = 0;
    int servoStartAngle = 90;
    int servoEndAngle = 10;

    boolean servoActivated = false;

    // variables will change:
    int buttonState = 0;         // variable for reading the pushbutton status

    int photoCellPin = 2;
    int photoCellThreshold = 500;
    int photoCellActivated = false;

    void setup() {
      Serial.begin(9600);
      // initialize the LED pin as an output:
      pinMode(ledPin, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);

      servo.attach(servoPin);
      servo.write(servoStartAngle);

    }

    void loop(){
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);

      int photoCellVal = analogRead(photoCellPin);

      if (photoCellVal > photoCellThreshold){
       photoCellActivated = true;
      } else {
       photoCellActivated = false;
      }

      // check if the pushbutton is pressed.
      // if it is, the buttonState is HIGH:
      if (buttonState == LOW && buttonPushed == false) {
        // turn LED on:
        buttonPushed = true;
        Serial.println("button pushed");
      } else if (buttonState == LOW && buttonPushed == true){
       buttonPushed = false;
       Serial.println('deactivate');
      }

      if (buttonPushed == true){
       digitalWrite(ledPin, HIGH);
      } else {
       digitalWrite(ledPin, LOW);
      }

      if (buttonPushed && servoActivated == false && photoCellActivated == true){
        servoActivated = true;
        Serial.println("activate motor");

        for(angle = servoStartAngle; angle > servoEndAngle; angle--){
          servo.write(angle);
          Serial.println(angle);
          delay(15);
        }
      } else if (buttonPushed == false && servoActivated == true){ //deactivate
        for(angle = servoEndAngle; angle < servoStartAngle; angle++){
          servo.write(angle);
          Serial.println(angle);
          delay(15);
        }
        delay(200);
        servoActivated = false;

      }

      delay(200);
    }

body:
I can support what mheavers said in a comment above. Use a Bareduino or any kind of custom Board, use sleep-modes and avoid delay(). I wrote a blog-post about my experiences with this setup [here][1], if you get it right the ATmel can go down below 1mA in sleep. In your case an extreme scenario (depending on your usage pattern) could be to wake-up the Arduino with an interrupt triggered through the sensor and otherwise sleep completely. You will find example on the net where people used a setup like this for remote controls for instance.

  [1]: https://holadimake.wordpress.com/2015/01/02/building-a-cellular-tracker-part3-running-on-batteries-for-months/


body:
>I'm wondering how long I can leave this running off battery power. Does anyone know how to estimate this?

If your circuit draws 1A @ 12V, a 12V 1Ah battery will power it for approximately one hour. A 9V alkaline typically contains about 565mAh. You can use the datasheets to sum all the power consumption, but its probably easier just to measure it with a multimeter.

> As a side note, if anyone spots a way to improve battery life in my
> sketch / wiring, I'd love to know.

-Check out the ATTiny series ([parametric][1]); they are tiny, low-power, and Arduino-compatible; perfect when you only need a couple of pins.

-Use an interrupt to monitor the button's pin; the MCU can sleep until the interrupt fires.

Generally:
1) The interrupt will set a flag so main() knows that something happened, then wake the processor.
2) Main() resumes, checks the flag, turns on/off the LED accordingly, tells the servo where to go, waits for the servo to get there (delay()), clears the flag, and then puts the MCU back to sleep.

-As others have pointed out, delay() is bad. delay() tells the MCU to **do nothing** (NO-OP) repeatedly, for a period of time. This is different from having **nothing to do** because it's asleep.

  [1]: http://www.atmel.com/v2PFResults.aspx#(actives:!(8238,8394,8362,8282,8431,8300,8358,8392,8378,8445,8236,8449,8474,8248,8264,8447,8256,8254,8286,8462,8429,8458,8466,8400,8302,8278),data:(area:'',category:'34864[33180[33086]]',pm:!((i:8238,v:!(1,7)),(i:8394,v:!(0,7)),(i:8362,v:!(5,12)),(i:8282,v:!(5)),(i:8431,v:!(1,8)),(i:8300,v:!(1,5)),(i:8358,v:!(1,19)),(i:8392,v:!(0,1)),(i:8378,v:!n),(i:8445,v:!(5,6,9)),(i:8236,v:!(0,9)),(i:8449,v:!(1,3)),(i:8474,v:!(0)),(i:8248,v:!(0,1)),(i:8264,v:!(1,2)),(i:8447,v:!(0,1)),(i:8256,v:!(1,4)),(i:8254,v:!(3,16)),(i:8286,v:!(0)),(i:8462,v:!(0,2)),(i:8429,v:!(1,2)),(i:8458,v:!(0,1)),(i:8466,v:!(4)),(i:8400,v:!(0,7)),(i:8302,v:!(0)),(i:8278,v:!(0))),view:table),sc:1)


message:
Can i use arduino code, without using arduino board but just using MCU included

I am developing a product, and to ease my job i am planning to use MCU inside the arduino with the library of Arduino.

Since all the registers are already defined inside the library, and all required things to registers of corresponding MCU are done to "make a pin input/output , enable interrupt , enable UART , enable I2C". I think that i can directly use the arduino coding enviroment even if i use MCU seperately.

Is it possible and how?  (can i use it in commertial product, i have already prototyped it with arduino)

body: Yes, you can. Once you have a .hex file for a specific MCU and environment you can use a programmer to upload it to a discrete MCU.


body:
Ignacio said everything is needed. Just search on google :) You can use programmer like [khazama][1].

Also you can use arduino board to program atmel chips.
[Using an Arduino as an AVR ISP ][2]

And now you need only .hex file to upload to your chip

[How to find .HEX][3]

I just want to point out one thing. Do not play with lock bits:)

  [1]: http://khazama.com/project/programmer/
  [2]: http://arduino.cc/en/Tutorial/ArduinoISP
  [3]: https://alselectro.wordpress.com/2014/01/26/where-are-the-hex-files-compiled-by-arduino/


body:
You can program an AVR microcontroller easily with an existing Arduino as the programmer. AFAIK there's no easy way around SMD packages. The last time I've gotten them, I have to solder programming wires on them before placing it on the board. If you have space, you can also wire the ISP pins to a connector on the board.

In any case, here are the steps to program your chip, whether DIP or SMD.

1. Upload the Arduino ISP Sketch to your Arduino board's MCU.
2. Wire up the Vcc and GND, and the SPI pins (MOSI,MISO,SCL). (The wiring is actually described in the comment section of the sketch. As for the pin out on the ATmega328, go to [page 3][1]. You can find similar datasheets if you're using other MCUs.)
3. Write your code
4. Click "File>Upload using programmer" or just press Ctrl + Shift + U.
5. Done!

I think most AVR MCUs come with an internal calibrated resonator, but if you want to drive it at a higher speed (16MHz/20MHz...) you will need to connect the MCU to a crystal oscillator. As always, refer to the datasheet. ;-)

Here's another link you can refer to: [link][2]

Hope this helps.

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
  [2]: http://arduino.cc/en/Tutorial/ArduinoToBreadboard


message:
fast memory buffer and setting output state

I'm intending to set up a digital delay using a circular buffer (in SRAM) with an Arduino Due (@84MHz). The lenth of the buffer determines the delay. I need about 1us resolution and the delay needs to be dynamically settable between 0 - 500us. I'll probably use most of the memory just for the buffer.

I've got a very basic setup going (with a fixed delay, no buffer), that just updates a temporary variable with the current state of the input signal and then writes the whole word to another port in order to set the state.

Next up is designing the buffer so I can add some delay to the output of the signal.

Filling the buffer using interrupts watching signals on the same port shouldn't be too difficult but I am wondering:

a) taking speed in consideration, which buffer method will have the least processing overhead? Memory stack or an array[], or someting else?

b) is there a way to read a port and set an output port in one clock cycle? I am now using `REG_PIOD_ODSR=outbyte;` but ideally it needs to point to a memory address directly.

body:
I would use an array, they're about as simple as it gets. 84 clock cycles per sample is very tight, but definitely possible. I'm guessing that's too close to the line to do any sort time testing - you will probably have to set up your loop to take exactly 84 instructions. This means you will probably need to hand-code in assembler. Be very mindful of branching instructions - both branches will need to take the same number of clock cycles.

The Uno (AtMega328) runs most (all?) instructions in one clock cycle, I don't know if the same applies to the Due. You would need to hand-code the assembler, check out how many cycles each instruction takes, and pad it out (there is a do nothing "NOP" instruction, which typically takes one cycle.

HOWEVER -

You can get all this work done for you by using a chip made for this purpose. This is called a Digital Delay Line, http://en.wikipedia.org/wiki/Digital_delay_line (or Analog Delay Line if you want analog values, e.g. for sound playback).


message:
Simulink with arduino : data acquisition

I'm working on data acquisition from a sensor attached to the Arduino : MPU6050 using a model in Ssimulink. I have installed the hardware support in Simulink but I don't know how to start building the model. The model must read the data from the Arduino by deploying it into the Arduino.

My connection Arduino <=> MPU6050 is :

    Arduino    MPU 9150
    3.3V       VCC
    GND        GND
    A5         SCL
    A4         SDA
    DIGITAL 2  INT
    GND        AD0

update : i have use a s-function but I get the following error:
_The call to realtime_make_rtw_hook, during the after_make hook generated the following error: Could not download the model to the target hardware. Verify the connection between the computer and target hardware.

The build process will terminate as a result.

Caused by: Could not download the model to the target hardware. Verify the connection between the computer and target hardware._

But the target is definitely connected, and downloading others module (like led blinking ) with simulink is working fine. I've also tested this on a different PC with Windows 8 (64bits) with the same result. Can anyone give me a hint please?

body:
I just made my GY-521(MPU6050) work with Simulink using s-function.
I wish this would be helpful for you.

I am using an Arduino MEGA 2650 board. The sensor data is read in in real time.
Note that currently only Arduino MEGA 2650, Arduino MEGA 2650 ADK, and Arduino DUE support the real time windows target.
If you are using other types of board, this answer may not applied.

Your hardware connection looks correct. But if you have some troubles you can refer to mine for checking:

    5v VCC
    GND GND
    SCL SCL(check the register map of your board)
    SDA SDA(check the register map of your board)

Above four connections are adequate if you just read raw sensor data.
INT is needed if you are going to read fused data. But I did not try that.

Next you may write a small program in Arduino IDE to ensure everything works.
You can refer to the Arduino MPU6050 examples.
The code written here will be used to construct your Simulink s-function later.

Now you can start to build your Simulink block using s-function builder.
If you did not do this before, here is a good tutorial:

https://m.youtube.com/watch?v=_OLctOFjjYQ

In our case, you need to copy Wire.h, twi.h and their .c counterparts in your current working directory where your s-function resides.

And do not forget to rename generated .c file to .cpp, and add external "C" declaration. All of these are illustrated in above video tutorial.

After all of above are done, you turn your simulation mode to external, and run.
You can view your sensor data in scope if everything goes right.

----------------

Source code and configuration used in my function:
I include all headers in the `Libraries` panel of S-Function Builder,

    #ifndef MATLAB_MEX_FILE
    #define ARDUINO 100
    #include <Arduino.h>
    #include <Wire.h>
    #include <Wire.cpp>
    #include <twi.h>
    #include <twi.c>
    #define MPU 0x68
    #endif

Wire.* and twi.* files are copied from Arduino IDE's directory. I put these files along with my S-Function block file.

The address of I2C is 0x68 here.

Next, the code for sensor outputs are placed in `Outputs` panel. And do not forget to add ports in `Data Properties` panel.

    #ifndef MATLAB_MEX_FILE
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 14, true);

    int raw = Wire.read() << 8;
    raw = raw | Wire.read();
    ax[0] = (float)raw / 8192.0f;

    raw = Wire.read() << 8;
    raw = raw | Wire.read();
    ay[0] = (float)raw / 8192.0f;

    raw = Wire.read() << 8;
    raw = raw | Wire.read();
    az[0] = (float)raw / 8192.0f;

    raw = Wire.read() << 8;
    raw = raw | Wire.read();
    temp[0] = (float)raw / 340.0f + 36.53f;

    raw = Wire.read() << 8;
    raw = raw | Wire.read();
    gx[0] = (float)raw / 131.0f;

    raw = Wire.read() << 8;
    raw = raw | Wire.read();
    gy[0] = (float)raw / 131.0f;

    raw = Wire.read() << 8;
    raw = raw | Wire.read();
    gz[0] = (float)raw / 131.0f;
    #endif

Finally, initialization and configuration are done in `Discrete Update` panel.

    #ifndef MATLAB_MEX_FILE
    if (xD[0] != 1) {
        Wire.begin();

        /* Do not sleep */
        Wire.beginTransmission(MPU);
        Wire.write(0x6B);
        Wire.write(0);
        Wire.endTransmission(true);

        /* Gyroscope full scale range: 250 degs/s */
        Wire.beginTransmission(MPU);
        Wire.write(0x1B);
        Wire.write(0);
        Wire.endTransmission(true);

        /* Accelerometer full scale range: 4g */
        Wire.beginTransmission(MPU);
        Wire.write(0x1C);
        Wire.write(8);
        Wire.endTransmission(true);

        xD[0] = 1;
    }
    #endif

Please refer to your board's datasheet for specific address and LSB scales. I am using GY-521 here.


message:
use shiftIn and shiftOut with attiny85

I want my Attiny85 to communicate with another attiny85.
one attiny should send a message to my other attiny. When he receives the correct message he should turn one led on. Just a very simple test scatch.
I don't know why but the led never turns on.

Here is my code:

1st attiny85:

    int clk_pin = 4,
        data_pin = 3,
        led = 0;

    void setup() {
      pinMode(clk_pin, INPUT);
      pinMode(data_pin, INPUT);
      pinMode(led, OUTPUT);
    }

    void loop() {
      byte incoming = shiftIn(data_pin, clk_pin, LSBFIRST);

      if (incoming == 2)
      {
        digitalWrite(led, HIGH);
        delay(1000);
        digitalWrite(led, LOW);
        delay(1000);
      }
    }

2nd attiny:

    int clk_pin = 0,
        data_pin = 1;

    void setup(){
      pinMode(clk_pin, OUTPUT);
      pinMode(data_pin, OUTPUT);
    }

    void loop(){
      byte test = 2;
      shiftOut(data_pin, clk_pin, LSBFIRST, test);

      delay(5000);
    }

I think there might be something wrong with my shiftIn/shiftOut command. It's actually the first time I'm using this.

Thanks for helping!

body:
`shiftIn()` and `shiftOut()` are designed for communicating with different types of shift registers. These are typically external components which don't run code themselves, such as the 74HC595.

You can't use `shiftIn()` to read data that's been written using `shiftOut()`. The reason is that both functions try to act as the host in the communication -- i.e. the one that controls the clock line.

When you call `shiftIn()`, the clock line is pulsed each time it's ready to read a bit (i.e. it tells the shift register when to write). When you call `shiftOut()`, the clock line is pulsed each time it writes a bit (i.e. it tells the shift register when to read).

Neither one will respond to a clock line provided externally. The result is that your ATTiny's aren't synchronised so they won't be reading/writing at the same time.

A much simpler approach would be to setup a conventional serial connection between the two microcontrollers. You could do that either using [software][1] or [hardware][2] serial. The only caveat is that the sender would need to ensure the receiver is up-and-running before it transmits anything. This could be done using some kind of handshake at startup -- one device repeatedly sends something until the other replies.

  [1]: http://arduino.cc/en/Reference/SoftwareSerial
  [2]: http://arduino.cc/en/Reference/Serial


message:
Pulse measurement

I am currently doing the project in pulse measurement using an [Arduino Yún][1]. I am using the pulse sensor SEN-11574.

When I verify the code I get this error:

    Arduino: 1.5.8 (Linux), Board: "Arduino Yún"

    pulse-sensor-arduino/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduino/pulse-sensor-arduino.cpp:39: multiple definition of `pulsePin'
    sketch_feb10a.cpp.o:/home/system1/Downloads/arduino-1.5.8/sketch_feb10a.ino:18: first defined here
    pulse-sensor-arduino/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduino/pulse-sensor-arduino.cpp:39: multiple definition of `Pulse'
    sketch_feb10a.cpp.o:/home/system1/Downloads/arduino-1.5.8/sketch_feb10a.ino:18: first defined here
    collect2: error: ld returned 1 exit status
    Error compiling.

This is my code:

    #include <pulse-sensor-arduino.h>

    int pulsePin = 0;
    int blinkPin = 13;
    int fadePin = 5;
    int fadeRate = 0;

    volatile int BPM;
    volatile int Signal;
    volatile int IBI = 600;
    volatile boolean Pulse = false;
    volatile boolean QS = false;

    void setup() {

        pinMode(blinkPin, OUTPUT);
        pinMode(fadePin, OUTPUT);
        Serial.begin(115200);
    }

    void loop() {

        sendDataToProcessing('S', Signal);
        if (QS == true) {
            fadeRate = 255;
            sendDataToProcessing('B',BPM);
            sendDataToProcessing('Q',IBI);
            QS = false;
        }

        ledFadeToBeat();

        delay(5000);
    }

    void ledFadeToBeat() {
        fadeRate -= 15;
        fadeRate = constrain(fadeRate,0,255);
        analogWrite(fadePin,fadeRate);
    }

    void sendDataToProcessing(char symbol, int data ) {
        Serial.print(symbol);
        Serial.println(data);
    }

This is my pulse Arduino cpp file:

    #include "pulse-sensor-arduino.h"

    volatile int rate[10];                        // Array to hold last ten IBI values
    volatile unsigned long sampleCounter = 0;     // Used to determine pulse timing
    volatile unsigned long lastBeatTime = 0;      // Used to find IBI
    volatile int P =512;                          // Used to find peak in pulse wave, seeded
    volatile int T = 512;                         // Used to find trough in pulse wave, seeded
    volatile int thresh = 512;                    // Used to find instant moment of heart beat, seeded
    volatile int amp = 100;                       // Used to hold amplitude of pulse waveform, seeded
    volatile boolean firstBeat = true;            // Used to seed rate array so we startup with reasonable BPM
    volatile boolean secondBeat = false;          // Used to seed rate array so we startup with reasonable BPM
    volatile boolean Pulse = false;               // True when pulse wave is high, false when it's low
    volatile int pulsePin;

    volatile int PulseSensor::IBI = 600;          // Holds the time between beats, must be seeded!
    volatile int PulseSensor::BPM;                // Used to hold the pulse rate
    volatile int PulseSensor::Signal;             // Holds the incoming raw data
    volatile boolean PulseSensor::QS = false;     // Becomes true when Arduino finds a beat

    void PulseSensor::begin(int pPin)
    {
      pinMode(pulsePin, INPUT);
      pulsePin = pPin;

      // Initializes Timer1 to throw an interrupt every 2 ms.
      TCCR1A = 0x00;
      TCCR1B = 0x0C;  // CTC (Compare match mode) and ClockIO/256
      OCR1A = 0x7C;   // 2 ms
      TIMSK1 = 0x02;
      sei();          // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
    }

    // THIS IS THE TIMER 1 INTERRUPT SERVICE ROUTINE.
    // Timer 1 makes sure that we take a reading every 2 miliseconds
    ISR(TIMER1_COMPA_vect)
    {                         // Triggered when Timer1 counts to 124
      cli();                                      // Disable interrupts while we do this
      PulseSensor::Signal = analogRead(pulsePin); // Read the Pulse Sensor
      sampleCounter += 2;                         // Keep track of the time in ms with this variable
      int N = sampleCounter - lastBeatTime;       // Monitor the time since the last beat to avoid noise

      // Find the peak and trough of the pulse wave
      if(PulseSensor::Signal < thresh && N > (PulseSensor::IBI/5)*3){       // Avoid dichrotic noise by waiting 3/5 of last IBI
        if (PulseSensor::Signal < T){                        // T is the trough
          T = PulseSensor::Signal;                         // Keep track of lowest point in pulse wave
        }
      }

      if(PulseSensor::Signal > thresh && PulseSensor::Signal > P){          // Threshold condition helps avoid noise
        P = PulseSensor::Signal;                             // P is the peak
      }                                        // Keep track of highest point in pulse wave

      //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
      //
      // The signal surges up in value every time there is a pulse
      if (N > 250){                                   // Avoid high-frequency noise
        if ( (PulseSensor::Signal > thresh) && (Pulse == false) && (N > (PulseSensor::IBI/5)*3) )
        {
          Pulse = true;                               // Set the Pulse flag when we think there is a pulse
          PulseSensor::IBI = sampleCounter - lastBeatTime;         // Measure time between beats in mS
          lastBeatTime = sampleCounter;               // Keep track of time for next pulse

          if(secondBeat){                        // If this is the second beat, if secondBeat == TRUE
            secondBeat = false;                  // Clear secondBeat flag
            for(int i=0; i<=9; i++){             // Seed the running total to get a realisitic BPM at startup
              rate[i] = PulseSensor::IBI;
            }
          }

          if(firstBeat){                         // If it's the first time we found a beat, if firstBeat == TRUE
            firstBeat = false;                   // Clear firstBeat flag
            secondBeat = true;                   // Set the second beat flag
            sei();                               // Enable interrupts again
            return;                              // IBI value is unreliable so discard it
          }

          // Keep a running total of the last 10 IBI values
          word runningTotal = 0;                  // Clear the runningTotal variable

          for(int i=0; i<=8; i++){                // Shift data in the rate array
            rate[i] = rate[i+1];                  // And drop the oldest IBI value
            runningTotal += rate[i];              // Add up the 9 oldest IBI values
          }

          rate[9] = PulseSensor::IBI;                          // add the latest IBI to the rate array
          runningTotal += rate[9];                // Add the latest IBI to runningTotal
          runningTotal /= 10;                     // Average the last 10 IBI values
          PulseSensor::BPM = 60000/runningTotal;               // How many beats can fit into a minute? that's BPM!
          PulseSensor::QS = true;                              // Set Quantified Self flag
          // QS FLAG IS NOT CLEARED INSIDE THIS ISR
        }
      }

      if (PulseSensor::Signal < thresh && Pulse == true){   // When the values are going down, the beat is over
        Pulse = false;                         // Reset the Pulse flag so we can do it again
        amp = P - T;                           // Get amplitude of the pulse wave
        thresh = amp/2 + T;                    // Set thresh at 50% of the amplitude
        P = thresh;                            // Reset these for next time
        T = thresh;
      }

      if (N > 2500){                           // If 2.5 seconds go by without a beat
        thresh = 512;                          // Set thresh default
        P = 512;                               // Set P default
        T = 512;                               // Set T default
        lastBeatTime = sampleCounter;          // Bring the lastBeatTime up to date
        firstBeat = true;                      // Set these to avoid noise
        secondBeat = false;                    // When we get the heartbeat back
      }

      sei();                                   // Enable interrupts when youre done!
    } // end ISR

This is my pulse Arduino header file:

    #ifndef PULSE_SENSOR_ARDUINO_H
    #define PULSE_SENSOR_ARDUINO_H

    #include "Arduino.h"

    class PulseSensor
    {
    public:
      static void begin(int pulsePin);

      static volatile int BPM;
      static volatile int Signal;
      static volatile int IBI;
      static volatile boolean QS;
    };

    #endif

I modified the program, but there is a new error present:

    Arduino: 1.5.8 (Linux), Board: "Arduino Yún"

    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::begin(int)'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `pulsePin'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `__vector_17':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:54: multiple definition of `__vector_17'
    pulsesensor.cpp.o:pulsesensor.cpp:54: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::Signal'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `sampleCounter'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `lastBeatTime'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.thresh+0x0): multiple definition of `thresh'
    pulsesensor.cpp.o:(.data.thresh+0x0): first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data._ZN11PulseSensor3IBIE+0x0): multiple definition of `PulseSensor::IBI'
    pulsesensor.cpp.o:(.data._ZN11PulseSensor3IBIE+0x0): first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.T+0x0): multiple definition of `T'
    pulsesensor.cpp.o:(.data.T+0x0): first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.P+0x0): multiple definition of `P'
    pulsesensor.cpp.o:(.data.P+0x0): first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `Pulse'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `rate'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::BPM'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `PulseSensor::QS'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.firstBeat+0x0): multiple definition of `firstBeat'
    pulsesensor.cpp.o:(.data.firstBeat+0x0): first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o: In function `PulseSensor::begin(int)':
    /home/system1/Arduino/libraries/pulse-sensor-arduinom/pulse-sensor-arduino.cpp:39: multiple definition of `secondBeat'
    pulsesensor.cpp.o:pulsesensor.cpp:39: first defined here
    pulse-sensor-arduinom/pulse-sensor-arduino.cpp.o:(.data.amp+0x0): multiple definition of `amp'
    pulsesensor.cpp.o:(.data.amp+0x0): first defined here
    collect2: error: ld returned 1 exit status
    Error compiling.

Here is my change code

    #include <pulse-sensor-arduino.h>

    int blinkPin = 13;                // Pin to blink LED at each beat
    int fadePin = 5;                  // Pin to do fancy classy fading blink at each beat
    int fadeRate = 0;                 // Used to fade LED on with PWM on fadePin

    void setup(){
      pinMode(blinkPin,OUTPUT);         // Pin that will blink to your heartbeat!
      pinMode(fadePin,OUTPUT);          // Pin that will fade to your heartbeat!
      Serial.begin(115200);             // We agree to talk fast!

    }

    void loop(){
      sendDataToProcessing('P', PulseSensor::Signal);     // Send Processing the raw Pulse Sensor data
      if (PulseSensor::QS == true){                       // Quantified Self flag is true when arduino finds a heartbeat
        fadeRate = 255;                  // Set 'fadeRate' Variable to 255 to fade LED with pulse
        sendDataToProcessing('B',PulseSensor::BPM);   // Send heart rate with a 'B' prefix
        sendDataToProcessing('Q',PulseSensor::IBI);   // Send time between beats with a 'Q' prefix
        PulseSensor::QS = false;                      // Reset the Quantified Self flag for next time
      }

      ledFadeToBeat();

      delay(5000);                             //  Take a break
    }

    void ledFadeToBeat(){
      fadeRate -= 15;                         //  Set LED fade value
      fadeRate = constrain(fadeRate,0,255);   //  Keep LED fade value from going into negative numbers!
      analogWrite(fadePin,fadeRate);          //  Fade LED
    }

    void sendDataToProcessing(char symbol, int data ){
        Serial.print(symbol);                // Symbol prefix tells Processing what type of data is coming
        Serial.println(data);                // The data to send culminating in a carriage return
    }

My cpp file:

    #include "pulse-sensor-arduino.h"

    volatile int rate[10];                        // Array to hold last ten IBI values
    volatile unsigned long sampleCounter = 0;     // Used to determine pulse timing
    volatile unsigned long lastBeatTime = 0;      // Used to find IBI
    volatile int P =512;                          // Used to find peak in pulse wave, seeded
    volatile int T = 512;                         // Used to find trough in pulse wave, seeded
    volatile int thresh = 512;                    // Used to find instant moment of heart beat, seeded
    volatile int amp = 100;                       // Used to hold amplitude of pulse waveform, seeded
    volatile boolean firstBeat = true;            // Used to seed rate array so we startup with reasonable BPM
    volatile boolean secondBeat = false;          // Used to seed rate array so we startup with reasonable BPM
    volatile boolean Pulse = false;               // True when pulse wave is high, false when it's low
    volatile int pulsePin;

    volatile int PulseSensor::IBI = 600;          // Holds the time between beats, must be seeded!
    volatile int PulseSensor::BPM;                // Used to hold the pulse rate
    volatile int PulseSensor::Signal;             // Holds the incoming raw data
    volatile boolean PulseSensor::QS = false;     // Becomes true when Arduino finds a beat

    void PulseSensor::begin(int pPin)
    {
      pinMode(pulsePin, INPUT);
      pulsePin = pPin;

      // Initializes Timer1 to throw an interrupt every 2 ms.
      TCCR1A = 0x00;
      TCCR1B = 0x0C;  // CTC (Compare match mode) and ClockIO/256
      OCR1A = 0x7C;   // 2 ms
      TIMSK1 = 0x02;
      sei();          // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
    }

    // THIS IS THE TIMER 1 INTERRUPT SERVICE ROUTINE.
    // Timer 1 makes sure that we take a reading every 2 miliseconds
    ISR(TIMER1_COMPA_vect)
    {                         // Triggered when Timer1 counts to 124
      cli();                                      // Disable interrupts while we do this
      PulseSensor::Signal = analogRead(pulsePin);              // read the Pulse Sensor
      sampleCounter += 2;                         // Keep track of the time in ms with this variable
      int N = sampleCounter - lastBeatTime;       // Monitor the time since the last beat to avoid noise

      //  Find the peak and trough of the pulse wave
      if(PulseSensor::Signal < thresh && N > (PulseSensor::IBI/5)*3){       // Avoid dichrotic noise by waiting 3/5 of last IBI
        if (PulseSensor::Signal < T){                        // T is the trough
          T = PulseSensor::Signal;                         // Keep track of lowest point in pulse wave
        }
      }

      if(PulseSensor::Signal > thresh && PulseSensor::Signal > P){          // Threshold condition helps avoid noise
        P = PulseSensor::Signal;                             // P is the peak
      }                                        // Keep track of highest point in pulse wave

      //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
      // signal surges up in value every time there is a pulse
      if (N > 250){                                   // Avoid high frequency noise
        if ( (PulseSensor::Signal > thresh) && (Pulse == false) && (N > (PulseSensor::IBI/5)*3) )
        {
          Pulse = true;                               // Set the Pulse flag when we think there is a pulse
          PulseSensor::IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
          lastBeatTime = sampleCounter;               // Keep track of time for next pulse

          if(secondBeat){                        // If this is the second beat, if secondBeat == TRUE
            secondBeat = false;                  // Clear secondBeat flag
            for(int i=0; i<=9; i++){             // Seed the running total to get a realisitic BPM at startup
              rate[i] = PulseSensor::IBI;
            }
          }

          if(firstBeat){                         // If it's the first time we found a beat, if firstBeat == TRUE
            firstBeat = false;                   // Clear firstBeat flag
            secondBeat = true;                   // Set the second beat flag
            sei();                               // Enable interrupts again
            return;                              // IBI value is unreliable so discard it
          }

          // Keep a running total of the last 10 IBI values
          word runningTotal = 0;                  // Clear the runningTotal variable

          for(int i=0; i<=8; i++){                // Shift data in the rate array
            rate[i] = rate[i+1];                  // And drop the oldest IBI value
            runningTotal += rate[i];              // Add up the 9 oldest IBI values
          }

          rate[9] = PulseSensor::IBI;                          // Add the latest IBI to the rate array
          runningTotal += rate[9];                // Add the latest IBI to runningTotal
          runningTotal /= 10;                     // Average the last 10 IBI values
          PulseSensor::BPM = 60000/runningTotal;               // How many beats can fit into a minute? that's BPM!
          PulseSensor::QS = true;                              // Set Quantified Self flag
          // QS FLAG IS NOT CLEARED INSIDE THIS ISR
        }
      }

      if (PulseSensor::Signal < thresh && Pulse == true){   // When the values are going down, the beat is over
        Pulse = false;                         // Reset the Pulse flag so we can do it again
        amp = P - T;                           // Get amplitude of the pulse wave
        thresh = amp/2 + T;                    // Set thresh at 50% of the amplitude
        P = thresh;                            // Reset these for next time
        T = thresh;
      }

      if (N > 2500){                           // If 2.5 seconds go by without a beat
        thresh = 512;                          // Set thresh default
        P = 512;                               // Set P default
        T = 512;                               // Set T default
        lastBeatTime = sampleCounter;          // Bring the lastBeatTime up to date
        firstBeat = true;                      // Set these to avoid noise
        secondBeat = false;                    // When we get the heartbeat back
      }

      sei();                                   // Enable interrupts when youre done!
    } // end ISR

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

body:
(1)The declaration

     volatile boolean Pulse = false;

occurs in two locations.

Is that intended?

(2) Also

    volatile int PulseSensor::BPM;                // used to hold the pulse rate
    volatile int PulseSensor::IBI = 600;          // holds the time between beats, must be seeded!
    volatile int PulseSensor::Signal;             // holds the incoming raw data


message:
Arduino program wont work properly for some reason

I have a arduino program that I wrote with my teammembers. We are working on a project and try to move a RC car. Here is our code.

    int forward =12 ; //assign to correlating pin attached to TP06
    int backward = 11; //assign to correlating pin attached to TP07
    int left = 10; //assign to correlating pin attached to (left steer)
    int right = 9; //assign to correlating pin attached to (right steer)

    // TP09 & TP02 (don't remember which is left and right)

    void setup() {
    pinMode(forward, OUTPUT);
    pinMode(backward, OUTPUT);
    pinMode(left, OUTPUT);
    pinMode(right, OUTPUT);
    }

    void move_Forward() {
    digitalWrite(forward, HIGH);
    digitalWrite(backward, LOW);
    }

    void move_Backward() {
    digitalWrite(backward, HIGH);
    digitalWrite(forward, LOW);
    }

    void turn_Left() {
    digitalWrite(left, HIGH);
    digitalWrite(right, LOW);
    }

    void turn_Right() {
    digitalWrite(right, HIGH);
    digitalWrite(left, LOW);
    }

    void stop_Completely() {
    digitalWrite(forward, LOW);
    digitalWrite(backward, LOW);
    digitalWrite(right, LOW);
    digitalWrite(left, LOW);
    }

    // loop will keep going while arduino has power
    void loop() {
    move_Forward();
    turn_Left();
    }

When we run this code, for some reason forward pin and left pins are becoming deactivated, which are the pin numbers 12 and 10. Like it does not supply voltage anymore for some reason. However right pin and backward pins, which are pins 9 and 11, which was not included in loop, works! I can run the RC car with these pins. I dont understand why this is the case. Shouldn't the left and forward pins work? If they are not working, how come? Sorry I am new to arduino programming language and its been very challenging for me and my group. Thanks in advance.

body:
On many Arduinos, those pins (10-12) are shared with the ICSP header - are you programming/testing with it plugged in or unplugged? If plugged in, you might be affected by what you're plugged into.

Here's a useful pinout: http://t.co/MKtmCILSdj

Here's a Nano pinout: ![Nano pinout][1]

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

Note that the ICSP is electrically connected to pins D11, D12 and D13 - so if you have something plugged into the ICSP header, you have something connected to those pins which might be causing your problem.

If you're programming via serial port (TX/RX) and have nothing connected to ICSP, then this isn't your issue. If that's a case, it's possible to fry a few pins on a Nano and have it still appear to mostly work - trying another couple of pins might tell you more. (For instance, try D4 and D5 instead of D10 and D12.)


body: Have you tested this on more than one Arduino? My first Arduino board had a dead UART. Took me weeks and purchasing a second Arduino to figure it out. It worked well enough to not initially suspect the UART (I'm not a complete idiot). ;)


body:
First: turn off the old direction before turning on the new one. Now you're doing it the other way around.

Then, in your main loop you're repeating forward and left over and over. I guess you want to move forward for some time, then turn left, then move forward again, etc.
But moving forward does deactivate the reverse, but doesn't change left or right. So you're always repeating commands which haven't been changed in the first place: forward will always be active, and so will left be. You'll go in a circle, I don't know if that is the idea.

If you want to go straight, you'll probably want to turn off both left and right? Then add a delay before turning; right now your commands occur within microseconds of each other.


message:
Value of the counter collide on my lcd while decreasing. How can I remove it?

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

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12,11,5,4,3,2);
    int visitor=0;  //variable for counting visitor number

    unsigned long timer_1,timer_2;  //variables for recording time for ir_1 and ir_2

    void setup() {
       lcd.begin(20,4);
       pinMode(A0,INPUT);
       pinMode(A1,INPUT);
    }

    void loop(){
     lcd.setCursor(0,4);
       lcd.print("visitor=");
       lcd.setCursor(8, 4);

       lcd.print(visitor);

       if(digitalRead(A0)==1 && digitalRead(A1)==0)
      {
        timer_1= millis();
      }
      if(digitalRead(A0)==0 && digitalRead(A1)==1)
      {
        timer_2= millis();
      }
      if(timer_1>timer_2)
      {
       lcd.setCursor(8,4);
       visitor=visitor+1;
       lcd.print(visitor);
       delay(2000);
       timer_1=0;
       timer_2=0;
      }
     else if(timer_1<timer_2)
      {
       lcd.setCursor(8,4);
       visitor=visitor-1;
        if (visitor<=0)
      {
        visitor=0;
      }
       lcd.print(visitor);
       delay(2000);
       timer_1=0;
       timer_2=0;

      }

    }

Two IR sensors are placed in A0 and A1.

While the value of `visitor` is decreasing from 10 to 9 the LCD is showing 90 because  the '0' of previous 10 is here. How can I remove it?

body:
A simple option would be to call `lcd.clear()` at the start of `loop()`. That will clear the entire LCD display. Everything else should work fine because it looks like you're outputting the entire display contents every time round.

Alternatively, you could remove the extra digit by printing a space over it, e.g.:

    if (visitor < 10) print(" ");
    lcd.print(visitor);

If `visitor` is a 1-digit number (i.e. less than 10), it will output a space at the start, getting rid of any underlying digits leftover from a previous iteration. If you want the number to be left-aligned then you could print the space after the number instead.


message:
create a interruption-proof power

I need to create a interruption-proof power for a project of mine, very similar to the design [of this link][1].

My problem is that I need to adjust the current delivered of the solar panel (21V, 1.2A) to 5V and simultaneously charge a battery 12V, 18Ah. If the solar panel does not supply power, the battery takes its place.

Does anyone know any circuit to do something? Or can someone give me a light as do something?

  [1]: http://www.feirinhadigital.com.br/rbr/ham/projetos-usuarios/NO-BREAK/nobreak.htm

body:
Rough block diagrams below show two ways this can be achieved - "Easiest" costs least but is inefficient. "Better" uses PV panel output more efficiently. Details of either can be discussed if of interest.

'Schottky diodes' should be used to minimise losses.

(1) "Easiest"

Connect PV panel to battery with diode.
Panel is clamped to battery voltage (+ diode drop).
This will not hurt the PV panel but wastes some of the available power.
[What is the formal PV panel specification. Is it 21V O/C or loaded or .... Do you have a datasheet link for it?].

Use 12V (nominal) to 5V converter to power load.
This could be

 - A linear regulator - only about 40% efficient - very wasteful.

 - A buck converter (build or buy from eg ebay)

![enter image description here][1]

(2) "Better"

Use a buck regulator to charge the battery - ideally an MPPT (maximum power point transfer) controller. Details can be discussed if you are interested.

Use a second buck regulator to power the load. This must be capable of (at least) 11V to 22V input. Power this from a Schottky diode from the PV panel AND a Schottky diode from the battery. When the panel voltage is > battery voltage the panel will power the load.

![enter image description here][2]

  [1]: https://i.stack.imgur.com/8Vxlt.jpg
  [2]: https://i.stack.imgur.com/T4GsC.jpg