message:
SMS in modem's memory

I am working on SMS communication with my phone and Arduino. My intension is simple. When somebody send an SMS, the Arduino should read a text file located on my server and forward the content to the same number.

The problem here is, when I send an SMS to my Arduino, which is waiting for my message, it does not read my message. But when I separately run this [example code][1], I see my SMS is received. It means my SMS is already present in the modem memory. But why does this happen? How to solve this? Here is my code:

    // libraries
    #include <GSM.h>

    // PIN Number
    #define PINNUMBER ""

    // APN data
    #define GPRS_APN       "GPRS_APN" // replace your GPRS APN
    #define GPRS_LOGIN     "login"    // replace with your GPRS login
    #define GPRS_PASSWORD  "password" // replace with your GPRS password

    // initialize the library instance
    GSMClient client;
    GPRS gprs;
    GSM gsmAccess;
    GSM_SMS sms;

    // URL, path & port (for example: arduino.cc)
    char server[] = "yourdomain.com";
    char path[] = "/current.txt";
    int port = 80; // port 80 is the default for HTTP

    char k[30];
    char z = '*';
    int s=0;
    String place;
    char remoteNum[20];  // telephone number to send sms

    void setup() {
        // initialize serial communications and wait for port to open:
        Serial.begin(9600);
        while (!Serial) {
            ; // wait for serial port to connect. Needed for Leonardo only
        }
        Serial.println("SMS connected");
        // connection state
        boolean notConnected = true;
        while(notConnected) {
            if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
               (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
                notConnected = false;
            else {
                Serial.println("Not connected");
                delay(1000);
            }
        }
        Serial.println("GPRS connected...");
        Serial.println("Server Connecting.");
        // if you get a connection, report back via serial:
        serverr();
    }

    void loop() {
        if (sms.available()) {
            Serial.println("Message received from:");
            sms.remoteNumber(remoteNum, 20);
            Serial.println(remoteNum);
            sms.flush();
            Serial.println("MESSAGE DELETED");
        }
    }

    void smss() {
      // I just want phone number
        if (client.available()) {
            char c = client.read();
            //***************************************************
            //       Filtering a specific message
            //**************************************************
            if (z==c) {
                s=1;
            }
            if(s == 1) {
                int i=0;
                k[i] = c;
                i=i+1;
                // Serial.print(k);
            }
            place +=k;
            //Serial.print(place);
        }
        //***************************************************

        if (!client.available() && !client.connected()) {
            sms.beginSMS(remoteNum);
            Serial.print("Place =");
            Serial.print(place);
            sms.print(place);
            sms.endSMS();
            sms.flush();
            Serial.println("MESSAGE DELETED");
            Serial.println();
            Serial.println("disconnecting.");
            client.stop();
            // do nothing forevermore:
            for(;;)
                ;
        }
    }

    // if you didn't get a connection to the server:
    // Serial.print(server);

    void serverr() {
        if (client.connect(server, port)) {
            client.print("GET /current.txt");
            Serial.print("GET /current.txt");
            client.println(" HTTP/1.1");
            Serial.println(" HTTP/1.1");
            client.println("Host: www.yourdomain.com");
            Serial.println("Host: www.yourdomain.com");
            client.println("User-Agent: Arduino");
            Serial.println("User-Agent: Arduino");
            client.println("Accept: text/html");
            Serial.println("Accept: text/html");
            client.println("Connection: close");
            Serial.println("Connection: close");
            client.println();
            Serial.println();

            Serial.println("\nCOMPLETE!\n");
            //client.stop();
        } else {
            Serial.println("connection failed");
            Serial.println("\n FAILED!\n");
        }
    }

  [1]: http://arduino.cc/en/Reference/GSMSMSRead

body:
I see one problem with the global structure of your program; everytime `loop()` is run, it:

1. checks if an SMS is present, and gets the originating phone number if present, otherwise it just goes on, ie `smss()` function returns **without** modifying `remoteNumber`
2. send an SMS to `remoteNumber`

One problem here is that your `loop()` will repeatedly try to send an SMS to the same `remoteNumber` even if no SMS was received; actually, to solve this issue, you should modify `smss()` to:

- either **wait (forever) for an SMS to be received** and return only in this situation
- or **return a value (eg `bool`) that indicates whether an SMS was received** or not; then an SMS should be sent if and only if an SMS was just received.

Here is an example:

    void setup()
    {
        GSM and GPRS initialization
        Connection to server
    }

    void loop()
    {
        if (smss())
        {
            Reading the txt file content in server

            sms.beginSMS(remoteNum);
            sms.print(txtMsg);
            sms.endSMS();
        }
    }

    bool smss() // I just want phone number
    {
        if (sms.available())
        {
            Serial.println("Message received from:");
            sms.remoteNumber(remoteNum, 20);
            Serial.println(remoteNum);
            sms.flush();
            Serial.println("MESSAGE DELETED");
            return true;
        }
        return false;
    }

Note that this code does not integrate error support as it should; indeed `sms.remoteNumber()` may return error codes (any value `>1`), in which case you should consider no SMS was received at all.


sender: user

message:
digital pin's current limit, ohm's law and DC motor

A digital pin's output voltage on an UNO board is 5V, which is equal to the output from the VCC. I read that the DC current limits of those pins are 40mA and 200mA respectively, and that a higher current could damage the board. Now, since **V=RI**, I expect to get the same current whether I connect a DC motor to the VCC or to a digital pin. But, the motor spins slower when connected to the digital pin. Therefore, I'm not getting the same current, and the only thing I could think of in order to explain this apparent contradiction with ohm's law is that there must be some mechanism to keep the current flowing through a digital pin inferior to 40mA. But I also read somewhere (can't find/remember the source) that there are no such mechanisms (except for a fuse concerning the USB)... So as you see, I can't understand what's going on. It will be really nice if someone could explain that to me... thanks in advance!

sender: assistant

body:
The ATmega (or any other processor that could reasonably be used on an Arduino) output pins consist of a `Totem Pole` driver with a PMOS transistor which can drive the output towards Vdd and an NMOS transistor which can drive it towards ground.  Each of these can be modeled as a switch which has a small resistance when "on", and due to device physics the PMOS transistor has a higher resistance than the NMOS.

The 40ma figure is an "Absolute Maximum" rating - a limit above which damage could be possible.  At some current less than that, it is likely the voltage drop across the PMOS transistor will start to be great enough that the output voltage can only marginally be considered a logic "high" - it **will be notably less than the supply**.

Connecting your motor to an ATmega pin is an extreme, **far out of spec**.  When you do that, the voltage drop across the PMOS transistor is much larger, making the output voltage quite low.  Additionally, the current flowing through the resistance produces heat within the chip, which can (at least as a rule-of-thumb concern) lead to damage.  Finally, your motor will produce `inductive kickback`, "spike" voltage possibly high enough to pierce the gate oxide of the MOS gates in the chip, destroying it.  `Latchup` is another possibility - a *sometimes temporary* condition where the bulk of the die ends up biased to conduct in the wrong direction and the chip effectively shorts out its power supply, turning it into a *miniature space heater*.

**There really are no components on your typical Arduino board designed to directly control a motor.**

Instead, for unidirectional control you should use a circuit with an `NPN` bipolar transistor, `NMOS FET`, magnetic relay, or solid state relay.  The latter are commonly available pre-assembled on shields.  With a transistor solution driving the motor in only one direction, it is generally advisable to pick an NPN transistor or NFET and place it in the negative lead of the motor, as the N devices work better due to the greater mobility of electrons than electron-holes.

For bidirectional control, look for a `motor shield` based on an `H bridge` IC such as the `TB6612FNG` or the less efficient bipolar `L298` or `L293`/`SN754410`.  This basically puts a high current `Totem Pole` driver on each lead of the motor, allowing you to drive them high & low for one direction or low & high for the other.


message:
Problems with using example code for Wi-Fi shield (arduino)

I have problems with the Wi-Fi shield example code.

    #include <SPI.h>
    #include <WiFi.h>

    char ssid[] = "*****";          //  your network SSID (name)
    char pass[] = "*****";   // your network password

    int status = WL_IDLE_STATUS;
    char servername[]="google.com";  // remote server we will connect to

    WiFiClient client;

    void setup() {
        Serial.begin(9600);
        //disable SD SPI
        pinMode(4, OUTPUT);
        digitalWrite(4, HIGH);

        Serial.println("Attempting to connect to WPA network...");
        Serial.print("SSID: ");
        Serial.println(ssid);

        status = WiFi.begin(ssid, pass);
        if ( status != WL_CONNECTED) {
            Serial.println("Couldn't get a wifi connection");
            // don't do anything else:
            while(true);
            }
         else {
         Serial.println("Connected to wifi");
         Serial.println("\nStarting connection...");
         // if you get a connection, report back via serial:
         if (client.connect(servername, 80)) {
             Serial.println("connected");
             // Make a HTTP request:
             client.println("GET /search?q=arduino HTTP/1.0");
             client.println();
          }
        }
    }

     void loop() {

    }

The Wi-Fi Shield has connected with the internet Wi-Fi, but the last printing was "Starting connection..." I can't get to connect to (google.com), why?

body:
I had this problem aswell. The problem was a bug with the official editor of arduino. I fixed this by downgrading the editor to version 1.0.3. (from 1.0.5) You can find a download link for it at the Arduino website.

Hope this helped!<br>
-Kad


body:
Have you upgraded the firmware in your wifi shield? If not, it will have problems connecting. Compile and upload this sketch. If it shows the firmware version as 1.0.0, then you need to upgrade the firmware. If it shows 1.1.0, then it is current as of today.

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

    #include <SPI.h>
    #include <WiFi.h>

    void setup() {
      //Initialize serial and wait for port to open:
      Serial.begin(9600);

      // check for the presence of the shield:
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");
        // don't continue:
        while(true);
      }

      Serial.print("Firmware version: ");
      Serial.println(WiFi.firmwareVersion());
    }

    void loop() {}

Please Note: The chips are numbered differently but run the same Wi-Fi firmware. You can upgrade the firmware without any worries.


body:
    #include <WiServer.h>

    #define WIRELESS_MODE_INFRA 1
    //#define WIRELESS_MODE_ADHOC 2

    // Wireless configuration parameters ----------------------------------------
    unsigned char local_ip[] = {146, 227, 174, 29};      // Indirizzo IP
    unsigned char gateway_ip[] = {146, 227, 175, 254};     // Indirizzo gateway IP
    unsigned char subnet_mask[] = {255, 255, 248, 0};   // Subnet Mask
    const prog_char ssid[] PROGMEM = {"enduroam"};     // SSID access point

    unsigned char security_type = 3; // 0 - open; 1 - WEP; 2 - WPA; 3 - WPA2

    // WPA/WPA2 passphrase
    const prog_char security_passphrase[] PROGMEM = {"EAP-MSCHAP V2"}; // max 64 characters
    // setup the wireless mode
    // infrastructure - connect to AP
    // adhoc - connect to another WiFi device
    unsigned char wireless_mode = WIRELESS_MODE_INFRA;

    unsigned char ssid_len;
    unsigned char security_passphrase_len;
    // End of wireless configuration parameters ----------------------------------------
    // This is our page serving function that generates web pages
    boolean sendMyPage(char* URL) {

        // Check if the requested URL matches "/"
        if (strcmp(URL, "/") == 0) {
            // Use WiServer's print and println functions to write out the page content
            WiServer.print("<html>");
            WiServer.print("Hello World!");
            WiServer.print("</html>");

            // URL was recognized
            return true;
        }
        // URL not found
        return false;
    }

    void setup() {
      // Initialize WiServer and have it use the sendMyPage function to serve pages
      WiServer.init(sendMyPage);

      // Enable Serial output and ask WiServer to generate log messages (optional)
      Serial.begin(57600);
      WiServer.enableVerboseMode(true);
    }

    void loop(){

      // Run WiServer
      WiServer.server_task();

      delay(10);
    }


message:
Arduino Pro Micro, get data out of Tx pin?

I have a [Sparkfun Arduino Pro Micro with an ATmega32u4 on it][1] and a [Roving Networks RN32 Bluetooth Module][2]

Theoretically, I should be able to solder the Rx of the Bluetooth to the Tx on the arduino and vice versa and I should get serial communication over the Bluetooth.

Of course, I do not. However, as a first question: How do I get my Arduino to transmit data over the Tx pin?

I uploaded this to the Arduino with no hiccups:
<!-- language-all: lang-cpp -->

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

    void loop(){
      Serial.print("HelloWurld");
    }

However, when I plug up my o-scope, I see no signal over the Tx line. Nada. I see data coming over the USB into the COM port on my computer, but nothing over the Tx pin.

How do I get the Arduino to put out serial data on the Tx pin?

  [1]: https://www.sparkfun.com/products/12640
  [2]: https://www.sparkfun.com/products/10253

body:
The bluetooth board uses **3.3V**, not 5V according the [datasheet][1].

So you'll need to **shift the voltage level** between it and the Arduino board (which is **5V**). Note that the spec sheet shows how this can easily be done with 2 resistors (`R1` and `R2` in sheet typical application circuit, page 5).

Also, on the bluetooth module, the RS232 interface has 4 pins:

- UART_TX
- UART_RX
- **UART_CTS**
- UART_RTS

**UART_CTS** must be **0** to ensure the device reads incoming bytes. Normally this is done by an internal pulldown resistor, but you must ensure you did not connect that pin to **+V**.

Finally, ensure that the baud rate of the module is properly set to **9600 bauds**, the same as in your program.

  [1]: https://www.sparkfun.com/datasheets/Wireless/Bluetooth/rn-42-ds.pdf


body:
You appear to have a "pro micro" style board in which the USB communication is directly sourced from the main ATmega32u4 processor, rather than generated as serial data and then forwarded to a distinct USB-serial converter as on traditional Arduinos.   *Your question could have been resolved much more quickly if you had clearly stated the type of board you were using in words, rather than only as a product link (so I edited that into your question)*.

According to the [documentation][1] for the official Arduino Pro Micro:

> Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data using the ATmega32U4 hardware serial capability. Note that on the Micro, the Serial class refers to USB (CDC) communication; for TTL serial on pins 0 and 1, use the Serial1 class.

Therefore to generate output on the hardware UART you will need to change all occurrences of `Serial` to `Serial1`

    void setup(){
        Serial1.begin(9600);
    }

    void loop(){
        Serial1.print("HelloWurld");
    }

The transmit data will be sourced from ATmega32u4 pin 21 which is "D1" (digital pin 1) on the headers.  If you wish to probe it, that would be the best place to do so.

If you wish to transmit data out of a **different pin** which is not connectied to the ATmega32u4's UART (as your example with digital pin 5 hints you might) you must instead use [SoftwareSerial][2] or similar implementation to bit-bang the serial data out of a general purpose I/O pin.

For example (inspired by [this example][3]):

    SoftwareSerial mySerial(4, 5); // RX, TX

    void setup(){
        mySerial.begin(9600);
    }

    void loop(){
        mySerial.print("HelloWurld");
    }

  [1]: http://arduino.cc/en/Main/arduinoBoardMicro
  [2]: http://arduino.cc/en/Tutorial/SoftwareSerialExample
  [3]: http://arduino.cc/en/Tutorial/SoftwareSerialExample


body:
Just hook up the serial pins from the bluetooth module to the corresponding Pro Micro pins: TX to RX and RX to TX. I hope this can help someone.

Then look for data like this:

    void setup(){
       Serial1.begin(9600); // Init Hardware Serial port on pins 0 and 1 - Bluetooth
       Serial.begin(9600); // Init Virtual Serial Port - Machine

       Keyboard.begin(); // Init HID - Keyboard
    }

    void loop(){
       if (Serial1.available() > 0) {

         char myData = Serial1.read()

         // Send data from Bluetooth/Sensor to the Machine - Virtual Serial Port
         Serial.println(myData);

         // Emulate HID Device - Keyboard
         if ( myData == 0x7F ) { // Detect code of android backspace key
            Keyboard.write(0xB2); //  Convert received code char to PC/Linux ascii keycode for the backspace key. This can change between different OS!
         }

         else {
            Keyboard.write(myData);
         }

       }
    }


body:
You also may want to try the "[SoftwareSerial][1]" library.  That way you can use almost any pins you want for serial comms.  As a matter of fact, you can have a couple of serial ports.

Please do read up on the SoftwareSerial library though.  It does have some restrictions.

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


body:
So I stumbled upon this thread while having similar problem, but with HC-05 module. So because I have too much free time on my hands during finals (no I don't) I decided to create a small github repo that might help someone sometime. https://github.com/Sackhorn/HC-05-Pro-Micro-Hookup

The code is:

    //Writen for pro micro
    //These proved to be usefull
    //http://arduino.stackexchange.com/questions/1471/arduino-pro-micro-get-data-out-of-tx-pin
    //https://forum.sparkfun.com/viewtopic.php?f=32&t=38889&sid=8178cdb38005ff33cc380a5da34fb583&start=15

    void setup()
    {
      pinMode(9, OUTPUT);
      digitalWrite(9, HIGH);
      Serial.begin(9600);
      Serial1.begin(38400);
    }

    void loop()
    {

      //Serial1 is the physical Serial Connections on TX and RX pins
      if (Serial1.available()) Serial.write(Serial1.read());

      // Serial is from my understanding the virtual connection with computer via USB
      if (Serial.available()) Serial1.write(Serial.read());
    }

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

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


message:
Can I load programs through the RS232 pins?

Can I upload new programs onto a MEGA2560 through a serial port connected to pins 2&3?  (through the correct RS232<->TTL level shifters)

I know the 16U2 chip acts as a USB->serial converter and it also asserting the reset which starts the bootloader running on the 2650. Does it do anything else?

As long as I can time the reset correctly, is there anything else preventing reprogramming directly through the RX/TX pins?

And if I do this, will the application program still be able to use the serial channel?

body:
The stock bootloader will accept the load of new programs on PE0(RX input) and PE1(TX output) (of the ATmega2560) just after reset. Note PE0/1 on the Arduino correspond to pins D0 and D1. Not D2 and D3. You could change the Boot loader if desired.

There is a 1K series resistor between the 16U2 and 2560's PE0/1. So you can directly connect your external TTL serial port's TX(out) to PE0(D0), without harm. And correspondingly connect PE1(D1) to the TTL Serial port's RX(in).

Next you need to synchronize the bootloader. Either by manually synchronizing the Reset of the 2560 with the starting of the download (of AVRdude). Or by connecting the DTR(out) of the TTL Serial Port through a 100nF capacitor to the RESET pin of the Arduino.

I would also recommend putting the 16U2 into reset, to get it out of the way. Simply place a jumper between ICSP1's RESET2(pin5) and GND(pin6).


message:
Setting up the MMA8452 to trigger interrupt

I am working with the MMA8452q accelerometer by Freescale.  I am trying to set it up to be in low power mode, to go to sleep when no motion has happened, and to wake up due to motion being detected and trigger the  interrupt that corresponds to it.  I am using Arduino.

I have verified the accelerometer works (i.e. can read off accelerometer data and communicate properly to it via I2C), and I have also verified that the interrupt and handler all work (by manually triggering the interrupt as compared to using the accelerometer).  However, after initializing using the code below, my interrupt due to motion is not getting triggered.

-The datasheet can be found here: http://www.freescale.com/files/sensors/doc/data_sheet/MMA8452Q.pdf

-App note can be found here: http://cache.freescale.com/files/sensors/doc/app_note/AN4074.pdf

My code is as follows:

    void MMA8452::initMMA8452(unsigned char fsr)
    {
        //CONFIGURE THE ACCELEROMETER
        MMA8452Standby();  // Must be in standby to change registers

        //Set up the full scale range to 2, 4, or 8g.
        if ((fsr==2)||(fsr==4)||(fsr==8))
            writeRegister(XYZ_DATA_CFG, fsr >> 2);
        else
            writeRegister(XYZ_DATA_CFG, 0);

        writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | bmRES1DOT56);  //1.56Hz resolution in both wake and sleep mode (lowest power)
        writeRegister(CTRL_REG2, readRegister(CTRL_REG2) | (LP << SMODS) | (LP << MODS) | (1 << SLPE));  //LOW POWER MODE IN SLEEP & ACTIVE STATES WITH LOWEST SAMPLING

        writeRegister(CTRL_REG3, (1 << WAKE_FF_MT));  //ONLY WAKE UP FROM MOTION DETECTION
        writeRegister(CTRL_REG4, (1 << INT_EN_ASLP) | (1 << INT_EN_FF_MT));  //ENABLE SLP/AWAKE INTERRUPT (INTERRUPT THROWN WHENEVER IT CHANGES) & MOTION INTERRUPT TO KEEP AWAKE
        writeRegister(ASLP_COUNT, ASLP_TIMEOUT); //162s TIMEOUT BEFORE SLEEPING

        writeRegister(CTRL_REG5, (1 << INT_CFG_FF_MT) | (1 << INT_CFG_ASLP));  //INTERRUPT SLEEP AND FREE FALL TO INT1 PIN OF MMA8452

        //SETUP THE MOTION DETECTION
        writeRegister(FF_MT_CFG, (1 << ELE) | (1 << OAE));   //MOTION DETECTION AND LATCH THE RESULT WHEN IT HAPPENS AS OPPOSED TO COMBINATIONAL REAL TIME
        writeRegister(FF_MT_THS, MOTION_THRESHOLD);     //MOTION DETECTION THRESHOLDS
        writeRegister(FF_MT_COUNT, MOTION_DEBOUNCE_COUNT);   //TIME MOTION NEEDS TO BE PRESENT ABOVE THE THRESHOLD BEFORE INTERRUPT CAN BE ASSERTED

        MMA8452Active();
    };

body:
I played around more with it, and this code works:

    void MMA8452::initMMA8452(unsigned char fsr, unsigned char dr, unsigned char sr, unsigned char sc, unsigned char mt, unsigned char mdc)
    {
     MMA8452Standby();

 //Set up the full scale range to 2, 4, or 8g.
 if ((fsr==2)||(fsr==4)||(fsr==8))
  writeRegister(XYZ_DATA_CFG, fsr >> 2);
 else
  writeRegister(XYZ_DATA_CFG, 0);

 writeRegister(CTRL_REG1, readRegister(CTRL_REG1) & ~(0xF8));
 if (dr<= 7)
  writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | (dr << DR0));
 if (sr<=3)
  writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | (sr << ASLP_RATE0));

 writeRegister(CTRL_REG2, readRegister(CTRL_REG2) | (LP << SMODS) | (LP << MODS) | (1 << SLPE));  //LOW POWER MODE IN SLEEP & ACTIVE STATES WITH LOWEST SAMPLING
 writeRegister(ASLP_COUNT, sc);

 // Set up interrupt 1 and 2: 1 = wake ups, 2 = data
 writeRegister(CTRL_REG3, (1 << WAKE_FF_MT) | (1 << IPOL));  // Active high, push-pull interrupts, sleep wake up from motion detection
 writeRegister(CTRL_REG4, (1 << INT_EN_ASLP) | (1 << INT_EN_FF_MT) |  (1 << INT_EN_DRDY));  // DRDY ENABLE SLP/AWAKE INTERRUPT (INTERRUPT THROWN WHENEVER IT CHANGES) & MOTION INTERRUPT TO KEEP AWAKE
 writeRegister(CTRL_REG5, (1 << INT_CFG_ASLP) | (1 << INT_CFG_FF_MT));  // DRDY on INT1, ASLP_WAKE INT2, FF INT2
 writeRegister(CTRL_REG5, readRegister(CTRL_REG5));

    //SETUP THE MOTION DETECTION
    writeRegister(FF_MT_CFG, 0xF8);   /*MOTION DETECTION AND LATCH THE
          //RESULT WHEN IT HAPPENS AS OPPOSED
          //TO COMBINATIONAL REAL TIME*/
        writeRegister(FF_MT_THS, mt);  //MOTION DETECTION THRESHOLDS
        writeRegister(FF_MT_COUNT, mdc);   //TIME MOTION NEEDS TO BE
              //PRESENT ABOVE THE THRESHOLD BEFORE INTERRUPT CAN BE ASSERTED

        MMA8452Active();
    }


message:
Reset an Arduino Uno in code

Is it possible to reset an Arduino (i.e., to reboot it) from code (i.e from the sketch itself)? I know that is possible with a special circuit but is there a chance to make it just with code?

Below is my code and the comment `//reset` is where I want to force a reset.

    #include <TrueRandom.h>

    int i;
    int randSeed;
    long randNumber;

    void setup(){
      Serial.begin(9600);
      Serial.println("20 pseudo Zufallszahlen:");
      for (i=1;i<=20;i++) Serial.print(random(10));
      Serial.println();
      Serial.println();
      //randomSeed(TrueRandom.random());
      randSeed = analogRead (A0);
      randomSeed(randSeed);
      Serial.print("Der 'seed' Wert: ");
      Serial.println(randSeed);
      Serial.println();
      Serial.println("20 Zufallszahlen mit analogem 'seed' Wert:");
      for (i=1;i<=20;i++) Serial.print(random(10));
      Serial.println();
      Serial.println("---------------------------");
      Serial.println();
      delay(500);
      //reset
    }

    void loop() {
    }

I want to reset the micro-controller at the end of the setup function to show the effect of random numbers with and without a seed.

body:
There three ways to accomplish this. (last is my favorite)

1) Jumper an unused IO to the RESET pin. Leave it as INPUT for normal
    run, As it is externally pulled high. And when desired to reset set
    it as LOW and Output. (bang its rebooting).

    setup() {
      ...
      pinMode(PINtoRESET, INPUT);    // Just to be clear, as default is INPUT. Not really needed.
      digitalWrite(PINtoRESET, LOW); // Prime it, but does not actually set output.
      ...                            // Does disable 10K pull Up, but who cares.

then when desired...

    ...
      pinMode(PINtoRESET, OUTPUT);   // lights out. Assuming it is jumper-ed correctly.
      while(1);                      // never gets here.

2) Jump to beginning of the code.

    void(* resetFunc) (void) = 0;  // declare reset fuction at address 0
    ...
    resetFunc(); //call reset

**But be careful**, this does not perform a true reset, in that all the registers ARE NOT DEFAULTED. Rather they and the IO are left as is. Where somethings from the bootloader and then the heap will be initialized. And reset are not!

3) Use the watchdog. The [SoftReset](https://github.com/WickedDevice/SoftReset) library makes it easy. Although it is not difficult to implement directly. Shown below..

    #include <avr/wdt.h>
    ...
    setup() {
      ...
      MCUSR = 0;  // clear out any flags of prior resets.
      ...

then when desired...

    ...
    wdt_enable(WDTO_15MS); // turn on the WatchDog and don't stroke it.
    for(;;) {
      // do nothing and wait for the eventual...
    }
    ...


body:
In case you have the original Arduino bootloader which you want to execute as a part of the reset, you can do a SW reset by jumping to the bootloader reset address (0x7800 on ATmega328p boards)

    void reset() { asm volatile ("jmp 0x7800"); }

The watchdog reset approach will not work because of a bug in the bootloader. Here's a note from ATmega328P Datasheet page 45:

>Note: If the watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the watchdog timer will stay enabled. If the code is not set up to handle the watchdog, **this might lead to an eternal loop of time-out resets**. To avoid this situation, the application software should always clear the watchdog system reset flag (WDRF) and the WDE control bit in the initialization routine, even if the watchdog is not in use.

This is exactly what [will happen](https://arduino.stackexchange.com/q/2922/13327) after a watchdog reset on a system with Arduino bootloader.


message:
Formula / calculation of the function random() / randomSeed()

In which file can I find the calculation that is called with `random()`? If it is not too much could you also post the content in your answer? I am using an Arduino Uno and its standard IDE.

I found this in the "WMath.cpp" but that is not the final calculation.

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

    void randomSeed(unsigned int seed)
    {
      if (seed != 0) {
        srandom(seed);
      }
    }

    long random(long howbig)
    {
      if (howbig == 0) {
        return 0;
      }
      return random() % howbig;
    }

    long random(long howsmall, long howbig)
    {
      if (howsmall >= howbig) {
        return howsmall;
      }
      long diff = howbig - howsmall;
      return random(diff) + howsmall;
    }

body:
The underlying `random()` function isn't part of the Arduino code. It's actually part of `avr-libc`. The Arduino IDE only comes with pre-compiled object code for it (as far as I know).

It's open source though. You can get information about it here:

 * http://www.nongnu.org/avr-libc

If you look down the page a short way, you'll find the "Source code and documentation" link.

The `random()` function is under `libc/stdlib/random.c`. I would paste the source code here, but technically I'd have to include a whole copyright notice with it.


body:
Read Peter Bloomfield's answer here: https://arduino.stackexchange.com/a/1482/7727

Then read the following:

For everyone's reference, [Arduino's WMath.cpp is found here.][1]

[Documentation for AVR-Libc's random() function is here.][2]

[Source code for AVR-Libc is found here][3], as linked-to from [here][4].

I downloaded "avr-libc-2.0.0.tar.bz2.sig 08-Feb-2016" and extracted it. Like Peter said, the source code for "random" is in "**avr-libc-2.0.0\libc\stdlib\random.c**"

To save you the hassle, here's the source code, with their included copyright and license statement right at the top of it.

    /*-
     * Copyright (c) 1990, 1993
     * The Regents of the University of California.  All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     * 1. Redistributions of source code must retain the above copyright
     *    notice, this list of conditions and the following disclaimer.
     * 2. Redistributions in binary form must reproduce the above copyright
     *    notice, this list of conditions and the following disclaimer in the
     *    documentation and/or other materials provided with the distribution.
     * 3. Neither the name of the University nor the names of its contributors
     *    may be used to endorse or promote products derived from this software
     *    without specific prior written permission.
     *
     * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     * SUCH DAMAGE.
     *
     * Posix rand_r function added May 1999 by Wes Peters <wes@softweyr.com>.
     *
     * $Id: random.c 1944 2009-04-01 23:12:20Z arcanum $
     */

    /*
     * From:
    static char sccsid[] = "@(#)rand.c 8.1 (Berkeley) 6/14/93";
    */

    #include <stdlib.h>
    #include "sectionname.h"

    ATTRIBUTE_CLIB_SECTION
    static long
    do_random(unsigned long *ctx)
    {
     /*
      * Compute x = (7^5 * x) mod (2^31 - 1)
      * wihout overflowing 31 bits:
      *      (2^31 - 1) = 127773 * (7^5) + 2836
      * From "Random number generators: good ones are hard to find",
      * Park and Miller, Communications of the ACM, vol. 31, no. 10,
      * October 1988, p. 1195.
      */
     long hi, lo, x;

     x = *ctx;
     /* Can't be initialized with 0, so use another value. */
     if (x == 0)
      x = 123459876L;
     hi = x / 127773L;
     lo = x % 127773L;
     x = 16807L * lo - 2836L * hi;
     if (x < 0)
      x += 0x7fffffffL;
     return ((*ctx = x) % ((unsigned long)RANDOM_MAX + 1));
    }

    ATTRIBUTE_CLIB_SECTION
    long
    random_r(unsigned long *ctx)
    {
     return do_random(ctx);
    }

    static unsigned long next = 1;

    ATTRIBUTE_CLIB_SECTION
    long
    random(void)
    {
     return do_random(&next);
    }

    ATTRIBUTE_CLIB_SECTION
    void
    srandom(unsigned long seed)
    {
     next = seed;
    }

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/WMath.cpp
  [2]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga114aeb1751119382aaf3340355b22cfd
  [3]: http://download.savannah.gnu.org/releases/avr-libc/
  [4]: http://www.nongnu.org/avr-libc/


message:
Allocate object memory statically; intialize it dynamically?

I have an object whose constructor gets passed a parameter. If I know the parameter value at compile time, I can construct the object statically:

`static FOOOBJ foo(3);`

(I understand that it isn't really done statically, i.e. by the compiler, but is actually done during setup).

But if I don't know the parameter value at compile time, I'd still like to pre-allocate space for the object but construct the object in that space at run time. Can it be done without a separate `.initialize()` method?

body:
You can use placement syntax to specify an existing allocation in which to instantiate the class.

    FOOOBJ foo(0);

     ...

      FOOOBJ *f = new (foo) FOOOBJ(3);


body:
Using an `initialize()` method to a class is contrary to the principle of a class constructor, i.e. once a class instance has been **constructed**, it should be "**ready to use**".

As suggested by Ignacio's answer, C++ placement syntax is much better for your purpose.

However, with Arduino libraries, placement syntax is not supported "out of the box", so you  have to implement it yourself; don't fear, that is quite straightforward:

    void* operator new(size_t size, void* ptr)
    {
        return ptr;
    }

Placement syntax can be a complex beast in C++, but for your specific purpose, its usage can be rather simple:

    static char buffer[sizeof FOOOBJ];
    static FOOOBJ* foo;

    void setup() {
        ...
        foo = new (buffer) FOOOBJ(3);
        ...
    }

The difference with your current code is that `foo` is now a pointer, hence any method call will use `->` instead of `.`.

If you absolutely want to keep using `foo` as an instance and not a pointer, then you can do it (but I don't advise it as explained later) by using a **reference** instead:

    static char buffer[sizeof FOOOBJ];
    static FOOOBJ& foo = *((FOOOBJ*) buffer);

    void setup() {
        ...
        new (buffer) FOOOBJ(3);
        ...
    }

The problem with this code, is that you cannot know if `foo` has already been constructed with a real `FOOOBJ` instance or not; using a pointer, you can always check if it is `0` or not.

Using placement syntax, you must be aware that you cannot `delete` the `foo` instance above. If you want to destroy `foo` (i.e. ensure that its destructor is called), then you have to explicitly call the destructor:

    foo->~FOOOBJ();


message:
Calculating location with 4 piezo's

i've got the following problem i'd like to get solved and i'm breaking my head, so please help!

I have a rectangle with the following size 40 cm * 50 cm. On each corner of this rectangle I placed a Piezo element (it's an electronic element which measures the vibration)

The rectangle is defined as followed: the left upper corner = A the left lower corner = B the right lower corner = C the right upper corner = D

I'm trowing a ball on the surface and I'd like to calculate it's X and Y axis. The outcome of the piezo elements are as followed:

A,B,C,D - 0 lowest vibration, 1023 highest vibration These values can be mapped to a number I can decide, so that means I can make it whatever we need it to be. Example: map 0,1023,0,100, meaning the new mapping will be 0 - 100.

I found a possible solution here: http://mathafou.free.fr/pbg_en/sol114.html The problem I got is that i don't know where the ball will be and therefor I don't know the angle it will fall on.

The thing I do now is:

Example: We trow the ball. The outcome could be ABC or what would be best ABCD results.

I thought Pythagoras could come in handy here. The thing I did was: A*A+B*B=C*C (to get the square calculation done) A+B = AB, B+C = BC, A+C= AC, (to get the sides of a triangle) AB*BC=AC (We don't know AC but we can square root the outcome of AB*BC)

But then i realised I just know how long the side is and I still don't know where the ball landed :(

The following I already implemented to scale it when it works (maybe not relevant now) A+B+C+D = Total outcome we can possibly get at that point (as we are relying on vibration) A,B,C,D/Total = the scale we need to calculate with

I call this A1,B1,C1,D1 so I can re-use this in the code The reason I do this, is the follow up I need it for. Im going to use a projector to project a video on the exact X/Y position. But that's not relevant I guess for now.

I'm programming this in Processing 2 : http://processing.org

body:
You might want to look into how LORAN works, as I believe you can do something similar.

First premise: You want to look for the **initial transient** caused by the impact propagating to sensors in various places on the periphery.  The signal in the material will end up bouncing around quite a bit before it dies out, but the leading edge of the initial transient should be unambiguous, so use that.

Second premise: You have *no idea* when the ball actually hits - you can also measure the **difference in timing** between when various sensors first detect it.

So take any two sensors, measure the time lag between when they detect the ball, and convert that via the speed of sound in your material.  This yields the *difference* in the distance of the impact point from the two sensors.  If you know the position of the two sensors, and plot the curves of points which satisfy the equation of the measured difference in distance from each of them you can a class of conic section called a `hyperbola`.

But so far you do not have an answer, but only a pair of curves along which the impact must lie.  So now take at least one new sensor, and repeate the exercise generation a new equation.

Combine the equations and solve to find the intersection of the curves - this is your point of impact.  It is possible to have more than one mathematical solution, but I think you will find that only one possible solution lies in the area between the sensors.

(Unfortunately, the ATmega328p A/D converter probably isn't fast enough to do a good job of this - at 10KSPS each sample is around 34mm in air, and around half a meter in typical solids - so you either need a much faster A/D, or else tune a comparator circuit to detect pulses and measure them with ATmega timer channels.)


message:
Solar Tracker Code - how to limit steppers to max & min angle?

a couple of friends and i are working on a double axis solar tracker with a Adafruit Motor-shield V2 and 2x Adafruit bipolar stepper motors (200/rev).
We got the following code so far but are stuck with getting the steppers to stop at a certain angle (90° for vertical and 180° for horizontal) so that we dont tangle up the wires and avoid unnecessary movement. Any help and sugestions would be much appreciated.

Cheers

    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_PWMServoDriver.h"

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    Adafruit_StepperMotor *stepperh = AFMS.getStepper(200, 1);  // declaring horizontal stepper
    Adafruit_StepperMotor *stepperv = AFMS.getStepper(200, 2);  // declaring vertical stepper

    int ldr1 = A0;  // right ldr
    int ldr2 = A1;  // centre ldr
    int ldr3 = A2;  // left ldr
    int ldr4 = A3;  // top ldr
    int ldr5 = A4;  // bottom ldr

    const int threshold = 550;  // limit to stop tracker from moving at night

    const int tol = 50;  // tolerance for ldrs // maybe vertical AND horizontal depending on difference?

    //int = countv
    //int = counth

    //const int maxh = ?    // to prevent overturning horizontal (50 steps = 90°)
    //const int minh = ?    // combine with count int's // i.e. if counth > 90 - stop
    //const int maxv = ?    // to prevent overturning vertical
    //const int minv = ?

    void setup()
    {
      AFMS.begin();
      stepperv->setSpeed(10);
      stepperh->setSpeed(10);
    }

    void loop()
    {
      int right = analogRead(ldr1);
      int centre = analogRead(ldr2);
      int left = analogRead(ldr3);
      int up = analogRead(ldr4);
      int down = analogRead(ldr5);

      //STOP MOVEMENT//
      if ((left < threshold) && (right < threshold) && (up < threshold) && (down < threshold)) {}  // stop any movement if sensor values below threshold
                                                                                // at begining to check after every sensor reading

      //HORIZONTAL MOVEMENT//
      if((right > centre + tol) && (left + tol < centre))   // && (right - ? > tol)
      {
        stepperh->onestep(BACKWARD,DOUBLE);  // add +1 to int counth // if (minh < counth < maxh) - move // else - stop // counth=counth++ , counth=counth--
      }
      else if((left > centre + tol) && (right + tol < centre))  // && (left - ? > tol)
      {
        stepperh->onestep(FORWARD,DOUBLE);
      }
      else {}  // do nothing

      //VERTICAL MOVEMENT//
      if((up > centre + tol) && (down + tol < centre))  // && (up - ? > tol)
      {
        stepperv->onestep(BACKWARD,DOUBLE);
      }
      else if((down + tol > centre) && (up + tol < centre))  // && (down - ? > tol)
      {
        stepperv->onestep(FORWARD,DOUBLE);
      }
      else{}  // do nothing
    }

body:
When working with steppers you have to realise that you are not dealing with absolute coordinates. Unlike with, for example servos, which you command to go to particular angle, you command steppers to rotate a particular amount of steps in a particular direction. This creates in your case the problem that you cannot actively check the positions of the steppers without some sensing element.

As a solution I would suggest that you would store the steps the steppers take in some variables, and then with the code limiting, that these variables don't go over a surtain number. With this method, you need to have a way of setting the zero point of the steppers, meaning from where to start the counting. This could for example be done by driving the system against some switch, and then setting the step variable to zero here. This is usually done once in the bootup, meaning that it is excecuted in the setup function.


body:
The only sure way is to use one or more position or limit switches. Steps can be lost (motor didn't move as commanded due to, f/ex, overload), the motor could be back-driven while powered down or if over-powered by the mechanical system, or your step counting could be faulty due to a bug or a power glitch.

At power-up or at any time your software thinks it might have got out of sync with the mechanicals, back into the limit switch at low speed (so you don't hard-crash), and reset your software counters, and reposition from there.


body: Stepper motors are nice and all but they actually make less than adequate servos for this purpose. the best way that I can see is with linear actuators that have position sensors in them and feed the Voltage divider outputs from those sensors to the Atmega chip. If you write the code to compare the signals from the light detectors with the voltage from the pos sensors it should be a lot better. Also, limit switches should be used in this arrangement too. They would be as a fail safe. The other benefit is that linear actuators usually hold a lot better without loosing their position due to outside stresses. Steppers can be used for prototyping, but it would still be better to start with small servos with sensors and get the system working first. I myself am trying to get a working system and I am having troubles with the coding also, but I am not good at coding. One other thing, I have looked at a lot of different codes to find something that might help me with my project and I have seen this. Stepper motor systems are written with minimal code which as I see it leaves room for much error. Atmega has plenty of room for code storage and plenty of ports for sensors in this use. Everyone knows that old phrase keep it simple but some times that is not always the best advice. You are working with something that needs to be somewhat complicated, to be less likely to fail. The more engineering you put into something the more likely something is to go wrong but less engineering gives you the same results. So consider all the posibilities and address them. Adding components and sub systems will in the end make your work better.


message:
Using multiple laptop battery packs to power everything

I'm working on a medium sized robot project with multiple arduinos to control stuff. I've been planning on using a lead-acid battery pack, but then I was given 10 working and identical Asus laptop battery packs rated at 14.8 V 4400 mAh, and one old Asus laptop.

I opened up one of the battery packs, because it was bad and it has a 4S2P battery configuration and a protection board.

Can I hook all of these battery packs in parallel, or will power leak between the battery packs, and is that be a problem?

Is there alternatively some 4S20P or 3S25P battery pack with charger I can purchase to put these batteries in?

(I do have a step-down converter that will provide the Arduinos with the right voltage, regardless of input voltage up to 36 V)

I tried to ask a similar question on electrical engineering, but ot was deemed off topic for the site.

body:
I'd be cautious about hooking them in parallel. [According to ADAfruit][1] power leakage between batteries *is* a problem.

> [multipack parallel] ... batteries are assembled by a company that is experienced and certified to test and assemble battery packs. The individual batteries are tested and sorted by machine so that each pack has matching batteries with the same capacity and internal resistance. Individuals do not have this equipment, which is why you should not try to make your own packs.

Are you certain all your batteries are the same age and have the same usage history? A brand-spanking new one *will* try to charge an old worn battery to its own fresh voltage.

  [1]: https://learn.adafruit.com/li-ion-and-lipoly-batteries/multi-battery-packs


body:
In case you didn't know it already you can hook any batteries in parallel by adding a diode on every battery to avoid current from any other battery flowing back to it. Like this:

     battery
          |+  diode
    +----||--->|---+
    |     |        |
    |              |
    |     |+       |
    +----||--->|---+----o V++
    |     |
    |
    _
    V GND

**The drawback** is that you have a small drop of voltage on the diodes and of course a small power loss too. If for example you're drawing 0.5 Amp from the batteries and you're using an 1N4001 diode which has a voltage drop of about 0.7 Volts then expect  0.350 Watts of power loss (0.5A x 0.7V). So choose the diode with the lowest voltage drop that can handle the current you need. There are solutions to lower the power that is wasted but they're more complex.


message:
How to make XBee module interrupt/wake arduino

What I am trying to do is, to have arduino in low power mode and waking up only when a packet is received and is available to be read from the buffer.

A scenario : Zigbee XBee module is not receiving anything, arduino is asleep. Once this particular module receives any data from any other module, it makes the arduino wake up and process this packet.

I've looked almost everywhere possible about this, and people say they do not have a 100% working solution.

Does the XBee module produce a particular output on a specific pin when it receives data? If so, can I connect that pin to the interrupt enabled pin on arduino and with that interrupt arduino or wake it up?
do I need arduino mega for that or is the uno a good enough option?

body: The pin number 9 and 13 on the Xbee are DTR/RTS used for hardware handshaking. You can connect it to the interrupt pins on the Arduino and program the arduino to wake when the pulse changes. Enable the DTR/RTS feature from X-CTU and it should work. Check [this](http://www.digi.com/support/forum/3314/hardware-flow-control-of-xbee-module) for more information.


message:
Adafruit motor shield + Adafruit stepper not working

I have the Adafruit Motor Shield V2 and an [Adafruit stepper motor][1]. I have not soldered the shield onto the Arduino (which is an Uno) yet because I don't want to make anything permanent yet. I have the Arduino plugged into a DC wall adapter and have the VIN jumper in the shield, and the green power light on the shield is lit. This is how the stepper is connected. ![setup][2]

As you can see in the picture, all the wires from the stepper are plugged in. The order of the wires is what it says it should be on the [website][1], which is `orange-pink-red-blue-yellow`.  My sketch's code is an adapted version of the StepperExample from the Adafruit motor library. Here's the full code

    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_PWMServoDriver.h"

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();

    Adafruit_StepperMotor *myMotor = AFMS.getStepper(513, 2);

    void setup() {
      Serial.begin(9600);
      Serial.println("Stepper test!");

      AFMS.begin();
      myMotor->setSpeed(5);
    }

    void loop() {
      myMotor->step(100, FORWARD, SINGLE);
    }

But the stepper still doesn't move. Can anyone point out what I'm doing wrong here?

  [1]: https://www.adafruit.com/product/858
  [2]: https://i.stack.imgur.com/LPtx3.jpg

body:
As far as I know, you have to solder the header pins. Here is a nice video demonstrating the assembly: [Motorshield V2 assembly][1]

  [1]: http://www.youtube.com/watch?v=yt-SEOZT-hI


message:
Convert a Bitstring into an integer value

I have got a String filled up with 0 and 1 and would like to get an Integer out of it:

    String bitString = "";
    int Number;
    int tmp;

    bitString = "";
      for (i=1;i<=10;i++)
      {
        tmp= analogRead (A0);
        bitString +=  tmp % 2;
        delay(50);
      }
    // now bitString contains for example "10100110"
    // Number = bitstring to int <-------------
    // In the end I want that the variable Number contains the integer 166

body:
Check out `strtoul()`

It should work something like this:

`unsigned long result = strtoul(bitstring.c_str(), NULL, 2);`

Now you have a long variable which can be converted into an int if needed.


body:
If you only need the string for printing you can store value in an integer and then use the [Serial.print(number,BIN)](http://arduino.cc/en/Serial/Print) function to format the output as a binary value.  Appending integers to strings is a potentially costly operation both in performance and memory usage.

    int Number = 0;
    int tmp;

    for (int i=9;i>=0;i--) {
      tmp = analogRead (A0);
      Number += (tmp % 2) << i;
      delay(50);
    }
    Serial.print(Number, BIN);


message:
How to update a text file dynamically

I have Two Arduinos, One with the help of sensors it will dynamically updates in to my server database. Other Arduino, reads the stored contents from the server database and sends sms to phones.

Now, I have a text file in my server which updates dynamically for every 5 min - 10 min. I am trying to read that text file contents.

I want my server to be always connected, So It must be in `setup()` function.
I want update only to my text file which dynamically changes, so it must be `loop()` function.

How to implement this ? Any Suggestion ?

body:
It's difficult to answer without details of how your server works.

If your arduino is simply connected to the server, the server could open the arduino serial port (e.g.: COM5: or /dev/ttyUSB0) and simply read data.  The arduino would only need to serialWrite() data for the server to parse and store.

If your arduino is not connected but has ethernet support you could do a HTTP request to your server, and pass the data as a parameters to the request, e.g.:

    http://your.server.ip/send_data?param1=10.3&param2=5.6&param3=foo

When your server processes this HTTP request, it appends param1, param2, param3 to that text file.

The arduino could also beam data back to your server via IR, or bluetooth, etc.

There's lots of ways to do this.


message:
Use Higher Resistance Than Instructed in a Circuit

I'm following the "Get Started with Arduino" Guidebook, and I'm at the part where pulse width modulation (PWM) is discussed.

The instructions say to create a simple circuit with a breadboard, red LED, arduino (connected at pin 9 and ground) and a 270 ohm resistor. My power source will be the usb connection.

I have a 510 ohm resistor.

1. May I use it instead?
2. In general, will using a resistor with a higher resistance than intended in a circuit fry the arduino?

Thanks very much for your help. I'm new to arduino and electronic circuits. I have a Uno R3.

body:
The cases where using a higher value resistor will damage a circuit exist, but are a bit less usual than the cases where it may simply produce a weaker result than desired, or a different frequency response than desired.

The primary situations where you do have to watch out come about where "feedback" is used to adjust one thing in relation to something else, and so putting a larger resistor on the "sense" side of the circuit can cause the "output" to be too high.  Examples you might run into would be adjustable voltage regulators (obvious potential for damage with wrong output) and op-amps (higher than desired output, though more often distortion than damage).

It seems quite likely the the role of the resistor in your circuit is to limit the current through the LED - protecting that (and to a more vaguely best-practices degree, the ATmega pin) from damage.

For your needs it could be worth noting that a parallel combination of two 510 ohm resistors will give an effective resistance of half that, or 255 ohms.  This is very close to the design intent, so might be a decent substitution (cheap resistors have a larger tolerance for piece-to-piece variation of value than that anyway).

Normally I would say the desired 270 ohms feels a little small, and that I'd prefer to start with 330 ohms.  But if you do parallel two 510's, the 255 ohms would give just under 20ma of current if connected directaly across a 5v supply.  Given your LED will have some forward voltage drop (varies widely with color), and your Arduino pin a little of its own, the actual voltage and thus current will be less - as a guess the end result is likely to be in the 15ma range, and not unreasonable for many common LEDs.

Resistors would also be a fairly easy component to salvage out of old electronics - the leads will end up short, but other than that you basically just need to read the color code, and perhaps confirm the value after removal with a meter.

Ultimately though it is worth buying an assortment of resistors - the 1/4 watt size are generally preferred for breadboarding as the leads are the best fit.


body: If the resistor is in series w the LED, it'll just be about half as bright when you use 510 vs 270 ohms. I=E/R and all -> half the current. Your PWM will still work, but starting from a lesser brightness on down.


message:
Cheapest way to connect android device to arduino wirelessly

I'm building a simple RC car which I want to control using android phone. The phone has bluetooth and Wi-Fi. My questions is what will be the cheapest way to connect the two devices at about 50-120m range? I have thought of the following:

 - Cheap bluetooth module ([like this][1]). Will this fit into my problem? What range I will archieve using this module.

 - Wi-fi module. I can set the android device to be "wi-fi hotspot", but the wi-fi shields are pretty expensive tho.

Any suggestions will be greatly appreciated.

  [1]: http://www.ebay.com/itm/Slave-HC-06-Wireless-Bluetooth-Transeiver-RF-Master-Module-Serial-for-Arduino-/181358244980?pt=LH_DefaultDomain_0&hash=item2a39cb3474

body:
**Solution 1**

If you don't want to change the coverage radius, sadly none of them would help you to achieve a coverage of 50m.

But if you are not using a camera feed and just want to control, I think [RF transceiver][1] would be best solution for you. But to implement this you mist connect an Arduino Mega ADK to your android device. Serially receive your directions to mega and then transmit the directions over RF transceiver.

**Solution 2**

If you are willing to change the coverage range to less than 15m, you can use [Wi-Fi Module][2]. This will also help you to get live camera feed from your RC car to your phone. Forget about Bluetooth module as they are slow, less range.

You can increase the coverage of Wi-Fi Module if you have a Wi-Fi AP with huge transmit power. As long as the module is able to receive the signal from AP, your car would do great.

**P.S.** :- Here is a cool tip. Record every turn instruction and the time after which it was given. When the signal from transmitter or AP is absent for more than a particular time, you can program the car to take a U-turn and reverse the directions. Your car will come home without any instruction.

  [1]: https://www.sparkfun.com/products/153
  [2]: https://www.sparkfun.com/products/10050


message:
Looking for a protocol, any hints?

I am looking for a multi-purpose wire protocol for Arduino.

Requirements:

 1. Range of at least 500ft (200m)
 2. No shield required
 3. Able to communicate between Arduino and Raspberry Pi
 4. Be able to run "point-to-multipoint"

body:
There is nothing that will work given those constraints.

You only have low power 5V signals on the Arduino which won't handle your distance requirements.

You could look into [RS-485](http://en.wikipedia.org/wiki/RS-485) using a [shield](https://www.sparkfun.com/products/11959) on the arduino side and a [breakout board](https://www.sparkfun.com/products/10124) on the Raspberry Pi.


message:
DC-DC converter with Arduino not working

I've got a program running on the Arduino that is supposed to turn on and off a pump.  currently, I am outputting the reads of the components that need to be read and it shows when the port (port 13) is supposed to turn on and when it's supposed to turn off.  When I use a multimeter between the port 13 and ground, everything works as expected.

When I start the program and the port is off, I get a reading of 0.03v @20v max (to be more precise, I get 14.0 at 200mV) - Shouldn't this be zero? or is there always going to be some electricity flowing?

When the port is turned on: `digitalWrite(airPump, HIGH);` (and yes, airPump is set to 13), the voltage reads between 4.0 and 4.51 with spikes down to 3.65 on my multimeter set at 20v max.  is it ever stable? (pictured below)
![enter image description here][1]

So, the main question is: I'm supposed to be sending the power from port 13 to a DC-DC converter.  I tested the converter on a separate bread board just by itself.  I used a DC power supply and set it to 4.5v, then ran the power through the vIn, grounded the ground pin and ran the vOut to the multimeter (then to ground with the multimeter) and I got it set to output only 2.5v with a constant 4.5 running into it. (pictured below)
![enter image description here][2]

I also tested whether or not changing the voltage input would change the output at all and it seems it does not, from 1.5-15v, the converter stays steady at 2.5v

Now when I do the exact same set up on the arduino with the power from port 13 running into the voltage in on the DC-DC converter, it gives me a reading of 0.01v.  Any idea why this is happening?
![enter image description here][3]

I've checked probably over 30 times and rearranged everything just as many, but nothing seems to help.  I can't get a stable 2.5V output from the converter with the arduino...

UPDATE: Below is a simple wiring diagram:
![enter image description here][4]

The image shows what it is supposed to do, but for testing purposes I made it so if the rH is higher than average (I just breath on it) then the pump will turn on.

  [1]: https://i.stack.imgur.com/Hybdk.jpg
  [2]: https://i.stack.imgur.com/ekznO.jpg
  [3]: https://i.stack.imgur.com/rWelz.jpg
  [4]: https://i.stack.imgur.com/rBXeK.png

body:
The arduino output pin cannot provide enough current to drive the pump. The DC-DC converter is not designed for this use.

You need external power supply with enough current to drive the motor that you switch on and off with the arduino output pin.

Search for "Arduino 3V DC motor control" for examples of how to do this, there are many options.


message:
Measure LiPo / Li-Ion SOC or the ever standing question of how much juice is remaining in my battery?

So I have a project in which an arduino runs on a two cell LiPo battery and I need a fast, straight forward way to determine remaining battery charge (with an accuracy of 10% so I only have a readout with 10 LEDs on it) without using any major extra components (so using an external battery charge meter IC is cheating :P). How should I go about this?

(using arduino mini, LiPo is two cells: 7,4V 150mAh)

body: Use a low-leakage op amp to divide the battery voltage by 8 (AV of 1/8). Connect the output to an analog input. Set your reference to the internal 1.1V reference (`INTERNAL`). Perform analog reads. Full battery will be about 975 ((8.4V/8)/1.1V⋅1024 ~= 977.45455). Empty will be about 700 ((6.0V/8)/1.1V⋅1024 ~= 698.18182). Note that the voltage scaling for Li-ion cells is non-linear; see the datasheet for the cells for the appropriate scaling (and if you want more precise full and empty values).


body: If you are using a single cell, then the [Fuel gauge](https://www.sparkfun.com/products/10617) from Sparkfun would be great. Instead of reading analog values manually it sends the battery level via I2C.


message:
portd not writing on digital ports 5 and 7

I try to build a function generator (preferably a sine) with an [R-2R ladder][1] and a [Arduino Leonardo by Borderless Electronics][2].

For performance reasons one should use `portd` instead of `digitalWrite`.
However the signal is not at all what I want (just noise). So upon further investigation I found that the digital pins were never on `HIGH`. Pin 6 worked flawlessly. Furthermore I have tested the two failing pins with simple test programms and they behaved exactly as I would have expected.

Here is the code I use

     int sine[255];

     void setup()
     {
         pinMode(0, OUTPUT);
         pinMode(1, OUTPUT);
         pinMode(2, OUTPUT);
         pinMode(3, OUTPUT);
         pinMode(4, OUTPUT);
         pinMode(5, OUTPUT);
         pinMode(6, OUTPUT);
         pinMode(7, OUTPUT);

         float x;
         float y;
         for(int i=0;i<255;i++)
         {
              x=(float)i;
              y=sin((x/255)*2*PI);
              sine[i]=int(y*128)+128;
         }
    }

    void loop()
    {
         for (int i=0;i<255;i++)
         {
              PORTD=sine[i];
              delayMicroseconds(10);
         }
    }

I tested this with two Arduinos of the exactly same type.

**Question:** Why are pins 5 and 7 never on `HIGH`?

**Edit:** I have simplified everything down to one statement in the loop: `portd = x;`

I vary x manually

**expected** findings:

x  ->  #pin that is on high

0  -> None

1  -> 0

2  -> 1

4  -> 2

8  -> 3

...

128 -> 7

**actual** findings

x  ->  #pin that is on high

0  ->  None

1  ->  3

2  ->  2

4  ->  0

8  ->  1

16 ->  4

32 ->  None

64 ->  None

128->  6

I test this by simply connecting an oscilloscope to the output pins. The behaviour is extremely strange since the pins seem to be in random order, some even missing to `portd`. Furthermore `portd = B11111111`, according to the manual, is equivalent to `portd = 255;` and should set all pins on `HIGH`. But in my case it sets every pin to `HIGH`, except pins 5 and 7 are on `LOW`.

  [1]: http://www.auctoris.co.uk/2011/05/25/arduino-function-generator-part-2/
  [2]: https://www.indiegogo.com/projects/9-arduino-compatible-starter-kit-anyone-can-learn-electronics

body:
This is because on ATmega 32u4, which is used in Arduino Leonardo,  pins 5 and 7 are not mapped to port D but to port C and E respectively, as you can see in the [ATmega 32u4 - Arduino Pin Mapping][1].

![enter image description here][2]

So you will have to:

- either find another port where all 8 bits are available as digital outputs (note that I'm not sure one such port exists)
- or split each `sine[i]` in 2 parts because you will have to work with 2 ports at the same time.

  [1]:http://arduino.cc/en/Hacking/PinMapping32u4
  [2]: https://i.stack.imgur.com/FHUON.png


body:
As @jfpoilpret points out, Arduino pins are not always mapped to port bits in a straightforward manner, and it’s crucial to understand the mapping for your particular model.

In fact, the Arduino Leonardo is designed in a way that **none** of the ports has all 8 bits usable as I/O pins. As far as the microcontroller is concerned, ports B and D each have all 8 bits available, but the Arduino Leonardo/Micro design uses one bit on each port for a LED.

I would also recommend that if you’re using a PORTx register directly, instead of going through the Arduino API, that you also use the DDRx register to set pin directions, instead of trying to use `pinMode`.


message:
How many total digital pin outs does the Arduino Yun have

I have read the details on the products page for Arduino Yun but I have also read, on a Arduino forum, that there are only 18 digital pins because of Tx, and Rx. Is this true? I am not worried about the PWM, or analog capabilities of the pins, just purely digital.

body:
According to the official specification, it has 20 digital IO pins which can be used with `digitalRead()` and `digitalWrite()` etc.. As is typical on Arduino boards though, pins 0 and 1 *also* act as serial Rx and Tx (respectively).

You can program it to use them for either purpose.

The information you read might be referring to problems with uploading though. If you have something physically connected to pin 0 and/or 1, then you may have to disconnect it while you do an upload, otherwise it can interfere with the communication between your computer and the microcontroller.

If you're doing a lot of tinkering, then sometimes it's simply easier to avoid using pins 0 and 1 altogether, meaning you'd only have 18 IO pins left.


message:
Detecting ball moving between IR pair and handling ambient light changes

I plan to use the [SEN-00241](https://www.sparkfun.com/products/241) IR Emitter and Detector pair to detect a ping pong ball moving fast between them.

I understand I could watch for voltage changes to detect this passing object, however how do people generally deal with ambient light changes? From my research it seems that the voltage will change with ambient light, and although I can take steps to create funnel vision between the 2 I'm sure it may still be an issue.

Would you take constant readings and find averages over 10 consecutive readings to allow for changes in ambient light and set a new baseline reading? Then if the voltage changes dramatically and only for a few reads then I know that was the ball and not to change the baseline reading.

body:
this is the same problem that IR remote/television has; how can TV they tell if that high voltage is a direct light or a logic 1 sent by remote? Simply because remote does not send a "HIGH" signal, but a modulated one, tipically at 36KHz. This mean a logic "HIGH" is a train of "HIGH-LOW" at 36KHz (you can see it as PWM at 50%duty cicle and 36KHz frequency)

Ambient light des not have fast variation, and inside light are at 50-60Hz, so they will be "filtered" out.

So, until you see high voltage change at 36KHz, you have your beam fine, if it is not the case, then look at voltage: if fixed at normally low voltage, beam is broken; is fixed at normally high voltage then some light stronger than your emitter is "blinding" the sensor.

note that because 36KHz is a very use frequency on Remote, there a a lot of chip that will emit or read a modulated IR, but expose a normal digital input/output, but still can be done by software, expecially if hardware assistet (like PWM for output), interrupt for input


message:
error: no '' member function declared in class 'SonarSRF08'

Hi, I am a pretty novice coder and I am getting this error consistently with a library I have installed. Here is the code I am trying to run:

    #include <Wire.h>
    #include <SonarSRF02.h>
    #include <SonarSRF08.h>

    #define leftAddress ( 0xF2 >> 1)
    #define rightAddress ( 0xE0 >> 1)
    #define mainAddress ( 0xF8 >> 1)
    SonarSRF02 LeftSonar;
    SonarSRF02 RightSonar;
    SonarSRF08 MainSonar;

    char unit = 'c'; // 'i' for inches, 'c' for centimeters, 'm' for micro-seconds

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

        LeftSonar.connect(leftAddress);
        Serial.println("Left SRF02 US-Sensor ");
        Serial.println(LeftSonar.getSoft());

        RightSonar.connect(rightAddress);
        Serial.println("Right SRF02 US-Sensor ");
        Serial.println(RightSonar.getSoft());

        MainSonar.connect(mainAddress);
        Serial.println("Main SRF08 US-Sensor ");
        Serial.println(MainSonar.getSoft());
    }

    void loop() {
        float sensorReading = 0;

        sensorReading = LeftSonar.getRange(unit);
        // print out distance
        Serial.print("Distance from left: ");
        Serial.print(sensorReading);
        Serial.print(" ");
        Serial.print(unit);
        Serial.println();

        sensorReading = RightSonar.getRange(unit);
        // print out distance
        Serial.print("Distance from right: ");
        Serial.print(sensorReading);
        Serial.print(" ");
        Serial.print(unit);
        Serial.println();

        sensorReading = MainSonar.getRange(unit);
        // print out distance
        Serial.print("Distance from main: ");
        Serial.print(sensorReading);
        Serial.print(" ");
        Serial.print(unit);
        Serial.println();
    }

My project is using an SRF08 sensor with an Arduino Mega 2560

body:
**Please note that I did not try to run your code on my Mega because I don't have SRFs**

However, here is what I tried to recreate your error:

 - I went to the arduino homepage and downloaded the 1.0.5 version.

 - I downloaded the zipped library from this page [SRF08 Ultra Sonic Range Finder][1]

 - I imported the library into the arduino IDE. For this, I had to unpack the .zip and rename the folder of the library because arduino complained about non-ascii characters. I just called the enclosing folder "arduinoSRFmaster" without dashes. After that it let me import the library the usual way:

   ![How to Install a Library][2]

 - After that I copied your code into a new sketch and hit Ctrl + R to compile and verify. It compiled just fine:

   ![Successfull compiling][3]

(Picture updated for compiling against MEGA)

**Please provide more information, like yor OS, Arduino Version, where you got the SRF Library from etc. if that didn't help.**

  [1]: http://playground.arduino.cc/Main/SonarSrf08
  [2]: https://i.stack.imgur.com/DbRD3.png
  [3]: https://i.stack.imgur.com/jdTRP.png


message:
Parallel shift registers

I'm having trouble with using parallel shift registers, I've studied example codes and I've come up with this function to set the pins to on or off. The problem is the first time the function runs all the output pins are set to HIGH regardless of the values in the array.

        void updateRegister(int ClockPin,int DataPin,int LatchPin){
          int pinState;//Holds the state of the data pin
          pinMode(ClockPin, OUTPUT);//Sets the pinmode of the pins
          pinMode(DataPin, OUTPUT);//Sets the pinmode of the pins
          pinMode(LatchPin, OUTPUT);
          digitalWrite(LatchPin, 0);//Turns latch off to prevent bleedover while shifting

          digitalWrite(DataPin, 0);//clear everything
          digitalWrite(ClockPin, 0);//clear everything

          for (int i=1; i<=16; i++){//Repeats 16 times with i increment from 1 to 16
              if (Qout[i]){pinState= 1;}//Checks the array for the value and if it is true sets the pinstate to 1, HIGH
              else{pinState= 1;}//If it equals false set it to 0, LOW

              digitalWrite(DataPin, pinState);//Sets the data pin depening on the pinstate
              digitalWrite(ClockPin, 1);
              digitalWrite(DataPin, 0);
              digitalWrite(ClockPin, 0);
            }
          digitalWrite(LatchPin, 1);//Turns latch pin back on
        }

I'm storing the boolean values of the each pin in an array called Qout which is defined and all set to false like this

        boolean Qout [17];//Holds the state for each pin
        for (int i = 1; i < 17; i++ ) {Qout[i]=false;}//Sets all output to off

I know I should start at Qout[0] but it just makes it way more confusing.

Can someone help me fix my function so that it actually works.

This is what I based it on [ShftOut23][1]

  [1]: http://arduino.cc/en/Tutorial/ShftOut23

body:
First of all, fix the following part of your code:

    if (Qout[i]){pinState= 1;}//Checks the array for the value and if it is true sets the pinstate to 1, HIGH
    else{pinState= 1;}//If it equals false set it to 0, LOW

into:

    if (Qout[i])
    {
        //Checks the array for the value and if it is true sets the pinstate to 1, HIGH
        pinState = 1;
    }
    else
    {
        //If it equals false set it to 0, LOW
        pinState = 0;
    }

Of course, if you always set `pinState` to `0`, it won't work as you expect :-)

Note that you should rather use `HIGH` and `LOW` constants (more readable) instead of `1` and `0`.

Finally, you could make the code much simpler this way:

    pinState = (Qout[i] ? HIGH : LOW);


message:
Connecting Nokia 106 to Arduino

I was wondering if this can be done. I got a Nokia 106 and am trying to make it talk, but the audio jack doesn't seem to cooperate and the Fbus pins are right under the SIM slot, which is right under the battery. Any advice?

Added: It seems that it talks AT commands, since it is a GSM model, but I'm not 100% positive.

body:
Here's the picture of the Nokia FBUS connector from your link:
![enter image description here][1]

And here's a (slightly dubious) method of connection from some random web page
![enter image description here][2]

which goes on to say

> The F-bus protocol uses 115,200bps so we can easily use the Arduino’s serial function to communication with the phone. All you need to is hook up the phones TX to the Arduino’s RX and then use a resistor divider (I choose 330 ohm resistors) to connect the Arduino’s TX to the phones RX as shown above.

That page goes on to show how to use an Arduino to get the phone to send SMS text messages.

Sources:

 - http://www.insidegadgets.com/2013/01/12/how-to-use-nokia-f-bus-to-send-an-sms-message/
 - http://forum.gsmhosting.com/vbb/f148/nokia-105-new-100-working-solution-1731398/

  [1]: https://i.stack.imgur.com/mPvXc.png
  [2]: https://i.stack.imgur.com/2l8Jh.png


message:
Unable to read text file from server

I saw the [Web client Example ][1] , In the example, the server connection is initialized in `setup()`. But I want the server to update the text file every time. So, I need the server connection to be in `loop()`.

But, it is not working. Where is the problem in my code.

    #include <GSM.h>

    #define PINNUMBER ""

    // APN data
    #define GPRS_APN       "GPRS_APN" // replace your GPRS APN
    #define GPRS_LOGIN     "login"    // replace with your GPRS login
    #define GPRS_PASSWORD  "password" // replace with your GPRS password

    // initialize the library instance
    GSMClient client;
    GPRS gprs;
    GSM gsmAccess;

    // URL, path & port (for example: arduino.cc)
    char server[] = "yourdomain.com";
    char path[] = "/current.txt";

    int port = 80; // port 80 is the default for HTTP

    void setup() {
    // initialize serial communications and wait for port to open:
    Serial.begin(9600);
    Serial.println("SMS connected");

    // connection state
    boolean notConnected = true;

    // After starting the modem with GSM.begin()
    // attach the shield to the GPRS network with the APN, login and password
    while(notConnected) {
       if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
        notConnected = false;

    else {
         Serial.println("Not connected");
         delay(1000);
        }
       }
    Serial.println("GPRS connected...");
    Serial.println(" Connecting to Server ");
    }

    void loop() {
    if (client.connect(server, port)) {
      client.print("GET /current.txt");
      Serial.print("GET /current.txt");
      client.println(" HTTP/1.1");
      Serial.println(" HTTP/1.1");
      client.println("Host: www.yourdomain.com");
      Serial.println("Host: www.yourdomain.com");
      client.println("User-Agent: Arduino");
      Serial.println("User-Agent: Arduino");
      client.println("Accept: text/html");
      Serial.println("Accept: text/html");
      client.println("Connection: close");
      Serial.println("Connection: close");
      client.println();
      Serial.println();
      Serial.println("\nCOMPLETE!\n");
      //client.stop();

    } else {
      Serial.println("connection failed");
      Serial.println("\n FAILED!\n");
    }

    if (client.available()) {
      char c = client.read();
      Serial.print(c);

    } else {
      Serial.println();
      Serial.println("disconnecting.");
      client.stop();
    }
    }

  [1]: http://arduino.cc/en/Tutorial/GSMExamplesWebClient

body:
Its working as long as the connection doesn't break or the server doesn't stall. We must wait till the response .

    while (client.connected())
    {
     while(client.available())
     {
     char ch = client.read();
     Serial.print(ch);
     }
    }
     client.stop();


message:
Can a PC connect to an Arduino for serial communication without installing the entire dev kit?

I'd like to send a prototype board to a friend pre-programmed and wired. Ideally they should just need to plug in the USB and connect to it over a serial COM port.

With another laptop I used for testing I had to install the full dev kit, sketch editor and all to get it working.

Can I somehow send just the portion of the kit that provides the COM drivers and not the rest? Is there a prebuilt install for just that portion?

body: On Windows in `C:\Program Files\Arduino` there is a folder called `drivers`, which contains all the drivers for the Arduino boards. I think that's what you are looking for.


message:
LED Cube lighting wrong LEDs randomly

So I built my First LED Cube and the thing turns ON!!! Pretty happy about that but here is my problem.

When I try and get the Cube to display say a basic "outline" (a wire form of a cube only the outer most LEDs are on)

The shift registers, that I have daisy chained together, give the correct display 80% of the time, but the other 20% give completely wrong LEDs lighting up.

I have used 4 74HC595 shift registers linked together so I am only using 3 of my Arduino ports to control the 5*5*5 Cube.
The basic shape is there but the ones that are not meant to be lighting up cause a lot of flickering (or *ghosting*?) in the center of the cube.

I have thought about using pull up or pull down resistors but I find that, when I run my program at a slower rate, the LEDs that are lighting wrongly are lighting up controlled so I think it has to be something with my code or setup.

Has anyone got any experience with LED cubes doing this?

Also I am only using the output enable and disable to make use the wrong this is not displayed when I am shifting the data out, should I be using the clear?

One last thing, does anyone have recommendations for the delay time to let each layer shine for?

My code is below

    int clockPin = 8;
    int dataPin = 7;
    int set = 6;

    void setup()
    {
      //set pins to output so you can control the shift register
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(set,OUTPUT);
    }

    void loop()
    {
          digitalWrite(set,HIGH); // DISABLES OUTPUT
      // level 1 ( top )
          shiftOut(dataPin, clockPin, MSBFIRST, B00000011);//from left 3rd to the 7th = levels 5-1,, The right first LED
          shiftOut(dataPin, clockPin, MSBFIRST, B11111000);// Makes the " wire cube "
          shiftOut(dataPin, clockPin, MSBFIRST, B11000110);// Makes the " wire cube "
          shiftOut(dataPin, clockPin, MSBFIRST, B00111111);// Makes the " wire cube "
          digitalWrite(set,LOW);  // enables output
          delay(2);

           digitalWrite(set,HIGH); // DISABLES OUTPUT
     // level 2
          shiftOut(dataPin, clockPin, MSBFIRST, B00000101);//from left 3rd to the 7th = levels 5-1,, The right first LED
          shiftOut(dataPin, clockPin, MSBFIRST, B00010000);// Makes the " wire cube "
          shiftOut(dataPin, clockPin, MSBFIRST, B00000000);// Makes the " wire cube "
          shiftOut(dataPin, clockPin, MSBFIRST, B00010001);// Makes the " wire cube "
          digitalWrite(set,LOW);  // enables output
          delay(2);

          digitalWrite(set,HIGH); // DISABLES OUTPUT
     // level 3
          shiftOut(dataPin, clockPin, MSBFIRST, B00001001);//from left 3rd to the 7th = levels 5-1,, The right first LED
          shiftOut(dataPin, clockPin, MSBFIRST, B00010000);// Makes the " wire cube "
          shiftOut(dataPin, clockPin, MSBFIRST, B00000000);// Makes the " wire cube "
          shiftOut(dataPin, clockPin, MSBFIRST, B00010001);// Makes the " wire cube "
          digitalWrite(set,LOW);   // enables output
          delay(2);

          digitalWrite(set,HIGH); // DISABLES OUTPUT
     // level 4
          shiftOut(dataPin, clockPin, MSBFIRST, B00010001);//from left 3rd to the 7th = levels 5-1,, The right first LED
          shiftOut(dataPin, clockPin, MSBFIRST, B00010000);// Makes the " wire cube "
          shiftOut(dataPin, clockPin, MSBFIRST, B00000000);// Makes the " wire cube "
          shiftOut(dataPin, clockPin, MSBFIRST, B00010001);// Makes the " wire cube "
          digitalWrite(set,LOW);   // enables output
          delay(2);

          digitalWrite(set,HIGH); // DISABLES OUTPUT
     // level 5 ( bottom )
          shiftOut(dataPin, clockPin, MSBFIRST, B00100001);//from left 3rd to the 7th = levels 5-1,, The right first LED
          shiftOut(dataPin, clockPin, MSBFIRST, B11111000);// Makes the " wire cube "
          shiftOut(dataPin, clockPin, MSBFIRST, B11000110);// Makes the " wire cube "
          shiftOut(dataPin, clockPin, MSBFIRST, B00111111);// Makes the " wire cube "
          digitalWrite(set,LOW);   // enables output
          delay(2);
    }

Any help would be appreciated

Thanks

body:
I have a similar circuit (running a 7-segment display); I don't use reset, and for something like this (since the only state it keeps is reset on sending of new data, which is every frame).

For debugging, I would suggest seeing if there are any patterns. For example, if it doesn't happen on LEDs controlled by the first shift register, then it's likely to be due to the connection between them.

You might try seeing if a pulldown resister (try >10kOhm) between the data pin and ground has an effect, too.

If you get really desperate, it might be worth getting an oscilloscope - see what is actually happening on the wire.


body:
I have had a similar issues when building [this instructable][1], a 8x8x8 LED cube. Lighting up some of the LEDs caused wrong LEDs to light up simultaneously, even though according to the circuit diagram they where not suppose to. The wrong LEDs that lighted up seemed to be random, though it was reproducible.

The root cause was, after some debugging using a Multimeter's continuity test, that some of the LEDs legs where touching in places they shouldn't, and so the current was flowing where it was not supposed to flow. I strongly recommend to investigate that direction, verifying that Ground paths and Vcc paths are properly isolated from each other. This should be easier to do with a 5x5x5 cube.

About the delay - I suggest you'll take a look at the Arduino code in that instructable - it seems that between the different layers, the code does not use any delay, only between effects. The final result seems to works great.

  [1]: http://www.instructables.com/id/Led-Cube-8x8x8/?ALLSTEPS


body:
A simple way to test for short between LEDs is to write a loop that lights one of them at a time, one right after the other, for 50ms or so. It's relatively easy to notice two LEDs lighting together (a short) or a missing blink in the sequence (an open), assuming you can see all the LEDs at once.

Update (6 years later, but hey - I since people still read this question):

I use a sketch that does exactly this to help find shorts and opens when I'm building up a new board. I'd previously implied that you need all of the LEDs attached, but you need at most 2.

On a newly soldered cpu with power & ground (and reset jumpered to ground), holding an LED on each of two adjacent pins will show a shorted pair, while a single LED on one pin will display an open or a short to ground (or to +5, if you orient your LED+resistor that way). I keep a few LEDs with a resistor soldered to the cathode, or ground, leg to use as digital probes.


message:
Arduino Interrupt Debouncing

I have an issue with debouncing.
I am using a MCP23017 as an I/O-extender with an Arduino. This uses I2C to communicate with each other.

A variable amount of switches is connected to the MCP23017 (0-16 switches). On change of the inputs, an interrupt is generated and the Arduino captures this on rising edge. So whenever a button is pushed or released, an interrupt is generated.

Now I'm confused as how I should debug them. One option would be to set a delay after an interrupt (of let's say 50 ms), before turning the interrupts back on. This could have an issue however, since multiple inputs are connected to the same interrupt line.

Another option is to have a timestamp or something for the last time each switch was changed, and check if the time difference is big enough, otherwise ignore the next pulse. The problem with this is that it uses quit some resources as I have limited memory and there can be up to 8 extenders (so 8 * 16 = 128 inputs).

What is the most efficient way to handle these interrupts with debouncing?

body: Add [debouncing circuitry](http://www.labbookpages.co.uk/electronics/debounce.html) if you can; it's not that difficult.


body:
Depends on the application.

Define efficiency. What are you looking to optimize for? Manhours spend coding/testing, processor speed, response time?

Are theses keys to a piano synth? Yes you'll want interrupt speed, and each key needs to not affect the surrounding keys.

Is it going to be rare that two keys are pressed anywhere near each other? a timeout for the ISR is perfectly legitimate.

Will the user not observe any lag when he flips a switch and resources are tight? Then polling could be a viable option.

Are the EMI concerns and you need to filter out false positives? Well you're going to need do some more. Like sampling for sustained values or counting how long until the falling edge occurs.

There are so many options depending on what you want it to do.


message:
What is the circular gold pad on arduino mega 2560 v2 and above?

Could someone point me to the documentation that describes the gold dot and surrounding gold circle on the front of my arduino mega v2 board. It is right above the ICSP header and reset button, and directly underneath the letter 'U' in the silk screened word 'communication'
I've not been able to find any reference to it anywhere. Is is a jumper, a test pad, RF pad???

body:
That is most likely a Fiducial Mark for the vision system of a pick-and-place assembly robot to key off of in order to more precisely place the components on their pads.

If you look carefully, you will see a second one located below the DC barrel jack.

Boards like this are manufactured in a gridded panel having a number of copies in each direction, and only cut apart after they are largely complete.  With such a large workpiece, any linearity error in the manufacturing could result in a high-density component being misplaced far enough to cause problems.  Having a pair of fiducials on each individual board in the panel can help calibrate out errors not only which might otherwise accumulate over the large dimensions of the entire panel, but also rotational skew of the panel in its holder.

![Picture of the Arduino 2560 from arduino.cc site][1]

You can see both on this picture of the Arduino Mega 2560 from the arduino.cc site

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


body: To add to Chris's answer: fiducials appear at three levels. First there are fiducials at the panel level, which contains one or more PCBs, depending on their size. Next there are fiducials for the PCB, acting as a position reference for component placement. Sometimes you can see component fiducials close to some fine pitch components, to make sure they are placed with high precision. You'll sometimes see these latter fiducials on opposite corners of QFP (Quad Flat Package) parts. (The AVR controller on the Arduino Mega 2560 is in QFP.)


message:
8-segmet LED's on Adafruit Trinket

I would like to have an array of eight 7- and [8-segment LED][1] numerical displays on my Adafruit Trinket.
I know that there are some prebuilt arrays of 4 LED's. So 2 in array would do just fine.
However, my Adafruit Trinket doesn't have enough ports for that. I have heard something about connecting it to a small piece of controlling hardware that makes me able to have way less ports in need.
What is the appropriate way of connecting a lot of those LED's on only a few ports on a micro controller?

My ideal output would be as follow:
88 88:88:88 or maybe 88 88.88.88
So ideally there would be a small space between the first group of 2 digits and the rest.
Basically, the last 6 digits will represent a time in minutes, seconds and hundreds of seconds.

  [1]: http://4.bp.blogspot.com/-d4ug4mb_Cw0/T6y7ZVrbb-I/AAAAAAAAAsE/nj6Tfp0j26s/s400/SEV1.jpg

body:
For LED displays, I advise using a [MAX7219][1].

This circuit:

- can manage up to 8 digits (7-segments + 1 LED for DP or colon separator) or up to 64 LEDs
- needs only 3 pins to manage display
- can be daisy-chained if you need to interface with more than 64 LEDs
- requires only 1 resistor to be fully functional
- is easily supported on Arduino with [this library][2]

I have used it in several circuits and happy with it.

Note that there also [other libraries][3] that support this circuit but I haven't used them.

This circuit has only one downside: its price (about $10 each); but the price is counter-balanced by its simplicity and the fact you don't need any additional component (e.g. transistors) besides a simple resistor.

  [1]: http://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf
  [2]: http://playground.arduino.cc/uploads/Main/LedControl.zip
  [3]: http://playground.arduino.cc/Main/LEDMatrix