message:
Signal sampling: losing data every 103 points when it is recorded in SD

I'm working on a system of acquisition and ECG datalogging with the Arduino, and I'm having the following problem:
I'm losing data every 103 points (just 103). No matter the sampling frequency to use, every 103 points, some points are lost, damaging the signal sampling.
It could be the recording time on the SD card, but even when the SD.close () command is run only once, the data is lost.
Here is a simple test algorithm with a 100 Hz sine wave at the entrance.
___

    #include <SD.h>
    #include <SPI.h>

    int CS = 4;
    int ECG_PIN = 1;
    int voltage;

    int index = 0;
    const int bufferSize = 5;
    int vetor[bufferSize];
    int RECORD_TIME = 20000;
    File logFile;

    void setup(){
      pinMode(CS, OUTPUT);
      pinMode(ECG_PIN,INPUT);

      if(!SD.begin(CS)){
        return;
      }
      logFile = SD.open("ECG_log.txt", O_CREAT | O_WRITE);

    }

    void loop(){
      while(millis() <= RECORD_TIME){

          voltage = analogRead(ECG_PIN);
        if(logFile){

           logFile.println(voltage);

           delay(0.5);
        }
      }
      logFile.close();
    }

___

![enter image description here][1]

What could it be? Speed analogRead ()? Problem on the SD card?

Sorry if the question is very basic, I am beginner, in a way, the Arduino platform. Any help will be very welcome.

Thanks!...

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

body:
It's all to do with writing to the SD card.

You have a buffer of 512 bytes which is one "block" of the SD card.  When you have written to the card enough to fill that buffer up it has to write that buffer to the SD card and empty the buffer so you can start filling it again.

That writing to the SD card takes time - lots and lots of time (relatively), and it can't be doing anything else at the same time as writing to the SD card.

The only way you can get around that is to have your sampling performed within an interrupt - maybe a timer interrupt - so that it can interrupt the writing to the SD card.  However, that's not a simple task.

You would need to implement a system known as *ping-pong* buffers.  You have a pair of buffers for storing incoming samples within your interrupt routine.  When one buffer is filled up you switch to the other buffer and signal to your main loop() routine that you have filled the buffer.  It's then the job of loop() to save that buffer to the SD card and empty it ready for when the second buffer has been filled up.  The name *ping-pong* comes from the game of table tennis (also known as *ping-pong*) as you are switching from one buffer to the other and back again in a constant backwards-and-forwards motion like the ball in a game of table tennis.

Getting the right size of buffers is also critical.  You have to ensure that the time taken to fill one buffer is always going to be longer than the longest amount of time it takes to write a buffer to the SD card, including any flushing of the internal SD card buffer.  The best size is probably going to be to match that internal SD card buffer so every *ping* or *pong* you will be doing an entire SD card block's worth of data - so 512 bytes.

That means you have 3 buffers of 512 bytes - your two ping-pong buffers and the SD card's buffer, which is 1536 bytes - not far off the limit of an Uno, so you may struggle with that.  For this kind of thing it is better to use one of the boards with a more meaty chip, like the Mega2560.

Also the line:

    delay(0.5);

is meaningless.  `delay()` takes an integer value, so `0.anything` is actually truncated to `0`.  To delay for less than a millisecond you should use `delayMicroseconds()`.


sender: user

message:
Arduino with ESP8266

I have completed the circuit and code to interface ESP8266 module with Arduino UNO.

When i send `AT`,`AT+RST` from serial monitor the reply is correct .

But when i send AT commands to search WIFI networks (`AT+CWLAP`) & connect to WIFI (`AT+CWJAP="SSID","password"`) the reply is `ERROR`.

But the IP address (may be default) is obtained as `192.168.4.1`
 when i send `AT+CIFSR` .

Here is my code

    #include <SoftwareSerial.h>
    SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                                 // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                                 // and the RX line from the esp to the Arduino's pin 3

    void setup()
    {
        Serial.begin(9600);
        esp8266.begin(9600); // your esp's baud rate might be different
    }

    void loop()
    {
        if(esp8266.available()) // check if the esp is sending a message
        {
            while(esp8266.available())
            {
                // The esp has data so display its output to the serial window
                char c = esp8266.read(); // read the next character.
                Serial.write(c);
            }
        }
        if(Serial.available())
        {
            // the following delay is required because otherwise the arduino will read the first letter of the command but not the rest
            // In other words without the delay if you use AT+RST, for example, the Arduino will read the letter A send it, then read the rest and send it
            // but we want to send everything at the same time.
            delay(1000);
            String command="";
            while(Serial.available()) // read the command character by character
            {
                // read one character
                command+=(char)Serial.read();
            }
            esp8266.println(command); // send the read character to the esp8266
        }
    }

sender: assistant

body:
Finally i found the solution .

Send `AT+CWMODE=1` first , then all other commands working fine.


message:
One free pin. Need to display output for the user?

I'm working with [lightblue bean][1]. I have a device that writes data to an SD card on a long button press and switches what will be written (from a list of 5 items) on short button press.

The output, printed both to the SD card and to serial looks like this:

    12:38, 7/15/15, subway
    12:55, 7/15/15, subway
    12:38, 7/15/15, bus
    12:55, 7/15/15, rail

etc. It's basically a time stamp then a vale from this list:

    char* modes[]= {"walking", "subway", "bus", "railroad", "other"};

This works perfectly. But the bean has very few pins:

![enter image description here][2]

 - 5 SCK  -- connected to SD card.
 - 4 MISO -- connected to SD card.
 - 3 MOSI -- connected to SD card.
 - 2 SS   -- connected to SD card.
 - 1      -- input button, takes long and short presses
 - 0      --
 - A1 SDA --- connected to real time clock for timestamp
 - A0 SCL --- connected to RTC (real time clock) for timestamp

I have ***one*** free DIGITAL pin. I need to let the user know what they have selected. This could be done with 5 LEDs that light up next to the user's choice, or maybe displayed text? This is a portable item so a servo that points to the user's choice might be too unreliable.

I've done some research into shift registers. They all seem to need 3 digital pins min. If I could do it with 2 I could rework the button...

Ideas?

  [1]: https://punchthrough.com/bean/arduino-users-guide/
  [2]: https://i.stack.imgur.com/aU3Q2.png

body:
Seems you have I²C on the board you could possibly use an I²C LCD backpack, like from [breakouts][1] if you already have an LCD, this means you can have the RTC and display on the I²C bus and probably more things.

Another option seems you mentioned LEDs, you could still use the I²C bus and use an I/O expander and hook LEDs up to that and address them over the I²C. You can use a PCF8575(16 I/O), as there are [Arduino libraries][2]. There are [breakouts][3] for it. Or you could make your own from another AVR, like one from the ATTiny line, seems there is 5 LEDs.

A I²C bus example:
[![enter image description here][4]][4]
<sub>(source: [ermicro.com](http://www.ermicro.com/blog/wp-content/uploads/2009/02/i2c_00.jpg))</sub>

Seems you want to use the PWM, you can use a dot/bar driver IC, such as the [LM3914](http://www.ti.com/lit/ds/symlink/lm3914.pdf) it takes an analog value and shows it as a point on the strip of LEDs, example below:
![enter image description here][5]

The IC can also work down to 3V.

What you will need to do is add a [low pass filter][6] to convert the PWM to a smooth analog value. You will add this in place of the input circuitry(D1 & C1) there:

![enter image description here][7]

If there is any confusion on the LM3914, there are quite a few tutorials on google.

  [1]: http://www.adafruit.com/products/292
  [2]: http://playground.arduino.cc/Code/I2CPortExpander8574
  [3]: https://www.sparkfun.com/products/8130
  [4]: https://i.stack.imgur.com/mkTCK.jpg
  [5]: https://i.stack.imgur.com/wKf0v.jpg
  [6]: https://en.wikipedia.org/wiki/Low-pass_filter
  [7]: https://i.stack.imgur.com/K3iut.gif


body:
I've found a solution! [7-segment display breakout board][1].

![I][2]

This works art 3.3v which is critical for a lightblue bean. I think a servo might be the most creative solution.

I'm still convinced there must be some way to use PWM...

  [1]: https://learn.sparkfun.com/tutorials/using-the-serial-7-segment-display/assembly
  [2]: https://i.stack.imgur.com/2qSpy.png


body:
The 7-segment display board is all very well, but that displays 4 digits. That isn't exactly 5 LEDs. In any case that board has a chip on it, if you are going to buy another chip you may as well get an Attiny and use that. Just have serial input (same as the 7-segment board did).

On the Attiny you have 8 pins, 3 of which will be reserved: Vcc, Gnd, Reset. That leaves you with 5 for the communications *and* the 5 LEDs. So, use one pin for incoming serial, or two pins for SDA/SCL, and use the remaining 3 pins for the LEDs. You can can use [Charliplexing](https://en.wikipedia.org/wiki/Charlieplexing) to use 3 pins to light up to 6 LEDs.

![Charliplexing schematic][1]
---

For the fun of it, I made up an example using my Uno (it still only uses 3 pins to light 6 LEDs).

![Charliplexing demo][2]

There are 3 x 100 Ω resistors as in the schematic. One is completely hidden by the LEDs (leading from the middle yellow wire to the middle pins of the LEDs).

Code:

    const byte X1 = bit (2);   // D2 on Uno
    const byte X2 = bit (3);   // D3 on Uno
    const byte X3 = bit (4);   // D4 on Uno

    const byte patterns [7] [2] = {
    // PORT DDR
      { 0,   0, }, // all off
      { X1, X1 | X2 }, // LED1: X1 on,  X2 off, X3 HiZ
      { X2, X1 | X2 }, // LED2: X1 off, X2 on,  X3 HiZ
      { X2, X2 | X3 }, // LED3: X2 on,  X3 off, X1 HiZ
      { X3, X2 | X3 }, // LED4: X2 off, X3 on,  X1 HiZ
      { X1, X1 | X3 }, // LED5: X1 on,  X3 off, X2 HiZ
      { X3, X1 | X3 }, // LED6: X3 on,  X1 off, X2 HiZ
    };

    void setup ()
      {
      }  // end of setup

    void loop ()
      {
      for (int i = 0; i < 7; i++)
        {
        DDRD = patterns [i] [1];
        PORTD = patterns [i] [0];
        delay (500);
        }  // end of for loop
      }  // end of loop

The code displays each of the 6 LEDs (plus all off) in a cycle. For each one it configures the DDR (data direction register) plus the PORT (output register) appropriately to light the desired LED.

It works perfectly, except that you may need to work out which LED is which by experimentation.

  [1]: https://i.stack.imgur.com/ZJfsk.png
  [2]: https://i.stack.imgur.com/SYzzc.jpg


message:
Multiple if statement conditions

I would like to make this code using the Arduino Uno. I am using three on/off switches and based on the truth table would like to turn on one of 8 LEDs. When I use `digitalWrite()`, I get an error code saying that there are too few arguments.

Here is the code

<!-- language: c -->

    int x = A3;    // select the input pin for the switch
    int y = A4;
    int z = A5;

    int ledPin1 = 2;      // select the pin for the LED
    int ledPin2 = 3;
    int ledPin3 = 4;
    int ledPin4 = 7;
    int ledPin5 = 8;
    int ledPin6 = 9;
    int ledPin7 = 12;
    int ledPin8 = 13;

    void setup(){

      // declare the ledPin as an OUTPUT:
      pinMode(ledPin1, OUTPUT);
      pinMode(ledPin2, OUTPUT);
      pinMode(ledPin3, OUTPUT);
      pinMode(ledPin4, OUTPUT);
      pinMode(ledPin5, OUTPUT);
      pinMode(ledPin6, OUTPUT);
      pinMode(ledPin7, OUTPUT);
      pinMode(ledPin8, OUTPUT);

      pinMode(x, INPUT);
      pinMode(y, INPUT);
      pinMode(z, INPUT);
    }

    void loop() {

      if ( (x = LOW) && (y = LOW) && (z = LOW))              //condition 1
      {
        digitalWrite (ledPin1 = HIGH);
        digitalWrite (ledPin2 = LOW);
        digitalWrite (ledPin3 = LOW);
        digitalWrite (ledPin4 = LOW);
        digitalWrite (ledPin5 = LOW);
        digitalWrite (ledPin6 = LOW);
        digitalWrite (ledPin7 = LOW);
        digitalWrite (ledPin8 = LOW);
      }

      if ( (x = LOW) && (y = LOW) && (z = HIGH))             //condition 2
      {
        ledPin1 = LOW;
        ledPin2 = HIGH;
        ledPin3 = LOW;
        ledPin4 = LOW;
        ledPin5 = LOW;
        ledPin6 = LOW;
        ledPin7 = LOW;
        ledPin8 = LOW;
      }

      if ( (x = LOW) && (y = HIGH) && (z = LOW))             //condition 3
      {
        ledPin1 = LOW;
        ledPin2 = LOW;
        ledPin3 = HIGH;
        ledPin4 = LOW;
        ledPin5 = LOW;
        ledPin6 = LOW;
        ledPin7 = LOW;
        ledPin8 = LOW;
      }

      if ( (x = LOW) && (y = HIGH) && (z = HIGH))              //condition 4
      {
        ledPin1 = LOW;
        ledPin2 = LOW;
        ledPin3 = LOW;
        ledPin4 = HIGH;
        ledPin5 = LOW;
        ledPin6 = LOW;
        ledPin7 = LOW;
        ledPin8 = LOW;
      }

      if ( (x = HIGH) && (y = LOW) && (z = LOW))               //condition 5
      {
        ledPin1 = LOW;
        ledPin2 = LOW;
        ledPin3 = LOW;
        ledPin4 = LOW;
        ledPin5 = HIGH;
        ledPin6 = LOW;
        ledPin7 = LOW;
        ledPin8 = LOW;
      }

      if ( (x = HIGH) && (y = LOW) && (z = HIGH))               //condition 6
      {
        ledPin1 = LOW;
        ledPin2 = LOW;
        ledPin3 = LOW;
        ledPin4 = LOW;
        ledPin5 = LOW;
        ledPin6 = HIGH;
        ledPin7 = LOW;
        ledPin8 = LOW;
      }

      if ( (x = HIGH) && (y = HIGH) && (z = LOW))                //condition 7
      {
        ledPin1 = LOW;
        ledPin2 = LOW;
        ledPin3 = LOW;
        ledPin4 = LOW;
        ledPin5 = LOW;
        ledPin6 = LOW;
        ledPin7 = HIGH;
        ledPin8 = LOW;
      }

      if ( (x = HIGH) && (y = HIGH) && (z = HIGH))                //condition 8
      {
        ledPin1 = LOW;
        ledPin2 = LOW;
        ledPin3 = LOW;
        ledPin4 = LOW;
        ledPin5 = LOW;
        ledPin6 = LOW;
        ledPin7 = LOW;
        ledPin8 = HIGH;
      }
    }

![Fritzing diagram][1]

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

body:
`digitalWrite (ledPin1 = HIGH);` should be `digitalWrite (ledPin1, HIGH);`

PS `if ( (x = LOW) && (y = LOW) && (z = LOW)) ` should be `if ( (x == LOW) && (y == LOW) && (z == LOW))`. `=` is for assignment, `==` is for comparison.


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

>
>    void loop() {
>
>      if ( (x = LOW) && (y = LOW) && (z = LOW))              //condition 1
>      {

Apart from the issue of needing `==` instead of `=` you are never *reading* those pins. In fact you are comparing the pin *numbers* (which will never change), not the data on those pins.

You need:

void loop() {

      if ( (digitalRead (x) == LOW) &&
           (digitalRead (y) == LOW) &&
           (digitalRead (z) == LOW))              //condition 1
        {

... and so on.

---

This is wrong too, I'm surprised it compiled:

>        digitalWrite (ledPin1 = HIGH);
>        digitalWrite (ledPin2 = LOW);
>        digitalWrite (ledPin3 = LOW);
>        digitalWrite (ledPin4 = LOW);
>        digitalWrite (ledPin5 = LOW);
>        digitalWrite (ledPin6 = LOW);
>        digitalWrite (ledPin7 = LOW);
>        digitalWrite (ledPin8 = LOW);

It should be:

      digitalWrite (ledPin1, HIGH);
      digitalWrite (ledPin2, LOW);
      digitalWrite (ledPin3, LOW);
      digitalWrite (ledPin4, LOW);
      digitalWrite (ledPin5, LOW);
      digitalWrite (ledPin6, LOW);
      digitalWrite (ledPin7, LOW);
      digitalWrite (ledPin8, LOW);

> when i use digital write i get an error code saying that there are too few arguments.
> ...
>  I just dont know why the simulation program is still not lighting the LED

Oh I see, it did *not* compile. No wonder the LEDs didn't turn on.


body:
Here's a little tip for you (it has nothing to do with your problem, it's just a good programming method).  This will massively reduce the size of your program.

You have three boolean state variables, and you are comparing the state of all combinations - that's 8 combinations.  If you take each boolean value as 1 bit of a value between 0 and 7 - that is values (as binary) 000, 001, 010, 011, 100, 101, 110, and 111 - then you can use much simpler methods for controlling your LEDs.

For instance, this (untested) code will turn three digital reads into a single number between 0 and 7:

    uint8_t value = digitalRead(x) | (digitalRead(y) << 1) | (digitalRead(z) << 2);

`x` is the least significant bit, and `z` is the most significant.  So `value` will now be a value between 0 and 7 representing the state of those three pins.

Now you can use that `value` variable to decide which pin to turn on.  Here's another trick:  Store you LED pins as an array.  That means, instead of having `ledPin1`, `ledPin2`, etc, you just have a list of pin numbers known as `ledPin[x]`:

    const uint8_t ledPin[8] = { 2, 3, 4, 7, 8, 9, 12, 13 };

Now you can use a `for` loop to iterate though that list and turn on the LED you want:

    for (uint8_t i = 0; i < 8; i++) {
        if (i == value) {
            digitalWrite(ledPin[i], HIGH);
        } else {
            digitalWrite(ledPin[i], LOW);
        }
    }

In fact, that can be further compressed, since HIGH and LOW are basically truth values (HIGH is 1, or true, and LOW is 0, or false):

    for (uint8_t i = 0; i < 8; i++) {
        digitalWrite(ledPin[i], i == value);
    }

So your whole program could look like this:

    const uint8_t x = A3;    // select the input pin for the switch
    const uint8_t y = A4;
    const uint8_t z = A5;

    const uint8_t ledPin[8] = { 2, 3, 4, 7, 8, 9, 12, 13 };

    void setup() {
        for (uint8_t i = 0; i < 8; i++) {
            pinMode(ledPin[i], OUTPUT);
        }
        pinMode(x, INPUT);
        pinMode(y, INPUT);
        pinMode(z, INPUT);
    }

    void loop() {
        uint8_t value = digitalRead(x) | (digitalRead(y) << 1) | (digitalRead(z) << 2);
        for (uint8_t i = 0; i < 8; i++) {
            digitalWrite(ledPin[i], i == value);
        }
    }

Saves a huge amount of typing and also ends up using considerably less Flash memory.


body:
The sole error in digitalWrites is that digitalWrite (ledPin1 = HIGH); should be **digitalWrite (ledPin1, HIGH);** same for other digitalWrite calls;

 **"too few arguments to function"** clearly implies that the number of arguments you are passing are less than expected by the function;

***by the way your code will also work fine if you update your assignments to digitalWrite statements in your code in all the if/else blocks;***

you can read more about the digitalWrite function in the link below
https://www.arduino.cc/en/Reference/DigitalWrite


body:
Since you mentioned you are new to programming, I am posting your own solution modified to work with right things; this code can be optimize to a great extent if you get good at programming; For your benefit, I will post both your approach and a slightly better approach

**Your approach:**

 int x = A3;    // select the input pin for the switch
 int y = A4;
 int z = A5;

 int ledPin1 = 2;      // select the pin for the LED
 int ledPin2 = 3;
 int ledPin3 = 4;
 int ledPin4 = 7;
 int ledPin5 = 8;
 int ledPin6 = 9;
 int ledPin7 = 12;
 int ledPin8 = 13;

 void setup(){

  // declare the ledPin as an OUTPUT:
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  pinMode(ledPin5, OUTPUT);
  pinMode(ledPin6, OUTPUT);
  pinMode(ledPin7, OUTPUT);
  pinMode(ledPin8, OUTPUT);

  pinMode(x, INPUT);
  pinMode(y, INPUT);
  pinMode(z, INPUT);
    }

    void loop() {

  if ( (x = LOW) && (y = LOW) && (z = LOW))              //condition 1
  {
   digitalWrite (ledPin1, HIGH);
   digitalWrite (ledPin2, LOW);
   digitalWrite (ledPin3, LOW);
   digitalWrite (ledPin4, LOW);
   digitalWrite (ledPin5, LOW);
   digitalWrite (ledPin6, LOW);
   digitalWrite (ledPin7, LOW);
   digitalWrite (ledPin8, LOW);
  }

  if ( (x = LOW) && (y = LOW) && (z = HIGH))             //condition 2
  {
   digitalWrite(ledPin1, LOW);
   digitalWrite(ledPin2, HIGH);
   digitalWrite(ledPin3, LOW);
   digitalWrite(ledPin4, LOW);
   digitalWrite(ledPin5, LOW);
   digitalWrite(ledPin6, LOW);
   digitalWrite(ledPin7, LOW);
   digitalWrite(ledPin8, LOW);
  }

  if ( (x = LOW) && (y = HIGH) && (z = LOW))             //condition 3
  {
   digitalWrite(ledPin1, LOW);
   digitalWrite(ledPin2, LOW);
   digitalWrite(ledPin3, HIGH);
   digitalWrite(ledPin4, LOW);
   digitalWrite(ledPin5, LOW);
   digitalWrite(ledPin6, LOW);
   digitalWrite(ledPin7, LOW);
   digitalWrite(ledPin8, LOW);
  }

  if ( (x = LOW) && (y = HIGH) && (z = HIGH))              //condition 4
  {
   digitalWrite(ledPin1, LOW);
   digitalWrite(ledPin2, LOW);
   digitalWrite(ledPin3, LOW);
   digitalWrite(ledPin4, HIGH);
   digitalWrite(ledPin5, LOW);
   digitalWrite(ledPin6, LOW);
   digitalWrite(ledPin7, LOW);
   digitalWrite(ledPin8, LOW);
  }

  if ( (x = HIGH) && (y = LOW) && (z = LOW))               //condition 5
  {
   digitalWrite(ledPin1, LOW);
   digitalWrite(ledPin2, LOW);
   digitalWrite(ledPin3, LOW);
   digitalWrite(ledPin4, LOW);
   digitalWrite(ledPin5, HIGH);
   digitalWrite(ledPin6, LOW);
   digitalWrite(ledPin7, LOW);
   digitalWrite(ledPin8, LOW);
  }

  if ( (x = HIGH) && (y = LOW) && (z = HIGH))               //condition 6
  {
   digitalWrite(ledPin1, LOW);
   digitalWrite(ledPin2, LOW);
   digitalWrite(ledPin3, LOW);
   digitalWrite(ledPin4, LOW);
   digitalWrite(ledPin5, LOW);
   digitalWrite(ledPin6, HIGH);
   digitalWrite(ledPin7, LOW);
   digitalWrite(ledPin8, LOW);
  }

  if ( (x = HIGH) && (y = HIGH) && (z = LOW))                //condition 7
  {
   digitalWrite(ledPin1, LOW);
   digitalWrite(ledPin2, LOW);
   digitalWrite(ledPin3, LOW);
   digitalWrite(ledPin4, LOW);
   digitalWrite(ledPin5, LOW);
   digitalWrite(ledPin6, LOW);
   digitalWrite(ledPin7, HIGH);
   digitalWrite(ledPin8, LOW);
  }

  if ( (x = HIGH) && (y = HIGH) && (z = HIGH))                //condition 8
  {
   digitalWrite(ledPin1, LOW);
   digitalWrite(ledPin2, LOW);
   digitalWrite(ledPin3, LOW);
   digitalWrite(ledPin4, LOW);
   digitalWrite(ledPin5, LOW);
   digitalWrite(ledPin6, LOW);
   digitalWrite(ledPin7, LOW);
   digitalWrite(ledPin8, HIGH);
  }
    }

----------

**Slightly better approach:**(better programmers may be able to write even more optimized code)

 int x = A3;    // select the input pin for the switch
 int y = A4;
 int z = A5;

 int ledPin1 = 2;      // select the pin for the LED
 int ledPin2 = 3;
 int ledPin3 = 4;
 int ledPin4 = 7;
 int ledPin5 = 8;
 int ledPin6 = 9;
 int ledPin7 = 12;
 int ledPin8 = 13;

 void setup(){

   // declare the ledPin as an OUTPUT:
   pinMode(ledPin1, OUTPUT);
   pinMode(ledPin2, OUTPUT);
   pinMode(ledPin3, OUTPUT);
   pinMode(ledPin4, OUTPUT);
   pinMode(ledPin5, OUTPUT);
   pinMode(ledPin6, OUTPUT);
   pinMode(ledPin7, OUTPUT);
   pinMode(ledPin8, OUTPUT);

   pinMode(x, INPUT);
   pinMode(y, INPUT);
   pinMode(z, INPUT);
 }

 void loop() {
   int pinToTurnHigh = 2; // just making sure its a valid pin
   if ( (x = LOW) && (y = LOW) && (z = LOW))              //condition 1
   {
  pinToTurnHigh = ledPin1;
   }

   if ( (x = LOW) && (y = LOW) && (z = HIGH))             //condition 2
   {
  pinToTurnHigh = ledPin2;
   }

   if ( (x = LOW) && (y = HIGH) && (z = LOW))             //condition 3
   {
  pinToTurnHigh = ledPin3;
   }

   if ( (x = LOW) && (y = HIGH) && (z = HIGH))              //condition 4
   {
  pinToTurnHigh = ledPin4;
   }

   if ( (x = HIGH) && (y = LOW) && (z = LOW))               //condition 5
   {
  pinToTurnHigh = ledPin5;
   }

   if ( (x = HIGH) && (y = LOW) && (z = HIGH))               //condition 6
   {
  pinToTurnHigh = ledPin6;
   }

   if ( (x = HIGH) && (y = HIGH) && (z = LOW))                //condition 7
   {
  pinToTurnHigh = ledPin7;
   }

   if ( (x = HIGH) && (y = HIGH) && (z = HIGH))                //condition 8
   {
  pinToTurnHigh = ledPin8;
   }
   resetAllLEDs();
   digitalWrite(pinToTurnHigh, HIGH);
 }

 void resetAllLEDs()
 {
   digitalWrite(ledPin1, LOW);
   digitalWrite(ledPin2, LOW);
   digitalWrite(ledPin3, LOW);
   digitalWrite(ledPin4, LOW);
   digitalWrite(ledPin5, LOW);
   digitalWrite(ledPin6, LOW);
   digitalWrite(ledPin7, LOW);
   digitalWrite(ledPin8, LOW);
 }


message:
Using CD4053 for arduino

I would like to use CD4053 for multiplexing in arduino but the problem is that I don't understand how CD4053 works, is it the same as CD4051, can someone help me, provide example code and circuit??

body:
Consider one of the many I2C I/O boards (search for i2c expander on eBay) that can be purchased for a few bucks.  They are also available from many of the people that support Arduino.   It then only requires 2 pins from the Arduino for up to 8 external devices which can have from 8, 16 and sometimes more I/O per board.  They can be used as input or output.

You can also operate several displays on the same two pins as the I/O.

Have fun


body:
The 4053 can replace the 4051 ([data sheet][1]). To do that the three output pins on 4053 should be tied together (pin 4, 14 and 15, see logic diagram).

The device allows adding eight analog pins at the cost of three digital pins and one analog pin. The device will multiplex the eight new analog pins onto the arduino analog pin. Three digital pins are used to select which pin is multiplexed.

The arduino [tutorial][2] for 4051 will work just fine with the above modification of the wiring.

Cheers!

  [1]: http://media.digikey.com/pdf/Data Sheets/Fairchild PDFs/CD4051BC.pdf
  [2]: http://playground.arduino.cc/Learning/4051


message:
Password code using interrupts and timers on Arduino Uno

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

I have a group project where we are trying to make a user enter a password that we have pre-selected for them. They enter the password using tactile buttons, and they have 5 tries to enter the password correctly. If they enter the password incorrectly, one of 5 LED's will light up to indicate that they have entered it wrong. If they get it right, one LED will light up.

We are using timers to time out the attempt if the users take too long to enter the entire password, or if they take too long between pressing buttons. Also, if they use all 5 tries, we are trying to make the LED's that were on turn off one by one.

Right now the code doesn't get past Serial.print("done").

This is our code:

    int input_pin_blue = 5;
    int input_pin_yellow = 6;
    volatile int state_button_red = LOW;
    volatile int state_button_blue = LOW;
    volatile int state_button_yellow = LOW;
    int num_wrong = 0;
    double time_between_buttons = 0;
    double time_since_first_button = 0;
    const int max_time_between_buttons = 10000;
    const int max_time_since_first_button = 30000;
    int reset = 4;
    void setup() {
     pinMode(input_pin_blue, INPUT);
     pinMode(input_pin_yellow, INPUT);
     pinMode(4, INPUT);
     pinMode(8, OUTPUT);
     pinMode(9, OUTPUT);
     pinMode(10, OUTPUT);
     pinMode(11, OUTPUT);
     pinMode(12, OUTPUT);
     pinMode(13, OUTPUT);
     attachInterrupt(0, handler_red, CHANGE);
     attachInterrupt(1, handler_blue_yellow, CHANGE);
     Serial.begin(9600);
    }
    void loop() {
     Serial.print("bhi"); //wait for button press

     for (num_wrong = 0; num_wrong < 5; num_wrong++) {
      Serial.print("blah"); //wait for button press

      while (state_button_red == LOW && state_button_blue == LOW && state_button_yellow == LOW) {
       Serial.print("waiting"); //wait for button press
      }

      Serial.print("DOne");

      if (state_button_red == LOW) {                  //check if first button pressed is incorrect
       digitalWrite(num_wrong + 8, HIGH);
      } else if (state_button_red == HIGH) {
       time_between_buttons = millis();
       time_since_first_button = millis();

       while (state_button_red == LOW && state_button_blue == LOW && state_button_yellow == LOW
               && time_between_buttons < max_time_between_buttons && time_since_first_button < max_time_since_first_button) {
        //wait for button press
       }

       if (state_button_yellow == LOW || time_between_buttons < max_time_between_buttons || time_since_first_button < max_time_since_first_button)
    //check if second button pressed is incorrect or time has run out
       {
        digitalWrite(num_wrong + 8, HIGH);
       } else if (state_button_yellow == HIGH) {
        time_between_buttons = millis();

        while (state_button_red == LOW && state_button_blue == LOW && state_button_yellow == LOW
                && time_between_buttons < max_time_between_buttons && time_since_first_button < max_time_since_first_button) {
         //wait for button press
        }

        if (state_button_blue == LOW || time_between_buttons < max_time_between_buttons || time_since_first_button < max_time_since_first_button)
    //check if third button pressed is incorrect or time has run out
        {
         digitalWrite(num_wrong + 8, HIGH);
        } else if (state_button_blue == HIGH) {
         time_between_buttons = millis();

         while (state_button_red == LOW && state_button_blue == LOW && state_button_yellow == LOW
                 && time_between_buttons < max_time_between_buttons && time_since_first_button < max_time_since_first_button) {
          //wait for button press
         }

         if (state_button_yellow == LOW || time_between_buttons < max_time_between_buttons || time_since_first_button < max_time_since_first_button)
    //check if fourth(last) button pressed is incorrect or time has run out
         {
          digitalWrite(num_wrong + 8, HIGH);
         } else if (state_button_yellow == HIGH) {
          digitalWrite(13, HIGH);
          num_wrong = 10;
         }
        }
       }
      }
     }

     if (num_wrong == 10) {
      while (digitalRead(reset) == LOW) {
       //wait for reset
      }
     } else if (num_wrong == 5) {
      while (digitalRead(reset) == LOW) {
       digitalWrite(8, LOW);
       delay(100);
       digitalWrite(8, HIGH);
       digitalWrite(9, LOW);
       delay(100);
       digitalWrite(9, HIGH);
       digitalWrite(10, LOW);
       delay(100);
       digitalWrite(10, HIGH);
       digitalWrite(11, LOW);
       delay(100);
       digitalWrite(11, HIGH);
       digitalWrite(12, LOW);
       delay(100);
       digitalWrite(12, HIGH);
      }
     }

     if (digitalRead(reset) == HIGH) {
      digitalWrite(13, LOW);
      delay(100);
      digitalWrite(12, LOW);
      delay(100);
      digitalWrite(11, LOW);
      delay(100);
      digitalWrite(10, LOW);
      delay(100);
      digitalWrite(9, LOW);
      delay(100);
      digitalWrite(8, LOW);
     }
    }
    // interrupt handler function
    void handler_red() {
     state_button_red = !state_button_red;
    }
    void handler_blue_yellow() {
     if (digitalRead(input_pin_blue) == HIGH) {
      state_button_blue = !state_button_blue;
     }

     if (digitalRead(input_pin_yellow) == HIGH) {
      state_button_yellow = !state_button_yellow;
     }
    }

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

    int input_pin_blue = 5;
    int input_pin_yellow = 6;
    volatile int state_button_red = LOW;
    volatile int state_button_blue = LOW;
    volatile int state_button_yellow = LOW;
    ...
    pinMode(input_pin_blue, INPUT);
    pinMode(input_pin_yellow, INPUT);
    ...
    attachInterrupt(0, handler_red, CHANGE);
    attachInterrupt(1, handler_blue_yellow, CHANGE);

    // interrupt handler function
    void handler_red() {
        state_button_red = !state_button_red;
    }
    void handler_blue_yellow() {
        if (digitalRead(input_pin_blue) == HIGH) {
            state_button_blue = !state_button_blue;
        }

        if (digitalRead(input_pin_yellow) == HIGH) {
            state_button_yellow = !state_button_yellow;
        }
    }

On the Uno external interrupt 0 is pin D2 not D5, and interrupt 1 is pin D3, not D6.

Hence you are not testing the correct pins.

Also I would use INPUT_PULLUP instead of INPUT mode for those pins, unless you have external pull-up or pull-down resistors on them.


message:
How to detect if more than one button was pressed

I am designing a turn signal bicycle blinker using two pushbuttons as input, one for each side, with a corresponding light for each button.
The idea is this:

 1. Pressing one side makes same side start blinking;
 2. Pressing same side again to turn it off;
 3. Pressing other side turns off this side and turns other side on;
 4. (now the tricky part!) if __both__ buttons are pressed (or more precisely, if one button is pressed before the other is released), then - and only then - I start blinking both sides ("warning signal" feature).

As I see it, the problem is that I need to wait until I release a single button (that would be one complete click) to turn a single side on, because if I press the second while the first remains pressed, that would be another event/gesture ("both_click", for lack of a better name).

Another design option would be to turn a single light on immediately on press, and if I press the second before release the first, then in would _also_ turn the other light (thus comprising the "warning", both-lights-blinking mode). While that sounds feasible, there is all the debouncing logic in the Button ("Botao") class, and I am afraid I painted myself into a corner with the specific object-oriented design choices I've made.

EDIT: a third design option would be to add a `run` method on each button and, instead of only running the tested "pseudo-event" method, save the current state and event in variables, testing those variables in `loop()` (property `button.wasPressed` instead of method `button.wasPressed()`, for example).

I'm posting my current code (relevant parts only). Note there is a comment in the loop where I think I should detect double click.

Main .ino file:

    #include "PiscaPisca.cpp"
    #include "Botao.cpp"

    PiscaPisca pisca;

    Botao botao1;
    Botao botao4;

    void setup() {

      pisca.configure(LEFT, RIGHT, BUZZER);

      botao1.configure(BUTTON1);
      botao4.configure(BUTTON4);
    }

    void loop() {

      // HOW SHOULD I DETECT BOTH WERE PRESSED??
      // if (bothPressed()) { pisca.toggleWarning(); }

      if (botao1.wasPressed()) { pisca.toggleLeft();  }
      if (botao4.wasPressed()) { pisca.toggleRight(); }

      pisca.run();
    }

Botao.cpp (this is a button class with debounce)

    #include <Arduino.h>

    class Botao
    {
        int _pino;

        const int DEBOUNCE_DELAY = 30;

        int buttonState;
        int lastState = HIGH;

        int lastDebounceTime;

        public : void configure(int pino)
        {
            _pino = pino;
            pinMode(pino, INPUT_PULLUP);
        }

        public : boolean wasPressed()
        {
            return debounce(LOW);
        }

        public : boolean wasReleased()
        {
            return debounce(HIGH);
        }

        public : boolean debounce(int state)
        {
            boolean gotEvent = false;

            int reading = digitalRead(_pino);

            if (reading != lastState) {
                lastDebounceTime = millis();
            }

            if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
                if (reading != buttonState) {
                    buttonState = reading;

                    if (buttonState == state) {
                        gotEvent = true;
                    }
                }
            }

            lastState = reading;

            return gotEvent;
        }
    };

PiscaPisca.cpp (the state-machine itself)

    #include "Arduino.h"
    #include "PwmPin.cpp"
    #include "Beeper.cpp"

    typedef enum {
        NONE        = 0,
        RIGHT_LIGHT = 1,
        LEFT_LIGHT  = 2,
        BOTH        = 3
    };

    class PiscaPisca
    {
        PwmPin _left;
        PwmPin _right;

        Beeper _beeper;

        long _timeReference = 0;

        const int PERIOD = 350;

        boolean
            _running = false,
            _lightState = false;

        int _sides_to_turn = NONE;

        public : void configure(int leftPin, int rightPin, int buzzerPin)
        {
            _left.configure(leftPin);
            _right.configure(rightPin);
            _beeper.configure(buzzerPin);
        }

        public : void run()
        {
            evaluateBlink();
        }

        public : void toggleLeft()
        {
            checkRestart(LEFT_LIGHT);
        }

        public : void toggleRight()
        {
            checkRestart(RIGHT_LIGHT);
        }

        void checkRestart(int lightSide)
        {
            _timeReference = 0;

            // some clever bit-twiddling can never hurt too much:
            _sides_to_turn = lightSide & ~_sides_to_turn;

            Serial.println(lightSide);
            Serial.println(_sides_to_turn);

            if (_sides_to_turn > 0)
            {
                _running = true;
            }
            else
            {
                lightsOff();
                _running = false;
                _lightState = false;
            }
        }

        void evaluateBlink()
        {
            if (!_running)
            {
                return;
            }
            else
            {
                long currentMillis = millis();
                if (currentMillis - _timeReference > PERIOD) {
                    _timeReference = currentMillis;
                    _lightState = !_lightState;
                    performBlink();
                }
            }
        }

        void performBlink()
        {
            if (_lightState)
            {
                _beeper.beepIn();
                lightsOn();
            }
            else
            {
                _beeper.beepOut();
                lightsOff();
            }
        }

        void lightsOn()
        {
            if (isLightSet(LEFT_LIGHT))
            {
                _left.on();
            }
            if (isLightSet(RIGHT_LIGHT))
            {
                _right.on();
            }
        }

        boolean isLightSet(int lightSide)
        {
            return (_sides_to_turn & lightSide) == lightSide;
        }

        void lightsOff()
        {
            _left.off();
            _right.off();
        }

    };

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

Interesting question, and tricky to get perfect. :)

I wrote a switch manager class a while back. It's just a .h file which you can put in your libraries folder (or add to your sketch).

**SwitchManager.h**

    #include <Arduino.h>

    class SwitchManager
      {
      enum { debounceTime = 10, noSwitch = -1 };
      typedef void (*handlerFunction) (const byte newState,
                                       const unsigned long interval,
                                       const byte whichSwitch);

      int pinNumber_;
      handlerFunction f_;
      byte oldSwitchState_;
      unsigned long switchStateChangeTime_;  // when the switch last changed state
      unsigned long lastLowTime_;
      unsigned long lastHighTime_;

      public:

         // constructor
         SwitchManager ()
           {
           pinNumber_ = noSwitch;
           f_ = NULL;
           oldSwitchState_  = HIGH;
           switchStateChangeTime_ = 0;
           lastLowTime_  = 0;
           lastHighTime_ = 0;
           }  // end of constructor

         void begin (const int pinNumber, handlerFunction f)
           {
           pinNumber_ = pinNumber;
           f_ = f;
           if (pinNumber_ != noSwitch)
             pinMode (pinNumber_, INPUT_PULLUP);
           }  // end of begin()

         void check ()
           {
           // we need a valid pin number and a valid function to call
           if (pinNumber_ == noSwitch || f_ == NULL)
             return;

            // see if switch is open or closed
            byte switchState = digitalRead (pinNumber_);

            // has it changed since last time?
            if (switchState != oldSwitchState_)
              {
              // debounce
              if (millis () - switchStateChangeTime_ >= debounceTime)
                 {
                 switchStateChangeTime_ = millis ();  // when we closed the switch
                 oldSwitchState_ =  switchState;  // remember for next time
                 if (switchState == LOW)
                   {
                   lastLowTime_ = switchStateChangeTime_;
                   f_ (LOW, lastLowTime_ -  lastHighTime_, pinNumber_);
                   }
                 else
                   {
                   lastHighTime_ = switchStateChangeTime_;
                   f_ (HIGH, lastHighTime_ - lastLowTime_, pinNumber_);
                   }

                 }  // end if debounce time up
              }  // end of state change
           }  // end of check()

         unsigned long getLastStateChangeTime () const { return switchStateChangeTime_; }
         unsigned long getLastStateLowTime ()    const { return lastLowTime_; }
         unsigned long getLastStateHighTime ()   const { return lastHighTime_; }

      };  // class SwitchManager

More details [here](http://www.gammon.com.au/switches).

Put that into a folder called `SwitchManager`, put that into your sketch folder -> `libraries` folder and restart the IDE.

That basically handles:

* debouncing
* detecting state changes (eg. now on, was off)

Using that we can now write a sketch that does the indicators:

    #include <SwitchManager.h>

    typedef enum {
        NONE,
        LH_DOWN,
        RH_DOWN,
        LH_LIGHT_ON,
        RH_LIGHT_ON,
        BOTH
    };

    const unsigned long BLINK_INTERVAL = 500; // ms

    // pin assignments
    const byte LH_SWITCH_PIN = 2;
    const byte RH_SWITCH_PIN = 3;
    const byte LH_LIGHT = A4;
    const byte RH_LIGHT = A5;

    SwitchManager LHswitch;
    SwitchManager RHswitch;

    byte state = NONE;

    void handleLHPress (const byte newState, const unsigned long interval, const byte whichPin)
      {
      // switch down?
      if (newState == LOW)
         {
         switch (state)
           {
           // if other switch down, switch to warning mode
           case RH_DOWN:
             state = BOTH;
             break;

           // if already on or warning signal, turn all off
           case LH_LIGHT_ON:
           case BOTH:
             state = NONE;
             break;

           // otherwise switch is now down, but not yet released
           default:
             state = LH_DOWN;
             break;
           }  // end of switch
         return;
         }  // end of LH switch down

      // switch must be up

      if (state == LH_DOWN)  // if down, switch to down-and-released mode
        state = LH_LIGHT_ON;
      }  // end of handleLHPress

    void handleRHPress (const byte newState, const unsigned long interval, const byte whichPin)
      {
      // switch down?
      if (newState == LOW)
         {
         switch (state)
           {
           // if other switch down, switch to warning mode
           case LH_DOWN:
             state = BOTH;
             break;

           // if already on or warning signal, turn all off
           case RH_LIGHT_ON:
           case BOTH:
             state = NONE;
             break;

           // otherwise switch is now down, but not yet released
           default:
             state = RH_DOWN;
             break;
           }  // end of switch
         return;
         }  // end of RH switch down

      // switch must be up

      if (state == RH_DOWN)  // if down, switch to down-and-released mode
        state = RH_LIGHT_ON;
      }  // end of handleRHPress

    void setup ()
      {
      LHswitch.begin (LH_SWITCH_PIN, handleLHPress);
      RHswitch.begin (RH_SWITCH_PIN, handleRHPress);
      pinMode (LH_LIGHT, OUTPUT);
      pinMode (RH_LIGHT, OUTPUT);
      }  // end of setup

    unsigned long lastBlink;
    bool onCycle;

    void blinkLights ()
      {
      lastBlink = millis ();
      onCycle = !onCycle;

      // default to off
      digitalWrite (LH_LIGHT, LOW);
      digitalWrite (RH_LIGHT, LOW);

      // every second time, turn them all off
      if (!onCycle)
        return;

      // blink light
      switch (state)
        {
        case NONE:
          break;

        case LH_DOWN:
        case LH_LIGHT_ON:
          digitalWrite (LH_LIGHT, HIGH);
          break;

        case RH_DOWN:
        case RH_LIGHT_ON:
          digitalWrite (RH_LIGHT, HIGH);
          break;

        case BOTH:
          digitalWrite (LH_LIGHT, HIGH);
          digitalWrite (RH_LIGHT, HIGH);
          break;

        }  // end of switch on state

      }  // end of blinkLights

    void loop ()
      {
      LHswitch.check ();  // check for presses
      RHswitch.check ();  // check for presses

      if (millis () - lastBlink >= BLINK_INTERVAL)
        blinkLights ();

      // other stuff
      }  // end of loop

The state machine has a number of states:

* NONE  -> all lights off
* LH_DOWN  -> LH switch depressed, not yet released
* RH_DOWN  -> RH switch depressed, not yet released
* LH_LIGHT_ON  -> LH switch depressed, and released
* RH_LIGHT_ON  -> RH switch depressed, and released
* BOTH  -> Warning lights mode (flash both lights)

If we get a LH down while the RH is still pressed, or vice-versa, we switch to warning mode.

On a button release we switch from "switch down" to "switch released".

A second press, while either or both lights are on cancels them.

Note that my switches were wired to ground with the internal pull-up, so they are LOW when pressed and HIGH when not pressed.


message:
How do you send data via I2C without the wire library?

I have the following digital potentiometer: [DS1803-100](http://datasheets.maximintegrated.com/en/ds/DS1803.pdf) which, according to the datasheet, can be controlled using a two-wire serial interface. I have managed to get it working using Wire, however I can't seem to get it working using only digitalWrite ([link to code](http://pastebin.com/MknvWvjt)). Can somebody tell me why? For reference, **0x50** is the *address + r/!w bit*, **0xA9** is the *command (write to pot 0 in my case)* and the next **0xA9** is the *value to write*. I know there's something wrong with the code, however I cannot figure out what. Thank you in advance!

EDIT: Here is the code

    int PIN_SCK = 12;
    int PIN_SDA = 11;

    const int delayvalue = 10;

    void setup(){
        digitalWrite(PIN_SCK, 1); // I can first declare the state
        digitalWrite(PIN_SDA, 1);
        pinMode(PIN_SCK, OUTPUT); // then turn them on
        pinMode(PIN_SDA, OUTPUT);

        delay(1000);

        digitalWrite(PIN_SDA, 0); // start bit

        shift_out(PIN_SDA, PIN_SCK, 0x50);
        shift_out(PIN_SDA, PIN_SCK, 0xA9);
        shift_out(PIN_SDA, PIN_SCK, 0xA9);

        digitalWrite(PIN_SDA, 1); // stop bit

    }

    void loop(){

    }
    // uint8_t is the same as 8 bits aka one byte
    void shift_out(uint8_t datapin, uint8_t clockpin, uint8_t val){
        uint8_t i;

        for (i = 0; i < 8; i++)  {
            digitalWrite(datapin, !!(val & (1 << (7 - i))));
            delay(1);
            digitalWrite(clockpin, 0);
            delay(delayvalue);
            digitalWrite(clockpin, 1);
            delay(delayvalue);
        }

        digitalWrite(datapin, 0); // to enable stop bit
        delay(100); // wait fro aknowledgement

    }

body:
I2C is a lot more complex than just shifting bytes out.

See: [I2C - Two-Wire Peripheral Interface - for Arduino](http://www.gammon.com.au/i2c)

Your code does not seem to take any of that into account.

Why do you not want to use the Wire library? The hardware on the chip (what chip do you have?) supports it. Why ignore that and try to do it yourself?


body:
Well, short answer: It was the acknowledge bit, I forgot to send a clock pulse in order to receive it (duh! my device generates the clock for the attached potentiometer, I was waiting for the device to "send" me a bit, I needed to "request" the bit on a rising edge of the clock).

Long answer: the code looks like this now:

    int PIN_SCK = 12;
    int PIN_SDA = 11;

    const int delayvalue = 10;

    void setup(){
        digitalWrite(PIN_SCK, 1); // I can first declare the state
        digitalWrite(PIN_SDA, 1);
        pinMode(PIN_SCK, OUTPUT); // then turn them on
        pinMode(PIN_SDA, OUTPUT);

        delay(1000);

        digitalWrite(PIN_SDA, 0); // start bit
        delay(10);
        digitalWrite(PIN_SCK, 0);
        delay(10);

        shift_out(PIN_SDA, PIN_SCK, 0x50);
        shift_out(PIN_SDA, PIN_SCK, 0xA9);
        shift_out(PIN_SDA, PIN_SCK, 0xA9);

        digitalWrite(PIN_SDA, 1); // stop bit

    }

    void loop(){

    }
    // uint8_t is the same as 8 bits aka one byte
    void shift_out(uint8_t datapin, uint8_t clockpin, uint8_t val){
        uint8_t i;

        for (i = 0; i < 8; i++)  {
            digitalWrite(datapin, !!(val & (1 << (7 - i))));
            delay(1);
            digitalWrite(clockpin, 1);
            delay(delayvalue);
            digitalWrite(clockpin, 0);
            delay(delayvalue);
        }

        digitalWrite(datapin, 0); // to enable stop bit
        delay(10);

        // Here I handle the AKNOWLEDGE signal which happens after
        // each byte sent. Be it address, command or value
        digitalWrite(clockpin, 1);
        delay(10);
        digitalWrite(clockpin, 0);
        delay(10);

    }

So basically I followed and reproduced the signals in [this timing diagram](https://i.stack.imgur.com/5Kv55.png) faithfully with one small exception: I did not generate a rising edge when I expected the acknowledge bit (basically the diagram but with SCK being 0 right below the acknowledge bits).

Hope this helps somebody!


message:
Is there an equivalent to Grbl for Excellon PCB drilling?

For CNC milling we have code such as Grbl Controller in the PC, and Grbl itself in an Arduino, and these handle the appropriate G-code files. Is there an equivalent package to handle Excellon files and drive a 3-axis drilling machine?

body:
No, there is no existing Arduino library to parse [Excellon format][1] drill files in order to control a drilling machine. Looking at the [specification][2] it looks to be very similar to G Code, and some brief googling shows that there are various utilities for converting it to G Code that could be run from something like grbl.

  [1]: https://en.wikipedia.org/wiki/Excellon_format
  [2]: http://web.archive.org/web/20071030075236/http://www.excellon.com/manuals/program.htm


message:
Cannot pass objects of non-trivially-copyable type 'class String' through '...'

I'm attempting to send data from a serial connection to a GSM modem, but having problems.
The string from rx looks like this:

    1.0 2.0 3.0 4.0
Here's my code to replace the spaces and then I just want to pass the whole string on, regardless of what's inside (there could be negative values too).

                    data_current[data_index++] = ',';
                    char received = bike_port.read(); //bike
                    char test[32];
                    inData += received;
                      if (received == '\n')
                      {
                          String nospace = inData;
                          nospace.replace("\t",",");
                          debug_println("Data: ");
                          debug_println(nospace);
                          inData = ""; // Clear recieved buffer
                          delay(1000);
                      }
                      sprintf(test,32,"%d,%d,%d,%d",(String) nospace);
                    //strtok(received, tmp);
                    for (int i=0; i<strlen(test); i++) {
                      data_current[data_index++] = test[i];
                    }
I have also tried

    sprintf(test,32,"%ld,(String) nospace);
What I get now is this error

    cannot pass objects of non-trivially-copyable type 'class String' through '...'
Without the sprintf line I can successfully echo the string to debug_println (Serial Monitor).
What am I doing wrong?

body:
The basic problem here is that you're trying to pass a `String` object to `sprintf()`. That isn't possible because `String` is a C++ class, and `sprintf()` is a C variadic function. The only way to pass a string to it is as a `char *`.

The rest of your call to `sprintf()` doesn't seem to make sense either, although I suspect it's not what you actually want here. You'd normally use `sprintf()` if you want to format several values into a string.

As you've suggested in the comments, adding the contents of `nospace` to `data_current` character-at-a-time would be the sensible approach. You could do it something like this:

    for (int i = 0; i < nospace.length(); ++i) {
        data_current[data_index++] = nospace[i];
    }

Note that `strlen()` won't work on `nospace` because it's a `String` object not a `char` array.

This is all assuming that there's enough space in `data_current` though. Without seeing the rest of your code, I can't tell you if it will definitely work or not.

-----
**Update:**
As an alternative, you could use `memcpy()` to do a block transfer:

    memcpy(data_current + data_index, nospace.c_str(), nospace.length());
    data_index += nospace.length();

I'm not sure there's much benefit to doing that though. It's hypothetically more efficient, but it probably won't make a noticeable difference unless your string is moderately long and it's being called very frequently. (It's trading-off the loop overhead against a function-call overhead.)


body:
Let me get this straight. You want to change:

    1.0 2.0 3.0 4.0

to:

    1.0,2.0,3.0,4.0

Right?

How about:

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

      char indata[32] = "1.0 2.0 3.0 4.0";

      int len = strlen (indata);
      for (int i = 0; i < len; i++)
        if (isspace (indata [i]))
          indata [i] = ',';

      Serial.println (indata);   // prints: 1.0,2.0,3.0,4.0

---

> Only problem is that when I change "1.0 2.0 3.0 4.0" to the actual incoming read (bike_port.read()), than I get error ...

In that case, as Jake C said, modify the incoming byte like this:

     char received = bike_port.read(); //bike
     if (isspace (received))
       received = ',';


body:
As a companion to Nick Gammon's excellent answer, here is a streaming version of that (assuming this is coming in one serial port and out another to the modem).

    if (Serial.available()) {
      int inByte = Serial.read();
      if (inByte == ' ')
        Serial1.write(',');
      else
        Serial1.write(inByte);
    }


message:
Can I Implement a PLL on an Arduino?

Is it possible to create a system like a PLL using an Arduino?
I ask this because there are some parts in the PLL system, such as: phase detector, VCO, divider, and I don't know how to make for each part in Arduino board.

body:
A PLL is a very complex device which is not something that can easily be created purely in code.

Many microcontrollers include a PLL as part of their oscillator systemm which allows them to run internally at a higher speed than their external crystal.  This is not a programmable peripheral that you can use for your own things, but an integral part of the workings of the microcontroller.

While it may be possible to write one in software the results would be very somewhat limited. The best you could hope for is to use timers to measure an incoming frequency and use the results to output another frequency through some means, maybe PWM.

To create a real PLL you would be best off using either a dedicated PLL chip (which you can buy off the shelf) or use some form of programmable logic like a CPLD that has a built in PLL block.

Some microcontrollers, most notably the Cypress PSoC range, have programmable logic blocks built in that may be more suited to your task than an Arduino.

A typical digital PLL looks something like this:

![enter image description here][1]

Implementing all that in code would be both tricky and somewhat slow on a little 8-bit MCU with no floating point support.  However, the basic principal of what a PLL can be summarised in one simple sentence:

> The frequency coming in determines the frequency going out.

The PLL, or *Phase Locked Loop* is just one method of achieving that desired result.

Another method, which is *not* using any form of PLL, is purely algorithmic and consists of just three things:

![enter image description here][2]

Three simple blocks, all of which the Arduino is, to a certain extent, capable of performing.

The first block, the *Frequency Detector*, works out what the frequency of the incoming signal is.  That could either be by counting the number of pulses that arrive over a certain time frame, or measuring the time between successive pulses.  Which method you use (*Frequency Counting* or *Frequency Measuring*) is really down to what frequency ranges you are using.  Frequency Counting is better for higher frequencies, whereas Frequency Measuring is better for low frequencies.  There are many examples on the web of how to do both of those using timers on the Arduino.

The *Decision Making* is basically working out what your output frequency wants to be according to your input frequency.  This could be as simple as "Output = input * 2", for instance, or something more complex like "Between these frequencies I want to output this frequency, between these frequencies this other frequency, etc".  It's entirely up to you.

The third block just takes the decided-upon output frequency and generates it.  That could be done using the hardware PWM generation of the Arduino.

All this, though, will be limited to relatively low frequencies (tens of kHz maximum really) though with clever coding you could push it up slightly higher.

One thing that really makes this method differ from a PLL is that you don't get the "PL" portion of it - that is, the phase of the incoming frequency is lost, and the output frequency is running entirely with its own phase.  There is little or nothing you can do to synchronise the phases of the input and output like you get with a full PLL.

  [1]: https://i.stack.imgur.com/eAzru.png
  [2]: https://i.stack.imgur.com/I47sg.png


body:
There are two types of PLLs, hardware PLLs and [software PLLs][1]. Majenko has already addressed hardware PLLs so I will leave you to his answer for that.

Software PLLs perform the same function as regular hardware PLLs, but with code, and as a result are constrained by the clock speed and sample rate of the controller they are running on. Usually this means you are limited to sub MHz frequencies. The math and computation necessary to perform this [is quite complicated][2], and I do not expect you would get particularly good performance out of your standard Arduino controller, as all of them lack a floating point unit to perform these types of computations.

If you were to still try and attempt this you would have to do it using integer math only. The faster the CPU, the higher the frequency it will be able to lock on to. The fastest Arduino available today is the Arduino Due. Aside from being fast, the Due can perform 32-bit arithmetic in a single cycle, which should be handy. The frequency limit will be dictated by how many cycles all of your calculations take.

  [1]: https://en.wikipedia.org/wiki/Phase-locked_loop#Implementing_a_digital_phase-locked_loop_in_software
  [2]: http://liquidsdr.org/blog/pll-howto/


body:
You can absolutely make a PLL using an ATMega microcontroller, and I have made one myself using a ATTiny45. The way I did it is by setting the clock source to the internal RC oscillator, and using that as my VCO (or in this case, Numerically Controlled Oscillator). The internal oscillator can be tuned between 50% and 200% of its nominal frequency by adjusting the OSCCAL register, which can safely be done without stopping the processor. I used the ADC to read the input signal. For the phase detector I programmed the MCU to alternatively add, then subtract the ADC registers from an accumulator register. This is mathematically equivalent to multiplying the incoming signal by a square wave from the local oscillator, and integrating the result. After a fixed number of cycles, I checked to see if the accumulator was negative or positive. If its negative, I set OSCCAL to a "high frequency" which is definitely higher than the input signal. If its positive, I set it to a "low frequency", which is definitely too low. Of course this is a form of Bang–bang control, so its never stable per se, but I found works perfectly. Its much better than my attempts at a PID controller. Looking on my oscilloscope, the is almost no jitter visible between the input system and the internal RC clock, which I outputted on the CLKO pin by setting the appropriate fuse bits.

Although I used GCC and USBTinyISP, I see no reason why my system can't be implemented on Arduino. Setting the fuse bits will require a bit of work though, you can read more here:

http://forum.arduino.cc/index.php?topic=124879.0

If there is enough interest, I can add more detailed information to my answer.


message:
avrdude : stk500_get sync<> attempt 10 of 10 not in sync : resp=0x20 how do i get pass this error for ardunio uno board

When I first started with a bare minimum code. The compiler compiles the code, but when I try to upload, this is the error message I get:

     AVRDUDE: STK500_GETSYNC<> ATTEMPT 10 OF 10 NOT IN SYNC :RESP=0X20

How do I fix this?

body:
There are multiple reasons why you are getting this error.

1. Bootloader is either missing or corrupted. This is fairly unlikely.

2. Wire connected to pin 0 (RX)

3. Wrong COM port is chosen within the arduino IDE.

4. Drivers are not installed. You can update it within the Device Manager if you are using Windows.

Here is a link to an article explaining the causes and how to fix them, http://www.instructables.com/id/A-solution-to-avrdude-stk500getsync-not-in-syn/


message:
WizNet chip on Ethernet Shield oddly hot

I'm making a thermometer and, so I can graph the data, I have an Uno with the WizNet shield sending the data to a LAN ip. The chip itself is oddly hot, its temperature measures at around __110-120ºF__ (43.33-48.89ºC). I want the program to be running almost 24/7. Is it okay for the chip to be this hot?

body:
According to the [WizNet forums][1] this is normal for these shields. Their justification being that it is a PHY and controller on a single chip. (Note this post only specifically mentions the W5100, which is among the more commonly used chips on these kinds of shields, however, I suspect that this is typical for most of the WizNet line, e.g. W5200 etc.)

  [1]: http://wizwiki.net/forum/viewtopic.php?f=20&t=2108&p=6933&hilit=w5100 temperature#p6933


message:
Arduino web server: redirect to mobile site on SD card?

Is there any way to have an Arduino web server redirect the client to a file on the SD card only if the client is using a mobile browser?

(My arduino server is already successfully serving pages on http://192.168.0.180, and successfully processes GET requests).

I was thinking of having this javascript code on the main page that's served by the arduino:

    <script type="text/javascript">
      <!--
      if (screen.width <= 800) {
        window.location = "http://192.168.0.180?mobile";
      }
      //-->
    </script>

My first thought was that maybe it's possible for the server to process that GET request and then serve a page from the SD card, instead of the regular page it serves.

Do you think this is possible, and how would you recommend to do it?

body:
Yes, it is perfectly possible. you just have to look at the right bits.

Fundamentally there is no difference between an Arduino and any other website, it's just somewhat simpler in how it operates.

All browsers follow the same rules - if they didn't they wouldn't work on the web.  Two of the rules you are interested in are:

* Browsers identify themselves along with their OS.
* Browsers respond to the "result" code the website provides in a specific way.

Besides the GET request a browser also sends a list of *headers*.  These contain lots of extra information about the request, including the domain name of the website that is being accessed (so the web server knows which site you want - it's not one webserver per site, that would be impractical.  For instance, the request to show this page from Firefox on Linux has these headers:

    Host: arduino.stackexchange.com
    User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.6.0
    Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
    Accept-Language: en-gb,en;q=0.5
    Accept-Encoding: gzip, deflate
    Cookie: (I won't bore you with this lot)
    Connection: keep-alive

The header of note is the *User-Agent:* one.  That tells the web server that I am using firefox from a 64-bit Intel Linux computer.  If I were to do it from my Android phone it would tell you it's from Chrome on Android.

By looking for that header and parsing it for certain keywords you can find if you're serving to a mobile device or not.

Now the second bullet above - browsers respond to the *response* code in different ways.  Normally you send the response code `200` which means "I accepted your request and here is the page you asked for".  Another response code that is useful is code `301` which means "The page you asked for isn't at this address any more - here is the new address you should go to instead".  That will then cause the browser to go to the newly provided address instead.

So instead of responding with

    HTTP/1.0 200 OK
    Content-type: text/html

    <web page content here>

You could instead respond with:

    HTTP/1.0 301 Moved Permanently
    Location: http://myarduino.local/mobile

And the browser will *redirect* to the new address you give in the *Location:* response header.

The full list of response codes is here: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

If you want to avoid the overhead of a browser redirect you can just serve different data to the browser depending on what the User-Agent header specifies.  After all, it's entirely down to you what is sent as the content of the page.  Whether you get that from purely programmatical means, or by reading a file off an SD card, is entirely up to you.


message:
How to input keyboard commands using Arduino Mega 2560?

I have an Arduino Mega 2560 connected to a Windows 8 laptop. I want to program it to send keystrokes to the attached computer (when a pin's digital read goes from HIGH to LOW.)

The trouble is, I cannot find any way to program my Arduino Mega to send keystrokes.

The supposedly "core" Keyboard and Mouse libraries only support 32u4 boards, and other libraries that give the Arduino keystroke functionality are out of sight. When I googled the issue, I found no question or explanation of how to send keystrokes on the Arduino Mega. When I searched further, I thought the V-USB library would be a potential workaround, but the library throws numerous errors when imported into an Arduino sketch (even on the 1.0.0 IDE it was designed for.)

After hours of searching, two final workarounds seem to have popped up:

 1. Some method to run a Python code to send keystrokes to the PC, and then connect the Arduino code to Python. (I don't know Python...)
 2. Use some program called Gobetwino, which runs between the Arduino and PC, to   convert Serial commands into keystrokes somehow. (Pressing and releasing a key can't be simulated very well by repeatedly sending Serial commands, I think.)

Both are very unideal, very tedious, and are equally likely to just not work. I have spent hours on this.

Does anyone have any suggestions to get me out of this hell? Libraries, workarounds, anything?

(Feel free to PM me questions for clarification.)

body:
You are right, the mega can't do what you want unless something in the middle catches the serial/IO and translates to a keystroke command.

Another option, more expensive, is to buy an Arduino Leonardo which is also available as a small usb stick type of device. Then use serial/analog or ano from the mega to the Leonardo.

The Leonardo boards can emulate any usb device such as keyboard, mouse, joystick etc.

Maybe not of interested but also look at Teensy 3.1. It can do what the Leonardo does but is 32 bit and very flexible. The only benefit of the mega is the massive number of pins. Teensy costs about $20.

It all depends on what your project requires.


message:
Adjust time calculation after Timer0 frequency change

I have an Arduino Nano with an 328P and need all 6 PWM pins.

Thus, I had to adjust the prescaler and WGM Mode of Timer0.

It is now in phase correct PWM mode with a prescaler of 1.

    TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
    TCCR0B = _BV(CS00);

Now I need a working time calculation for other libraries, but since
Timer0 had that duty everything is out of order now.

I tried adjusting the wiring.c

    // the prescaler is set so that timer0 ticks every 64 clock cycles, and the
    // the overflow handler is called every 256 ticks.
    #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

to this

    #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 510))

But it's like I didn't change anything.
(tested other settings that **were changed** so it was compiled anew )

Whole Code:

    void setup() {

      // Set Timer 0, 1 and 2
      // Register A: Output A and B to non-inverted PWM and PWM mode to phase correct.
      // Register B: Pre Scaler to 1.
      TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
      TCCR0B = _BV(CS00);

      TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
      TCCR1B = _BV(CS10);

      TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20);
      TCCR2B = _BV(CS20);

      pinMode(8, OUTPUT);

    }
    void loop() {

      digitalWrite(8, LOW);
      delay(65000);
      digitalWrite(8, HIGH);
      delay(65000);

    }

body: You have set `MICROSECONDS_PER_TIMER0_OVERFLOW` to a proper value, however, this is only ever used by `MILLIS_INC`, which in turn is only ever used by `millis()`. This means that the other timing functions, such as `micros()`, `delay()`, `delayMicroseconds()` break when timer0 is changed. This is kind of a bug, and it may be fixed in a future version, but for now, the Arduino libraries are expecting you to leave timer0 alone. The best workaround is to only use `millis()` for your timing critical functions.


body:
Fixing the timekeeping functions with your PWM settings is not so
simple. You should at least try to rewrite `ISR(TIMER0_OVF_vect)`,
`micros()`, and probably `delay()`. Here is why:

First, there is a rounding problem. Time is kept using two global
variables:

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

    volatile unsigned long timer0_millis;
    static unsigned char timer0_fract;

The first one is what `millis()` returns. The second one keeps track of
how much time has passed since the last full millisecond, and it does so
in units of 8 µs. The two variables are incremented by
`ISR(TIMER0_OVF_vect)` like this:

 m += MILLIS_INC;  // temporary copy of timer0_millis
 f += FRACT_INC;   // temporary copy of timer0_fract

On a normal Uno configuration, the ISR is called every 1024 µs.
Then `MILLIS_INC` is 1 and `FRACT_INC` is 3. With your timer
configuration, the ISR is called every 31.875 µs (510 cycles), then
`MILLIS_INC` should be 0 and `FRACT_INC` should be 3.984375. But since
we are dealing with integers, it will be rounded down to 3, and your
`millis()` will tick about 25% too slow.

A simple fix would be to

    #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 512))

in order for `FRACT_INC` to be 4 and `millis()` to be 0.4% too fast. Or
you could make `timer0_fract` a 16-bit variable and have it count clock
cycles, just to avoid this error. Either option should fix `millis()`,
but you still have a problem with `micros()`.

`micros()` works by reading both `timer0_overflow_count` (incremented by
1 in the ISR) and the actual counter value. Since your counter is now
going alternatively up and down, it will be harder to compute a
microsecond count from these readings. Maybe you could take two
consecutive readings of the counter, just to know whether it is going up
or down...

And then there is `delay()`, which relies on `micros()`. If you fix
`micros()`, `delay()` should work fine. If not, You could rewrite
`delay()` to use `millis()` instead, which should be easy but you will
loose some accuracy.


body:
THIS IS AN INCOMPLETE ANSWER - Edgar knows what he's talking about, listen to him

I am currently working with this same thing but in an ATMega2560. [This website](https://ucexperiment.wordpress.com/2012/03/16/examination-of-the-arduino-millis-function/) helped me understand the millis() function better. The timer overflows every 510 counts (see datasheet, pg 123 for the atmega2560). I believe it is 510 and not 512 because it counts up and down, but does not repeat a count at the top or bottom - for example if you count starting from 1 up to 10 and then back down (without repeating 10) you will have counted 19 times, not 20. This counter starts at 0, counts to 255, and then back to 0, triggering an overflow before hitting 0 again. This is is 256 (count up including 0 and 255) + 254 (count down, not including 255 or 0) = 510.
I wrote a python script to visualize the effect of these changes and trying to account for them. This counts to 10 million, so it takes time to run, but by the end, even with scaling, the error if simply adjusting millis() after the fact could be ~7 seconds.

    #! /usr/bin/env python
    import numpy as np

    realT = np.zeros(10000000)
    timer0_millis = np.zeros(10000000)
    timer0_fract = np.zeros(10000000)
    i=0

    for i in range (1,10000000):
     timer0_millis[i] = timer0_millis[i-1] + 1
     timer0_fract[i] = timer0_fract[i-1] + 3
     realT[i] = i*31875
     if timer0_fract[i-1] >= 125:
      timer0_fract[i] = timer0_fract[i-1] - 125
      timer0_millis[i] = timer0_millis[i-1] + 1

    adjusted = timer0_millis*510/(256*64)

    print "after 100 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[99], realT[99]/1000000, adjusted[99])
    print "after 1000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[999], realT[999]/1000000, adjusted[999])
    print "after 10000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[9999], realT[9999]/1000000, adjusted[9999])
    print "after 100000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[99999], realT[99999]/1000000, adjusted[99999])
    print "after 1000000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[999999], realT[999999]/1000000, adjusted[999999])
    print "after 10000000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[9999999], realT[9999999]/1000000, adjusted[9999999])


body:
Thanks to Edgar's answer and Nebsie's explaination on how the counter exactly works I could come up with my own implementation of how to rectify delay and micros() that - so far - seems to work fine on my Arduino Uno.

I'm not saying that this is the most precise implementation, especially I have my doubts on micros() if for example an timer overflow occours between reading t1 and t2, but it is one that so far for me works well.

First thing - according to Edgar's recommendation I defined:

    #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 512))

However this doesn't affect timing of micros() or delay().

Function micros() I changed to read two times from TCNT0 - to determine whether it is counting upwards or downwards. This is done with the "if (t1 > t2)" clause. The overflow count "m" is multiplied by 510, because the counter elapses after 510 steps. Then the calculated counter value "t" is added to this, divided by the number of clocks per Microsecond. (Note: Prescaler = 1, therefore no further multplication).

    unsigned long micros() {
     unsigned long m;
     uint8_t oldSREG = SREG, t1, t2;
     uint16_t t;

     cli();
     m = timer0_overflow_count;
    #if defined(TCNT0)
     t1 = TCNT0;
    #elif defined(TCNT0L)
     t1 = TCNT0L;
    #else
     #error TIMER 0 not defined
    #endif

    #if defined(TCNT0)
     t2 = TCNT0;
    #elif defined(TCNT0L)
     t2 = TCNT0L;
    #else
     #error TIMER 0 not defined
    #endif

     if (t1 >= t2) {
      t = 510 - t2;  // counter running backwards
     } else {
      t = t2;    // counter running upwards
     }

    #ifdef TIFR0
     if ((TIFR0 & _BV(TOV0)) && (t2 > 1))  // if overflow flag is set -> increase m
      m++;
    #else
     if ((TIFR & _BV(TOV0)) && (t2 > 1))
      m++;
    #endif

     SREG = oldSREG;

     return ((m * 510) + t)  / clockCyclesPerMicrosecond();
    }

HOWEVER - this seems to work fine but I had issues to begin with (before editing this again). Due to the counter running much faster, every 268 seconds the unsigned long datatype of micros() overflows and starts from zero again. This led to an unwanted lockup of delay(), especially if long delay times, like in my case delays of one second per loop iterations are used. Therefore I also had to add an overflow detection to the delay() function in arduino wiring.c.

If the overflow occurs, timing might not be very precise. But since this is once overy 268 seconds it may be acceptable. So far with this change the delay function works fine again on my side.

    void delay(unsigned long ms)
    {
     uint32_t start = micros();
     uint32_t elapsed = 0;

     while (ms > 0) {
      yield();
      while ( ms > 0 && (micros() - 1000) >= (start + elapsed)) {
       ms--;
       elapsed += 1000;
      }
      if( start > micros() ) {  // overflow detected
       start = micros();  // reset start
       elapsed = 0;   // reset elapsed
      }
     }
    }


message:
Can I use analogRead to read a digital pin?

analogRead(nGPIO_max + lockerVal) were nGPIO_max(maximum digital pins in Arduino Uno is 13) and lockerval is 2. Which pin is it reading?

body:
To answer the question in the title: No, you cannot use `analogRead()` to read a digital pin. A digital pin cannot behave as analog because it isn't connected to the ADC (Analog to Digital Converter).

If you call something equating to `analogRead(15)` on an Uno, then it should read pin `A1`. You can see the pin assignments in the board-specific versions of `pins_arduino.h` (shipped with the IDE):

    static const uint8_t A0 = 14;
    static const uint8_t A1 = 15;
    static const uint8_t A2 = 16;
    static const uint8_t A3 = 17;
    static const uint8_t A4 = 18;
    static const uint8_t A5 = 19;
    static const uint8_t A6 = 20;
    static const uint8_t A7 = 21;

Using those raw numbers directly is generally not a good idea though as it obscures your code's meaning, and will potentially make it non-portable to other boards. It's better to call something like `analogRead(A1)`.

It's worth noting that the Arduino library fudges the pin numbers slightly. Calling `analogRead(1)` has the same result as calling `analogRead(A1)`. That means that even if you *tried* to use `analogRead()` on a digital pin, it might actually end up reading an analog pin instead. Alternatively, it might just return a meaningless result, depending on the pin number you give it.


message:
Arduino communication with ROS via UART

I am trying to program an Arduino Mega(Crius) from a Minnowboard Max A2 via an UART (Hardware Flow Control Off) interface.

I can successfully communicate with the ROS (robot Operating System) on the Ubuntu 12.04 installed on the Minnowboard Max via the UART1 port available on the Minnow Board.

The Crius UART has a FTDi compatible port with a DTR pin.
Unfortunately the MinnowBoard does not have any DTR pin to communicate with the Arduino (Only CTS/RTS pins for 1 of the 3 UART ports). Thus I cannot upload any sketch to the Arduino via the Minnowboard over the UART. I must always connect to the onboard FTDi-USB chip of the crius and upload the sketch.

Is there any workaround to upload the sketch to the Arduino via the UART from the Minnowboard ?

body:
You can use any GPIO you like on the Minnow to trigger a reset of the Mega to initiate the bootloader.  The Yún does just that to program the on-board ATMega chip through a script they have chosen to call "run-avrdude":

    #!/bin/sh

    echo 1 > /sys/class/gpio/gpio21/value
    avrdude  -q -q -c linuxgpio -C /etc/avrdude.conf -p m32u4 -U efuse:r:/tmp/efuse:d
    read EFUSE < /tmp/efuse
    rm -f /tmp/efuse
    if [ "x$EFUSE" = "x203" ] # 203 = 0xCB
    then
     avrdude -c linuxgpio -C /etc/avrdude.conf -p m32u4 -U lfuse:w:0xFF:m -U hfuse:w:0xD8:m -U efuse:w:0xCB:m -Uflash:w:$1:i $2
    else
     avrdude -c linuxgpio -C /etc/avrdude.conf -p m32u4 -U lfuse:w:0xFF:m -U hfuse:w:0xD8:m -U efuse:w:0xFB:m -Uflash:w:$1:i $2
    fi
    echo 0 > /sys/class/gpio/gpio21/value

You could do something similar to initiate the bootloader on the remote board - connect any GPIO pin to the RESET line of your Mega board, then perform the following logical actions:

1. Set the GPIO to OUTPUT
2. Set the GPIO to LOW
3. Delay a few ms
4. Set the GPIO to INPUT
5. Run avrdude.

By setting the GPIO to INPUT you are emulating an open-drain output.  If you were just to drive the GPIO HIGH it would hold the RESET pin HIGH and you wouldn't be able to use the USB interface, nor the RESET button.  By setting it to INPUT it is then effectively disconnected from the RESET pin so won't interfere.

The Yún again has a script that works in that way, "reset-mcu":

    #!/bin/sh

    echo 18 > /sys/class/gpio/export
    echo "high" > /sys/class/gpio/gpio18/direction
    echo 1 > /sys/class/gpio/gpio18/value
    echo 0 > /sys/class/gpio/gpio18/value
    echo 18 > /sys/class/gpio/unexport

I have a similar setup to you but using a BeagleBone Black and a PONTECH Quick240 PIC32 based controller.  In my IDE [UECIDE](http://uecide.org/beta) I set up a special board definition with the following programmer added to it which performs the manual reset through GPIO and runs the upload program (pic32prog) all in one operation:

    upload.local.name=Local upload
    upload.local.using=script
    upload.local.script.0=__builtin_bullet::Entering programming mode...
    upload.local.script.1=__builtin_gpio::7::low
    upload.local.script.2=__builtin_delay::100
    upload.local.script.3=__builtin_gpio::20::low
    upload.local.script.4=__builtin_delay::100
    upload.local.script.5=__builtin_gpio::20::hiz
    upload.local.script.6=__builtin_delay::100
    upload.local.script.7=__builtin_gpio::7::hiz
    upload.local.script.8=__builtin_delay::100
    upload.local.script.9=__builtin_bullet::Uploading sketch...
    upload.local.script.10=${core.root}/tools/linux_arm/pic32prog::-S::-d::${port}::-B::${upload.maxbaud}::-p::${build.path}/${filename}.hex
    upload.local.script.11=__builtin_bullet::Resetting board...
    upload.local.script.12=__builtin_delay::100
    upload.local.script.13=__builtin_gpio::20::low
    upload.local.script.14=__builtin_delay::100
    upload.local.script.15=__builtin_gpio::20::hiz

    sketch.upload=local

That one is a little different in that you have to hold a second GPIO LOW while you reset the board to initiate the bootloader, hence the two GPIOs in use there.


message:
Arduino Web Server and Relay Module

I am working on a web server project for work. I have a web server setup with an Arduino Meg2560 with Ethernet. I also have a 16 relay board connected to Ethernet with its own IP. I wanted to see if there is a way I can make calls to the relay board via IP from the Arduino Webserver. For example Relay 1 on the relay board can be turned on by typing 192.168.1.4/30000/00 but this opens the web GUI on the board. I need to do the same thing but without opening the webpage or web GUI.
![enter image description here][1]

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

        #include <SPI.h>
        #include <Ethernet.h>

        // MAC address from Ethernet shield sticker under board
        byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
        IPAddress ip(192, 168, 1, 177); // IP address
        EthernetServer server(80);  // Server Port 80

        void setup()
        {
          Ethernet.begin(mac, ip);
          server.begin();
        }

        void loop()
    {
    EthernetClient client = server.available();  // try to get client

    if (client) {  // got client?
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {   // client data available to read
                char c = client.read(); // read 1 byte (character) from client
                // last line of client request is blank and ends with \n
                // respond to client only after last line received
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    client.println("Content-Type: text/html");
                    client.println("Connection: close");
                    client.println();
                    // send web page
                    client.println("<!DOCTYPE html>");
                    client.println("");
                    client.println("");
                    client.println("<title>Arduino Web Page</title>");
                    client.println("");
                    client.println("");
                    client.println("
Hello from Arduino!
");
                    client.println("
A web page from the Arduino server
");
                    client.println("");
                    client.println("");
                    break;
                }
                // every line of text received from the client ends with \r\n
                if (c == '\n') {
                    // last character on line of received text
                    // starting new line with next character read
                    currentLineIsBlank = true;
                }
                else if (c != '\r') {
                    // a text character was received from client
                    currentLineIsBlank = false;
                }
            } // end if (client.available())
        } // end while (client.connected())
        delay(1);      // give the web browser time to receive the data
        client.stop(); // close the connection
    } // end if (client)
}

body:
Documentation on the [controller][1] you are using is pretty scant, but it looks like you just need to make a GET request to the URI corresponding to the action you need to take.

> http://192.168.1.4/30000/00 : Relay-01 OFF
>
> http://192.168.1.4/30000/01 : Relay-01 ON
>
> http://192.168.1.4/30000/02 : Relay-02 OFF
>
> http://192.168.1.4/30000/03 : Relay-02 ON
>
> http://192.168.1.4/30000/04 : Relay-03 OFF
>
> http://192.168.1.4/30000/05 : Relay-03 ON
>
> …
>
> http://192.168.1.4/30000/14 : Relay-8 OFF
>
> http://192.168.1.4/30000/15 : Relay-8 ON
>
> http://192.168.1.4/30000/41 : Enter
>
> http://192.168.1.4/30000/40 : Exit
>
> http://192.168.1.4/30000/42 : Next Page
>
> http://192.168.1.4/30000/43 : Next Page

For example If I wanted to turn off relay 3, I would simple make a GET request to `http://192.168.1.4/30000/04` and close the connection. Example code:

    IPAddress server(192,168,1,4);
    EthernetClient client;
    client.connect(server, 80);
    client.println("GET /30000/04 HTTP/1.1");
    client.println("Connection: close");
    client.println();
    client.stop();

  [1]: http://www.sainsmart.com/sainsmart-ethernet-control-module-lan-wan-web-server-control-with-rj45-port.html


message:
PWM timers, channels and pins

I've got this code from the [MultiWii][1] project, which is relevant to the hardware, [ATmega32u4][2], I have. It is part of a function called `initOutput()`.

In the comment it says "connect pin 6", which is the bit of that which specifies pin 6 as I would like to change it to another pin, specifically A0.

    // Enhanced PWM mode
    TCCR4E |= (1<<ENHC4);

    // Prescaler to 16
    TCCR4B &= ~(1<<CS41);
    TCCR4B |= (1<<CS42) | (1<<CS40);

    // Phase and frequency correct mode and top to 1023, but
    // with enhanced PWM mode we have 2047.
    TCCR4D |= (1<<WGM40);
    TC4H = 0x3;
    OCR4C = 0xFF;

    // Connect pin 6 to timer 4 channel D
    TCCR4C |= (1<<COM4D1) | (1<<PWM4D);

  [1]: http://www.multiwii.com/
  [2]: http://www.atmel.com/devices/ATMEGA32U4.aspx

body: It's the `(1<<COM4D1)` that enables pin 6, or more specifically **OC4D** for timer output. You cannot use A0 instead, since there is no output compare capability on that pin; only pins 13, 5, 10, 9, 6, and 12 can be connected to timer 4. See the datasheet for details.


message:
Can I connect TFT LCD screen to Arduino Leonardo same way as it's recommanded for Arduino Uno?

I want to connect the *Arduino TFT LCD 1.77" screen* to an *Arduino Leonardo*. Acording to [this](https://www.arduino.cc/en/Guide/TFTtoBoards) tutorial I should connect some pins on LCD screen to *ICSP pins* on Leonardo but I don't have equipment to do it. Can I just connect LCD screen to Leonardo in the way it't recommanded for an *Arduino Uno* (same tutorial above) using only digital and power pins. And then use sketches for Uno. Will it work?

Also, is it safe for LCD screen?

body:
I think it could work, but not easily. I.e. you would need to tweak the code and anyway you will end up with really low performance.

This is the reason:

> SPI: on the ICSP header. These pins support SPI communication using the SPI library. Note that the SPI pins are not connected to any of the digital I/O pins as they are on the Uno, They are only available on the ICSP connector. This means that if you have a shield that uses SPI, but does NOT have a 6-pin ICSP connector that connects to the Leonardo's 6-pin ICSP header, the shield will not work.

Source: https://www.arduino.cc/en/Main/ArduinoBoardLeonardo

> The screen can be configured for use in two ways. One is to use an Arduino's hardware SPI interface. The other is to declare all the pins manually. There is no difference in the functionality of the screen between the two methods, but using hardware SPI is significantly faster when drawing.
If you plan on using the SD card on the TFT module, you must use hardware SPI.
All the examples are written for hardware SPI use.

Source: https://www.arduino.cc/en/Guide/TFT#toc4

In the end I think it would be better to get the equipment needed...

Edit: You can try with this constructor:

> When not using hardware SPI, you can use any available pins, but you must declare the MOSI and SCLK pins in addition to CD, DC, and RESET.

    #define SCLK 4
    #define MOSI 5
    #define CS   6
    #define DC   7
    #define RESET 8

    TFT myScreen = TFT(CS, DC, MOSI, SCLK, RESET);

Source: https://www.arduino.cc/en/Reference/TFTLibrary


body:
You can hook up the "Adafruit_ST7735" or from what i later learned after getting my Esplora. Thats when i had my adruino-epiphany. Okay so IF your wondering why im including this super rad Controller shaped arduino, the answer is, its a leonardo. well its just a different flavor of the Atmega32u4 whis is the chip that made ext serial programmers kinda obsolete and makes the uno and megas so unique as well. so with that being said the Esplora has a native language when refering back the tft libraries, but its not too far from a simple (ctrl+F) and replace Esplora references with actual defines and references. and in this case the Leonardo would need to have the icsp header used by the corresponding pins on the display (for this instance of using an SPI connection with the serial display we will not swap the Miso and Mosi  like we would a nother instance.just connect miso to miso and mosi to mosi i usually plug up the whole icsp header and then that wwill leave you with the two pins you MUST DEFINE to make it work which would be :

    // Pins SCLK and MOSI are fixed in hardware, and pin 10 (or 53)
// must be an output
//#define sclk 13    // for MEGAs use pin 52
//#define mosi 11    // for MEGAs use pin 51
#define cs 10   // for MEGAs you probably want this to be pin 53
#define dc 9
#define rst 8  // you can also connect this to the Arduino reset

    // Pins SCLK and MOSI are fixed in hardware, and pin 10 (or 53)
// must be an output
//#define sclk 13    // for MEGAs use pin 52
//#define mosi 11    // for MEGAs use pin 51
#define cs 10   // for MEGAs you probably want this to be pin 53
#define dc 9
#define rst 8  // you can also connect this to the Arduino reset

// Color definitions
#define BLACK           0x0000
#define BLUE            0x001F
#define RED             0xF800
#define GREEN           0x07E0
#define CYAN            0x07FF
#define MAGENTA         0xF81F
#define YELLOW          0xFFE0
#define WHITE           0xFFFF

#include <ST7735.h>
#include <SPI.h>

// Option 1: use any pins but a little slower
//ST7735 tft = ST7735(cs, dc, mosi, sclk, rst);

// Option 2: must use the hardware SPI pins
// (for UNO thats sclk = 13 and sid = 11) and pin 10 must be
// an output. This is much faster - also required if you want
// to use the microSD card (see the image drawing example)
ST7735 tft = ST7735(cs, dc, rst);
float p = 3.141592; // value for pi
int tft_width = 128;
int tft_height = 160;
int x1 = 60;
int y1 = 60;
int x2 = 20;
int y2 = 80;
int ballx = 60;
int bally = 60;
int deltay = 1;
int deltax = 1;

int ball_speed = 24;

int left_score = 4;
int right_score = 4;

int background_color = 0x00;
void setup(void) {
  tft.initR();               // initialize a ST7735R chip

  tft.writecommand(ST7735_DISPON);
  tft.fillScreen(background_color);
  delay(700);
  for(int i = 0; i < 9; i++){
    pinMode(i,OUTPUT);
  }
  for(int i = 0; i < 9; i++){
    digitalWrite(i,HIGH);
  }
  delay(500);

}

void loop() {
  for(int i = 0; i < left_score; i++){
    digitalWrite(i,HIGH);
  }
  for(int i = 0; i < right_score; i++){
    digitalWrite(i+4,HIGH);
  }
  int cur_r = random(20,32);
  int cur_g = random(55,64);
  int cur_b = random(10,32);
  int color = cur_r  | (cur_g << 5) | (cur_b << 11);
  int radius = 4;
  draw_paddles();
  draw_ball(color);
  delay(ball_speed);
}
void draw_input_text(){
  int cur_x2 =  analogRead(2);
  int cur_y2 =  analogRead(3);
  String xs = String(cur_x2);
  String ys = String(cur_y2);
  char cx[4];
  cx[0] = xs.charAt(0);
  cx[1] = xs.charAt(1);
  cx[2] = xs.charAt(2);
  cx[3] =0;
  char cy[4];
  cy[0] = ys.charAt(0);
  cy[1] = ys.charAt(1);
  cy[2] = ys.charAt(2);
  cy[3] =0;
  tft.fillRect(10,20,40,40,background_color);
  tft.drawString(12,22,cx ,YELLOW);
  tft.drawString(12,40,cy ,YELLOW);
}
void draw_paddles(){
  int cur_x =  analogRead(0);
  int cur_y =  analogRead(1);
  int hval = 620;
  int lval = 350;

  if ( y1 < tft_height - 20  && cur_y > hval) y1++;
  else if ( y1 > 0 && cur_y < lval ) y1--;

  int cur_x2 =  analogRead(2);
  int cur_y2 =  analogRead(3);

  if ( y2 < tft_height - 20 && cur_y2 > hval ) y2++;
  else if (y2 > 0 && cur_y2 < lval ) y2--;
  tft.fillRect(2, y1-3, 5, 27, background_color);
  tft.fillRect(3, y1, 3, 20, YELLOW);
  tft.fillRect(tft_width-3, y2-3, 5, 27,background_color);
  tft.fillRect(tft_width-3, y2, 3, 20, YELLOW);
}
void draw_ball(int color){
   int bradius = 6;
    tft.fillCircle(ballx, bally, bradius , color);
    ballx += deltax;
    bally += deltay;
    if ( ballx < 7 && bally > y1 && bally < y1+20) deltax *= -1;
    else if ( ballx > tft_width-7 && bally > y2 && bally < y2+20) deltax *= -1;
    else if ( bally <= bradius || bally >= tft_height - bradius ) deltay *= -1;
    if (ballx <=  0 ) {
      left_score--;
      tft.drawString(2,42, "Right Won!" ,~background_color,2);
      tft.drawString(2,62, "Get Ready!" ,CYAN,2);
      for (int i = 0; i <250; i++){
        delay(10);
        draw_paddles();
      }
      int cur_r = random(0,26);
      int cur_g = random(0,30);
      int cur_b = random(0,18);
      background_color = cur_r  | (cur_g << 5) | (cur_b << 11);
      tft.fillScreen(background_color);
      ballx = 64;
      bally = 80;
      if (ball_speed > 1) ball_speed--;
      digitalWrite(left_score,LOW);
    } else if (ballx >= tft_width  ) {
      right_score --;
      tft.drawString(2,42, "Left Won!" ,YELLOW,2);
      tft.drawString(2,62, "Get Ready!" ,GREEN,2);
      for (int i = 0; i <250; i++){
        delay(10);
        draw_paddles();
      }
      int cur_r = random(0,26);
      int cur_g = random(0,30);
      int cur_b = random(0,18);
      background_color = cur_r  | (cur_g << 5) | (cur_b << 11);
      tft.fillScreen(background_color);
      ballx = 64;
      bally = 80;
      if (ball_speed > 1) ball_speed--;

      digitalWrite(4+right_score,LOW);

    }
}

enjoy getting that code to fudge around with  i  stole it right form  here http://lucidtronix.com/tutorials/7
 but the point i had to bring up is that i believe the guy before mentioned that it is a muchslower connectionor process than if it were.....were you saying softwareserial was the option then?
 because im not an explert or novice or maker by any means. but i have picked up along the lines that hardware serial will always trump software serial compilation any day once you get your head wrapped around the brevity of what ports and pins are actually what are used or have the data displayed on the serial ports. and like software is a necessity im afraid, but its as simple as reasigning pins and when that gets too hard going out and just bbuying a mega, haahah hope i sorta helped. id say go out and snag an esplora whilst their like toing a fire clearance sale on the originallt 50$+ boards. but their reference and prebuilt array of sensors is a bit underwhelming for the newbies in what it alll does, but kinda overwhelmine and difficult to transistion onece having looked at some code as it is, but the language is more forg9ving, but i believe their also officially retiring the leonardo espolora and micro series so good luck this tft display kicks bum man and is the only one that hsnt broke