body:
I have got same problem and you can solve it in minutes! Firstly check all your I2C addresses with same code:

    #include "Wire.h"

    byte start_address = 0;
    byte end_address = 127;

    void setup()
    {
      byte rc;
      Wire.begin();

      Serial.begin(9600);
      Serial.println("\nI2C Scanner");

      Serial.print("Scanning I2C bus from ");
      Serial.print(start_address,DEC);  Serial.print(" to ");  Serial.print(end_address,DEC);
      Serial.println("...");

      for( byte addr  = start_address;
                addr <= end_address;
                addr++ ) {
          Wire.beginTransmission(addr);
          rc = Wire.endTransmission();

          if (addr<16) Serial.print("0");
          Serial.print(addr,HEX);
          if (rc==0) {
            Serial.print(" found!");
          } else {
            Serial.print(" "); Serial.print(rc); Serial.print("     ");
          }
          Serial.print( (addr%8)==7 ? "\n":" ");
      }

      Serial.println("\n-------------------------------\nPossible devices:");

      for( byte addr  = start_address;
                addr <= end_address;
                addr++ ) {
          Wire.beginTransmission(addr);
          rc = Wire.endTransmission();
          if (rc == 0) {
            Serial.print(addr,HEX); Serial.print(" = ");
            switch (addr) {
              case 0x50: Serial.println("AT24C32/AT24C64 - EEPROM"); break;
              case 0x68: Serial.println("DS1307"); break;
              default: Serial.println("Unknown"); break;
            }
          }
      }

      Serial.println("\ndone");
    }

    // standard Arduino loop()
    void loop()
    {
        // Nothing to do here, so we'll just blink the built-in LED
        digitalWrite(13,HIGH); delay(300);
        digitalWrite(13,LOW);  delay(300);
    }

And you will get something like this:

    I2C Scanner
    Scanning I2C bus from 0 to 127...
    00 2      01 2      02 2      03 2      04 2      05 2      06 2      07 2
    08 2      09 2      0A 2      0B 2      0C 2      0D 2      0E 2      0F 2
    10 2      11 2      12 2      13 2      14 2      15 2      16 2      17 2
    18 2      19 2      1A 2      1B 2      1C 2      1D 2      1E 2      1F 2
    20 2      21 2      22 2      23 2      24 2      25 2      26 2      27 2
    28 2      29 2      2A 2      2B 2      2C 2      2D 2      2E 2      2F 2
    30 2      31 2      32 2      33 2      34 2      35 2      36 2      37 2
    38 2      39 2      3A 2      3B 2      3C 2      3D 2      3E 2      3F 2
    40 2      41 2      42 2      43 2      44 2      45 2      46 2      47 2
    48 2      49 2      4A 2      4B 2      4C 2      4D 2      4E 2      4F 2
    50 2      51 2      52 2      53 2      54 2      55 2      56 2      57 2
    58 2      59 2      5A 2      5B 2      5C 2      5D 2      5E 2      5F 2
    60 2      61 2      62 2      63 2      64 2      65 2      66 2      67 2
    68 2      69 found! 6A 2      6B 2      6C 2      6D 2      6E 2      6F 2
    70 2      71 2      72 2      73 2      74 2      75 2      76 2      77 2
    78 2      79 2      7A 2      7B 2      7C 2      7D 2      7E 2      7F 2

    -------------------------------
    Possible devices:
    69 = Unknown

    done

The address `69` is your device, MPU-6050! Now check your code and you can see that you use:

    #define MPU6050_I2C_ADDRESS 0x68

But you must use the correct address of MPU, change it:

    #define MPU6050_I2C_ADDRESS 0x69

[Code source](https://sites.google.com/site/akvarkoota/arduino-mega-2560/tiny-rtc/i2c_scanner).


sender: user

message:
Functions of GSM

I am currently working on an arduino project and wanted to use a GSM module. This is my first time working with a GSM module. So I had a few queries.

What can a GSM module sim900a do with arduino programming?

Also can it do the following:

1. Send sms when motion is detected by a PIR sensor
2. Send sms to only a particular group of cell phones.
3. Respond to a particular kind of sms

sender: assistant

body:
None of those things you ask are a function of the SIM900A GSM module.

The SIM900A GSM module is capable of sending and receiving text messages (SMS). What you do with those text messages, and what text messages you send to where is entirely down to your Arduino program.

What you are asking is like "Can this car drive from Manchester to Carlisle?" The car can be driven from place to place, but it's *you* that does the driving. So you should be asking "I have a car. Am I capable of driving it from Manchester to Carlisle?"

So yes, the SIM900A GSM module is capable of being used to achieve those three things you ask, but the real question is not can the SIM900A do them, but *can you program the Arduino to get a SIM900A to do them?* And the answer is "Yes, it is perfectly possible if you know how", and we can help you to know how when you start working on the project and come across some stumbling blocks in your programming.


body:
> 1. Send sms when motion is detected by a PIR sensor

**Yes**, write a function that does this. Basic support functions in libraries will help you send the sms and detect the PIR. You need to provide the logic.

> 2. Send sms to only a particular group of cell phones.

If the question is if the GSM module supports group send the answer is **no**. You will have to write a function that sends the SMS to each number in the group.

> 3. Respond to a particular kind of sms

**Yes**, again but now you have to write a function that parses incoming messages and does some actions (just as any input parse).

The answer to all these questions is **no** if the function is already available in libraries. The answer is **maybe** if someone has already done something similar.


message:
Reading sensor data over MUX

I will start by saying I am very new to using Arduino.  The project I am planning is to create several arrays of sensors (each array will consist of 4 DS18B20 sensors and one temperature/humidity sensor) and using a MUX connected to Arduino I want to read the data from each [ten] array.  I have found sketches I can modify to do this task in a continuous cycle but I need to be able to display data from an array for an extended time period of several minutes.  My Arduino will output to a 3.2" LCD so there is only enough screen space to show data for one array at a time.

body:
The DS18B20 is a [1-Wire][1] device and doesn't require a multiplexer, each device has its own address on the bus and you can connect a lot of them with a single wire. Depending on the humidity sensor you pick you may be able to use the same bus for it as well.

It is harder to find 1-Wire humidity sensors, but you could use a [DS2438 Smart Battery Monitor][2] which also includes an ADC to give you values from an analog humidity sensor.

The challenge of designing your project will be setting up an easy to understand display and controlling how/when it changes.

[1]: http://playground.arduino.cc/Learning/OneWire
[2]: http://electronicdesign.com/test-amp-measurement/1-wire-technology-simplifies-humidity-and-temperature-measurement


message:
Load Arduino flash code from SD card

I have an Arduino Uno. It doesn't have a lot of memory space, which is a bit of a nuisance. I was wondering:  Is it possible to load a text file from an SD card and compile it on the Arduino into code that the Arduino can use. I don't really care if it is slow or uses 99% of the memory space just to load on the code. If it is possible would this work: use bootup code to load a piece of code to Arduino, dispose of bootup code so there is more code, do what ever that code does, dispose of that code, load new code.

body:
See [topic #16812](http://forum.arduino.cc/index.php?topic=16812.0), “Load sketch code from SD Card”, in forum.arduino.cc, which explains how to replace the ordinary Arduino bootloader with one that can load programs from an SD card.

Also see [Bootdrive loads Arduino sketches from SD card](http://dangerousprototypes.com/2012/02/22/bootdrive-load-arduino-sketches-from-a-sd-card/) at dangerousprototypes.com, which gives different code to do the same thing.  It also mentions [BootDrive for Arduino](http://baldwisdom.com/bootdrive/) from baldwisdom.com.

Note, the program code that these loaders install into flash is already compiled, as opposed to being original C source code.  If you want to load source-level code into the Arduino, look for an interpreter / interpretive language to run on the Arduino.


body:
The flash memory is only designed to be reloaded 10,000 times. While that might seem a lot, if you are planning a system where, every day you load some part of code into flash, and then some other part, etc. you will use up those 10,000 writes fairly quickly.

>  I don't really care if it is slow or uses 99% of the memory space just to load on the code.

Well, you **will** care because if 99% of the memory space is the loader, you will only have 1% for the code, which defeats the purpose.

> It doesn't have a lot of memory space, which is a bit of a nuisance.

I suggest a larger processor such as the Atmega1284 (128k of flash), Atmega2560 (256k of flash) or the Atmega644P (64k of flash).

All but the Atmega2560 come in DIP versions of the chips, if that helps.


message:
Problems with Windows 8.1 install of Arduino IDE

I have replaced my Arduino, thinking it would solve the problem, but I still get it. Whenever I try to upload code, I get the error messages programmer is not responding and not in sync. Then I heard Arduino had drivers required. But my Windows 8.1 didn't recognize Arduino Uno. It was put in the other devices area as an unknown device in the device manager. The update driver button is greyed out. I get the message:

> The drivers for this device are not installed (code 28). There are no
> compatible drivers for this device. To find a driver for this device,
> click update driver.

That's the greyed out button… When I look at driver details, it says 'No driver files are required or have been loaded for this device.' For the not in sync/programmer not responding error, I've tried restarting the board before uploading, restarting whilst uploading, you say it, I've done it. How can I fix this so I can finally follow my dream to be an engineer/programmer?

body:
Getting started with a new toolchain can be quite a challenge…

I'm not a Windows guy, but it looks like there **are** drivers that need to  be installed to get things working with the Arduino. I'm guessing that what is going on here is that Windows is looking locally for drivers and not finding them (or any indication that drivers are needed). I think the button was grayed out because it couldn't help – not because help wasn't needed.

Here are a few sources that I found by searching on:

> arduino driver windows 8.1

 1. [[SOLVED] Arduino drivers for Windows 8.1 64bit][1]
 2. [Windows 8.1 (64bit) USB-serial driver for Arduino?][2]
 3. [Installing the Arduino IDE – Windows 8.1 & 10][3]
 4. [Install Arduino Drivers on Windows 8][4]

While we're at it, it is worth mentioning that "out of sync" error message from avrdude are very common. A bit of searching here will find you some good resources on solving them as well – deal with the drivers first, then see if errors persist.

[1]: https://forum.arduino.cc/index.php?topic=205837.0
[2]: http://answers.microsoft.com/en-us/windows/forum/windows8_1-windows_install/windows-81-64bit-usb-serial-driver-for-arduino/418f4de7-1361-4f98-ace6-4f6c0c44340b?db=5&auth=1
[3]: http://openenergymonitor.org/emon/node/3727
[4]: http://mytechblog.com/tutorials/arduino/install-arduino-drivers-on-windows-8/


message:
Sensor for very low temperature (liquid nitrogen)

I'm looking for a way to measure temperatures in range of 40 to -200 °C (100 to −320 °F). The usual solution DS18B20 works only down to -55 °C (-67 °F).

Any ideas?

*p.s.*
Precision of 2 °C would be good enough.

body:
You probably want a K-type thermocouple (the most common type).

They have a range of around -200°C to +1350°C (depending on probe).

Alternatively a Resistive Temperature Device (RTD) can be used, since these have a typical range of around -240°C to 650°C with higher accuracy.

This might be of help to you: http://digital.ni.com/public.nsf/allkb/C50FA55B3B2F85D9862572D00083350E


body:
I did a search on "cryogenic temperature sensors" and found these from [Lake Shore Cyrotronics][1] – the price is shocking. It appears that you can use [silicon diodes][2] as cryogenic temperature sensors, so you might be able to use less expensive parts if you don't need a ton of accuracy.

[1]: http://www.lakeshore.com/products/Cryogenic-Temperature-Sensors/Pages/default.aspx
[2]: http://www.lakeshore.com/products/cryogenic-temperature-sensors/silicon-diodes/dt-670/Pages/Overview.aspx


message:
Watchdog approach

I'm developing up a project that is designed to run 24/7 (an energy monitor) logging via wifi.

Due to a variety of considerations I've ended up with a design that links an Arduino Nano with an ESP8266-01.

I was considering designing in a watchdog, but had the thought that each of these MCUs could act as the watchdog for the other.  My hypothesis is that the likelihood of both going down simultaneously is relatively low, and as both need to communicate with each other regularly, they will know when the other unit has become non-responsive, and they would also be able to initiate a hardware (rather than software) reset on the other device.

Is this a valid/workable approach?  Or is there something else I need to consider that would warrant an external watchdog(s)?

EDIT: as there were a few comments re: low-power etc., just wanted to clarify that this will be powered from the 240v supply it monitors (using a switch-mode supply), so this isn't expected to be an issue.

body:
I had a [similar project](http://www.gammon.com.au/forum/?id=12821) a while back, including the desire for the watchdog.

> My hypothesis is that the likelihood of both going down simultaneously is relatively low ...

Here's the problem. If it is solar powered (or even just battery powered) then the likelihood is quite high that they will both get insufficient power at much the same time (ie. low voltage).

One thing I noticed was that if voltage slowly drops (as it does when the sun goes down, and the battery discharges) then the processor can enter a brown-out situation where it basically just goes dead, without resetting.

Now you **can** set brown-out detection in the fuses, but the reference voltage generator, needed to make it work, itself increases the power consumption. So you get the situation where the brownout detection drains the battery, causing a brown-out situation, where without brownout detection it might have lasted all night.

---

Anyway, the net effect was that the design on the linked page wasn't as reliable as I hoped.

To make this answer more complete, here is my watchdog processor schematic:

[![Watchdog processor schematic][1]][1]

And this was the code for it:

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

    // Reset solar panel watchdog
    // Author: Nick Gammon
    // Date: 22 March 2015

    // ATMEL ATTINY 25/45/85 / ARDUINO
    // Pin 1 is /RESET
    //
    //                  +-\/-+
    // Ain0 (D 5) PB5  1|    |8  Vcc
    // Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
    // Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
    //            GND  4|    |5  PB0 (D 0) pwm0
    //                  +----+

    /*

     After reset waits for TIME_TO_WAIT minutes, then brings D0 (pin 5) high for long
     enough to activate a MOSFET and reset the other board.

     Fuses: Low: E2 High: DD

     (Brownout at 2.7V)

    */

    #include <avr/sleep.h>    // Sleep Modes
    #include <avr/power.h>    // Power management
    #include <avr/wdt.h>      // Watchdog timer

    const byte MOSFET = 0;          // pin 5
    unsigned long counter = 0;

    const float TIME_TO_WAIT = 30; // minutes
    const unsigned long SLEEPS_TO_WAIT = TIME_TO_WAIT * 60.0 / 8.0;  // 8 second sleeps

    // watchdog interrupt
    ISR (WDT_vect)
      {
       wdt_disable();  // disable watchdog
      }  // end of WDT_vect

    #if defined(__AVR_ATtiny85__)
      #define watchdogRegister WDTCR
    #else
      #define watchdogRegister WDTCSR
    #endif

    void setup ()
      {
      wdt_reset();
      pinMode (MOSFET, OUTPUT);
      ADCSRA = 0;            // turn off ADC
      power_all_disable ();  // power off ADC, Timer 0 and 1, serial interface
      set_sleep_mode (SLEEP_MODE_PWR_DOWN);
      }  // end of setup

    void loop ()
      {
      counter++;

      if (counter >= SLEEPS_TO_WAIT)
        {
        digitalWrite (MOSFET, HIGH);
        delayMicroseconds (10000);
        digitalWrite (MOSFET, LOW);
        // our job here is done
        sleep_enable ();       // ready to sleep
        sleep_cpu ();          // sleep
        }

      goToSleep ();
      }  // end of loop

    void goToSleep ()
      {
      noInterrupts ();       // timed sequence coming up
      // pat the dog
      wdt_reset();

      // clear various "reset" flags
      MCUSR = 0;
      // allow changes, disable reset, clear existing interrupt
      watchdogRegister = bit (WDCE) | bit (WDE) | bit (WDIF);
      // set interrupt mode and an interval (WDE must be changed from 1 to 0 here)
      watchdogRegister = bit (WDIE) | bit (WDP3) | bit (WDP0);    // set WDIE, and 8 seconds delay

      sleep_enable ();       // ready to sleep
      interrupts ();         // interrupts are required now
      sleep_cpu ();          // sleep
      sleep_disable ();      // precaution
      }  // end of goToSleep

The design intention here was that the watchdog processor would reset overnight (when the solar panel lost power and the supercapacitor eventually discharged) and in the morning it would power up, wait 30 minutes (for the sun to rise and the voltage to become stable) and then unconditionally reset the other processor from whatever state it was in.

---

> as there were a few comments re: low-power etc., just wanted to clarify that this will be powered from the 240v supply it monitors (using a switch-mode supply)

Yes, well I also live in a country with 240V power. Today during 41°C heat the power failed a number of times for very short intervals. Various computers reset or behaved strangely. Like with a low voltage battery, a brown-out, or brief failure, of the mains power could simultaneously strike all your devices, including the watchdog device.

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


body:
As a watchdog mechanism to protect against software lockup type issues then using one processor to detect issues and reset the other is an economical idea.  However, I would completely agree with Nick that if you want protection from hardware issues like brown outs or slow rise time of the power supply then both micros could share the same vulnerabilities that a dedicated watchdog device would be able to address.  How significant this is depends on your power arrangements.

The other case to consider is now much does the software of one device interact with and depend on that of the other device such that it is conceivable that one device locking up in some way could impact the other defeating the watchdog functionality.

Personally I've seen too many situations where an internal micro watchdog failed to detect and recover an issue so would always go for an external device in any professional product.  Even there I would advise the use of a devices which requires the watchdog to be kicked within a time window rather than just within a maximum time period - otherwise if things contrive to go wrong in such a way that the watchdog is permanently getting kicked it will not recover the situation.  [I saw the micro pin responsible for kicking a simple external watchdog accidentally reconfigured by runaway code as a timer output once.]

I suspect that if you are thinking that your product needs a watchdog then it is worth doing properly with an external one.


message:
Error when trying to write analog and digital signals from different pins (Arduino UNO)

I'm using the Arduino UNO and started noticing some funny behavior when I was trying a few basic projects. Specifically when trying to write an analog signal through one of the PWM pins, then a digital signal through another.

Using some LED's connected to a few different permutations of pins 8-13, I found that when I have an analog output set for one of the pins (in this case 9, 10, or 11 as they're the only one's of the set capable of PWM) and then try to output a digital signal from a different pin to another LED the digital signal seems much weaker. That is, the LED shines very very dim.

The pins 2-7 work fine.
Does the behavior described above indicate anything wrong with the arduino? are those pins potentially damaged, or is there something I'm not understanding here?

My code:<br/>

    void setup()
    {}

    void loop()
    {
       analogWrite(9, 255);
       delay(1000);
       analogWrite(9, 0);
       delay(2000);
       digitalWrite(8, HIGH);
       delay(1000);
       digitalWrite(8, LOW);
       delay(2000);
    }

[![Diagram][1]][1]

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

body:
The pin groups your describe are on different ports of the chip which have different current sourcing ratings.
I'm sure you'll find an even brightness using similar LEDs on all pins and using a 1K res in series with each led to limit current.
Also , to ensure the sourcing transistors are ON within the chip, be sure to declare the pins as output when required.


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

I tested your code and it does indeed behave the way you said. But that is because you have not declared any pins as output.

`analogWrite` does this for you automatically in the library, however `digitalWrite` does not. This is because sending a digital pin `HIGH` when it is `INPUT` turns on the internal pull-up resistors. These are around 50k. Thus you will only see very dim output on the LED. Add this line to `setup`:

     pinMode (8, OUTPUT);

(And preferably pin 9 as well, just in case you decide to change to digital writes later).


message:
Recovering from lost USB connection (Leonardo to Raspberry Pi)

I have several Arduino Leonardos connected to a Raspberry Pi (running Ubuntu) via USB. They appear as `/dev/ttyACM0`, `/dev/ttyACM1`, etc.

Occasionally, one will disappear and even pressing the Arduino's reset button won't bring it back. Is there any way to "refresh" or "reinitialize" the ttyACM* devices to make them reappear without having to reboot the Raspberry Pi?

body:
The USB devices are created dynamically. You might find this question and answer from the SE Raspberry Pi helpful: [How to force rescan of USB serial devices?][1].

You can use the **dmesg(8)** command on the Pi to see the messages generated by the USB sub-system. Watch the output to see if there are errors associated with the Arduino dropping off the bus. This is what the output will look like (roughly, this is from an Uno connected to a Raspbian system), note the last line which is a disconnect from unplugging the Uno from the Pi. Resetting the Uno did not do anything that the Pi saw. I would guess that that is because the reset button on the Uno doesn't reset the 16U2 (the processor handling the USB port).

    [  459.936719] usb 1-1.3: new full-speed USB device number 5 using dwc_otg
    [  460.051182] usb 1-1.3: New USB device found, idVendor=2a03, idProduct=0043
    [  460.051212] usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
    [  460.051229] usb 1-1.3: Product: Arduino Uno
    [  460.051245] usb 1-1.3: Manufacturer: Arduino Srl
    [  460.051262] usb 1-1.3: SerialNumber: 75431343334351F061E2
    [  460.088018] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device
    [  460.089250] usbcore: registered new interface driver cdc_acm
    [  460.089270] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters
    [  534.212365] usb 1-1.3: USB disconnect, device number 5

From reading that question and its answers it appears that [some versions of the Leonardo may have problems][2] that can cause this behavior.

Another thing that might be worth looking into is the power supply for the Leonardos. If they are being powered by the Pi through the USB interface that might be pushing the capability of the Pi to provide power.

[1]: https://raspberrypi.stackexchange.com/questions/13455/how-to-force-rescan-of-usb-serial-devices
[2]: https://www.raspberrypi.org/forums/viewtopic.php?f=91&t=59420


body:
Every device is also found on a symlink, named by its hardware wireing. So this names stay the same after re-appering!

    root@raspberrypi:/etc/udev/rules.d# ls -l /dev/serial/by-path/
    total 0
    lrwxrwxrwx 1 root root 13 May  2 18:11 platform-20980000.usb-usb-0:1.2:1.0 -> ../../ttyACM0
    lrwxrwxrwx 1 root root 13 May  2 18:11 platform-20980000.usb-usb-0:1.3.1:1.0-port0 -> ../../ttyUSB0
    lrwxrwxrwx 1 root root 13 May  2 18:11 platform-20980000.usb-usb-0:1.3.1:1.0-port1 -> ../../ttyUSB1


message:
How to diagnose unresponsive Leonardo serial port?

I was using an Arduino Leonardo (in the form of an [RPI hat][1]) to control a single DC motor via a [motor controller](https://www.pololu.com/product/2990). I have it wired to set Phase and Enable to control motor speed and direction, and I read sensors on the motor's encoder to directly measure motor speed.

I triple checked all my wiring, and a test program I wrote to spin the motor at half-speed seemed to work just fine. Then it suddenly stopped working. Now, when I plug the Leonardo into my machine, the ttyACM0 device does not appear, and I seem to have no way to communicate with it anymore.

I've noticed that when I press the reset button, the Leonardo's status light flashes for a few seconds and ttyACM0 does momentarily appear. But as soon as the flashing stops, ttyACM0 disappears again. I tried upload a new sketch when the device reappears, but I get a "broken pipe" error.

What's going on here? Did I somehow fry my Leonardo, or is it possible I just screwed up the serial port? How do I fix it?

Edit: For the host, I've tried Ubuntu 14 running on a Raspberry Pi 2 and a generic 64bit laptop.

Edit: My `setup()` is simply:

    void count_pan_changes(){
        /*
        CW  => 11,00,11,00,...
        CCW => 10,01,10,01,...
        */
        int a = digitalRead(MOTOR_ENCODER_A_PIN);
        int b = digitalRead(MOTOR_ENCODER_B_PIN);
        int direction = (a == b) ? +1 : -1;
        motor_controller.record_direction(direction);
    }

    void setup(){
        attachInterrupt(digitalPinToInterrupt(MOTOR_ENCODER_A_PIN), count_pan_changes, CHANGE);
    }

Edit: I'm not sure why, but when I disconnected the Leonardo from it's 5V UBEC power supply and powered it directly from my laptop via USB, then ttyACM0 suddenly came back. However, when I reconnect it to its own power supply, I again have problems connecting to it. The first upload and serial terminal seem to work, but as soon as I disconnect, further uploads/serial connections seem to fail with a "broken pipe" error. I'm powering it via a UBEC by connecting the 5V and Gnd lines to one of the Leonardo's GVS headers (i.e. it's not going in through any onboard regulator on the Arduino or RPi). Should this work? The motor is behind a separate UBEC.

Edit: Now power cycling isn't even fixing it. I tried erasing the contents using:

    avrdude -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -e

as explained [here][2]. This keeps /dev/ttyACM0 from disappearing, but if I try and upload a sketch using `ano upload`, I still get the error:

    IOError: [Errno 32] Broken pipe

  [1]: https://www.dfrobot.com/wiki/index.php?title=Raspberry_Pi_B+_Meet_Arduino_Shield_SKU:DFR0327
  [2]: http://forum.arduino.cc/index.php?topic=261139.0

body:
I think this might be a bug in Arturo. This is how I was able to fix my Leonardo:

1. Fix disappearing `/dev/ttyACM0` by pressing reset to temporarily bring it back, then erase all content with:

    avrdude -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -e

    Now /dev/ttyACM0 stays there, but trying to upload my sketch throws a broken pipe error.

2. Upload a blank sketch using the Arduino IDE.

Then I could upload my sketches normally.


body:
Since your code does not open the serial port, it is entirely expected that the serial port will appear briefly on reset, and then disappear. Initially it appears as the bootloader looks for a new sketch, and disappears because your code does not open Serial.

If you time it correctly you should be able to upload a new sketch after pressing Reset. You need to press Reset fairly precisely after the IDE announces that is uploading. You only have a window of a second or so.


message:
Resetting 16U2 Processor on Uno (R3)

[This question][1] got me thinking, the OP was wondering about how to "bring back" Leonardo boards connected to a Raspberry Pi via USB. The Leonardos would occasionally drop off line and could not be brought back by resetting the board.

So I got curious and hooked a Uno up to a Pi via USB and started poking around. I had the idea that perhaps resetting the 16U2 would do the trick. It does not. After resetting the 16U2 (by grounding the reset pin in the ICSP connector). This is what I see in the kernel log on the Pi:

    [ 6277.570058] usb 1-1.3: USB disconnect, device number 11
    [ 6278.576503] usb 1-1.3: new full-speed USB device number 12 using dwc_otg
    [ 6278.684793] usb 1-1.3: New USB device found, idVendor=03eb, idProduct=2fef
    [ 6278.684823] usb 1-1.3: New USB device strings: Mfr=0, Product=1, SerialNumber=0
    [ 6278.684841] usb 1-1.3: Product: ATmega16U2 DFU

As opposed to this:

    [ 6325.960510] usb 1-1.3: USB disconnect, device number 12
    [ 6329.267003] usb 1-1.3: new full-speed USB device number 13 using dwc_otg
    [ 6329.382675] usb 1-1.3: New USB device found, idVendor=2a03, idProduct=0043
    [ 6329.382703] usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
    [ 6329.382720] usb 1-1.3: Product: Arduino Uno
    [ 6329.382736] usb 1-1.3: Manufacturer: Arduino Srl
    [ 6329.382753] usb 1-1.3: SerialNumber: 75431343334351F061E2
    [ 6329.384088] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device

Which is what I see if I unplug and replug the USB cable.

I'd like to know what happens differently during a 16U2 reset vs. an unplug/replug cycle.

I'd also like to know if there is a way to simulate unplugging and replugging the USB cable. The 16U2 reset comes close (the Pi notices that something happened), but it would be nice if there were a way that either code on the Uno or on the Pi could "wake up" a down USB link.

[1]: https://arduino.stackexchange.com/questions/19508/how-to-recreate-missing-ttyacm-devices

body:
What I think is happening here is that the HWBE fuse is set (hardware boot enable).

From the datasheet:

> The Hardware Boot Enable Fuse (HWBE) can be programmed so that upon
special hardware conditions under reset, the bootloader execution is forced after reset.

What this means is that under normal booting (power-on reset) the bootloader is not entered, and the device immediately identifies as a TTY device (ttyACM0) as you saw:

    [ 6329.384088] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device

However if you manually reset it, it enters DFU mode with its bootloader, so you can reprogram the main code. Thus it identifies differently:

    [ 6278.684841] usb 1-1.3: Product: ATmega16U2 DFU

Thus, a forced reset via the Reset pin acts differently to a power-on rest. By design.

---

If you search for `uno enter dfu mode` you will get quite a few hits. People use that technique to reprogram their ATmega16U2 (eg. to act as a MIDI interface).


message:
HC-05 Bluetooth Module - INQ-Command doesn't work

For a project I need to connect a Bluetooth Remote control with an Arduino Nano.

**The Problem**

I am trying to setup a connection to said Bluetooth remote Control. This device is visible! (I have confirmed it with a smartphone)

Here are the steps that I am trying to do with the Arduino and HC05 module:

    AT <-- confirms, that Command Mode is running successfully
    OK

    AT+ROLE? <-- 1 For Bluetooth Master Mode
    +ROLE:1
    OK

    AT+CMODE? <-- 1 allows connecting to any BT address
    +CMOD:1
    OK

    AT+INQM? <-- Show Inquiry access values
    +INQM:1,1,48
    OK

    AT+INQ <-- Inquiry Bluetooth Device

After ~60 seconds, it just says "OK", but according to [this tutorial][1]  or according to [this youtube video][2] it should display all Bluetooth-devices, that are ready to connect.
The BT device is definately visible. (I tried multiple BT devices like smartphones and peripheral devices).

**Why is the inquiry not working? What is wrong here?**

**The circuit is exactly like in this picture:**

[![circuit][3]][3]

For setting up the Bluetooth-connection I wire the EN-Pin to +3,3V, which successfully activates **AT-Command-Mode**
[According to this site][4], you can do it like that.

Here is my code, that I use, to communicate with the module. - It works good!

<!-- language: c -->

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(2, 3); // RX | TX
    // Connect the HC-05 TX to Arduino pin 2 RX.
    // Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.
    //

    char c = ' ';
    int buf[64]; //buffer to store AT commands
    int len = 0; //stores the length of the commands

    void setup()
    {
        Serial.begin(9600);
        Serial.println("Arduino is ready");
        delay(500);
        mySerial.begin(9600);
        Serial.println("BlueTooth is ready");
    }

    void loop()
    {

      if(Serial.available())
      {
        len = Serial.available(); //store number of bytes to read
        for(int i = 0; i<len; i++) //store all bytes into the buffer
        {
          buf[i] = Serial.read();
        }
        for(int i = 0; i<len; i++)
        {
          mySerial.write(buf[i]);
          Serial.write(buf[i]);
        }
      }

      if(mySerial.available())
      {
        len = mySerial.available();
        for(int i = 0; i<len; i++)
        {
          buf[i] = mySerial.read();
        }
        for(int i = 0; i<len; i++)
        {
          Serial.write(buf[i]);
        }
      }

    }

[Here is a related question but the answer doesn't help.][5]

  [1]: https://alselectro.wordpress.com/2014/10/21/bluetooth-hc05-how-to-pair-two-modules/
  [2]: https://youtu.be/Vr4cdpsoVEo?t=6m30s
  [3]: https://i.stack.imgur.com/lwMAs.jpg
  [4]: http://www.martyncurrey.com/arduino-with-hc-05-bluetooth-module-at-mode/
  [5]: https://electronics.stackexchange.com/questions/180962/hc-05-bluetooth-atinq-command-not-working

body:
Try this example from the datasheet:

    AT+INIT
    AT+INQM=1,9,48  // max of 9 devices, timeout of 61 seconds
    AT+INQ

And use this in your loop() instead:

    void loop() {
      while (Serial.available())
        mySerial.write(Serial.read());
      while (mySerial.available())
        Serial.write(mySerial.read());
    }


body:
I did a factory reset of the device. That resolved the issue

    AT+ORGL
    AT+RESET

Another thing that is very important: The KEY-Pin (EV-Pin on some boards) must be HIGH (3Volts), during the INQ-command. If this PIN is not High, the inq-command will not work.

If you put 3V to this PIN and release it, you indeed are in AT-Command mode. But not all AT-commands work (e.g. the said at+inq command). If you want to enable all AT-commands the PIN **must remain** high.


message:
Replacing delay() with millis()

I'm currently attempting to replace delay() in my project so that i may perform other tasks while waiting on a particular event to fire.

The issue I'm having, is every example i've found using millis / elapsedmillis has everything inside the loop, where I'm trying to use it inside void buttons(). needless to say, either it's not going to work outside of loop, or I'm doing something ridiculous, and too tired, or too ignorant to see what i'm doing wrong..

The end goal is to have the button draw over the top of the existing one, wait 1000ms then draw the next button.
(time interval will be changed later to sync with hardware spin down etc)

Here is the complete sketch, perhaps someone can show me a reliable way to replace delay in the buttons funciton:

<!-- language: c -->

    #include <Adafruit_GFX.h>
    #include <TouchScreen.h>
    #include <stdint.h>
    #include <SPI.h>
    #include <SD.h>
    #include <MCUFRIEND_kbv.h>
    MCUFRIEND_kbv tft;
    #include <elapsedMillis.h>

    elapsedMillis timer0;
    elapsedMillis sinceTime1;
    elapsedMillis sinceTime2;
    elapsedMillis sinceTime3;

    #define debug = false;
    //#define debug = true;

    #if defined(__SAM3X8E__)
    #undef __FlashStringHelper::F(string_literal)
    #define F(string_literal) string_literal
    #endif

    // most mcufriend shields use these pins and Portrait mode:
    uint8_t YP = A1;  // must be an analog pin, use "An" notation!
    uint8_t XM = A2;  // must be an analog pin, use "An" notation!
    uint8_t YM = 6;   // can be a digital pin
    uint8_t XP = 7;   // can be a digital pin
    uint8_t Landscape = 0;

    uint16_t TS_LEFT = 120;
    uint16_t TS_RT = 940;
    uint16_t TS_TOP = 940;
    uint16_t TS_BOT = 180;
    #define MINPRESSURE 10
    #define MAXPRESSURE 1000

    // For better pressure precision, we need to know the resistance
    // between X+ and X- Use any multimeter to read it
    // For the one we're using, its 250 ohms across the X plate
    TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

    #define LCD_CS A3
    #define LCD_CD A2
    #define LCD_WR A1
    #define LCD_RD A0

    // Assign human-readable names to some common 16-bit color values:
    #define BLACK   0x0000
    #define BLUE    0x001F
    #define RED     0xF800
    #define GREEN   0x07E0
    #define CYAN    0x07FF
    #define MAGENTA 0xF81F
    #define YELLOW  0xFFE0
    #define WHITE   0xFFFF

    int16_t BOXSIZE;
    int16_t PENRADIUS = 3;
    uint16_t oldcolor, currentcolor;

    #define SD_SCK 13
    #define SD_MISO 12
    #define SD_MOSI 11
    #define SD_CS 10
    // In the SD card, place 24 bit color BMP files (be sure they are 24-bit!)

    void setup() {
      // Init TouchScreen
        ts = TouchScreen(XP, YP, XM, YM, 300);     //call the constructor AGAIN with new values.

        BOXSIZE = tft.width() / 6;
        tft.fillScreen(BLACK);

      // put your setup code here, to run once:
        Serial.begin(9600);

      tft.reset();

      uint16_t identifier = tft.readID();
    if (identifier == 0x7789) {
            //Serial.println(F("Found ST7789V LCD driver"));
            TS_LEFT = 120; TS_RT = 940; TS_TOP = 940; TS_BOT = 180;
            Landscape = 1;
        } else {
            //Serial.print(F("Unknown LCD driver chip: "));
            //Serial.println(identifier, HEX);
            return;
        }

        //Serial.print(F("Found LCD driver chip ID: "));
        //Serial.println(identifier, HEX);

      tft.begin(identifier);

      //Serial.print(F("Initializing SD card..."));
      if (!SD.begin(SD_CS, SD_MOSI, SD_MISO, SD_SCK)) {
        Serial.println(F("failed!"));
        return;
      }
      //Serial.println(F("OK!"));
      tft.begin(identifier);
      tft.setRotation(3);
      BOXSIZE = tft.width() / 6;
      tft.fillScreen(BLACK);
      bmpDraw("splash.bmp", 80, 20);
      delay(5000);
      loadhome();

    }

    void loop() {
    //DO STUFF HERE

    //Testing Text stuff here
      tft.setTextColor(BLACK);
      tft.setTextSize(2);
      tft.setCursor(15, 33);
      tft.print("123.456");
      tft.setTextColor(BLACK);
      tft.setCursor(115, 33);
      tft.print("543.210");
      tft.setTextColor(BLACK);
      tft.setCursor(215, 33);
      tft.print("789.654");
      buttons();
    }

    void loadhome(){
      tft.setRotation(3);
      BOXSIZE = tft.width() / 6;
      tft.fillScreen(BLACK);
      bmpDraw("cell.bmp", 10, 25);
      bmpDraw("cell.bmp", 110, 25);
      bmpDraw("cell.bmp", 210, 25);
      bmpDraw("stop.bmp", 15, 175);
      bmpDraw("locked.bmp", 90, 175);
      bmpDraw("play.bmp", 165, 175);
      bmpDraw("home.bmp", 240, 175);
      bmpDraw("coolstp.bmp", 15, 105);
      bmpDraw("spinstp.bmp", 240, 105);

      tft.setTextColor(RED);
      tft.setTextSize(3);
      tft.setCursor(50, 3);
      tft.print("X");
      tft.setTextColor(RED);
      tft.setCursor(150, 3);
      tft.print("Y");
      tft.setTextColor(RED);
      tft.setCursor(250, 3);
      tft.print("Z");

    }

    int homer = 0;
    int play = 1;
    int lock = 0;
    int cool = 0;
    int spin = 0;

    const int interval = 1000;
    unsigned long curMillis; //Current millis

    void buttons(){
      //Touchscreen stuff
        TSPoint p = ts.getPoint();

        // if sharing pins, you'll need to fix the directions of the touchscreen pins
        pinMode(XM, OUTPUT);
        pinMode(YP, OUTPUT);

        p.x = map(p.x, TS_LEFT, TS_RT, 0, tft.width());
        p.y = map(p.y, TS_TOP, TS_BOT, 0, tft.height());
    /*
    //Use to map buttons
    //Be sure to mark out button code before use!!
     if (p.z > MINPRESSURE && p.z < MAXPRESSURE) {
        Serial.print(F("p.y ="));
        Serial.print(p.y);
        Serial.println("");
        Serial.print(F("p.x ="));
        Serial.print(p.x);
        Serial.println("");
     }
    */
    // Begin Buttons
    //Coolant Button
    if (p.y > 110 && p.y < 170 && p.x > 250 && p.x < 300) { // if stop area is pressed
      if(cool == 0){
       bmpDraw("coolen.bmp", 15, 105);
       //Serial.println(F("Coolant Button Pressed!"));
       cool = 1;
      } else {
       bmpDraw("coolerr.bmp", 15, 105);
       sinceTime1 = 0;
       //delay(500); //replacing with millis()
       if (sinceTime1 >= 1000) {
       bmpDraw("coolstp.bmp", 15, 105);
       //Serial.println(F("Coolant Button Pressed!"));
       cool = 0;
       }
      }
    }

    //Stop Button
    if (p.y > 185 && p.y < 235 && p.x > 250 && p.x < 300) { // if stop area is pressed
       //Serial.println(F("Stop Button Pressed!"));
       Serial.write(0x18);
       Serial.print("\n");
    }

    //Lock Button
    if (p.y > 185 && p.y < 235 && p.x > 182 && p.x < 234) { // if stop area is pressed
      if(lock == 0){
        Serial.print("$X\n");
       bmpDraw("unlocked.bmp", 90, 175);
       //Serial.println(F("Lock/Unlock Button Pressed!"));
       lock = 1;
      } else {
        Serial.print("$X\n");
       bmpDraw("locked.bmp", 90, 175);
       //Serial.println(F("Lock/Unlock Button Pressed!"));
       lock = 0;
      }
    }

    //Play-Pause Button
    if (p.y > 185 && p.y < 235 && p.x > 110 && p.x < 160) { // if stop area is pressed
      if(play == 0){
       Serial.print("~\n");
       bmpDraw("play.bmp", 165, 175);
       //Serial.println(F("Play/Pause Button Pressed!"));
       play = 1;
      } else {
       Serial.print("!\n");
       bmpDraw("pause.bmp", 165, 175);
       //Serial.println(F("Play/Pause Button Pressed!"));
       play = 0;
      }
    }

    //Home Button
    if (p.y > 185 && p.y < 235 && p.x > 35 && p.x < 90) { // if stop area is pressed
      if(homer == 0){
       bmpDraw("homeg.bmp", 240, 175);
       //Serial.println(F("Home Button Pressed!"));
       homer = 1;
      } else {
       Serial.print("$H\n");
       bmpDraw("homey.bmp", 240, 175);
       sinceTime2 = 0;
       //delay(500); //replacing with millis()
       if (sinceTime2 >= 1000) {
       bmpDraw("homer.bmp", 240, 175);
       }
       //delay(500); //replacing with millis()
       sinceTime2 = 0;
       if (sinceTime2 >= 1000) {
       //delay(750);
       bmpDraw("homeg.bmp", 240, 175);
       //Serial.println(F("Home Button Pressed!"));
       }
       homer = 1;
      }
    }

    //Spindle Button
    if (p.y > 110 && p.y < 170 && p.x > 35 && p.x < 90) { // if stop area is pressed
      if(spin == 0){
       bmpDraw("spinen.bmp", 240, 105);
       //Serial.println(F("Spindle Button Pressed!"));
       spin = 1;
      } else {
       bmpDraw("spinerr.bmp", 240, 105);
       sinceTime3 = 0;
       //delay(500); //replacing with millis()
       if (sinceTime3 >= 1000) {
       bmpDraw("spinstp.bmp", 240, 105);
       //Serial.println(F("Spindle Button Pressed!"));
       }
       spin = 0;
      }
    }

    }

    #define BUFFPIXEL 15

    void bmpDraw(char *filename, int x, int y) {

      File     bmpFile;
      int      bmpWidth, bmpHeight;   // W+H in pixels
      uint8_t  bmpDepth;              // Bit depth (currently must be 24)
      uint32_t bmpImageoffset;        // Start of image data in file
      uint32_t rowSize;               // Not always = bmpWidth; may have padding
      uint8_t  sdbuffer[3*BUFFPIXEL]; // pixel in buffer (R+G+B per pixel)
      uint16_t lcdbuffer[BUFFPIXEL];  // pixel out buffer (16-bit per pixel)
      uint8_t  buffidx = sizeof(sdbuffer); // Current position in sdbuffer
      boolean  goodBmp = false;       // Set to true on valid header parse
      boolean  flip    = true;        // BMP is stored bottom-to-top
      int      w, h, row, col;
      uint8_t  r, g, b;
      uint32_t pos = 0, startTime = millis();
      uint8_t  lcdidx = 0;
      boolean  first = true;

      if((x >= tft.width()) || (y >= tft.height())) return;

      //Serial.println();
      //Serial.print(F("Loading image '"));
      //Serial.print(filename);
      //Serial.println('\'');
      // Open requested file on SD card
      if ((bmpFile = SD.open(filename)) == NULL) {
        Serial.println(F("File not found"));
        return;
      }

      // Parse BMP header
      if(read16(bmpFile) == 0x4D42) { // BMP signature
        read32(bmpFile);
        //Serial.println(F("File size: "));
        //Serial.println(read32(bmpFile));
        (void)read32(bmpFile); // Read & ignore creator bytes
        bmpImageoffset = read32(bmpFile); // Start of image data
        //Serial.print(F("Image Offset: ")); Serial.println(bmpImageoffset, DEC);
        // Read DIB header
        read32(bmpFile);
        //Serial.print(F("Header size: "));
        //Serial.println(read32(bmpFile));

        bmpWidth  = read32(bmpFile);
        bmpHeight = read32(bmpFile);
        if(read16(bmpFile) == 1) { // # planes -- must be '1'
          bmpDepth = read16(bmpFile); // bits per pixel
          //Serial.print(F("Bit Depth: ")); Serial.println(bmpDepth);
          if((bmpDepth == 24) && (read32(bmpFile) == 0)) { // 0 = uncompressed

            goodBmp = true; // Supported BMP format -- proceed!
           // Serial.print(F("Image size: "));
           // Serial.print(bmpWidth);
           // Serial.print('x');
           // Serial.println(bmpHeight);

            // BMP rows are padded (if needed) to 4-byte boundary
            rowSize = (bmpWidth * 3 + 3) & ~3;

            // If bmpHeight is negative, image is in top-down order.
            // This is not canon but has been observed in the wild.
            if(bmpHeight < 0) {
              bmpHeight = -bmpHeight;
              flip      = false;
            }

            // Crop area to be loaded
            w = bmpWidth;
            h = bmpHeight;
            if((x+w-1) >= tft.width())  w = tft.width()  - x;
            if((y+h-1) >= tft.height()) h = tft.height() - y;

            // Set TFT address window to clipped image bounds
            tft.setAddrWindow(x, y, x+w-1, y+h-1);

            for (row=0; row<h; row++) { // For each scanline...
              // Seek to start of scan line.  It might seem labor-
              // intensive to be doing this on every line, but this
              // method covers a lot of gritty details like cropping
              // and scanline padding.  Also, the seek only takes
              // place if the file position actually needs to change
              // (avoids a lot of cluster math in SD library).
              if(flip) // Bitmap is stored bottom-to-top order (normal BMP)
                pos = bmpImageoffset + (bmpHeight - 1 - row) * rowSize;
              else     // Bitmap is stored top-to-bottom
                pos = bmpImageoffset + row * rowSize;
              if(bmpFile.position() != pos) { // Need seek?
                bmpFile.seek(pos);
                buffidx = sizeof(sdbuffer); // Force buffer reload
              }

              for (col=0; col<w; col++) { // For each column...
                // Time to read more pixel data?
                if (buffidx >= sizeof(sdbuffer)) { // Indeed
                  // Push LCD buffer to the display first
                  if(lcdidx > 0) {
                    tft.pushColors(lcdbuffer, lcdidx, first);
                    lcdidx = 0;
                    first  = false;
                  }
                  bmpFile.read(sdbuffer, sizeof(sdbuffer));
                  buffidx = 0; // Set index to beginning
                }

                // Convert pixel from BMP to TFT format
                b = sdbuffer[buffidx++];
                g = sdbuffer[buffidx++];
                r = sdbuffer[buffidx++];
                lcdbuffer[lcdidx++] = tft.color565(r,g,b);
              } // end pixel
            } // end scanline
            // Write any remaining data to LCD
            if(lcdidx > 0) {
              tft.pushColors(lcdbuffer, lcdidx, first);
            }
           // Serial.print(F("Loaded in "));
            //Serial.print(millis() - startTime);
            //Serial.println(" ms");
          } // end goodBmp
        }
      }

      bmpFile.close();
      if(!goodBmp) Serial.println(F("BMP format not recognized."));
    }

    // These read 16- and 32-bit types from the SD card file.
    // BMP data is stored little-endian, Arduino is little-endian too.
    // May need to reverse subscript order if porting elsewhere.

    uint16_t read16(File f) {
      uint16_t result;
      ((uint8_t *)&result)[0] = f.read(); // LSB
      ((uint8_t *)&result)[1] = f.read(); // MSB
      return result;
    }

    uint32_t read32(File f) {
      uint32_t result;
      ((uint8_t *)&result)[0] = f.read(); // LSB
      ((uint8_t *)&result)[1] = f.read();
      ((uint8_t *)&result)[2] = f.read();
      ((uint8_t *)&result)[3] = f.read(); // MSB
      return result;
    }

body:
The usual technique at this scale of technology is to keep loop() pretty short, mostly making frequent calls to a timer function that keeps a list of things to be done (implemented with callback-functions) and the times at which to do them, and which calls those functions at the appropriate times. The upper level(s) of your sketch would schedule tasks by registering one or more callback-functions to be run at a given time or periodically.

When the timer function is called, if there is nothing to do, or when a callback-function returns, the timer function returns immediately to its caller (probably loop()). loop() can do other work, as long as it can still call the timer function as frequently as your task dispatching requires.

The [SimpleTimer library][1] at Arduino Playground is an implementation of such a timer-function.

  [1]: http://playground.arduino.cc/Code/SimpleTimer


body:
Taking JRobert's advice, i checked out the simpletimer library.. the final solution was to set up three timers and change the way the buttons functioned.

as per documentation of the simpletimer library, added the following global:

    #include <SimpleTimer.h>
    SimpleTimer timer;
    ...

Then to setup, i added my three timers

    timer.setInterval(7000, spindle); //times based on hardware reality
    timer.setInterval(2000, coolant);
    timer.setInterval(21500, homer);
    ...

Then started the timers in loop by adding:

    timer.run();
    ...

Finally, i edited the buttons and added variables to denote state of button.
i.e.

    /*
    0 == on,
    1 == transitional1
    2 == transitional2
    3 == stopped
    */
    int homeb = 0;
    int cool = 0;
    int spin = 0;

Changed the touch screen code for each button to kick off the timers...

    //Coolant Button
    if (p.y > 110 && p.y < 170 && p.x > 250 && p.x < 300) { // if stop area is pressed
      if(cool == 3){
       bmpDraw("coolen.bmp", 15, 105);
       //PWM the spindle pin on
       cool = 0;
      } else {
        if(cool == 0){
          //PWM the spindle pin off
          cool = 1; //Start the timer sequence for stopping coolant
        }
      }
    }

then i added a void for each timer, this is where i redraw the buttons

    void coolant() {
      if (cool == 1){
       bmpDraw("coolerr.bmp", 15, 105);
       cool = 2;
      } else {
        if (cool = 2){
       bmpDraw("coolstp.bmp", 15, 105);
       cool = 3;
        }
      }
    }

Hope this helps someone else in the future, as it was a real pickle for me to figure out at first.. Thanks again, and credit goes to JRobert, his advice pointed me directly to the solution.


message:
Connecting an arduino uno to an arduino due

So I am trying to get my arduino uno to talk to my arduino due but I'm having issues getting the data outputted on the due side. My arduino uno is the master while the due is the slave. The sensor is connected to the uno and I just require the arduino due to receive and spit out the data as it has a faster sampling rate than the arduino uno. I connected them along the serial (Tx and Rx) lines. And I'm using Serial3 on my arduino due to receive the transmitted data. Both arduinos are grounded together. But powered differently by usb cables connected to my machine. On the arduino uno end ( for brevity sake) the data is sent in binary with the $ sign as the starter bit. Here is the code for the receiving end ( the slave). I just can't seem to get the data out on the serial monitor.

        byte b = '$';
        unsigned char buffer[12];
        int count =0;

        void setup() {
        Serial.begin(115200);
        Serial3.begin(115200);
        delay(5);

        }

       void loop() {
       if(Serial.available())
       {
        if (b == Serial.available())
       {
        while(Serial.available())
        {
          buffer[count++] = Serial.read();
           if(count == 12)break;
          //Send the byte to serial port three
          Serial3.write(buffer, count);
        }
     }

     if (Serial3.available()){
      //get a byte from serial port 3
      if(b == Serial3.available()){
        buffer[count++] = Serial3.read();
        //Send the byte to the USB serial port
        Serial.write(buffer, count);
      }
     }
     Serial.println("lyca");
     }
      }

body:
    if(Serial.available())
    {
     if (b == Serial.available())
    {
     while(Serial.available())
     {

I think you may be getting your knickers in a twist there.

... Is serial available? Yes. Is serial available? Still yes! But yes doesn't equal '$'!!!... WHAT?!

You really really need to rethink your understanding of serial communication.

**Read this: http://hacking.majenko.co.uk/reading-serial-on-the-arduino**


body:
There seem to be a confusion on Serial & Serial3. You say that:

 - Serial is used to send back debug data to the PC
 - Serial3 is used to get data from the master

But this is not clear/coherent to your code. Let's try to see your code with proper indentation. I added comments.

    void loop() {
      if(Serial.available()) { //isnt Serial your debug port? did you mean Serial3?
        if (b == Serial.available()) { //same. Serial3? also, read() instead of available() ?
          while(Serial.available()) { //same. Serial3?
            buffer[count++] = Serial.read(); //Serial3?
            if(count == 12) {
        break; //will this work for several frames? how can count ever go back to 0?
      }
            Serial3.write(buffer, count); //isnt Serial your debug output?
          }
        }
    //your indentation didnt show it, but we're still guarded by the first 'if' here.
    //Also I guess you meant Serial here?
        if (Serial3.available()) {
    //why check for a SoF? what do you do with data coming up fro the debug PC?
          if(b == Serial3.available()) {
    //messing with data in your buffer, potentially outside of it? (count can be>11 here)
            buffer[count++] = Serial3.read();
            Serial.write(buffer, count);
          }
        }
        Serial.println("lyca");
      }
    }

What about this (code below still has several flaws, but should perform better than yours)

    void loop(void) {
      if(Serial3.available() > 0) { //available data from master?
        while(Serial3.available() > 0) { //if statement above for clarity, this while on its own would be enough
          inByte = Serial3.read();
          if(inByte  == SOF_BYTE) { //is this a start of frame?
            mybuff.ptr = 0; //let's say we dump everything in buff whenever we get a new SoF
         Serial.println("SoF received");
          }
          else { //let's not keep SoF
            mybuff.append(inByte);
          }
        }
      }
      if(mybuff.size >= FULLFRAME_SIZE) { //we've got a full frame, output it
     Serial.print("Full frame received:");
     Serial.println(mybuff.string);
     mybuff.ptr = 0; //now that we've consumed the frame, kill it
      }
      else {
        Serial.print(".") // no frame, show progress/still alive
      }
      delay(refreshtime);
    }


message:
Unable to use RGB matrix and the serial monitor at once

Recently I bought the following matrix:
https://learn.adafruit.com/32x16-32x32-rgb-led-matrix/overview

I own an Arduino Uno for those who are interested.

I got the 32x32 variant and I am very happy with it. I managed to connect all the wires correctly and get the examples of the library working.

The problem I am facing right now is I can't get it to work properly for a personal project of mine. Somehow I am unable to use the serial functions and the matrix library functions in one project.

Currently my project looks like this:

My Arduino is connected like this:

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

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

And the code I wrote is:

    #include <gamma.h>
    #include <RGBmatrixPanel.h>
    #include <Adafruit_GFX.h>
    #include <gfxfont.h>

    #define CLK 8
    #define OE  9
    #define LAT 10
    #define A   A0
    #define B   A1
    #define C   A2
    #define D   A3

    RGBmatrixPanel matrix(A, B, C, D, CLK, LAT, OE, false);
    String incomingCommand = "";

    void setup() {
      Serial.begin(9600);
      matrix.begin();
      matrix.fillRect(0, 0, 32, 32, matrix.Color333(0, 0, 0));
    }

    void loop() {
      if (Serial.available() > 0) {
        int incomingByte = Serial.read();
        char receivedChar = (char) incomingByte;
        incomingCommand += receivedChar;
      }

      if (incomingCommand.indexOf('#') > - 1 && incomingCommand.indexOf('%') > - 1) {
        String rawCommand = incomingCommand.substring(incomingCommand.indexOf('#'), incomingCommand.indexOf('%') + 1);
        rawCommand = rawCommand.substring(1, rawCommand.length() - 1);
        Serial.print("Following command received: ");
        Serial.println(rawCommand);
        if (rawCommand == "turnledon") {
          matrix.drawPixel(0, 0, matrix.Color333(7, 7, 7));
        }
        incomingCommand = "";
        rawCommand = "";
      }
    }

The idea is that a command gets sent from the serial monitor. Based on the command one led on the matrix will turn on. An example of a future command will look similar to this: "#drawPixel_X1_Y2%", hence the part that checks on "#" and "&".

The problem is that the functionality of the serial monitor isn't working with line 14 and 48 of the code. As soon as I remove those lines, the serial monitor works perfectly and I can receive and write to the serial monitor. I have no idea what is causing this.

I was wondering if someone ever faced a similar problem or knows what I am doing wrong right now.

Thank you in advance!

body:
According to Adafruit https://learn.adafruit.com/32x16-32x32-rgb-led-matrix/overview these led matrixes require active scanning. It means that the RGBMatrixPanel will set up some scanning interrupt to refresh the screen periodically.

This can very much interfere with serial receive, as according to Adafruit, the panels require a serious data transmission all the time.

Try the followings:

 * have one byte serial commands, e.g. N for "on" and F for "off" (I know you will need more complex commands, but this is just to verify the theory)
 * remove all debug Serial.printlns (those also consume some time)

So try this:

    void loop() {
      if (Serial.available() > 0) {
        char incomingByte = Serial.read();
        if (incomingByte=='N') {
           matrix.drawPixel(0, 0, matrix.Color333(7, 7, 7));
        }
        if (incomingByte=='F') {
           matrix.drawPixel(0, 0, matrix.Color333(0, 0, 0));
        }
      }
    }


message:
Briefly "wake up" Arduino in response to an event

I want to connect a device to a door handle, so whenever someone opens the door I'll be able to send a message via my arduino that is connected to a WIFI shield.

I have a simple orientation sensor, so I know when the handle is being pushed. The problem is I don't want to keep the Arduino on all of the time (energy issues).

The orientation sensor closes a circuit for about 100ms, so I thought to connect the battery to the Arduino in series with the sensor, but the problem is that it might take more than 100ms to connect and send the data - I need at least 5 seconds to be sure.

Any ideas on how to make the Arduino "power up" for 10 seconds each time someone uses the door handle and then to cut off the power?

body:
Easy answer: Don't.

Have the Arduino sleep most of the time, and let the door handle invoke an interrupt that wakes it up. Then do whatever processing is required, and then go back to sleep.

This won't work as well with a full Arduino as it would with a bare MCU since the rest of the board has its own quiescent load, but once you get it working with an Arduino you can get a bare MCU, wire it up, write the code to it, and away you go.


body:
I had a similar situation some time ago. I don't have the schematic at hand, but it looked more or less like the one below.

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

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

It works as follows:

1. Momentary switch closes and saturates Q1 via R1. It also powers the Arduino. The I/O in on the Arduino has not been programmed yet so it floats. Q1 energizes the coil of the relay which closes its N.O. contact. Now the circuit has latched and you have power to the Arduino for as long as you want.

2. Arduino starts, does its work (xmits signal or whatever) and then programs the selected I/O pin as output and pulls it low. This will divert current away from the base of Q1, which will cut the current to the coil and everything closes down and no power is drawn from the battery.
R1 should be some 10 times greater than R2 for this to work. Say R1 = 1K, and R2 = 100 Ohm.

This is a concept drawn from memory, it might require some refining :-)


body:
You may find the answer to [How can a let my atmega328 run for a year on batteries?][1] from SE Electrical Engineering helpful. It is a very detailed resource on power saving measures for the Arduino.

[1]: https://electronics.stackexchange.com/questions/49182/how-can-a-let-my-atmega328-run-for-a-year-on-batteries/49233#49233


body:
You are much better off **sleeping** the Arduino. In power-down mode the processor can use as little as 100 nA (0.1 µA) which is somewhat less than the self-discharge rate of batteries anyway.

I have a page about [power saving techniques](http://www.gammon.com.au/power).

You also would want to make a custom board, or at least choose an Arduino without a voltage regulator, LEDs, USB chip, etc.

The Atmega328P, when in power-down sleep mode, can be woken by an external interrupt, such as what your door could provide.


message:
How to make precise square wave?

I am playing with stepper motors and I need a precise square wave generator for f=29.710617283951Hz. I've done this on Raspberry Pi without any problems, but I need something smaller and with less power consumption.

Is it even possible to get that frequency?

body:
You can user Timer 1 on the Atmega328P (such as is found on the Uno) to get you into that ball park:

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

    const unsigned long countTo = 33658;  // F_CPU / 8 / 29.71 / 2

    void setup ()
      {
      pinMode (10, OUTPUT);

      // PWM, top at OCR1A
      TCCR1A = bit (WGM10) | bit (WGM11);  // PWM
      TCCR1B = bit (WGM13) | bit (CS11);   // PWM, prescaler of 8
      OCR1A = countTo - 1;                 // zero relative
      OCR1B = (countTo / 2) - 1;           // 50% duty cycle
      bitSet (TCCR1A, COM1B1);   // clear OC1B on compare
      }  // end of setup

    void loop ()
      {
      }  // end of loop

I measured a frequency of 29.67 Hz on one device and 29.41 Hz on another. The Uno is driven by a resonator, not a crystal, so a couple of percent error is to be expected.

---

I have a [page about the hardware timers](http://www.gammon.com.au/timers) and a cheat-sheet for Timer 1:

[![Timer 1 information][1]][1]

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


body:
Reducing the power requirement, compared to an R-Pi, should be straightforward, achieving 29.7106Hz is doable, reducing the size is harder (an R-Pi is quite compact).

Some of the available options depend on your electronics skills, and budget.

I'll assume you want to use off-the-shelf hardware as much as practical, but are okay to wire 'modules' together (size could be a bit smaller than an R-Pi using off-the-shelf parts, but could be *significantly* reduced by a custom made part).

I'll also assume you want to keep costs under $100. (I apologise if I am wrong, but this seems like a level that many of this community might find interesting :-)

### Preamble: ###

Even at 16MHz, 29.7106Hz represents a count of approximately 538,528, which requires 19 bits. So I would *not* use a chip with 8 or 16 bit timers. I would make my life easier by using a chip with 32 bit timers.

Further, the code will be manipulating quantities with at-least 19 bits, so I would *not* use an 8 or 16bit CPU. I would make my life easier by using a 32bit CPU that operates on 32bit quantities in a single operation. This may become very important if you opt for a software-heavy approach.

### Initial Approach: ###

Lets assume our 32 bit processor has a clock of 64MHz.
To generate a clock frequency close to 29.710617284Hz (as good as my calculator will do), load a timer with 2,154,112 (maybe 2,154,111, depending on how the counter triggers).

The more accurate divisor is 2,154,112.094.

That count is within 0.05ppm (parts/million) of 29.710617284Hz at a 64MHz clock.
Also, a count of +/- 1 is a change of less than 0.5ppm. That is about 30x better than the more relaxed requirement, '29.7106', mentioned in your comments.

Using 64MHz to drive the count will enable 4x better accuracy, 0.5ppm, than using a 16MHz clock, 2ppm, when we examine ways to implement this in the 'Options' section below.

*Summary so far:* if the microcontroller had a very accurate clock (much better than 0.5ppm error), then the problem is solved.

However, the crystals used to drive the microcontroller typically have a frequency stability of 30-50ppm, and may be even worse.

### Options to reach 0.5ppm: ###

*1. Replace the MCUs crystal with a much better part.*
This will typically require some soldering skill, and the parts I've seen (which are likely to replace the existing crystal) are stable at about 10ppm. That might be a factor of 3-5 better than the factory fitted crystal, so may be worth the effort, however there are better options.

*2. Feed the MCU with a higher-stability clock source than a crystal.*
Most MCU's can accept an external clock source in place of the crystal. Temperature Compensated Crystal Oscillators (TCXO) cost about $5, and can achieve 0.5ppm (0 to 40C, 2ppm -30C to +85C). So an improvement over an 'ordinary' crystal of 30-100x.

If this is appealing, I'd actually recommend looking at ST Micro's Nucleo boards. They are low-cost (under $12), so not much wasted if it doesn't work, and many of the boards already take an external oscillator, so may be easier to change. (They are 32bit CPU's with 32bit timers, and can run at 64MHz,) I imagine folks can recommend other boards.

*3. 'Discipline' the square-wave counter with an external high-quality clock*
The idea is to use a very accurate external clock, and adjust the square-wave count to get high-accuracy than the existing MCU crystal. While counting the MCU clock for the square wave, use a second counter to count the number of MCU clock cycles a known, high-quality, external timing source event takes. The external clock source could be a TCXO, an Oven Controlled Oscillator (OCXO), which can achieve 0.001ppm) or GPS.

Program code could estimate the error of the MCU clock vs higher-quality clock, and adjust the square-wave count *within each square-wave cycle*. This may keep the square-wave within 0.5ppm using one or more +1 or -1 adjustment of the counter. This approach has the advantage that the only electronics is connecting the high-quality timing source to a pin on the microcontroller. The rest is (carefully written) software.

Edit:
To be clear, this option 3 can use an unmodified, off-the-shelf, MCU development board. The original crystal is unchanged; there is no need to modify it to replace its crystal.

So it could use a small, e.g. Arduino-Nano size, microcontroller running at a reasonable rate (e.g. 64MHz) connected to a TCXO (or even OCXO), and get close to 0.5ppm error.


message:
Compilation error using arduino-mk on arch Linux (undefined reference to __dso_handle)

1. I'm compiling a simple sketch that reads values from an analog input
    and activates a buzzer on a digital input.
 2. working on an Arduino uno.
 3. the sketch compiles and runs fine on windows and arch linux using the Arduino
    IDE.

I recently tried to start working with Arduino-mk, I tried to compile the said sketch and got the following compiler error (analogVal is the variable holding the analogRead):

/usr/bin/avr-gcc -mmcu=atmega328p -Wl,--gc-sections -Os -o /home/niv/Gits/bin/uno/maglove/maglove.elf

    ~/Gits/bin/uno/maglove/maglove.ino.o ~/Gits/bin/uno/maglove/libcore.a  -lc -lm
    /home/niv/Gits/bin/uno/maglove/maglove.ino.o: In function `_GLOBAL__sub_I_nothing':
    maglove.ino:(.text.startup._GLOBAL__sub_I_nothing+0xc): undefined reference to `__dso_handle'
    maglove.ino:(.text.startup._GLOBAL__sub_I_nothing+0xe): undefined reference to `__dso_handle'
    maglove.ino:(.text.startup._GLOBAL__sub_I_nothing+0x18): undefined reference to `__cxa_atexit'
    /usr/bin/avr-ld: /home/niv/Gits/bin/uno/maglove/maglove.elf: hidden symbol `__dso_handle' isn't defined
    /usr/bin/avr-ld: final link failed: Bad value
    collect2: error: ld returned 1 exit status
    /home/niv/Gits/Arduino-Makefile/Arduino.mk:1416: recipe for target '/home/niv/Gits/bin/uno/maglove/maglove.elf' failed
    make: *** [/home/niv/Gits/bin/uno/maglove/maglove.elf] Error 1
    make: Target 'all' not remade because of errors.

I am not very experienced with Arduino yet, and google has failed me in finding this error or any keyword from it in the context of Arduino uno.

thanks.

body:
I can't say I fully understand what is going on, but it seems that if you add:

    void * __dso_handle;

You may be able to eliminate one of the problems. You might try the same trick with `__cxa_atexit` as well.

I found the idea by searching on:

> arduino __dso_handle

[This][1] is the webpage that I found that suggested the `void *` hack.

[1]: http://www.esp8266.com/viewtopic.php?f=29&t=2196&p=13039&hilit=dso_handle#p13039


message:
Xbee for Arduino Uno

I'm very new to Arduino, and I was wanting to control my Arduino wirelessly. Some googling shows that there is a shield for Arduino called Xbee that allows wireless communication. Unfortunately, I just purchased the #1 shield without checking specifications, (went back later, couldn't find them :/) and now i have a shield that appears to small for my Uno. [(XBee Pro 60mW Wire Antenna - Series 1 (802.15.4))](https://www.sparkfun.com/datasheets/Wireless/Zigbee/XBee-Datasheet.pdf)

Some more googling showed results that this was indeed the right shield, but I don't see how since the pin pattern is about half the size as the female ports on the Arduino. Is this the right shield? if so, how do I attach the two pieces of hardware?

[![My arduino][1]][1]
[![my xbee][2]][2]

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

body:
What you have there is an XBee *module*. It is designed to plug into an XBee *shield* which then plugs into the Arduino.

So you need to buy more.

That's the bad news.  The good news is that you have already bought the most expensive part, and the shield to go with it is pretty cheap.

Numerous people make the shields, such as:

* [Sparkfun](https://www.sparkfun.com/products/12847)
* [Seeed](http://www.seeedstudio.com/depot/xbee-shield-v20-p-1375.html?cPath=132_134)
* [DFRobot](http://www.dfrobot.com/wiki/index.php/Xbee_Shield_For_Arduino_(no_Xbee)_(SKU:DFR0015))

Also note that XBees talk to other XBees, so you need at least two of them to get any form of communication going.  If you want to talk to your computer there is a device called the [XBee Explorer](https://www.sparkfun.com/products/11812) which plugs into the PC to allow you to communicate with an XBee module.


message:
Why doesn't this debounce function work?

**Edit 2**
I made a function that works, but I'm still confused about just one thing...

I'm very confused about how variables work in C++.

**In this program...**

      boolean debounce(void)
    {
      static boolean buttonState=LOW;
      static boolean lastButtonState;
      boolean currentState = digitalRead(4);
      static unsigned long lastDebounceTime;
      if (currentState != lastButtonState){ //if the button state has changed
        lastDebounceTime=millis();  //reset timer
        }

      if ((millis()-lastDebounceTime) > 50)  //if 50 milliseconds has passed since last bounce
      {
        buttonState = currentState;  //read value again now that bouncing is over

        }
      lastButtonState = currentState;
      return buttonState;
    }

**Why does changing this**

    lastButtonState = currentState;

**To this**

    lastButtonState = buttonState;

**Make any difference in the program?**

When I try the latter line of code, the whole function stops working and I don't understand why.

body:
This probably won't answer your question completely, but here are some notes from me:

    buttonState = current ;  //read value again now that bouncing is over

This won't read the value again, it just copies `current` into `buttonValue`.

What you wanted is:

    buttonState = digitalRead(BUTTON); // read value again now that bouncing is over

You have multiple issues with your `debounce` call:

- `lastTimeDebounce` is never used by your code, so it is always zero.
- `lastButtonState` will be always `buttonVal` making the debounce function useless.

Some other tips:

- Don't use the same names for parameters as for global variables:

    boolean debounce(boolean lastButton, long lastDebounce, int BUTTON)

    The global variable `BUTTON` will be **shadowed** by `int BUTTON`, essentially overriding it.

- Don't use global variables (unless you have a very good reason)

**EDIT**

I would strongly recommend writing a function that debounces only **one** pin.

Because if you want a function which can debounce any pin you would need a state variable for each pin (which needs arrays hence a lot of space).

**EDIT2**:

Here is a debounce function that should work:

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

    const uint8_t PIN = 13;

    /*
     * Returns debounced value for `PIN`
     */
    boolean debounce(void)
    {
        // Current state of the pin
        boolean currentState;
        // Last state of the pin, initial value is zero
        static boolean lastCurrentState = 0;
        // Timer
        static unsigned long debounceTimer = millis();
        // Debounced value, initial value is zero
        static boolean debouncedValue = 0;

        // We first read the current state of the pin
        currentState = digitalRead(PIN);

        // Then we look if the state has changed
        if (currentState != lastCurrentState) {
            // If it has, we need to reset the debounce timer
            debounceTimer = millis();
        }

        // Then we check if the timer has expired
        if ((millis() - 50) > debounceTimer) {
            // The timer expired so we update the value
            debouncedValue = currentState;
        }

        // Save the latest state
        lastCurrentState = currentState;

        // We always return a debounced value:
        return debouncedValue;
    }

But always test such things with an oscilloscope, no guarantee. FYI: this is not an ideal debounce function, but it should make the idea clear.


body:
"It worked perfectly" is probably an overstatement. Yes, you saw the LED change when you pressed the button, but that doesn't mean it was getting debounced.

The problem is that you are trying to use global variables to remember the internal state of the debouncer function, and you're passing those variables into the function as parameters. In C (or C++, which is the underlying language that you're using), an assignment to a function parameter does NOT update the corresponding variable in the caller's environment. Therefore, `lastDebounceTime` never gets updated, and your `debounce()` function always just returns the current state of the button.


body:
Im not an expert of C programming, but I can see lot of troubles in your programming, because you do call a function debounce(), but it is not a function that does a complete task, so you set additional variables outside of it. This is a bad practice, because you can't call the same function to compute multiple keys, that's what functons are for - make one function and call multiple times with different parameters. You should switch to pointer orented parameters for lastButtonState.

        boolean LastButton_1; // global or static variable
        long LastDebounce_1;
        int BUTTON_1;
            ... and so on

        boolean debounce(boolean *LastButton, long *LastDebounce, int BUTTON)
            {
              //your code here, where you read and write to variables located at pointer
               boolean something, new_value;
               something = *LastButton; //read value at pointer address
               *LastButton = new_value; //store the value at pointer address
            }
    //now you call this
    debounce(&LastButton_1, &LastDebounce_1, BUTTON_1)

Perhaps it is not correct, since I know only very basic C, but the way is the right one


body:
If you only have one button to debounce, you can store it's state as
static variables in the `debounce()` function itself, like:

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

    bool debounce()
    {
        const int pin = 4;
        static bool last_state;
        static unsigned long last_change;
        unsigned long now = millis();

        if (now - last_change > 50) {
            bool state = digitalRead(pin);
            if (state != last_state) {
                last_change = now;
                last_state = state;
            }
        }
        return last_state;
    }

If you may have to debounce more than one button, the cleaner way would
be to store the state inside an object, and have the debounce function
be one of its methods. That's what the
[Bounce library](https://github.com/thomasfredericks/Bounce2) does.


message:
Custom arduino board

Hey There Arduino Coders. I am a relatively seasoned C/C++ programmer. However, I'm still new to the Arduino Game. I'm coming here today to ask you guys a direct question that I couldn't find a direct answer for on google... here it goes:

Is it possible,(also practical) to create my own arduino board? after creating a prototype with an arduino uno and various shields?

In other words. Is it possible to shrink the arduino(make a custom arduino), and all of its shields on to one board? It seems rather large to have to lug around all of those shields and such. CHEERS!

body:
Absolutely.  You might start with the [Arduino to Breadboard Tutorial][1] while defining your hardware requirement - for example, decide what voltage you are going to run at (and pick an appropriate regulator) and then decide if you can use the imprecise 8 MHz internal oscillator or if you need a more precise external resonator or crystal.

Once you have determined your required circuitry you can advance to making  circuit board, and possibly switch from the DIP version of the ATmega to a QFP package which is smaller and potentially ultimately easier to work with (for production you might even use a QFN, though that is a bit more challenging to solder by hand).  You may also want to look at what package technology your peripheral chips come in.

Do note though both that you can buy smaller premade Arduion-compatible PCBs, and that there are other chips which are worth considering for a permanent project, some with Arduino compatible libraries available, and some without.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard


body:
I have a page about a [breadboard Arduino](http://www.gammon.com.au/breadboard) which is basically an Atmega328P processor (same as in the Uno, inter alia) on a breadboard.

[![Breadboard Arduino][1]][1]

---

Also a [wire-wrapped Arduino](http://www.gammon.com.au/forum/?id=11109).

[![Wire-wrapped Arduino][2]][2]

---

You can go pretty minimalistic with a [ATtiny85 mounted on a button battery](http://www.gammon.com.au/forum/?id=12769) like this:

[![ATtiny85][3]][3]

---

>  Is it possible to shrink the arduino(make a custom arduino), and all of its shields on to one board?

Ah there you might be asking a bit much. There are hundreds, if not thousands, of shields people have designed for it. Certainly you can make up your own board to meet a specific purpose.

  [1]: https://i.stack.imgur.com/aaViV.jpg
  [2]: https://i.stack.imgur.com/YLNQj.jpg
  [3]: https://i.stack.imgur.com/4I3tx.jpg


body:
Yes it is possible. It can be as simple or as complex as you wish :)

 http://www.instructables.com/id/How-to-make-your-own-Arduino-board/


message:
sketch uploading give error?

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x30
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x0f
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x10
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x20
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x0f
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x10
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x30
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x0f
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x10
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x20

body:
This [Instructables post][1] has a list of potential causes for this error. Is this a new board? What board are you using? Is it a genuine Arduino board or a clone? Have you been able to upload to the board previously?

  [1]: http://www.instructables.com/id/A-solution-to-avrdude-stk500getsync-not-in-syn/


body:
Have you changed the atmega328 chip? If you have the new one may not have a bootloader or it may have one for a different board. Select every board option. Duemillemova maybe?
If you still have no luck, you might have over written your bootloader. Try burning the bootloader again. Instructables shows you how.


message:
How Atmel Studio 7 compile Arduino code?

Atmel stated in their website:

> Atmel Studio 7 features seamless one-click import of projects created in the Arduino development environment. Your sketch, including any libraries it references, will be imported into Studio 7 as a C++ project. Once imported, you can leverage the full capabilities of Studio 7 to fine-tune and debug your design. Atmel Studio 7 fully supports the powerful embedded debugger on the Arduino Zero board. For other Arduino boards, shield-adapters that expose debug connectors are available, or switch to one of the many available Xplained-Mini/PRO boards to fully leverage the Atmel HW eco-system. Regardless of what you choose, you will surely make something amazing.

I wonder how they do it? Is it just a plug-in meaning that we still have to install Arduino software? Or do they have their own compiler and debugger?

body:
It is almost always the case that a high-level environment like an IDE provides an interface to an existing tool-chain rather than being truly an all-in-one mega-application, which would a maintenance nightmare. Atmel Studio 7 is no exception, and [according to Atmel][1], uses and includes (quite likely by downloading it during the install process) the GCC tool-chain.

> Why Atmel Studio asked about Arduino IDE path when I try to import Arduino sketch?

Probably for the Arduino libraries, which are contained within the Arduino IDE executable.

  [1]: http://www.atmel.com/Microsite/atmel-studio/compiler-editor.aspx


body:
Atmel Studio allows for the arduino .ino file to actually be compiled as a c++ project. Doing so allows true debugging, and stepping through all arduino code. It was actually insightful as it walked me through **ARDUINO's main() function**, which is normally tucked away nicely in a library never to be seen.

The IDE allows for highly useful features such as refactoring, find and replace, syntax highlighting and much more. I found it very useful, and a pleasant upgrade from the arduino IDE.

I often switch back and forth between the Arduino IDE and Atmel Studio, very easy to do.

Installing the Arduino software allows Atmel Studio to locate the libraries when it is installed.

By installing the Vmicro(visual Micro) toolbar, things really come together, and seem very seamless.

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

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


message:
How to have arduinos work together?

I want to have an Arduino based game you can play on a nokia 5110 screen. The problem is you cant make a medium sized game on an Arduino because the flash size is only 32k. I sit possible to have multiple Arduino's connected to each other, communicating to make it possible to have a bigger game. If it is possible how does it work?

body:
Yes and no.

Yes you can make Arduinos communicate with each other and send messages to each other.

Can you use that to make a game?  Possibly.

Is it worth the effort?  No.

It would be a huge amount of work and be overly complex when you could just use a bigger Arduino, like a Mega2560 or a Due.


body:
You can have two Arduinos communicate with each other but it is fairly complex.  See this [instructable][1].  One process is using the I2C protocol.

A far easier option is to use a larger Arduino [model][2].  Consider the Mega 2560 since it has 8 times the Flash memory.

  [1]: http://www.instructables.com/id/I2C-between-Arduinos/?ALLSTEPS
  [2]: https://www.arduino.cc/en/Products/Compare


body:
You **can** make quite an impressive game.

[![Toorum's Quest][1]][1]

**Features**

* Based on ATmega328P running at 16 Mhz (same as Arduino Uno).
* The game has a display resolution of 104x80 with 256 colors.
* Video mode is tile based and supports up to 3 sprites per scan line.
* Sprites are multiplexed so there can be unlimited number of sprites vertically on the screen.
* 4 audio channels with triangle, pulse, sawtooth and noise waveforms.
* Chiptune music playroutine and sound effects.
* NES controller support.

Video of it in action:

<https://www.youtube.com/watch?v=sLvgW_zb6bQ>

Original [post on the Arduino forum](http://forum.arduino.cc/index.php?topic=197983.0).

---

So, before you start wanting to connect lots of Arduinos together, investigate what can be achieved with just one. :)

The first thing to do, as others have mentioned, is to store static information into PROGMEM (see [Putting constant data into program memory (PROGMEM)](http://www.gammon.com.au/progmem) for more details).

If Petri Häkkinen can get his title screen, levels, sprites, music, and game logic into an Atmega328P you can too! Have fun!

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


message:
SDA and SCL problem with MEMS

I have a simple question to ask you about SDA and SCL pins.
I have a gyro and I use these 2 pins to make it work; how can I use an accelerometer combined to a Gyro if these 2 pins are used? I should need another 2 SDA and SCL pins for the accelerometer... Tell me that I don't need to buy an IMU :D

EDIT: I'm using Gyro LG3D20H from Adafruit, reading gyro values each 10 ms.

body:
I2C is designed to have multiple devices connected. Assuming the gyro and accelerometer have different I2C addresses they can both be connected to the same SDA and SCL pins.

For more information see <http://www.gammon.com.au/i2c>

Naturally you can only "talk to" one at a time. You may need pull-up resistors on both SDA and SCL, unless the hardware already has them.


message:
Arduino with multiple buttons - will power be an issue?

I have a spare Arduino Uno lying around, which I figured I could attempt to turn into a game controller. First clear issue, that immediately popped up, was that there are not enough digital input pins on the board, but I think I can get around that by using analog pins with appropriate external resistors (is that actually a possibility?).

Another one, more severe, is that I'm not sure how I would need to go around wiring microswitch buttons with the board. Assuming they short the circuit when pushed (SPST), I could simply wire one contact to an input pin, set to `INPUT_PULLUP` mode, and connect the other to ground. However, since I know little about how such circuits work, I'm immediately in doubt about two things. Considering the board would be used as a controller, an external power source is out of question and I'd only want to rely on the USB power. Since I want to use plenty of buttons (up to fifteen), out of caution I'm worried that shorting this many input pins to the ground at once could overload the... regulator I think?

So my question is this: is it safe to use multiple, potentially simultaneously pressed, buttons connected to input pins on an Arduino Uno board, powered solely from a USB port? Additionally, just to be clear, is it normal to connect them all to a common ground on the board?

body:
Yes, it is safe to connect multiple buttons to ground. The pull-up resistors have a fairly high value - about 10 kΩ and we know from Ohm's Law that

    I = V / R = 5 V / 10k = 0.5 mA

per button. Your USB power is good for about 500 mA.

Welcome to StackExchange.


body:
Most of your idea is sensible. Let's go over the sensible part first, and then we'll cover the bits that need work.

Using an internal pullup and shorting the input to ground is the correct way to approach this. Note that the pins will read `HIGH` when off and `LOW` when triggered this way.

Each pullup on an AVR is between 20kohm and 50kohm. This means that the current consumption if all 15 buttons are pressed is at most about \$15 \cdot {5 \text{V} \over 20\text{k}\Omega} = 3.75\text{mA}\$. This isn't enough for the USB connection to care about.

As for using the analog connections, A0 through A5 also have digital GPIO capability, which means that you would treat them exactly the same as you would the digital pins (A6 and A7 don't have digital GPIO unless you're running a ATmegaXX8PB with a special core).

And now the bad news.

The Arduino Uno is based on the ATmega328P, which *does not* have native USB capability. It communicates with the host through a serial connection via a USB-UART bridge. If you're using a real (or real-enough) Uno then that bridge is a ATmega16U2 which is a MCU that *does* have native USB capability, so it can be reprogrammed to interpret the serial stream from the '328P and talk USB to the host.

But if you aren't then you will either need to run a piece of software on the host that translates the serial stream to HID actions, or you will have to run a software USB stack on the '328P such as V-USB which will allow you to use Low-Speed USB 1.1 directly.

My recommendation is to see if you can get an Arduino or other AVR-based board that has an ATmegaXXU4 so that you can use `Mouse` and `Keyboard` directly instead of having to faff around with HID profiles and software USB. Unless that's your thing, of course.


message:
Delay function broken?

I noticed timing inconsistencies in my project, and further debugging pinpointed it to the problem below. The text should be updating every second, but the returned values are >> 1000ms.

To clarify, the text is not showing up every second.  The delays between texts vary according to fluctuating start and finish values.

I'm using a Teensy 3.2. Changing the baud rate doesn't help.

Is my timing crystal busted? Is there a serial buffering issue? I don't know how to fix either of these.

[![example code][1]][1]

Any help would be appreciated!

Edit:

Here's the code if anyone wants to test.  I found that adding more delay functions screws the output up in completely unlinear ways.

<!-- language: c -->

    unsigned long start, finished, elapsed;

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

    void loop() {
      Serial.println("Start...");
      start = millis();
      Serial.println(start);
      delay(1000);
      finished = millis();
      Serial.println(finished);
      Serial.println("Finished");
      elapsed = finished - start;
      Serial.print(elapsed);
      Serial.println(" milliseconds elapsed");
      Serial.println();
    }

Edit #2:

I thought it was worth showing everyone this screenshot.  It looks like `delay(1000)` just isn't functioning at all.

[![screenshot][2]][2]

Edit #3:

I debugged it with an LED and it blinked at exactly 1s intervals.  It seems like `delay(1000)` works, so the problem must be related to the serial buffering.  I also updated my software but that didn't help.

Edit #4:

New developments from further debugging:

 - The problem is not reproducible on a different computer.  The Arduino serial monitor on other computers displays correctly.
 - Updating to the latest OSX, arduino IDE, and teensyduino did not help.
 - Terminal 'screen' command surprisingly prints correct serial communication.
 - Serial monitors from 3rd party apps, like CoolTerm and Arduino IDE do not work.

  [1]: https://i.stack.imgur.com/VuTQD.png
  [2]: https://i.stack.imgur.com/BprVs.png

body:
After correcting the syntax error (missing semicolon) I tried your code on my Teensy 3.0. The results look OK to me:

    Start...
    1250
    2250
    Finished
    1000 milliseconds elapsed

    Start...
    2250
    3250
    Finished
    1000 milliseconds elapsed

    Start...
    3250
    4250
    Finished
    1000 milliseconds elapsed

    Start...
    4250
    5250
    Finished
    1000 milliseconds elapsed

    Start...
    5250
    6250
    Finished
    1000 milliseconds elapsed

    Start...
    6250
    7250
    Finished
    1000 milliseconds elapsed

    Start...
    7250
    8250
    Finished
    1000 milliseconds elapsed

    Start...
    8250
    9250
    Finished
    1000 milliseconds elapsed

---

Since the code you posted doesn't compile, can you re-test please with your posted code, assuming you add in the semicolon, and put a space before "milliseconds elapsed".

---

Further down my test I see this:

    Start...
    153258
    154258
    Finished
    1000 milliseconds elapsed

    Start...
    154259
    155259
    Finished
    1000 milliseconds elapsed

    Start...
    155259
    156259
    Finished
    1000 milliseconds elapsed

Now are you talking about the "creep" in the start time? That doesn't totally surprise me, because the rest of the code must take *some* time to execute.

---

*I know this isn't an "answer" per se, but I can't post this much information into a comment.*


body: Since the subtraction's result (`finished - start`) displays alright, it means the right number is being stored in the variable, so it's Serial that is screwing up the task of printing it. Try reducing the baud rate to 9600 and try again.


message:
3.95 TFT LCD SPI or parallel interface

I would like to get one information about this TFT LCD module . This particular module works with parallel interface with arduino mega and uno.

I am trying to get rid of arduino in my project and use esp8266 itself. I have this module http://www.aliexpress.com/item/3-5-inch-TFT-Touch-LCD-Screen-Display-Module-For-Arduino-UNO-R3-HIGH-QUALITY-Free/1854595985.html

This has only the parallel interface pins mentioned which requires around more than 10 pins to make it work. Is there any possibility that there is an SPI interface supported for this one by  making use of any of the existing pins for the parallel interface.

I don't think so but still can someone confirm that. If so I need to get SPI interface ready TFT LCDs.

Thanks,

body:
In general, no. The interface used by the chip is normally hard wired either in the connections to the Chip On Glass or in the connections of the shield (most commonly the former) and as such cannot really be changed.

You will need to either use a TFT screen that has the interface already set to SPI (and there are many) or use some form of SPI I/O expander to provide enough I/O pins to drive a parallel display.

Note that using SPI to communicate with a screen makes the screen updates considerably slower than using a parallel interface. The bigger the screen the slower it gets.