message:
Long range wireless communication between two arduinos?

I'm working on a project that will require two arduinos to be able to relay information to each other from long distances (up to about 10 miles or around 16 km).  WiFi won't be guaranteed to be available to either arduino as this is a wilderness application.

What are my options for long range wireless communication?  I haven't decided on an arduino model yet so if one particular model would be best for this application let me know.

body:
Your range of options depends strongly on what your budget is, what country you are in, whether you are a licensed radio operator, whether cell service is available, etc.

### If you aren't licensed:

In the USA, unlicensed (or lightly licensed) radio options include GMRS ([General Mobile Radio Service](https://en.wikipedia.org/wiki/General_Mobile_Radio_Service)), FRS ([Family Radio Service](https://en.wikipedia.org/wiki/Family_Radio_Service)) and CB ([Citizens band radio](https://en.wikipedia.org/wiki/Citizens_band_radio)).  GMRS and FRS range typically is at most a few miles – ten miles is too much to hope for.  CB range would be ok but CB radios often are fairly large and antennas would be large, eg nine feet long.  I don't know whether it is legal to transmit digital data over GMRS/FRS/CB radio.

### If you are licensed:
[2-meter band](https://en.wikipedia.org/wiki/2-meter_band) radio might be a good choice.  Frequencies are 144 MHz to 148 MHz in the Americas and Asia, or 144 MHz to 146 MHz elsewhere.  Per wikipedia,
>The license privileges of amateur radio operators include the use of frequencies within this band  for telecommunication, usually conducted locally within a range of about 100 miles (160 km).

### If cell service is available:
Consider a [GSM](https://en.wikipedia.org/wiki/GSM) shield, eg the [Arduino GSM Shield](http://www.arduino.cc/en/Main/ArduinoGSMShield).

To access the cell network you would need to buy a [SIM card](http://www.arduino.cc/en/Guide/ArduinoGSMShield#toc4) for each GSM shield.

GPRS ([General Packet Radio Service](https://en.wikipedia.org/wiki/General_Packet_Radio_Service)) on GSM provides data rates between 10 and 240 kbs.  Other GSM protocols may be faster or slower.  Data rates depend also on whether 3G service is available or only 2G.


sender: user

message:
Help needed understanding Due performance

I'm going to be writing some performance critical code and have started trying to get an understanding of timers and how much "work" the Due CPU can do per second.  To help get started with this, I wrote a bare sketch that simply increments a counter whilst a timer which ticks every second dumps the value of the counter to the serial log and then resets the counter.  Here's the code I'm using:

    #include <Arduino.h>

    void EnableTimer7TickEverySecond();

    volatile uint32_t gCounter = 0;

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

     EnableTimer7TickEverySecond();

    //  while ( true )
    //  {
    //   ++gCounter;
    //  }
    }

    void loop()
    {
     ++gCounter;
    }

    void EnableTimer7TickEverySecond()
    {
     pmc_set_writeprotect(false);
     pmc_enable_periph_clk(ID_TC7);
     TC_Configure(TC2, 1, TC_CMR_WAVE |
      TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1);
     TC_SetRC(TC2, 1, 656000 * 64);
     TC_Start(TC2, 1);
     TC2->TC_CHANNEL[1].TC_IER = TC_IER_CPCS;
     TC2->TC_CHANNEL[1].TC_IDR = ~TC_IER_CPCS;
     NVIC_EnableIRQ(TC7_IRQn);
    }

    void TC7_Handler()
    {
     TC_GetStatus( TC2, 1 );

     Serial.println( (uint32_t)gCounter );

     gCounter = 0;
    }

When I run this, I get values averaging 446,000 in the serial log for the increments per second.  That is way lower than I was expecting.  On an ARM chip running at 84MHz, I'd expect at least 14 million increments as few ARM instructions take more than 2 clock cycles and an increment should involve a read from memory, addition and a write back to memory (approx 6 clock cycles by my reckoning).

The timer is configured correctly, the TX led flashes regularly at 1 second intervals as the Serial.println is called.  I've checked for overflow on the counter (oddly, I found that the number of increments when working with a uint64_t was slightly higher).  I've also tried not calling Serial.begin() until I'm about to write the value to the log (and then only writing the value once) and whilst there is a slight increase in "performance", it doesn't account for the whole difference between expectation and reality.

My best guess would be that loop() is called on some sort of timer or has a built in default delay, so it occurred to me that if I comment out the counter increment in loop() and instead comment in the infinite while loop in setup(), I should be able to counteract any delay caused by how frequently the Arduino IDE calls loop().  I have seen other examples that never bother with loop() and just stick all their code in setup().

I do see a performance increase with this setup, but only to around 9 million, not the 14+ million I would expect. Oddly though, sometimes, randomly, the value is 2 or 3 times the "usual" value.  Not between 2 and 3 times, but exactly 2 or 3 times.  This happens regardless of whether I am incrementing the counter inside the loop() function or my own loop inside setup().  It is not a case of the timer "skipping", the output is written every second like clockwork.

So, my questions are:

 - What does the Arduino library do to make loop() so inefficient?

 - Is there any harm in keeping all your code inside an infinite loop in
   setup() and never returning out of it?

 - Why would I sometimes see the number of increments being 2 or 3 times
   higher than usual?  Could the counter be getting cached (despite
   being marked as volatile) and not reset properly?  If so, how can I
   prevent this?

sender: assistant

body:
> What does the Arduino library do to make loop() so inefficient?

Alot.  For a start it's a function, so it has to push registers onto the stack before it runs, and pop them off afterwards.  Secondly there is the "serial event" system outside the loop.  In main.cpp in the core you can see how loop is called:

    setup();

    for (;;)
    {
        loop();
        if (serialEventRun) serialEventRun();
    }

> Is there any harm in keeping all your code inside an infinite loop in setup() and never returning out of it?

If you don't use serial events, no harm whatsoever.

> Why would I sometimes see the number of increments being 2 or 3 times higher than usual? Could the counter be getting cached (despite being marked as volatile) and not reset properly? If so, how can I prevent this?

My guess is the operations you are using are not atomic.  This is, the interrupt is able to be fired right in the middle of doing the series of instructions that perform the increment. The temporary registers end up not being the same as they were at the start of the operation, and consequently the value is corrupted.  You should wrap the increment in a *critical section* (i.e., disable interrupts before it, and enable them afterwards).

To better analyse the speed of execution you can look at the generated assembly code of your program.  If we look at the disassembled `main()` function for the bit where it loops you can get this:

    80596: f7ff fe05  bl 801a4 <loop>
    8059a: 4b04       ldr r3, [pc, #16] ; (805ac <main+0x30>)
    8059c: 2b00       cmp r3, #0
    8059e: d0fa       beq.n 80596 <main+0x1a>
    805a0: f7ff feec  bl 8037c <_Z14serialEventRunv>
    805a4: e7f7       b.n 80596 <main+0x1a>
    805a6: bf00       nop

`loop()` consists of this:

    801a4: 4b02       ldr r3, [pc, #8] ; (801b0 <loop+0xc>)
    801a6: 681a       ldr r2, [r3, #0]
    801a8: 3201       adds r2, #1
    801aa: 601a       str r2, [r3, #0]
    801ac: 4770       bx lr
    801ae: bf00       nop

If we feed that into `main()` where it calls `loop()` the finished code looks like:

    80596: f7ff fe05  bl 801a4 <loop>
    801a4: 4b02       ldr r3, [pc, #8] ; (801b0 <loop+0xc>)
    801a6: 681a       ldr r2, [r3, #0]
    801a8: 3201       adds r2, #1
    801aa: 601a       str r2, [r3, #0]
    801ac: 4770       bx lr
    801ae: bf00       nop
    8059a: 4b04       ldr r3, [pc, #16] ; (805ac <main+0x30>)
    8059c: 2b00       cmp r3, #0
    8059e: d0fa       beq.n 80596 <main+0x1a>
    805a0: f7ff feec  bl 8037c <_Z14serialEventRunv>
    805a4: e7f7       b.n 80596 <main+0x1a>
    805a6: bf00       nop

So that is what gets executed for every single iteration of `loop()`.  If we (incorrectly) assume that each instruction takes 1 clock tick, that's 13 ticks.  84,000,000 / 13 = ~6.4 million loops per second.

Now - if we map the instructions against actually how many clock cycles they take, we can get a clearer picture:

    bl                  1+P  (P = 1 to 3)
    ldr (pc relative)   2
    ldr (word)          2
    adds                1
    str (word)          2
    bx                  1+P  (P = 1 to 3)
    nop                 1
    ldr (pc relative)   2
    cmp                 1
    beq.n               1 or 1+P (P = 1 to 3)
    bl                  1+P (Only if serial event runs)
    b.n                 1 or 1+P (P = 1 to 3)
    nop                 1

So taking a worst case scenario where P = 3 (pipeline re-fill clock counts, that is), and no serial event running, we can calculate a total number of clock cycles of 4+2+2+1+2+4+1+2+1+4+0+4+1 = 28.

84,000,000 / 28 = 3,000,000 loops per second.

But hang on - that's still much more than you're seeing.  That's because you're still only looking at the small picture.  You're looking at just your sketch and forgetting what else there is going on.

Every millisecond the `SysTick_Handler()` gets called which does various tasks, including calling the `TimeTick_Increment()` routine to deal with `millis()`.  That's 1,000 times per second, and that eats into your processing time somewhat.

Another important point is *it can't be incrementing while you're running your interrupt*.  The more you do in your interrupt (*and using serial is a very heavy-weight thing to do in an interrupt*) the less of your 1-second slice you get for doing your incrementing.

As an experiment, why not try disabling all the interrupts except just the one you are using for your timer and see how it changes the value.


message:
CC3000 Blocking All Wireless Communication

I'm trying to send an email using an Arduino Uno and a Sparkfun CC3000. When I plugged in the arduino to the computer with the code I wrote for it, all wireless communication in the room I was in went down. This includes both computers that were there, my cell phone, even my Pebble Watch got disconnected. Any idea on why this happened and how to fix it? I replicated this numerous times to make sure it wasn't a fluke.

Here is my code

    PingTest.ino
    CC3000 Ping Test
    Shawn Hymel @ SparkFun Electronics
    February 1, 2014
    https://github.com/sparkfun/SFE_CC3000_Library

    Connects to the access point given by the SSID and password and
    waits for a DHCP-assigned IP address. Pings the give website or
    IP address and waits for a response.

    The security mode is defined by one of the following:
    WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA, WLAN_SEC_WPA2

    Hardware Connections:

     Uno Pin    CC3000 Board    Function

     +5V        VCC or +5V      5V
     GND        GND             GND
     2          INT             Interrupt
     7          EN              WiFi Enable
     10         CS              SPI Chip Select
     11         MOSI            SPI MOSI
     12         MISO            SPI MISO
     13         SCK             SPI Clock

    Resources:
    Include SPI.h and SFE_CC3000.h

    Development environment specifics:
    Written in Arduino 1.0.5
    Tested with Arduino UNO R3

    This code is beerware; if you see me (or any other SparkFun
    employee) at the local, and you've found our code helpful, please
    buy us a round!

    Distributed as-is; no warranty is given.
    ****************************************************************/

    #include <SPI.h>
    #include <SFE_CC3000.h>
    #include <SFE_CC3000_Client.h>
    #include <Client.h>
    #include <Temboo.h>
    #include "TembooAccount.h" // Contains Temboo account information

    // Pins
    #define CC3000_INT      3   // Needs to be an interrupt pin (D2/D3)
    #define CC3000_EN       9   // Can be any digital pin
    #define CC3000_CS       10  // Preferred is pin 10 on Uno

    // Connection info data lengths
    #define IP_ADDR_LEN     4   // Length of IP address in bytes

    // Constants
    char ap_ssid[] = "comcast";                  // SSID of network
    char ap_password[] = "gooddays";          // Password of network
    unsigned int ap_security = WLAN_SEC_WPA2; // Security of network
    unsigned int timeout = 30000;             // Milliseconds
    char remote_host[] = "www.sparkfun.com";  // Host to ping
    unsigned int num_pings = 3;    // Number of times to ping

    // Global Variables
    SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);
    SFE_CC3000_Client client = SFE_CC3000_Client(wifi);

    int numRuns = 1;   // Execution count, so this doesn't run forever
    int maxRuns = 10;

    void setup() {

      ConnectionInfo connection_info;
      IPAddress ip_addr;
      IPAddress remote_ip;
      PingReport ping_report = {0};
      int i;

      // Initialize Serial port
      Serial.begin(115200);
      Serial.println();
      Serial.println("---------------------------");
      Serial.println("SparkFun CC3000 - Ping Test");
      Serial.println("---------------------------");

      // Initialize CC3000 (configure SPI communications)
      if ( wifi.init() ) {
        Serial.println("CC3000 initialization complete");
      } else {
        Serial.println("Something went wrong during CC3000 init!");
      }

      // Connect and wait for DHCP-assigned IP address
      Serial.print("Connecting to: ");
      Serial.println(ap_ssid);
      if(!wifi.connect(ap_ssid, ap_security, ap_password, timeout)) {
        Serial.println("Error: Could not connect to AP");
      }

      // Gather connection details and print IP address
      if ( !wifi.getConnectionInfo(connection_info) ) {
        Serial.println("Error: Could not obtain connection details");
      } else {
        Serial.println("Connected!");
        Serial.print("IP Address: ");
        for (i = 0; i < IP_ADDR_LEN; i++) {
          Serial.print(connection_info.ip_address[i]);
          if ( i < IP_ADDR_LEN - 1 ) {
            Serial.print(".");
          }
        }
        Serial.println();
      }

      // Perform a DNS lookup to get the IP address of a host
      Serial.print("Looking up IP address of: ");
      Serial.println(remote_host);
      if ( !wifi.dnsLookup(remote_host, &remote_ip) ) {
        Serial.println("Error: Could not lookup host by name");
      } else {
        Serial.print("IP address found: ");
        for (i = 0; i < IP_ADDR_LEN; i++) {
          Serial.print(remote_ip[i], DEC);
          if ( i < IP_ADDR_LEN - 1 ) {
            Serial.print(".");
          }
        }
        Serial.println();
      }

      // Ping IP address of remote host
      Serial.print("Pinging ");
      for (i = 0; i < IP_ADDR_LEN; i++) {
        Serial.print(remote_ip[i], DEC);
        if ( i < IP_ADDR_LEN - 1 ) {
          Serial.print(".");
        }
      }
      Serial.print(" ");
      Serial.print(num_pings, DEC);
      Serial.println(" times...");
      if ( !wifi.ping(remote_ip, ping_report, 3, 56, 1000) ) {
        Serial.println("Error: no ping response");
      } else {
        Serial.println("Pong!");
        Serial.println();
        Serial.print("Packets sent: ");
        Serial.println(ping_report.packets_sent);
        Serial.print("Packets received: ");
        Serial.println(ping_report.packets_received);
        Serial.print("Min round time (ms): ");
        Serial.println(ping_report.min_round_time);
        Serial.print("Max round time (ms): ");
        Serial.println(ping_report.max_round_time);
        Serial.print("Avg round time (ms): ");
        Serial.println(ping_report.avg_round_time);
        Serial.println();
      }

      // Disconnect
      if ( wifi.disconnect() ) {
        Serial.println("Disconnected");
      } else {
        Serial.println("Error: Could not disconnect from network");
      }

      // Done!
      Serial.println("Finished ping test");

    }
        TembooChoreo SendEmailChoreo(client);
    void loop() {
      if (numRuns <= maxRuns) {
        Serial.println("Running SendEmail - Run #" + String(numRuns++));

        //TembooChoreo SendEmailChoreo(client);

        // Invoke the Temboo client
        SendEmailChoreo.begin();

        // Set Temboo account credentials
        SendEmailChoreo.setAccountName(TEMBOO_ACCOUNT);
        SendEmailChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
        SendEmailChoreo.setAppKey(TEMBOO_APP_KEY);

        // Set profile to use for execution
        SendEmailChoreo.setProfile("Testofsoftware");

        // Identify the Choreo to run
        SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail");

        // Run the Choreo; when results are available, print them to serial
        SendEmailChoreo.run();

        while(SendEmailChoreo.available()) {
          char c = SendEmailChoreo.read();
          Serial.print(c);
        }
        SendEmailChoreo.close();
      }

      Serial.println("\nWaiting...\n");
      delay(30000); // wait 30 seconds between SendEmail calls
    }

body:
not a direct answer but the [sparkfun hookup guide][1] connects pin 8 (SDCS) to the chip select for the SD card. If this line is floating, I'm not sure of the impact.

  [1]: https://learn.sparkfun.com/tutorials/cc3000-hookup-guide


body:
Because of the limited information given any answers given will be by nature limited. However, I can suggest several troubleshooting tips.

----------
## Tips ##

 1. Verify that username and password used are exactly right(punctuation, spaces, etc.). Where you put`comcast` you should put the name of the network not the name of the provider. I am not sure if you have done this or not.
 2. Make sure network is in fact WPA2.
 3. In order to debug the issue make sure if you are getting nothing through serial to set it to the baud rate of `115200`.
 4. If you are using the breakout board make sure you correctly wired it and check any solder points:
![wiring][1]
 5. Make sure you have the correct libraries installed.  Also, try sample code from the examples. Libraries can be found [here][2].

----------
Many of these seem obvious but can through someone off. So try these and let me know the results. A lot of information about setup can be found [here][3].

**EDIT** Try removing the

    if ( wifi.disconnect() ) {
        Serial.println("Disconnected");
      } else {
        Serial.println("Error: Could not disconnect from network");
      }
block. It appears that you are disconnecting before going into the main loop. This would obviously make it impossible to send an email. The reason pining would work sometimes would be that wifi.disconnect() is called sometimes but not all the time. To narrow the issue try an example code from the library.

  [1]: https://i.stack.imgur.com/7kL9c.png
  [2]: https://github.com/sparkfun/SFE_CC3000_Library
  [3]: https://learn.sparkfun.com/tutorials/cc3000-hookup-guide


message:
Calculate how much battery power left

I run my 12V car battery trough a trimpot into my pro micro, micro controller.
I am using (voltPinValue1 * 0.01465) to get the Volt out of analog in. I have trimmed the pots and getting the right V.

But now I want to calculate for how long I can run for, example the stereo and some LED:s, but don't know how.. Does anybody know how I can do this??

Sorry for my English

Thanks! //Rasmus

body:
You really need to know the current being drawn rather than the instantaneous voltage. A voltage drop profile of a battery changes depending on the current draw, and just using the voltage is very very hard indeed.

You could measure the voltage over time, and try and calculate the slope of the voltage and attempt to predict when it would reach a specific pre-determined cut-off point, but since that change in voltage will be non-linear it's not really something that can easily be calculated.

But, if you can measure the current instead, and you know the Ah of the battery, then you can get a better estimate of how long the battery will run until it's considered flat.


message:
Stack isn't popping off correct data?

So, I was working on a project where I needed to get a random object from a stack, so to make sure my design was correct, I made a dummy program that does nothing but fill a stack with data, then print it out.
![enter image description here][1]

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

why in the world is nothing coming out of the stack but -1s??

Here's the stack.h file.

http://pastebin.com/vjhNLpNu

body:
You're not telling it how big your stack should be, and it defaults to 0 entries, which means nothing gets stored.

    class Stack
    {
    private:
        int *p;
        int top,length;

    public:
        Stack(int = 0);  <<== CONSTRUCTOR - DEFAULT SIZE IS 0
        ~Stack();

        void push(int);
        int pop();
        void display();
    };

When you make your Stack object you must give it a size for the number of entries in the stack:

    Stack stack(4);


body:
You never allocate space for the stack.

The way it's written, you need to pass the stack size into the constructor, and then it's fixed for the lifetime of the object; i.e. it won't grow automatically when you call `push()`. You're not passing anything into the `Stack` constructor, so the parameter is defaulting to `0`, meaning it has zero size.

The solution is to declare the stack something like this:

    Stack stack(10);

(10 is just an arbitrary size -- use whatever you expect to need.)

Incidentally, there isn't an effective safeguard in your code to handle an empty stack. The result is that you're technically getting undefined behaviour at the moment when you call `push()` (it's writing to arbitrary memory locations).


message:
How to power on Arduino a few seconds later after GSM module initialization?

I've connected a SIM900A GSM module to Arduino and the circuit works standalone on a 12V power supply. The problem is when I provide the 12V power supply, both GSM module and Arduino starts but the Arduino don't initializes the program for GSM module and hence the send or receive message functions don't work. Also when I first power on the GSM module and let it initialize first and then power on the Arduino, everything works fine. How to deal with this problem?

body:
Let the 12 V charge a large capacitor over a resistor. The time to charge to 63% is RxC. Place a 5 V zener diode parallel to the capacitor, so that doesn't damage the microcontroller. Then either connect to the microcontroller's reset, or, and this is "nicer", use a MAX809 reset controller. The latter will keep the output low until a precise threshold is reached, there's for instance a 4.00 V version. Use that output to keep the microcontroller reset for some time.

Not sure how much delay you want, but a 10 uF capacitor and a 100k resistor will give you (from the top of my head) about half a second before the voltage on the capacitor reaches 4 V.


body:
It sounds like your problem is that the GSM module needs time to initialize before it is ready to be talked to by the Arduino.

A crude way of providing this would be to use the `delay()` function in the Setup() of your sketch.  The argument to that is an `unsigned long` number of milliseconds (thousandths of a second) so it can produce delays far longer than you need.

But a more sophisticated solution would be to repeatedly try to talk to the module and check for an expected response.  Apparently, with at least some of these, if you disable baud rate detection they will announce themselves with a prompt when they are ready - you could wait for that.  But I think repeatedly trying until you get a response is going to be the most robust.


message:
Can I use Serial.println() in a class?

I'm trying to convert a class header file from another c++ project to arduino, which in my mind involves replacing cout with Serial.println.

When I try to recomplile with all of these changes, I get this error from the compiler:

    error: 'Serial' was not declared in this scope
         Serial.print(p[i]);

Can someone explain this to me?

body:
You have to `#include <Arduino.h>`, or compile with the `-include Arduino.h` flag. The Arduino IDE normally does that for you, but you have to do it yourself if you are working outside the IDE.

There are a couple of Arduino Makefiles floating around the Web which, just like the IDE, take care of this for you.


message:
Is supplying 5V from both external 5V and USB harmful?

I have an arduino nano which is powered through unregulated 5V (pin 27). For debugging purpose, I'd like to connect the USB port to my computer in order to use the Serial.Print function. The external 5V will stay connected. Will this cause damage ?

edit : I forgot to mention that the external power supplied to pin 27 is regulated with a switching DC-DC converter (measured 5.1V). Sorry it was not clear in my question.

Here is my circuit :

![Schema](https://i.stack.imgur.com/avlw4.png)

The switching regulator is not exactly the one in the schema.

Is using the circuit with the battery power supply + usb connection to my computer will damage something ?

body:
No, it probably won't damage anything, as the PC's USB port is protected from overvoltage by the D1 schottky device on your arduino board.

**Update, my previous answer contained the following paragraph, which is not related to your problem**

> But you should take care of some things.
>
>  1. Make sure, the voltage applied to your +5V-Net is regulated properly elsewhere. I.e. choose a laboratory PSU or another good
> source.
>  2. Avoid having both your PC and your 5V-supply connected to line voltage. Ground levels may differ due to Y-capacitors present in the
> switching PSUs. Those provide a AC voltage of half your line voltage
> to DC ground (only with 0.3 to 0.7 mA, but enough to cause
> disturbances on your signals at 55 volts in the US or 115 V in the EU)
>  3. If you have to use two switching PSU for both PC and arduino, provide an equipotential bonding between your PC's mass (e.g.
> VGA-port-screw) to your arduino's PSU's ground directly, to prevent
> leakage currents from the Y-capacitors wandering around in your
> circuitry.

**Update according to your enhanced question**

You are using a battery powered DC-DC supply for your Arduino. So, my previous notes do not apply to your problem.

 - 5.1 V seem exact enough to drive your arduino safely. No need for additional stabilisation measures
 - D1 (see genuine arduino schematic) separates USB-Power from +5V and prevents current flowing in reverse direction over your USB connection.
 - Arduino circuitry and USB port have common GND so there are always well defined voltage levels.

In my opinion, there's nothing with your setup, which may harm your circuitry or your PC.

Depending on the maximum power of your DC-DC converter you may consider adding a fuse to protect converter and components in case of short circuit.


message:
How does coordinator XBee receive data from router?

I have two XBees S2, one is configured as an API coordinator connected to Arduino and the other as an AT router.

The coordinator sends a frame to the router to switch on a LED. I want to switch off that LED with a button and the router send a message to the coordinator to tell him that it switch off the LED.

How can I do this?

I have one Arduino with the coordinator. I'm asking what I have to put in the script to make the coordinator receive the data.

Here is my code, how the coordinator sends the data to the router:

    String inputString;
    int led = 13;
    void setup() {
    pinMode(led, OUTPUT);
    Seria.begin(9600);
    }
    void loop() {
    while (Serial.available() ) {
    // get the new byte:
    delay(3);
    char inChar = Serial.read();
    // add it to the inputString:
    inputString += inChar;
    }
    if (inputString.length() >0) {
    Serial.println(inputString);
    if (inputString == "on"){
    digitalWrite(led,HIGH);
    setRemoteState(5);

    }
    inputString="";
    }
    }

    void setRemoteState(char value){
    Serial.write(0x7E); // start byte
    Serial.write((byte)0x0);
    Serial.write(0x10);
    Serial.write(0x17);
    Serial.write((byte)0x0);
    // id of recipient or use 0xFFFF for broadcast
    Serial.write((byte)00);
    Serial.write((byte)00);
    Serial.write((byte)00);
    Serial.write((byte)00);
    Serial.write((byte)00);
    Serial.write((byte)00);
    Serial.write(0xFF);
    Serial.write(0xFF);
    // 16 bit of reciepent
    Serial.write(0xFF);
    Serial.write(0xFE);

    Serial.write(0x02);

      Serial.write('D');
      Serial.write('2');

     Serial.write(value);

    long sum = 0x17 + 0xFF + 0xFF + 0xFF + 0xFE + 0x02 + 'D' + '2' + value;
    Serial.write(0xFF - ( sum & 0xFF) );
    Serial.print(sum,HEX);
    }

body:
When you have one working as AT mode, it puts out whatever comes in, it is also called transparent mode.

You should first define which mode you want to use them and start coding.

If you choose AT, load the firmware for both and use Arduino to check the commands and execute tasks (supposing it is connected to the router).

If the task was done correctly, you send an okay message, otherwise, send error. This is a simple task in AT mode, just use Serial:

    if (led == 1)
       Serial.println("ok");
    else
       Serial.println("error");

If you choose API mode, it is a little bit different, where you have to mount the packet for sending data and put a message inside it. There are some [libs][1] out there you can achieve this.

On the other side, the coordinator will receive the message and interpret it.

If it is in AT mode, just read the serial. In API, you have to decode the packet and check the payload field where the data is located.

  [1]: https://code.google.com/p/xbee-arduino/


body: To change the state of digital pin 2,D2 set the "value" to 0x05 to switch it HIGH and set the "value" to 0x04 to switch the pin LOW


message:
Simulate a FTDI using an Arduino UNO

I'm looking to directly program an ESP8266 WiFi Module with out using a FTDI (USB-Serial interface) as suggested in this excelent [tutorial](https://www.openhomeautomation.net/control-a-lamp-remotely-using-the-esp8266-wifi-chip/). The real purpose is to have access to the GPIO ports of the module.

I heard (from [this page](http://hackaday.com/2009/09/22/introduction-to-ftdi-bitbang-mode/)) that one can use an Arduino UNO as an intermediate interface for burning the bootloader onto an AVR (e.g. ATmega168 or ATmega328). That is, using the ArduinoISP code example in the IDE.

Is it possible to use an Arduino UNO as temporal bridge to program the ESP8266? Can anyone please suggest some tutorial? Thanks

body:
The simplest way is to unplug the ATMega328P from the board (or otherwise disable it) and just use the ATMega16U2 by connecting the ESP8266 to pins 0 and 1 of the Uno.  No programming required at all then - the ESP8266 just takes the place of the ATMega328P.

If you really want to "pass it through" the ATMega328P then you will need to make a transparent pipe for the serial data.  That would involve nominating two more pins on the Uno to be a new serial connection, and using SoftwareSerial to interface with those pins.  Then you have a simple loop which reads from one port and writes to the other, and the same in reverse of course.  Make sure you have the baud rates right.  I don't know how well SoftwareSerial would perform at the (commonly) 115200 baud the ESP8266 works at.

EDIT: (Interfacing to a 3.3-V system)

Since the ESP8266 works at 3.3V, while the ATMEGA16U2 is powered at 5V, you might need to adapt the level of the ATMEGA16U2's TXD line (which is connected to the "RX" input line of the ATMEGA328P/Arduino Uno Board), to 3.3V.

To do this, connect a  1.5 kOhm resistor between the RX pin and ground. In fact, the connection between ATMEGA16U2 and ATMEGA328P is done using an 1kOhm series resistor. This, together with the 1.5k Ohm resistor, will create a resistor divider, which converts the 5V output to 3V.

See schematics below.
[![Suggested modifications][1]][1]

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


message:
Can't burn arduino bootloader to atmega8a with usbasp

I want to burn the arduino bootloader with arduino IDE, but I cant get it done. And here  is my circuit:
I have marked the way I connect the ISP port and the chip.

![enter image description here][1]

I choose Arduino NG/older as the board and Atmega8 as the processor, but when I start to burn the bootloader to the chip the LED on the usbasp just blink once and an error was given:

    Arduino:1.6.5 Hourly Build 2015/05/15 06:16 (Windows 7), 板："Arduino NG or older, ATmega8"

    avrdude: warning: cannot set sck period. please check for usbasp firmware update.

    avrdude: error: programm enable: target doesn't answer. 1

    烧录引导程序出错。

    avrdude: initialization failed, rc=-1

             Double check connections and try again, or use -F to override

             this check.

What should go wrong? I have check the connection many times and replace a chip as well, and I even add a 12M crystal(with 22pF caps) but things still keep the same.

**EDIT**
---
I do the flowing things as advise:

 1. short the jp3 jumper of the usbasp to make a slow commiuncation. And remove the crystal.
 2. I just found the way I connect the isp port might be wrong. so I changed it as flowing
![enter image description here][2]

And my actually circuit is like this:
![enter image description here][3]

But got no luck, things still the same :-(

  [1]: https://i.stack.imgur.com/ZzI6v.png
  [2]: https://i.stack.imgur.com/9Z7bn.png
  [3]: https://i.stack.imgur.com/imPKv.jpg

body:
You forgot the Pull Up resistor for Reset.

Using 12Mhz crystal is not a good idea because the Atmega8 config probably uses 8Mhz or 16Mhz, and the fuses which are burned during the bootloader process (yes, they burn fuses first, and THEN load the bootloader) will not expect there to be a 12Mhz crystal, so any further communication can fail because of this too.


body: Did you set the SLOW SCK jumper on the USBasp Programmer? Completely new ATMegas use the internal RC-Oscillator at a frequency of 8MHz, but the _divide clock by 8_ fuse is set too. That means that (before burning the fuses) the AVR is running at a clock frequency of 1MHz and the standard SCK clockrate of the USBasp is too high for this clock frequency. Therefore, you need to set the SLOW SCK jumper to get a lower SCK clockrate.


message:
arduino weather shield and wind speed

I have Arduino Mega and Weather Shield. I want to calculate wind speed.

    float get_wind_speed()
    {

    float deltaTime = millis() - lastWindCheck; //750ms

    deltaTime /= 1000.0;

      float windSpeed = (float)windClicks / deltaTime; //3 / 0.750s = 4

      windClicks = 0; //Sıfırla ve yeni oluşan rüzgarı izle
      lastWindCheck = millis();

      windSpeed *= 1.492; //4 * 1.492 = 5.968MPH

     Serial.println();
     Serial.print("Windspeed :");
     Serial.println(windSpeed);

     return(windSpeed);
    }

But when I run my code I see two windspeed value. First one is windspeed=0.0 or any value. Second one is windspeed=nan.

How can I make it better?

body:
When debugging a problem like this one, print out values of the variables that the calculation depends on.

In this case, you may find that both `windClicks` and `deltaTime` are 0 or 0.0.  The IEEE 754 floating-point-operations specification dictates a result of `NaN` (not-a-number) for various zero over zero calculations.  It dictates a result of `+Inf` or `-Inf` for calculations like 7/0.0 or -13/0.0.  [See, for example, the stackoverflow question, [Why does division by zero with floating point (or double precision) numbers not throw an exception](https://stackoverflow.com/q/12954193).]

If arithmetic generates a `NaN` or `+Inf` result, subsequent arithmetic using that result will also produce `NaN` or `+Inf` results.

To deal with the problem, you could use `deltaTime > 0` as a required pre-condition for calculation of `windSpeed`.  That is, have an if-statement protecting the calculation block.


message:
How do I even out Infared distance sensor readings?

I am using a standard infared distance sensor on a small robot and i am trying to even out the readings on it so it is more accurate. The readings are very sporadic and often take huge jumps in the distance. Is there a method of programming or circuit design that might make this easier to use? I'm trying to keep my robot from running into things.

body:
Wikipedia has a page on moving averages: http://en.wikipedia.org/wiki/Moving_average

I'd suggest at first try an exponential moving average:

> average = a * sample + (1 - a) * average

Experiment with different values of a (with 0 < a <= 1).

The smaller a is, the smoother the curve, but also the longer (more iterations) it takes for an actual change in the input to be reflected in average.


body:
My solution keeps reading for cycles (10 times) and calculate average it.

Be careful voltage output of many surface NOT same.


body:
IR sensors are very erratic in my experience. The best way is to take an average of multiple sensor readings. The number of readings required can be found by experimentation.

**Example Sketch** ([Source][1])

The example below should be similar, and a good start for your model of IR sensor.

    /*
     Sharp GP2Y0A21YK0F infrared proximity sensor (#28995)
     Collects an average of five readings from the sensor and displays the
     resulting value about every half second.

     See the SharpGP2Y0A21_Simple demonstration for additional usage notes,
     including connection diagram.

     This example code is for the Arduino Uno and direct compatible boards, using the
     Arduino 1.0 or later IDE software. It has not been tested, nor designed for, other
     Arduino boards, including the Arduino Due.

    */

    const int irSense = A0;          // Connect sensor to analog pin A0
    int distance = 0;

    void setup() {
      Serial.begin(9600);            // Use Serial Monitor window
    }

    void loop() {
      Serial.println(irRead(), DEC); // Call irRead function to read sensor
                                     // Print value in Serial Monitor
      delay(250);                    // Wait another 1/4 second for the next read
                                     // (Note: Because of delays built into the
                                     //   irRead function the display of values will
                                     //   be slower than in the SharpGP2Y0A21_Simple
                                     //   sketch
    }

    // Take multiple readings, and average them out to reduce false readings
    int irRead() {
      int averaging = 0;             //  Holds value to average readings

      // Get a sampling of 5 readings from sensor
      for (int i=0; i<5; i++) {
        distance = analogRead(irSense);
        averaging = averaging + distance;
        delay(55);      // Wait 55 ms between each read
                        // According to datasheet time between each read
                        //  is -38ms +/- 10ms. Waiting 55 ms assures each
                        //  read is from a different sample
      }
      distance = averaging / 5;      // Average out readings
      return(distance);              // Return value
    }

  [1]: https://www.parallax.com/downloads/sharp-gpy2y0a21yk0f-ir-distance-sensor-arduino-demo


body:
Averaging is a very good technique for improving noisy data, provided
you have a “nice” noise. “Nice” meaning that you never get “atypical”
data points, i.e. the error of any given data point is of the order of
the “typical” error amplitude. If you have for instance
[additive white Gaussian
noise](http://en.wikipedia.org/wiki/Additive_white_Gaussian_noise), then
it can be shown that averaging is in some way the “best” way to clean
your data.

However, if you have big sporadic errors, then **averaging is not a good
solution**. This is because you will have to average _a lot_ of samples
in order to smoothen out a single big error... and the more samples you
average, the more chances you have to get _another_ huge error that will
ruin your average. Of course, averaging will somewhat improve things,
and it is better than no smoothing at all, but there are better options.

The solutions to this problem lye in the realm of [robust
statistics](http://en.wikipedia.org/wiki/Robust_statistics). It may look
like hairy math, but there is actually a very simple smoothing filter
that is far more robust than the average: it's called the
[median](http://en.wikipedia.org/wiki/Median). The idea is quite simple:
you sort your list of samples from smallest to largest, then you pick
the one sample that ends right in the middle of the sorted list. Unlike
the average, this filter is completely insensitive to samples carrying
_huge_ errors, as long as the _majority_ of samples are reasonable.

Here is an implementation of a simple moving-median filter based on the
standard libc’s `qsort()`. It assumes samples have `int` type, but you
can change it to whatever numeric type you want. You can also change the
filter length: longer lengths provide more robustness against series of
consecutive bad samples, at the cost of more filter delay, more memory,
and more processing time.

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

    /*
     * Comparison function for qsort(): return an integer "less than, equal
     * to, or greater than zero if the first argument is considered to be
     * respectively less than, equal to, or greater than the second."
     */
    int compare(const void *pa, const void *pb) {
        int a = *(int *)pa;
        int b = *(int *)pb;
        return a<b ? -1 : a>b ? +1 : 0;
    }

    #define FILTER_LENGTH 11  // length of the median filter, should be odd

    /*
     * Input: raw sample.
     * Ouput: filtered sample.
     */
    int median_filter(int data) {
        static int input_buffer[FILTER_LENGTH];
        static int input_index;
        int sorted_buffer[FILTER_LENGTH];

        // Store the current data point.
        input_buffer[input_index] = data;
        if (++input_index >= FILTER_LENGTH) input_index = 0;

        // Sort a copy of the input buffer.
        for (int i = 0; i < FILTER_LENGTH; i++)
            sorted_buffer[i] = input_buffer[i];
        qsort(sorted_buffer, FILTER_LENGTH, sizeof *sorted_buffer, compare);

        // Return median.
        return sorted_buffer[FILTER_LENGTH/2];
    }

As I did not explicitly initialize the filter memory, this will output
zeros the few first times it is called. I encourage you to try this
filter and compare against an exponential moving average, and only then
decide which works best for you.


body:
The Sharp GP... infra red proximity sensors can produce noisy output sometimes.  This is partly caused by the fact that they work by repeating a brief, powerful IR pulse.

So - the very first tweak I would suggest when using any of these sensors is to try a cheap 10 micro Farad electrolytic capacitor on the 5V power connections, reasonably close to the sensor itself.  This is mentioned on some of their datasheets, but gets forgotten...


message:
Can the Arduino Eclipse plugin v2.2 be used with Arduino 1.5.8?

It keeps giving me this warning:

>You are using a version of the Arduino IDE that is newer than available at the release of this plugin.`

Does this means I need to use a night build?

body:
V2.2 is pretty old by now.
As far as I recall it should work fine.

V2.2 of the Arduino eclipse plugin should work fine with the Arduino IDE version 1.5.8.
What that phrase wants to say is: the plugin V2.2 was released before Arduino IDE 1.5.8 was released; as such the code can not make a statement on the compatibility.

But again V2.2 is old. We hope to release V3.0 end of February 2016


message:
Is it safe to feed 5v dc 1amp to an Arduino uno R3 board?

Is it safe to feed 5v dc 1amp to an Arduino uno board?

body: Yes as long as the polarity is correct, the board will only take the current it requires


body:
The 1 Ampère you're mentioning is likely the maximum rating of the power supply, i.e. it cannot sustain higher currents for a long time. However, if you connect your Arduino board (or any other device) to your power supply, the actually flowing current will depend on the voltage U and the resistance R of the device as I = U/R. You can think of this as the Arduino drawing as much power as it needs.

In other words: you must not exceed the maximum voltage, but you don't have to (and cannot in a simple way) adjust the current flowing into the Arduino.


body:
That's a common newbie question: "What will happen when I use a 1 A power supply for a device which only needs 0.1 A?"

The device will only draw the current it needs. It's the same as on your electricity grid. The nuclear power plant can supply a gigawatt, yet the bulb will only draw the 60 W it needs.

But do you want to apply that 5 V to the power connector? Then the 5 V is too low, you'll need at least something like 6.5 V, otherwise the onboard voltage regulator won't have enough headroom to output 5 V. If you're using the USB connector for a **regulated**(!) 5 V, then the onboard regulator will be bypassed. Never place an unregulated 5 V on the USB connector, though.


message:
Can anyone explain how hex codes 0x1A is used for sending ctrl+z & 0x0D for Carriage Return & 0x0A for LineFeed?

Please explain in detail. How the Hexadecimal code has been assigned?

Edit: This is the code:

    #include <Wire.h>
    void setup()
    {
       Wire.begin();
       Serial.begin(9600);
       delay(1000);
       Serial.println("AT+CMGF=1"); //set to SMS mode
       delay(1000);
       Serial.println("AT+CMGS=\"+918460588440\""); //set the phone number (wrapped in double quotes)
       delay(1000);
       Serial.println("hello world. this is arduino");
       delay(1000);
       Serial.write(0x1A); // sends ctrl+z end of message
       delay(1000);
       Serial.write(0x0D); // Carriage Return in Hex
       delay(1000);
       Serial.write(0x0A);
    }
    void loop() {}

body:
These hex values are the numbers in the ASCII table, https://en.wikipedia.org/wiki/ASCII.

Characters corresponding to values below 32 are control characters, reserved for special purposes. For the values you mention in the question:

- 0x0d = 1*16 + d*1 = 13 = CR (carriage return)
- 0x0a = 0*16 + a*1 = 10 = LF (line feed)
- 0x1a = 1*16 + a*1 = 26 = [SUB][1]

("control+Z" is not the ASCII control character, but how you would generate this control character (SUB) on a keyboard.)

A table with both hexadecimal and decimal numbers is also [given][2] in the Wikipedia article.

  [1]: https://en.wikipedia.org/wiki/Control-Z
  [2]: https://en.wikipedia.org/wiki/ASCII#ASCII_control_code_chart


body:
They are all to do with where in the alphabet they are.  There are 26 letters in the English alphabet, and Z is the 26th.  The 26 in hexadecimal is 0x1A.

A carriage return is a CTRL-M, and a line feed is a CTRL-J.  M is the 13th letter of the alphabet, and 13 in hexadecimal is 0x0D.  J is the 10th letter - 10 is 0x0A in hexadecimal.

Why are they CTRL-M and CTRL-J?  Well, that all stems from the old teletype interfaces used on the very early computers.  That's what they used, and that's what's stuck, and finally made it into the ASCII standard.


body:
(I've formatted your code and edited it into your question).

This code is apparently driving a device - GPRS shield? - to send an SMS. No doubt the code was written to meet the requirements of the device. Note that the CR and LF literals could have been written as '\r' and '\n', respectively. The author chose to write them in hex, probably because there is no "\" code defined for Ctrl-Z, and so wrote all three in a consistent style.


message:
How to fade in and fade out led strip connected to arduino based on continous analog input from capacitative sensor?

So I've been trying to get a capacitive sensor made from aluminum foil to work. And I have had success the kind of proximity and readings I need to light up a single LED and produce basic tone. Using this very basic code :

    {
      Serial.println(value1);//value that i get from analog sensor
      //this is just to get the values in order for the led and sound
      if (value1<=8) value1=-100;
      analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
      tone(tonepin,value1+100,100);
      delay(10);

All this works perfectly for me, the delay isn't perceivable, the response is for all practical purposes simultaneous to input. Except it's not beautiful, because the LED keeps flickering when values reduce or increase because the jumps are sudden I suppose.

SO I thought I'll try to fade in and fade out to different values from present values.  Used the fading examples. Here:

    Serial.println(value1);
      if (value1<=8) value1=-100;

      if (value1+100<=value2+100) {
        for(int fadeValue = value2+100 ; fadeValue <= value1+100; fadeValue +=5) {

        analogWrite(ledPin, fadeValue);

        delay(10);
        }
      }

      else
      {

        for(int fadeValue = value2+100 ; fadeValue >= value1+100; fadeValue -=5)
        {
            analogWrite(ledPin, fadeValue);

        delay(10);
        }
      }
      //analogWrite(ledPin,value1+100);
      tone(tonepin,value1+100,100);
      delay(10);
      value2=value1;

But this takes away the responsiveness, the whole thing is so slow to react, the sound and the light are obviously not in sync as I read my code. But also the light is not really fading, still blinking, but there seems to be some effect but I am not sure.

Any help with what I could do and what I am doing wrong would be nice.

body:
Smooth the change in output value by taking, e.g 10% of the new value, and 90% of the old value. You can try experimenting with different ratios and longer/shorter delays.

    int lastValue = 0;

    {
      Serial.println(value1);//value that i get from analog sensor
      //this is just to get the values in order for the led and sound
      if (value1<=8) value1=-100;
      value1 = (1*value + 9*lastValue)/10;// smooth the change in value by taking 10% of the current value, and 90% of the previous value
      analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
      tone(tonepin,value1+100,100);
      lastValue = value1;
      delay(10);


body:
You need to re-think the entire way of dealing with the fading.

Instead of saying "The value has changed, fade the LED to that brightness", you need to say "The value has changed. I want the LED to be this brightness." followed by "Is the LED the brightness I want? No? Then move it a bit towards the brightness I want".

Something like, in pseudo-code:

    TargetBrightness = SensorValue
    if LEDBrightness < TargetBrightness
        increment LEDBrightness
        set LED to LEDBrightness
    if LEDBrightness > TargetBrightness
        decrement LEDBrightness
        set LED to LEDBrightness

If that all happens too fast then you need to only run the brightness tests at certain periods.  Something like:

    TargetBrightness = SensorValue
    Has 10ms passed since last check? Yes?
        Remember the time this check happened.
        if LEDBrightness < TargetBrightness
            increment LEDBrightness
            set LED to LEDBrightness
        if LEDBrightness > TargetBrightness
            decrement LEDBrightness
            set LED to LEDBrightness


message:
arduino weather shield with gps

I have Arduino Mega and Weather shield and GPS Receiver - GP-635T (50 Channel).

here is my code for GPS

    #include <SoftwareSerial.h>
    #include <TinyGPS++.h>

    TinyGPSPlus gps;

    static const int RXPin = 5, TXPin = 4;
    SoftwareSerial ss(RXPin, TXPin);

    const byte GPS_PWRCTL = 6;

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

      pinMode(GPS_PWRCTL, OUTPUT);
      digitalWrite(GPS_PWRCTL, HIGH);
    }

    void loop()
    {
      smartdelay(800);
    }

And print weather with this code

    void printWeather()
    {
      Serial.print("lat=");
      Serial.print(gps.location.lat(), 6);
      Serial.print("lat=");
      Serial.print(gps.location.lng(), 6);
      Serial.print("altitude=");
      Serial.print(gps.altitude.meters());
      Serial.print("sats=");
      Serial.print(gps.satellites.value());

      char sz[32];
      Serial.print("date=");
      sprintf(sz, "d/d/d", gps.date.month(), gps.date.day(),gps.date.year());
      Serial.print(sz);

      Serial.print("time=");
      sprintf(sz, "d:d:d", gps.time.hour(), gps.time.minute(), gps.time.second());
      Serial.print(sz);
    }

But I see only zero for location and date and time. What should I do?

body:
You need to feed the output from the GPS module to the `TinyGPSPlus` routines, otherwise they won't do anything (other than return `0`). Try adding:

    while (Serial.available() > 0) {
      gps.encode(Serial.read());
    }

to your `loop`. `TinyGPSPlus` comes with examples that you should have a look at. It also provides many debug statistics, e.g. the number of characters processed (`gps.charsProcessed()`) and the if these made sense (`gps.passedChecksum()`).


body:
Until you have the correct baud rate *and* good satellite reception, many fields will be zero or empty.  I wrote a diagnostic program for [NeoGPS](https://github.com/SlashDevin/NeoGPS) that will try different baud rates and confirm that the GPS device is functioning.  The example program is in this directory:

    examples/NMEAdiagnostic

Installation instructions are [here](https://github.com/SlashDevin/NeoGPS/blob/master/doc/Installing.md).

If you're inside, you may not be able to receive anything.  Move next to a window or go outside.


message:
Arduino analog joystick

I'm planning to make a handbrake for my racing simulator (Assetto Corsa) and I wanted to know how can I transform arduino into a joystick so the game can read the **analog** input?

Thanks in advance, and sorry for my bad english.

body:
Never tried it with the Arduino, but it's [quite easy to do with Teensy](https://www.pjrc.com/teensy/td_joystick.html) (which is mostly compatible with Arduino).

[Teensyduino](https://www.pjrc.com/teensy/teensyduino.html) actually includes several examples.


body:
I made this [video][1] and [github][2] just for this about a year ago.

[![Breadboard][3]][3]

And here is the code:

    /*
    2-axis joystick connected to an Arduino Micro
    to output 4 pins, up, down, left & right

    If you are using pull down resistors, change all the HIGHs to LOWs and LOWs to HIGH.
    This skectch is using pull up resistors.

    */

    int UD = 0;
    int LR = 0;
    /* Arduino Micro output pins*/
    int DWN = 13;
    int UP = 12;
    int LEFT = 11;
    int RT = 10;
    /* Arduino Micro Input Pins */
    int IUP=A0;
    int ILR=A1;

    int MID = 10; // 10 mid point delta arduino, use 4 for attiny
    int LRMID = 0;
    int UPMID = 0;
    void setup(){

      pinMode(DWN, OUTPUT);
      pinMode(UP, OUTPUT);
      pinMode(LEFT, OUTPUT);
      pinMode(RT, OUTPUT);

      digitalWrite(DWN, HIGH);
      digitalWrite(UP, HIGH);
      digitalWrite(LEFT, HIGH);
      digitalWrite(RT, HIGH);

      //calabrate center
      LRMID = analogRead(ILR);
      UPMID = analogRead(IUP);
    }

    void loop(){

      UD = analogRead(IUP);
      LR = analogRead(ILR);
      // UP-DOWN
      if(UD < UPMID - MID){
       digitalWrite(DWN, LOW);
      }else{
       digitalWrite(DWN, HIGH);
      }

      if(UD > UPMID + MID){
       digitalWrite(UP, LOW);
      }else{
       digitalWrite(UP, HIGH);
      }
      // LEFT-RIGHT
      if(LR < LRMID - MID){
       digitalWrite(LEFT, LOW);
      }else{
       digitalWrite(LEFT, HIGH);
      }

      if(LR > LRMID + MID){
       digitalWrite(RT, LOW);
      }else{
       digitalWrite(RT, HIGH);
      }

      delay(400);

    }

  [1]: https://www.youtube.com/watch?v=bTqk_QoeRmw
  [2]: https://github.com/PhillyNJ/ArduinoParallaxJoystick
  [3]: https://i.stack.imgur.com/Ad4hZ.png


message:
Capacitive sensor touch detection on wearable

I have a wearable wristband project where I'd like to detect a touch to the outside of the wristband, like a button. However, all my attempts to get this to work with capacitive sensing fail.

The problems accumulate from these aspects:

- Without grounding, the behaviour seems totally arbitrary at times
- I need high response times (12 fps so < 100ms), so some resistor values keep hitting the timeout limit
- Testing is really hard, as behaviour changes after unplugging the USB connection to the computer. I have a bluetooth connection in the Arduino and debug via bluetooth connection to get a "actual scenario" type of reading
- I've also tried things like setting very short timeouts as well as low sample sizes as well as experimented with different resistors

However, I am not trying to really get any sort of gradual "capacitive sensing" here at all, I merely would need to detect a threshold for "is touching". In fact, the area that the user is touching could even be made out of metal (which it was in my tests so far) and touched directly (so nothing in between finger and metal).

This seems like such an obvious thing to try to achieve, I believe there must be some way to get this done. Any ideas?

body:
Expanding on my previous comment:

You can think of capacitive sensing as a form of impedance measurement,
even though it's more a threshold detection than an actual measurement.
In order to perform an impedance measurement, you have to build a
circuit like this:

    ┌─────────┐           ┌───────────┐
    │         ├───────────┤           │
    │  meter  │           │ impedance │
    │         ├───────────┤           │
    └─────────┘           └───────────┘

The important thing in this figure is that you need **two** electrical
contacts in order to close the circuit. The lower contact is often
provided by a common ground, but since your wristband is not properly
grounded, you will have to provide it by some other means.

My suggestion is to have two electrodes on the wristband: a lower
electrode in permanent contact with the user, and an upper electrode
that will be the touch button. If both electrodes are exposed metal,
then you have a full DC path all around, and this is not “capacitive”
sensing any more. Depending on how your sensing is done, this may not be
a problem, and it may be detected just like an infinite capacity.

If you want to avoid a full DC path, you can have one of the electrodes
covered by a thin layer of dielectric. Or even both, but then you have
two capacitors in series and need twice the sensitivity.


message:
How to remember variable values after rebooting an Arduino Uno R3 board?

Is there any way to store the values of necessary variables somewhere (may be in a file that gets updated by the program at various events), which can be read back when program starts after rebooting the Arduino board?

I am trying to control my AC appliances using IR remote control. Where I want Arduino to remember what was on and what was off in my room after a power failure.

Using EEPROM looks like a fairly good solution, though it has a limitation of 100,000 writes which is making me try to find another way out.

Using an external EEPROM which doesn't have that limitation or is fairly big, is a really good idea I got from fuenfundachtzig, thanks for this great idea. But I don't know how to implement this in my project. Any resource to gather knowledge on using external EEPROM, will be much appreciated.

body:
Store them in the on-chip EEPROM.

* http://www.arduino.cc/en/Reference/EEPROM
* http://www.arduino.cc/en/Tutorial/EEPROMWrite
* http://www.arduino.cc/en/Tutorial/EEPROMRead


body:
The internal RAM of the Arduino will be reset when you repower the chip, so if you want to keep your data, you need to store it in EEPROM.

If you are worried about the limited write/erase cycles, you should estimate how often the data would be updated (i.e. written to EEPROM) and how long you plan the lifetime of the device you build. If 100,000 cycles then still is an issue, you have several options:

- Keep the variables in RAM and only write them to EEPROM say every 5 minutes (100,000 cycles then makes about one year of continuous usage until the EEPROM might fail).
- Use an external EEPROM (in a socket) that could be easily replaced if needed.
- If replacing it is not an option, consider using an [FRAM][1] instead (advantage vs EEPROM: *much* more erase/write cycles but also very expensive, so not an option for large amounts of data but certainly for a few variables).

Note, however, that your description sounds like a typical use-case for user settings that you don't want to get lost on reboot. For those the internal EEPROM is the right place: only store them when they're changed and you're golden -- the user won't change them a 100,000 times easily...

  [1]: http://en.wikipedia.org/wiki/Ferroelectric_RAM


body:
EEPROM space, as already mentioned, will work if non-volatile is required. However, you have not qualified if it needs to be non-volatile or not. If not then you can use an \__attribute\__ to define the variable space not to be initialized. As the SRAM on the ATmega's are not cleared by reset or power cycle. The Compiler defaults to initializing them. Where this can be turned off per variable as in the below example:

    //non-initialized value
    union configUnion{
      uint8_t    byte[6]; // match the below struct...
      struct {
        uint16_t value1;
        uint16_t value2;
        uint16_t chksum;
      } val ;
    } config  __attribute__ ((section (".noinit")));

    void setup() {
      uint16_t sum;
      //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      // prints title with ending line break
      Serial.print("Out of Reset -");
      sum = getchksum();
      printValues();

      if (sum != config.val.chksum) {
        config.val.chksum = sum;
        Serial.print("chksum is incorrect setting config.val.chksum = 0x"); Serial.println(config.val.chksum, HEX);
      }

      config.val.value1++;
      config.val.value2++;
      Serial.print("setup new values - ");
      printValues();
      config.val.chksum = getchksum();
      Serial.print("updating chksum config.val.chksum = 0x"); Serial.println(config.val.chksum, HEX);
    }

    int counter = 0;

    void loop() {
      if (counter < 200) {
        Serial.print("after a while - ");
        printValues();
        Serial.println();
        while (true) {
          continue;
        }
      }
      counter++;
    }

    void printValues() {
      Serial.print(" value1 = 0x"); Serial.print(config.val.value1, HEX);
      Serial.print(", value2 = 0x"); Serial.print(config.val.value2, HEX);
      Serial.print(", sum = 0x"); Serial.print(getchksum(), HEX);
      Serial.print(", chksum = 0x"); Serial.println(config.val.chksum, HEX);
    }

    uint16_t getchksum() {
      int sum = 0;
      for (int position = 0; position < (sizeof(config) - sizeof(config.val.chksum)); position++) {
        sum = sum + config.byte[position];
      }
      return sum;
    }

Output of above code is below. Note that the first output was the result of powering the UNO up with the Reset button depressed and then released after the Monitor window was started. Otherwise the "incorrect setting" print would have been missed, before the monitor window can be started.

    Out of Reset - value1 = 0xBFED, value2 = 0xD2F9, sum = 0x377, chksum = 0xF457
    chksum is incorrect setting config.val.chksum = 0x377
    setup new values -  value1 = 0xBFEE, value2 = 0xD2FA, sum = 0x379, chksum = 0x377
    updating chksum config.val.chksum = 0x379
    after a while -  value1 = 0xBFEE, value2 = 0xD2FA, sum = 0x379, chksum = 0x379

    Out of Reset - value1 = 0xBFEE, value2 = 0xD2FA, sum = 0x379, chksum = 0x379
    setup new values -  value1 = 0xBFEF, value2 = 0xD2FB, sum = 0x37B, chksum = 0x379
    updating chksum config.val.chksum = 0x37B
    after a while -  value1 = 0xBFEF, value2 = 0xD2FB, sum = 0x37B, chksum = 0x37B

    Out of Reset - value1 = 0xBFEF, value2 = 0xD2FB, sum = 0x37B, chksum = 0x37B
    setup new values -  value1 = 0xBFF0, value2 = 0xD2FC, sum = 0x37D, chksum = 0x37B
    updating chksum config.val.chksum = 0x37D
    after a while -  value1 = 0xBFF0, value2 = 0xD2FC, sum = 0x37D, chksum = 0x37D

With this your variables will persist resets. As long as the power is not lost. Noting the above where you will get random data, to start.

Using either EEPROM or .noinit I would recommend that you checksum your persistent variable space during setup and if incorrect you can initialize or issue a warning.


body:
If you really need to update your NVRAM frequently, look into [FRAM (Ferroelectric Random Access Memory)][1] which claims a write life of 10^13 cycles (that's ~ 318,000 years if you write once/sec!). They're 8KB, and faster than Flash or EEPROM at 20MHz (SPI).

Adafruit (in the US) sells them on a breakout board for about US$6 in onesies. Or you can buy the bare chips from the usual suppliers for around US$1.30, but not DIP, only SOP8 packages.

  [1]: http://www.fujitsu.com/downloads/MICRO/fsa/pdf/products/memory/fram/MB85RS64V-DS501-00015-4v0-E.pdf


body: If you're open to a off-chip solution, it isn't too difficult to buy/build an SD card reader.


body:
This was puzzling me too. I just wanted to use the onboard button to trigger a "count up an integer" regardless any setup routines. For me, mpflaga's answer gave me the right direction. But the given example was far too complicated for my needs. So here's the bare minimum example for an integer value that survives a reset, counting up. (But NOT a power loss, as it's in RAM!) Enjoy!

```
uint8_t c __attribute__ ((section (".noinit")));

void setup() {
  Serial.begin(9600);
  Serial.print("Just startet. c = ");
  Serial.print(c);
  if(c>7){c=0;}else{c++;}
  Serial.println(" - Waiting for RESET.");
}

void loop() {
  // Do more stuff.
}
```


message:
Arduino Tre, will it ever come out?

Does anyone have any information other than "coming soon" about the Tre?

Could the Tre be stuck in development hell?

Perhaps the new partnership with Adafruit could expidite things, seeing as Ardiuno (.cc) was touting the Tre to be the first Arduino made in the USA?

I'm just giddily awaiting its arrival, so I'm just wondering!

body:
The latest news from Arduino that I can find is in their blog archive that the [second round of beta testing is out][1].

The mentioned this:

> When is the Arduino TRE going to be finally on the market? The board is ready, but we don’t have a final release date yet because we are still figuring out some manufacturing matters. We’ll keep you posted!

I'd imagine that the [Arduino LLC vs Arduino SLR][2] legal issue is also delaying the production.

Other than that, speculation is all that we know.

P.S: it's still spring until Sunday, June 21! :-)

  [1]: http://blog.arduino.cc/2014/12/12/arduino-tre-developer-edition-2nd-round-of-beta-testing/
  [2]: http://hackaday.com/2015/02/25/arduino-v-arduino/


message:
How to get weight data from glass electronic bathroom scale sensors?

I am doing a small project with a bathroom scale but I run into some problems. I am using an Arduino Uno V3, HX711 module amp and a scale.

Scale:
![Digital bathroom scale with 4 sensors][1]

HX711 amplifier:
![Amplifier][2]

I disassembled the scale to get to sensor wires and I am a bit confused. These sensors have three wires each. So they are half bridge sensors. The scale is using 4 sensors so when the scale is measuring it is measuring with a full bridge. And these 3 wires are RED, BLACK, BLUE. I don't know what is black (GND or Positive) and blue (same guess). Four red wires are given names E+, E-, S+ and S-. I will provide a picture of the disassembled scale.
![Sensor wires][3]

Two blue wires are soldered together on each side. I guess red wires are signal (S+, S-, E+ and E-) but what are Blue and Black? Then I soldered the wires to these wires to get sensor readings but I don't know what is what.
![Config][4]

The sensor is looking like this:
![enter image description here][5]

**I tried:**

 1. Two different libraries for this project both named HX711 (for this module)
 2. Changing A+ for A- on module

>     // Hx711.DOUT - pin #A1
>     // Hx711.SCK - pin #A0
>
>     #include "hx711.h"
>
>     Hx711 scale(A1, A0);
>
>     void setup() {
>
>       Serial.begin(9600);
>
>     }
>
>     void loop() {
>
>       Serial.print(scale.getGram(), 1);
>       Serial.println(" g");
>
>       delay(200);
>     }

with no success. I get 0.0g on the serial monitor when calm, and the same when load is on.

**My questions are:**
How to know which wire is GND, +5V and which is signal? How to connect 4 of these sensors to read data? How to use HX711 libraries available and HX711 module? And, most important, how to read data from this scale on serial?

  [1]: https://i.stack.imgur.com/Bxnr9.jpg
  [2]: https://i.stack.imgur.com/NppEm.jpg
  [3]: https://i.stack.imgur.com/04AzD.jpg
  [4]: https://i.stack.imgur.com/en6bG.jpg
  [5]: https://i.stack.imgur.com/EGMol.jpg

body:
1. The HX711 provides power to a bridge and amplifies the bridge's differential voltage.  The scale's original circuit board (which drives an LCD readout) also  provides power to a bridge.  You are unlikely to get any useful readings while both circuits are applying power to the bridge.

(You could cut the existing wires and attach connectors to allow changing back and forth between the original board and your Arduino circuit.)

2. Some scales like the one shown use a 9 V battery to run the electronics.  That voltage, if used, is likely to be incompatible with connecting an Arduino (typically powered by 3.3 V or 5 V) or an HX711 (powered with VDD in the range 2.7 V to 5.5 V) at the same time as the original board.


body:
Text mainly from my comments with some additions - with image added.

The sensors are quite possibly configured as in Fig1 in the data sheet.
 If so there should be +5 and 0V across two points, and weight signal between two others.

Use a DMM to Check for Vdd (probably 5V if pV battery, ~= 3V with Lithium battery). Find two leads to bridge with ~= Vdd on. Other two probably at Vdd/2 above ground. It is likely there are 4 wire effectively so each of the red wires on one side may be conncted tpo one on the other side - an Ohm-meter will tell you. Connect meter on LOW V range between other two and see if reading varies with weight change. Report back.

As jwpat7 says - you may need to repower sensors off HX711 supply to get correct readings.

HX711 looks nice. Under $1/module in modest volume on Alibaba and under $US/0.50 / IC in hundreds.

What Fig1? I know where is GND and VDD on HX711 module, and where goes the signal wires(A-,A+,B-,B+). That is clear. I dont know which colors of wires from sensors is GND VDD and Signal. I will do this. I will put back the power on the scale (3v from battery) and I will try to measure wires to determine what is what (i will put some load on the scale). I have a multimer so i will try to determine which wires are signal, and which wires are GND and VDD. I will report back. Tnx Russell. –

See fig  of [**HX711 Data sheet**](http://www.aviaic.com/uploadfile/hx711_brief_en.pdf) for larger view of this image.

![enter image description here][1]

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


body:
The sensor you have in your scale are a simple voltage dividers. Each consist of one resistor and one extensiometer, both connected in series. One wire (E+) is VDD another (E-) is GND and the third is divider output(S). You can not directly use it with HX711 which needs a bridge sensors not just dividers. You can try to set a 1/2vdd on S- and connect the signal from the sensor to S+. In case you get a negative weight, simply swap these connections. Your assumption that your scale uses full bridge, because it has four sensors, is completly wrong. You can read the signals  from the scale sensors using analog inputs in you arduino (without HX711) but you should amplify it before to get reasonable resolution. Good luck!
Greg


body:
Your four half bridge load cell sensors can connect into a full wheatstone bridge as in https://electronics.stackexchange.com/a/199470/30711

If your sensors are like this 50kg load cell from SparkFun's https://www.sparkfun.com/products/10245  or Ebay's http://www.ebay.com/itm/4pcs-Body-Load-Scale-Weighing-Sensor-Resistance-Strain-Half-bridge-Sensors-50kg-/251873576571 they might have a compression and tension gage both on the top surface. The Ebay site has a diagram like:

 [![three-wire 50kg load cell][2]][2]
... which indicates a positive strain gauge on the red-white, and a negative strain on the red-black. (note that the coloring order in this diagram does not match the coloring order in this picture.  I have a similar gauge with blue-red-black colors, and the positive strain gauge is the right pair, negative on the left.) The gauged surface on the center bar between the face-to-face coupled 'E's in the sensor should act like a parallel bar and has portions under compression and under tension, rather than purely under tension.  In cross-section, the gauged bar in the center is sort of the cross-piece in a Z-shaped spring. In this case, the strains oppose each other, and, if manufactured well, the reduction of resistance in the negative strain portion will offset the increase in resistance in the positive strain portion and the total white-black resistance should be constant.  One still needs to set up the bridge so that the voltage dividers move in opposite directions with added load, and 4 devices wired in a white-to-white and black-to-black loop should work as above.

If you wire four of these up carefully by flipping them around so the stress sensitive portions unbalance the bridge constructively, you can use all four sensors without any extra resistors.

Basically, two diagonally-opposite sides of a wheatstone bridge are each formed by the compression elements of two gauges wired in series, while the remaining two sides of the bridge are each formed from two tension elements from two cells.  With load on all the sensors, the compression resistances are reduced, while the tension resistances are increased and it pulls the bridge out of balance.

To get this, wire all four sensors in a big ring with maximum resistance, matching colors and initially ignoring the red center tap wires.  (This is the function of the soldered-together blues and blacks are in your scale.)  Choose two opposite (red) center taps as E+ and E-, and the remaining two (red) center taps as S+,S-.  Put the excitation voltage on the E+/E- from the diagram above and read a force-sensitive voltage difference across S+/S-, and this is what you feed into your HX711 as A+ and A-  (Ignore B+/B- as a second, unused channel.)

Here's a schematic with gauges 1-4 as G1 G2, G3, G4 per the above specs, applying an excitation on the G1 and G3 reds, and reading the signals off the G2 and G4 reds.  The G4 gauge is loaded a bit with some positive strain increasing the G4+ resistance, and some negative strain reducing the G4- resistance.  Ideally, loading G4 with 25kg would produce 0.5mV/V times its 2.5V excitation voltage, producing 1.250mV across Sig+/Sig-, and stretching R8 to be 1001 ohms and compressing R7 to 999 ohms as shown.   (The schematic/simulator thing on electronics.stackexchange.com is pretty cool.)

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/GYEy2.png)

<!-- End schematic -->

Instead of the "White" wires in the diagram and like on my gauges, consider it the "blue" wires from your scale's sensors.

With only two of these half-bridge sensors, one should not match the end colors and hook white-to-black (blue-to-black) and black-to white, (black-to-blue) imposing an excitation voltage from between these two junctions, and read the differences across the reds, as increased load pulls one side high and the other side low.  This will look like the plain 4-resistor wheatstone bridges in the common datasheets, rather than the 4-half-bridge/eight-resistor scheme above.

  [1]: https://i.stack.imgur.com/vS0Ff.png
  [2]: https://i.stack.imgur.com/PrHOR.jpg


message:
HIGH and LOW reversed

i've got a seven-segment-display on my arduino-nano and want to write some numbers on it. The problem is that HIGH and LOW seems to be reversed.
If the output should be

    0

 it displays

    -
I could solve this, replacing all HIGH and LOW through HIGHX and LOWX, and defining them reversed:

     #define HIGHX 0x0
     #define LOWX 0x1

but this is reversed and not a *good* solution...

The wiring is correct like this (just GND not connected):
![enter image description here][1]

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

But if i connect the GND, the hole display isn't showing something anymore.

body:
reversing a boolean can be done using the `!` operator.
So doing something like `print(!true);` will print `false` (or 0, I'm not sure.)

And you make a wrapper or class to abstract this specific/odd behaviour.

Like:

"setLedPin(pinnr,state){digitalWrite(pinnr,!state)} //The pins are inverted, LOW is ON, HIGH is off, this piece inverts it."

You may even make a class for these segment displays and pass to your constructor if it's an inverted or "normal" one.
Or even make two classes that implement the same interface, but for such a small difference, that shouldn't be necessary.


body:
With the given schematic both your logic for segments and digits should be active high, so it looks like you made a mistake. Especially because you say it doesn't work anymore when you connect ground. Check that you have the right transistor and that it's connected correctly: Emitter should go to ground, collector to the display's common cathode. (Check that your displays are common *cathode*!)

It's not a good idea to define some version of high as low, that's only confusing. Instead name the signals:

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

    #define DISPLAY_SEGMENT_ON HIGH
    #define DISPLAY_DIGIT_ON HIGH

The image can be found at several places on the Internet, so I guess you didn't draw it. This is a **common cathode** display, and the transistors are **NPN** types. If your displays are **common anode** then the whole thing flips upside-down: The Ground rail becomes Vcc, and the NPN transistors should be **PNP** types. Then you will indeed have inverted logic, and you should define:

    #define DISPLAY_SEGMENT_ON LOW
    #define DISPLAY_DIGIT_ON LOW


body:
If your display is a common anode type, the following will happen.

Suppose you put a HIGH on D12, and LOW on D2 then current will flow from D12 through the base-collector diode of Q1, through the LED and out D2 to ground.

If you now connect Gnd to ground wihout changing anything else, the current from D12 will flow through the base-emitter diode of Q1 to ground and not through the LED.

So the display is probably of the wrong type for your design.


message:
Arduino OR operator

I have been trying OR conditional operator in a if condition statement in my arduino program and the result is not what I expected.

My program:

    // three variables assigned to const int datatype as the
    // pin numbers they are assigned to are  going to remain
    // constant through out the program.
    const int led1=10;
    const int led2=11;
    const int led3=12;

    void setup(){
      // assigning the pins as input/output.
      pinMode(10,INPUT);
      pinMode(11,INPUT);
      pinMode(12,OUTPUT);
    }

    void loop(){
      control();
    }

    void control()
    {
      int task1 = digitalRead(led1);
      int task2 = digitalRead(led2);
      if (task1==HIGH || task2==HIGH)
      {
        digitalWrite(led3,HIGH);
      }
      else
      {
        digitalWrite(led3,LOW);
      }
    }

if the 'IF' conditional statement used without 'OR' operator is working fine that is not including both the tasks instead only one task either task1 or task2, else it is working without errors but the result is not as expected.
hardware part is all fine. i reckon that there is a problem with the OR || operator.

body:
Your code is correct for what you described you want it to do - raise `led3` when either or both of `led1` or `led2` is high, and make it low otherwise. Some things to check:

 - Do the push-buttons pull their respective pins HIGH? (Pulling LOW is more common).
 - Are the pins pulled to ground with a 5K or 10K resistor, and not left floating, when the respective button is not active?
 - Real buttons need to be de-bounced. They behave as if their contacts bounce several times before making contact (even though that isn't really what happens). If this is an experiment and you hold the button down, even briefly, you should get proper results without de-bouncing, but it's something to be aware of as you move on.


body:
If you aren't getting the expected result, as JRobert suggested you should look at your hardware. Ensure pull-ups/downs are being used correctly, your interpretation of your hardware's logic is correct (positive/negative logic), and maybe even use a simple sketch to check that everything is working correctly. Firstly I would simplify the control function. You could try replacing the OR with a bitwise OR, or changing your variables to booleans. Realistically, more code and a diagram illustrating your implementation would help us reproduce and troubleshoot this with you. I'm a little confused as to whether pins 10 & 11 are LEDs or Buttons. I would be happy to help you get a test program together if you can provide more detail. :)

    void control()
    {
        boolean task1 = digitalRead(led1);
        boolean task2 = digitalRead(led2);

        // Note that the if isn't needed
        digitalWrite(led3, (task1 || task2));

        // If your buttons use negative logic
        // digitalWrite(led3, (!task1 || !task2));
    }

For humour-sake when I hit a problem that doesn't make sense, I rework my logic to break down the problem and output in stages, or use the Serial library to output what is going on periodically.

 - [Arduino Serial Reference][1]

 - [Arduino Serial Tutorial][2]

Typically for inputs and outputs I define a structure which buffers everything per IO, and write my code with a loop-based mentality, much like how a game loop is implemented in video games. It is easy to print and trace when troubleshooting, and the positive/negative/default-state logic is abstracted. This will help you get started if you are curious.

 - [Game Loop Example][3]

  [1]: http://www.arduino.cc/en/reference/serial
  [2]: http://www.ladyada.net/learn/arduino/lesson4.html
  [3]: http://rbwhitaker.wikidot.com/the-game-loop


message:
Troubleshooting DC motor

I worked on the starterkit project #9 motorized pinwheel, and the motor worked just fine.

I then tried to add a potentiometer, and now the motor won't rotate at all any more (neither in the current nor in the project's baseline configuration). I also tried connecting the motor to the 9V battery directly, to no avail.

I did check the battery by briefly connecting a LED right away. The motor apparently also still generates current if I turn it manually (checked with a directly connected LED either).

What else can I do to check what's wrong with the motor? Is it possible that I somehow accidently killed it with my attempts with the potentiometer?

body:
If your motor doesn't work when connected to the 9V battery, either the battery is flat (which is likely since you were able to connect the LED without destroying it!! - they are a 2.5-3v part, not a 9v part) or the wiring to the motor is damaged. When you connect the motor directly to a 9v battery, it should turn pretty fast - may also work if you connect it to between 2 & 4 AA batteries.

9v batteries don't have that much energy in them... you would be better off with a battery pack with 6 AA batteries in it.


message:
How to draw a bitmap on a tft display?

I'd like to print a bitmap on my TFT.

I setup my screen with this library: http://forum.arduino.cc/index.php?topic=292777.0

It is like the Adafruit_GFX library (only a little bit changed). Everything works.

With the tool Img2Code I converted my image into a bitmap.

    void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
                                   const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color)

![screenshot][1]

How to include this code and print the bitmap on the tft?

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

body:
As the function prototype you have show suggests, the data needs to be in a uint8_t array format.

    void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
                const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color)

So your array data would look like:

    const uint8_t myBitmap[] = { 0xff, 0xff, 0xc0, 0x00, 0xc0, 0xff,
        0xc0, 0xc0, 0xff, 0xff, 0xde, 0xad, 0xbe, 0xef,
        .... etc ....
        0xff, 0xff, 0xff, 0xff, 0xff
    };

You then call the function with the needed parameters:

    tft.drawXBitmap(10, 20, myBitmap, 100, 80, 0xFFFF);

That is assuming you want to place it at (top left corner) 10,20 and the bitmap is 100x80 pixels in size.  It will draw it in white (0xFFFF).


message:
How to read data from a rotary encoder with ATmega328

I'm using a home made "bare bones" Arduino, made with the ATmega328, and I need to read angle data from a geared DC drill motor, turning at speeds between 0 and 450 RPM. This is so I can use it as feedback for an angle control system implemented on the Arduino.

I've not yet bought the encoder. I'm waiting until I find a suitable one which works easily with Arduino.

I have already written the control algorithm. I'm using state variable feedback, and the algorithm depends on a `getAngle()` function that I have not written yet. This function is inside an if statement that executes every 0.2 seconds. It needs to return the angle of the DC motor in degrees.

**My questions:**

 - How can I implement this `getAngle()` function using a rotary encoder?

 - What is an example of a rotary encoder that is suitable for this application?

 - Will it be better to use the interrupt pins of the Atmega328, or use some other method?

I have seen [a few library's on Arduino Playground][1] that claim to make reading angle data easier, but how do I use them? I need something that is fast (it, and the control algorithm operations, both needs to finish before the 0.2 seconds sample time), and more importantly it needs to be easy to implement. I'm coming up to the project deadline so I don't want to have to spend a whole day figuring out how to implement this `getAngle()` function.

Thank you!

  [1]: http://playground.arduino.cc/Main/RotaryEncoders

body:
Your encoder choice will probably be driven by the mechanical requirements and the precision you need:

 - Runs occasionally, and briefly to 450 RPM or runs continuously, and often at the higher speeds?
 - Do you need position to e.g., within 3 degrees (7 bits)? Or 1/3 degrees (10 bits)? Or are you willing to count pulses from an index mark (this gets more complicated if the direction of rotation can change).

An n-bit encoder can probably be read whenever you need a position sample, so interrupts would probably not be necessary. With an index wheel (a pulse every x degrees, plus a separate pulse at 0 degrees, e.g.)
you would probably benefit from tracking the position at interrupt level and letting the main loop simply access the last known position.

Your `getAngle()` implementation depends totally on the choices you make above. If you use a [Gray-coded][1] encoder wheel, you'd need to convert the code to a binary fraction and multiply by 360 to get degrees. If you use an index wheel, `getAngle()` just reads the current pulse-count maintained by your interrupt routine and converts it to degrees. But you need an interrupt routine to count angle-pulses and reset the count on the index pulse (not especially hard to do).

Fixed-point arithmetic is pretty fast. Floating point takes longer. Depending on what else, besides position-keeping, your code needs to do, and how math-heavy it is, whether you can afford floating point. The floating point library will take more code space, too, but my guess is you'll be constrained by time more than by code-space.

  [1]: http://en.wikipedia.org/wiki/Gray_code


body:
There is no such thing as an encoder that "works well with Arduino" - encoders are encoders, and there are several basic types. As @JRobert said, you need to make an appropriate choice, and an encoder that will *mechanically* couple well with your drill motor is probably your primary criteria, and of course an encoder that can spin unrestricted (some are only for an angular range like 180 or 270 degrees); my guess is you'll want to put the encoder on the ungeared motor, rather than the geared output of whatever it is you're driving, to get good feedback from a cheap (i.e. relatively small number of 'pulses per rev') encoder.  Search on DigiKey, Mouser, online hobby stores, etc.  Then just deal with whatever type of encoder it is, hack its electrical interface into the Arduino:
http://www.digikey.com.au/product-search/en?pv69=848&FV=fff4001e,fff80033&k=encoder&mnonly=0&newproducts=0&ColumnSort=0&page=1&stock=1&quantity=0&ptm=0&fid=0&pageSize=25

This (2-signal quadrature) encoder library for Arduino is superb, by Paul Stoffregen @ pjrc.com:
https://www.pjrc.com/teensy/td_libs_Encoder.html
For best results you'll want the 2 'quadrature encoder' outputs to go into 2 interrupt inputs on the Arduino, and there are only 2 available.  There is an option to run this library on only 1 IRQ-capable input (the other can go into any input), or even no IRQ-capable pins, but performance will suffer.

Sampling at only 5/second isn't much - don't be afraid to increase that substantially - 10 to 50 / second.

You also might want a PID control algorithm, depending on what your actual aims are.  the "PIDLibrary" by Breatt Beauregard on the Arduino Playground website is excellent.

Coding your 'getAngle()' function shouldn't be hard - for a rotary quadrature encoder, X pulses from the encoder corresponds to 1 revolution.  The 'encoder library' you end up using may provider more than 1 pulse output per actual pulse output from the encoder.  Do that math. Simple.


body:
You are mixing two related ideas together.  Keeping track of encoders is best done with at least one interrupt in my experience. Whether or not you should use 2 or can get away with none depends on the speed of the shaft.  In my experience, RPMs generally encountered at the hobby level can be handled by 1.  So your interrupt code is interrupted by phase A rising or falling (Pin Change Interrupt).  At that point it read phase B, depending on the combination of A and B you are either going forwards (interrupt count+) or backwards (interrupt count-).  You know by specifications how many pulses you will have in a 360 degree rotation, and by modulo math, (e.g. x % 360) you will know how many degrees you are currently at.

The concept of sampling rate has to do with how often you read the current interrupt values, but they themselves will always be accurate and realtime.

Keywords to google volatile.  Also use signed long integers, not unsigned (don't ask how I know :| )

Not sure why the other answer suggested a PID, I didn't see anything in your question that would need it. For holding an angle you are more likely to use acceleration and deceleration, not PID.

Search [google][1], you might find a way to build your own encoders.

![enter image description here][2]

  [1]: https://www.google.com/search?q=optical quadrature encoder diy&tbm=isch
  [2]: https://i.stack.imgur.com/e7PUl.jpg


body:
You will have to use interrupts or otherwise the encoder might be rotating but your Arduino is doing something else than reading the encoder. By using interrupts, the encoder counter is always updated when the encoder moves. This also means that the interrupt function has to be very short so that it only takes a few cycles to complete and thus leaves the majority of the Arduinos computing time for your sketch.

Here is a code that I've used in many applications from CNC handwheels to servos and for reading extremely accurate angle sensors. It is dead simple, uses two interrupts to read the quadrature signal (A & B channel) and also makes use of Arduinos built in pull-up resistors to keep the channels held high for reliable readings.

Assuming that your encoder is an open-collector output and works with 5V, you only need to connect 5V and GND to it and then the A channel to the first interrupt pin #2 and channel B to #3. That's it for the hardware.

This code goes at the start of your sketch, right before setup() function:

    const signed byte encoderDirections[] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0};
    volatile long encCount = 0;

It defines a constant array that is used for finding the direction that the encoder has turned based on the previous value and the current value. It is defined as constant as it is never changed. Also a global variable calle encCount is defined as a long type variable so that the encoder can count in both directions. It is absolutelu imperative to declare it as volatile so that the compiler and the microprocessor never try to do any "shortcuts" when you use this variable, but instead always loads it from its respective memory address. This is done so because the interrupt can fire at any time and change the variables value without any other function knowing it.

Next, in your setup() function you will want to include these lines to make the Arduino pins as inputs with the internal pull-up resistors connected. The latter two lines attach the interrupts 0 & 1 (hardware pins pins 2 & 3) so that whenever the pin state changes (low to high or vice versa), it halts the microprocessors operation and jumps to the encoder_interrupt function immediately.

    pinMode(2, INPUT_PULLUP);
    pinMode(3, INPUT_PULLUP);
    attachInterrupt(0, encoder_interrupt, CHANGE);
    attachInterrupt(1, encoder_interrupt, CHANGE);

Last you will need the actual interrupt function that reads the encoder and updates the counter value.

    void encoder_interrupt() {
      static unsigned int oldEncoderState = 0;
      oldEncoderState <<= 2;
      oldEncoderState |= ((PIND >> 2) & 0x03);
      encCount += encoderDirections[(oldEncoderState & 0x0F)];
    }

First this defines a variable that holds the previous encoder value that was read from the pins 2 & 3. This is declared as static, so the value is stored in memory even when this function exits so that it can be used the next time the interrupt routine is run.

The second line moves the previous interrupt channel values two bits to the left (multiply by 4) to make room for the new values.

The third line is an interesting one. It reads the PIND, meaning all the pins at D register, which holds many Arduino pin states, including the pins 2 & 3 that we are interested in. Next it shifts this value 2 bits to the right (divide by 4) to "drop" the pin 2 & 3 states to the lowest bits of this byte. Then it AND's this byte with 0x03 to zero everything else but the lowest two bits that now contain the interrupt channel states. Lastly these two bytes are OR'd with the previous encoder state values to obtain a 4 bit number.

On the forth line this 4 bit number is AND'd with a 0x0F to make sure the highest 4 bits are zero to make sure this number is truly a 4 bit number that stays between 0..15, as it is used as an index for the constant array we defined at the start of the program to get the encoders direction of rotation and this is then added to the counter variable.

And now you have an accurate and extremely fast way of reading a two channel encoder to keep track of its position.

If you want to calculate an angle from the encoders current position, you could do a function like this, but you have to know the line count of your encoder and multiply it by 4 so you know the encoder pulse count per revolution. For example, a 100 line rotary encoder gives out 400 pulses per revolution. I assume that there is a constant defined as follows at the start of program:

    const int LINE_COUNT = 400;

Also, this function assumes that the encoder could have turned more than one revolution and you just want the angle from some reference spot in degrees. Do take in to account that the long type variable will overflow after +-2 147 483 648 pulses as it is a 32 bit signed variable.

    float getAngle() {
      long curCount = encCount;  // Store the current count.
      while(curCount < 0) {
        curCount += LINE_COUNT;
      }
      while(curCount >= LINE_COUNT) {
        curCount -= LINE_COUNT;
      }
      return (curCount / LINE_COUNT * 360.0);
    }

First the encoder count is copied to a one use variable. then two while statements make sure the values is positive from 0 to LINE_COUNT-1, so it basically reduces the count to what it would be with just under one revolution. Then it returns the number of degrees by calculating the current position as a fraction of a one revolution count and multiplies this with 360 to get the degrees.