message:
Making CS (chip select) work in SPI (for and SD card and OLED)

[![This is how it looks.][1]][1]

I'm working on a project that will log data to an SD card and display a user interface on an OLED. [The SparkFun OLED breakout][2] was super easy to set up. I was also able to get the [SD-Card library][3] working independently, though that was harder.

The trouble is when I combine these examples the SD card *only* writes during "setup" after that it isn't writing to the SD card as the loop continues. The OLED still works just fine.  I've read up on SPI a bit and tried various things to get "chip select" to work (I suspect this is the problem) I even tried setting the CS pins to LOW or HIGH using digitalWrite, but this had no impact.

My pins are connected as follows:

              SD CARD      OLED
    MOSI        A5            A5     same pin
    MISO        A4            --     just SD connected
    SCK         A3            A3     same pin
    CS          A1            A2     different pins

The SD card writes in the main loop if I comment out all of the code that runs the OLED. The OLED works either way.  What could I try next?

Here is the code:
<!-- language-all: lang-cpp -->

     #include "application.h"
     #include "sd-card-library/sd-card-library.h"
     #include "SparkFunMicroOLED/SparkFunMicroOLED.h"
     #include "math.h"

     //////////////////////////////////
     // MicroOLED Object Declaration //
     //////////////////////////////////
     // Declare a MicroOLED object. If no parameters are supplied,
     // default pins are used, which will work for the Photon Micro
     // OLED Shield (RST=D7, DC=D6, CS=A2)
     // Since I use A1 as the chip select pin for the SD card these
     // defaults seem fine.

        MicroOLED oled;

     // Declare a file object?

        File myFile;

     // These are the pins for the SD card. A5, A4, and A3 are all
     // shared by the OLED.

        const uint8_t chipSelectSD = A1;
        const uint8_t mosiPin = A5;
        const uint8_t misoPin = A4;
        const uint8_t clockPin = A3;

     ////////////
     // setup //
     ////////////
     void setup() {
      delay(500);

      SD.begin(mosiPin, misoPin, clockPin, chipSelectSD);
      File dataFile = SD.open("data.txt", FILE_WRITE);
      dataFile.println("this text was printed to the SD card during setup");
      dataFile.close();

      oled.begin();  // Initialize the OLED
      oled.clear(ALL); // Clear the display's internal memory
      delay(1000);  // Delay 1000 ms
      oled.clear(PAGE); // Clear the buffer.
      randomSeed(analogRead(A0) + analogRead(A7)); //seed to make test pattern random.

                   }//end setup

    //////////////////
    // main loop //
    //////////////////
    void loop()  {

      SD.begin(mosiPin, misoPin, clockPin, chipSelectSD);
      File dataFile = SD.open("data.txt", FILE_WRITE);
      dataFile.println("The text was added during the loop.");
      dataFile.close();

    //test the display with text and pixels.
      printTitle("Pixels", 1);
      for (int i=0; i<512; i++)
      { oled.pixel(random(oled.getLCDWidth()),  random(oled.getLCDHeight()));
      oled.display(); }
       delay(9000);

                   } //end loop

    //-------------------------//
    // function to print titles //
    //-------------------------//
      void printTitle(String title, int font) {
      int middleX = oled.getLCDWidth() / 2;
      int middleY = oled.getLCDHeight() / 2;
      oled.clear(PAGE);
      oled.setFontType(font);
      // Try to set the cursor in the middle of the screen
      oled.setCursor(middleX - (oled.getFontWidth() * (title.length()/2)),
      middleY - (oled.getFontWidth() / 2));
      // Print the title:
      oled.print(title);
      oled.display();
      delay(1500);
      oled.clear(PAGE);
                                               } //end title function

[![enter image description here][4]][4]

This is how the SD card is hooked up.

      oled.begin();  // Initialize the OLED

Any attempt to use the SD card after this line will not work. I've looked for something like "oled.end()" but have not found a way to reset to the state where the SD card works.

I have tried commenting out all of the OLED code and then the SD card writes fine in the main loop. So, I started adding the OLED code back in. This line of code breaks the SD card writing in the main loop:

  [1]: https://i.stack.imgur.com/qB9Jv.jpg
  [2]: https://learn.sparkfun.com/tutorials/photon-oled-shield-hookup-guide
  [3]: https://github.com/technobly/SparkCore-SD
  [4]: https://i.stack.imgur.com/qfxAr.jpg

body:
I wanted to write to 2 SD cards simultaniously with one Arduino Mega. Used all the relevant pins including CS on 53 for the first SD card and 13 for the second SD card.  Can be any digital pin I think but this one makes the LED blink too).  Before the SD.begin(13) of the second SD card I do a digitalWrite(53,HIGH).  That de-selects the first SD card. and digitalWrite(13,HIGH) when switching back to SD.begin(53) I do a digitalWrite(13,HIGH).  This works real fine.

Now I tried to impelment this on a D1-Mini.  Cannot get it to work.
SD.begin(D8) starts the first SD fine.  By doing a digitalWrite(D8,HIGH) I tried to de-select SD1 and with SD.begin(D4) opened the second card. Strangely enough it still opens the first SD card again regardless of the pinnumber-parameter.
Maybe the SD library for ESP8266 remembers the first setting of the CS and later settings og the parameter with fifferent pinnembers are ignored???


sender: user

message:
Which board/shield to generate (non-PWM) analog outputs?

I am currently building a project involving a laser scanner (two galvanometers with mirrors that deflect a laser beam) that I want to control. The galvos need +-10V differential signals (and I'd like to have a least 12Bit) that I want create with some small board.

Most Arduinos I know use PWM to create an analog output which is not usable for this project. I found the Teensy3.1 which has at least one 12Bit DAC so that also doesn't work. An alternative would be a DAC breakout board like ["MCP4725"][1] but it would be nicer to just have a single board with no additional parts.

The best thing would be a small board with already two 12Bit DACs. (even If I had to upscale the voltage +-10v)

Is there a board I haven't found so far? Or have I missed a completely different approach?

  [1]: https://www.adafruit.com/products/935 "MCP4725"

sender: assistant

body:
For 12-bit dual DAC you want the [MCP4822](http://ww1.microchip.com/downloads/en/DeviceDoc/22249A.pdf) which has two channels of 0-4.095V in 1mV steps.

The output of that you would then need to pass through a suitable amplifier arrangement with an op-amp giving a gain of 5 and adding an offset of -10V.  The gain would change the 0-4.095V to 0-20.475V, and the -10V offset would change that to -10V to +10.475V.  If you want to get more precise you could use an offset of -10.2375V (it's not easy to make an offset voltage that precise) then you would get -10.2375V to 10.2375V in 12-bit resolution.

It's doubtful you'll find a board already made up with that specific arrangement (it's fairly specialised) but it's not something that's hard to make - all the components are available as DIP or other through hole components, and the circuit for the amplification stage is pretty simple (check for non-inverting op-amp circuits online, there's millions), so building it up on strip board or matrix board would be easy enough.


message:
How do pins on an arduino mega 2560 work?

I got a copy of Arduino from a local retailer here (it's a local copy and I'm pretty confused with how the pins actually work).

I know basic electronics so far, there should be two pins for every node one acting as the negative terminal and other as the positive terminal. If I were to connect an LED with my Arduino board which pins would I be utilizing?

Here let me tell you how pins are arranged on mine:

    IOREF                                                                         GND

                                             13
    RESET                                                                         12
    3.3V     //this left group marked power                                        .
    5V                                  //right group marked PWM                   2
    GND            //right groupmarked communication                          TX0 -1
    GND                                                                       RX0- 0

    V1N                                                                       TX3-14
                                                                             RX2 -15
    A0                                                                         ..
    A1                                                                      SCL -21
    ..   //THIS left GROUP MARKED ANALOG IN
    A7

    A8
    A9 //I believe it is part of the above group
    ..
    A14
    A15

         //the pins below marked DIGITAL
         52-50-`48-46...........................................................22`

body:
Any IO pin can be set to either be an input, where it reports to your program if the voltage present on that pin (relative to ground) is above or below a certain threshold (HIGH or LOW voltage), or it can be an output, where it can either be set to be a HIGH output (pin is connected internally to +5V) or a LOW output (pin is connected internally to GND).

To drive an LED you would connect one side of a small resistor (say 470Ω) to any IO pin you choose.  The other side of the resistor would connect to the anode of the LED.  The cathode of the LED would then connect to ground.  When you set the IO pin to HIGH it will provide 5V to the LED through the resistor (which is needed to limit the current as the LED is a non-linear, current driven, component) and the circuit is completed by the return path through ground.

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

Note that you *must not* exceed 40mA going into or out of any IO pin, and you *should not* exceed 25mA going into or out of any IO pin.  The total current going into or out of *all* IO pins *must not* exceed 200mA.

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


body:
> there should be two pins for every node one acting as the negative terminal and other as the positive terminal.

No, there is one pin per node, and a **common** "Ground" pin which is the negative terminal. On your Mega2560 are 5 ground pins (effectively equivalent because they are connected). They are circled on the photo below, and marked **GND** on the board.

[![Mega2560 board][1]][1]

---

As Majenko says in his answer you must use a resistor in series with any LED you connect, or you will damage both the LED and the processor.

You may find a "breadboard" handy for making connections, most prototyping boards have a long connected strip for sharing the Ground wire between different places, like this:

[![Prototyping board][2]][2]

The continuous blue lines indicate pins which are connected together (for Ground) and the continuous red lines are connected together for +5 V (usually).

---

> Btw can you tell me why there are two pins on the bottom horizontal row?

Just for convenience. You often want an extra ground pin, for example if you are trying to connect up two LEDs.

>  Secondly, yes each pin can be set as input or output but is there any specific difference in the type of pins?

Some of the pins can optionally be used for extra hardware-supported features.

* PWM: Pulse-width-modulated output
* COMMUNICATION: Serial input/output (4 serial ports)
* ANALOG IN: Analog-to-digital converter (ADC) input
* DIGITAL: Digital (not analog) input/output
* SDA/SCL: I2C communications
* Pins 50-53: SPI communications (not marked on the board)

However **all** pins, as you noted, can - if you wish - be used for digital input or output.

  [1]: https://i.stack.imgur.com/EWFnD.jpg
  [2]: https://i.stack.imgur.com/ArXKq.jpg


message:
Need assistance with program for POV Project

I've created a very basic POV project.

It has a 12V DC motor with a piece of wood on it.
The wood has 6 LEDs on it as well as a copper ring.
The power is delivered to the LEDs from brushes connecting to the copper ring and from the shaft of the motor (the ground is attached to the base of the motor.) I'm using a TCRT5000L Sensor to count the RPM and have attached the LEDs to pin 13 and ground of the Arduino. (I've attached white tape to one side of the wood so that the sensor only counts one rev.)

I need help (please) with the program.

This is the code that I am using:

    int pin = 13;
    volatile  int tcnt = 0;
    volatile  int lastcount = 0;
    volatile int state = LOW;

    void setup() {
      Serial.begin(9600);
      pinMode(pin, OUTPUT);
      attachInterrupt(1, blink, RISING);
    }

    void loop() {
      Serial.println(tcnt);
      if (tcnt != lastcount)
      {
         digitalWrite(pin, HIGH);
         delay(10);
         digitalWrite(pin, LOW);
         delay(10);
         lastcount = tcnt;
      }

       delay(10);

    }

    void blink() {
      tcnt = tcnt + 1;
      state = !state;
    }

My first issue is that the when I use the code above, the lights don't seem to switch on / off on the exact same area. They are within 30 degrees but certainly not precise.

The second issue (and the biggest) is that I'm sure that this code is not the best way to do what I need. For example, if I wanted to use this as an analog clock, so that the lights would only show on the current hour / minute, how would I do this?

Any help is greatly appreciated.

[![Side View][1]][1]

[![Top View][2]][2]

  [1]: https://i.stack.imgur.com/mtp02.jpg
  [2]: https://i.stack.imgur.com/rmGd4.jpg

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

Your **third** delay is the issue. It means you have up to 10 ms before you notice the need to turn on the light. Try this:

    const byte pin = 13;
    volatile bool detected;

    void setup() {
      pinMode(pin, OUTPUT);
      attachInterrupt(1, blink, RISING);
    }

    void loop() {
      if (detected)
        {
        delay(10);
        digitalWrite(pin, LOW);
        detected = false;
        }

    }

    void blink() {
      digitalWrite(pin, HIGH);
      detected = true;
    }

Now that immediately turns on the LED, so it will always happen at the same time. Then in the main loop you notice it is on, wait 10 ms, and then turn it off.


message:
I'm looking for a real small but decent Arduino, that can fit in a watch but power a servo and a gyroscope

I've been scouring the internet looking for a small Arduino that can power two sensors and a servo. Is there a way of getting a custom one? Does anyone know if theres software out there for creating custom Arduinos and having them made?

body:
Look at the ATtiny85 MCU. It's a small 8pin device, and pretty easy to get up and running using Arduino code. You could also use the ATtiny84 which has more pins and still very small.

Start here: https://code.google.com/p/arduino-tiny/

Also, there are plenty of tutorials on setting up and programming them.

Regarding a custom board, your least expensive route would be to design your own. Otherwise you would need to outsource the design.


body:
No, there is no software specifically for designing custom Arduinos.  However, the Arduino is open source, so you can design your own if you have the skills.

You can download the schematics for your chosen base design from the Arduino website, then use any PCB design software you like to design your own PCB.

You can then send that PCB design off to China (for example) to have it fabricated, and when you get them back you can solder the components on and hope it works.

Of course, designing and building very small circuits well is a talent that few possess. Hand building circuits with the very tiny components you will need to make it fit into a watch is very difficult and normally requires specialist equipment.  That is unless you want your watch to be the size of a dinner plate, like most of the watch kits you can buy.


body: You might look into building a circuit, on a breadboard, from basic components. Think Atmel, AtMega instead of Arduino. Depending on your experience and willingness to read datasheets, this might be easier than you imagine. After you have a large-scale working prototype, find miniature surface-mount versions of all of the components. Designing an actual circuit board to connect these things might be the real trick, but if you can get it done then you can have the board made. I believe, am uncertain about this, that there are software tools available that help turn schematics into circuit board designs. This part might be expensive. Getting to the point of having a large-scale working prototype, on the other hand, would be inexpensive and fun. Once you have a board designed you'll have to get it made. Testing this prototype might be difficult and perhaps expensive as well. (Engineers are paid well because they tend to know before construction if a design will work.) If you come up with something that works then selling the extras might pay for having it made.


message:
How to wirelessly communicate with I2C infrared thermometer

I've been getting involved with arduino recently as a means of improving a heating device which is quite small, a box about 15x10x5cm which I would like to rig with an [MLX90614][1] infrared sensor.

The box is already "wired" with many small flexible tubes, so I would like to set up the sensor so that I can read from it wirelessly, to keep it from getting anymore complicated than it needs to be.

What would be the most compact way to set up a transceiver capable of I2C (ideally with arduino uno coding compatibility) and to then communicate with another arduino? (I already have an Uno to act as the base station)

The reason I mention that the device should be codable with Arduino is that the MLX90614 uses a communication protocol that is beyond my skill level and which I can only operate with open source code libraries for arduino.

I've been doing some research and the best thing I've found so far is the [PanStamp][2], but I have never soldered before, and they are not in business at the moment.

Another limitation is size. I would prefer not to use another entire arduino Uno, with shield.

And of course low cost is a plus :)

So if any of you have worked on something like this before and you have a recommendation, it would be greatly appreciated.

-Ryan

  [1]: http://www.melexis.com/Infrared-Thermometer-Sensors/Infrared-Thermometer-Sensors/MLX90614-615.aspx
  [2]: http://www.panstamp.com/products/

body:
>So if any of you have worked on something like this before and you have a recommendation, it would be greatly appreciated.

See [Solar powered Arduino](http://www.gammon.com.au/forum/?id=12821) - I used a standalone Atmega328P on a prototyping board for that. That used the NRF24L01 to send information (the current voltage in this case) to another Arduino.

For small and simple you could get an [Arduino Nano](https://www.arduino.cc/en/Main/ArduinoBoardNano) or [Arduino Pro Mini](http://www.adafruit.com/products/2378). The Pro Mini is around $US10, and is quite small.

They have the same processor (Atmega328P) so you can connect your I2C sensor to it, and the NRF24L01 as well.

> I have never soldered before ...

I think you will have to do a little soldering, to connect up the sensor, and the transmitter, but soldering on connecting wires isn't too onerous.


message:
Having issues with sending output to WiFi Shield

I am doing simple proof of concept trying to send C++ program output to Adafruit CC3000 WiFi Shield (using Visual Studio 2013 Desktop Edition on Windows 8.1).

In my design laptop is connected to UNO via USB, UNO is connected to WiFi Shield, and WiFi Shield is connected to D-Link router running Adafruit example sketch ("EchoServer"). These connections are working fine.

Next, I am using TCP client sample code from Microsoft for WiFi connectivity with client code running on the laptop to connect to WiFi Shield. Tested this code with sample TCP server code from Microsoft, and client was able to communicate with server code but for some reason this client is not able to find WiFi Shield TCP Server. I get "Unable to connect to server" error with CC3000 continue to show it is listening for connections but never finds one

I am sure it is due to my lack of understanding TCP/networking world. Below is the client code I am running on laptop using Visual Studio:

    #define WIN32_LEAN_AND_MEAN

    #include <windows.h>
    #include <WinSock2.h>
    #include <ws2tcpip.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include<iostream>

    // Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
    #pragma comment (lib, "Ws2_32.lib")
    #pragma comment (lib, "Mswsock.lib")
    #pragma comment (lib, "AdvApi32.lib")

    #define DEFAULT_BUFLEN 512   //Default buffer length of port
    #define DEFAULT_PORT "7"  //Change this to change port

    int main()//int argc, char **argv
    {
     WSADATA wsaData;
     SOCKET ConnectSocket = INVALID_SOCKET;
     struct addrinfo *result = NULL,
      *ptr = NULL,
      hints;
     char *sendbuf = "100";
     char recvbuf[DEFAULT_BUFLEN];
     int iResult;
     int recvbuflen = DEFAULT_BUFLEN;
     /*
     // Validate the parameters - not necessary for use
     if (argc != 2) {
      printf("usage: %s server-name\n", argv[0]);
      system("pause"); return 1;
     }
     */

     // Initialize Winsock
     iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
     if (iResult != 0) {
      printf("WSAStartup failed with error: %d\n", iResult);
      system("pause"); return 1;
     }

     ZeroMemory(&hints, sizeof(hints));
     hints.ai_family = AF_UNSPEC;
     hints.ai_socktype = SOCK_STREAM;
     hints.ai_protocol = IPPROTO_TCP;

     // Resolve the server address and port
     iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
     if (iResult != 0) {
      printf("getaddrinfo failed with error: %d\n", iResult);
      WSACleanup();
      system("pause"); return 1;
     }

     // Attempt to connect to an address until one succeeds
     for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {

      // Create a SOCKET for connecting to server
      ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
       ptr->ai_protocol);
      if (ConnectSocket == INVALID_SOCKET) {
       printf("socket failed with error: %ld\n", WSAGetLastError());
       WSACleanup();
       system("pause"); return 1;
      }

      // Connect to server.
      iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
      if (iResult == SOCKET_ERROR)
      {
       closesocket(ConnectSocket);
       ConnectSocket = INVALID_SOCKET;
       continue;
      }
      break;
     }

     freeaddrinfo(result);

     if (ConnectSocket == INVALID_SOCKET) //If failed to get a socket, end program
     {
      printf("Unable to connect to server!\n");
      WSACleanup();
      system("pause"); return 1;
     }

     // Send an initial buffer
     iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
     if (iResult == SOCKET_ERROR) {
      printf("send failed with error: %d\n", WSAGetLastError());
      closesocket(ConnectSocket);
      WSACleanup();
      system("pause"); return 1;
     }

     printf("Bytes Sent: %ld\n", iResult);

     // Receive until the peer closes the connection
     do {

      iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
      if (iResult > 0)
      {
       printf("Bytes received: %d\n", iResult);
       std::cout << recvbuf << std::endl;
      }
      else if (iResult == 0)
       printf("Connection closed\n");
      else
       printf("recv failed with error: %d\n", WSAGetLastError());

     } while (iResult > 0);
     // shutdown the connection since no more data will be sent
     iResult = shutdown(ConnectSocket, SD_SEND);
     if (iResult == SOCKET_ERROR) {
      printf("shutdown failed with error: %d\n", WSAGetLastError());
      closesocket(ConnectSocket);
      WSACleanup();
      system("pause"); return 1;
     }
     // cleanup
     closesocket(ConnectSocket);
     WSACleanup();
     return 0;
    }

body:
At no point in your program are you telling it where to connect to.  You are requesting service "7", which of course is resolved to port number 7, but you aren't giving it an IP address or host name to connect to.  Ergo, it is trying to connect to port 7 of the same computer that the program is running on - which will fail.

You need to specify the IP address of the WiFi shield as the first parameter to `getaddrinfo()` (currently `NULL`):

> `int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res);`
>
> `node` specifies either a numerical network address (for IPv4, numbers-and-dots notation as supported by `inet_aton(3)`; for IPv6, hexadecimal  string format  as  supported  by  `inet_pton(3)`),  or  a network hostname, whose network addresses are looked up and resolved.  If `hints.ai_flags` contains the `AI_NUMERICHOST` flag, then node must be a numerical network address.  The  `AI_NUMERICHOST`  flag suppresses any potentially lengthy network host address lookups.
>
> If the `AI_PASSIVE` flag is not set in `hints.ai_flags`, then the returned socket addresses will be suitable for use with `connect(2)`, `sendto(2)`, or `sendmsg(2)`.  **If node is `NULL`, then the network address  will  be  set  to  the  loopback  interface address**  (`INADDR_LOOPBACK`  for  IPv4 addresses, `IN6ADDR_LOOPBACK_INIT` for IPv6 address); this is used by applications that intend to communicate with peers running on the same host.
>
> -- Extract from the `getaddrinfo(3)` manual page


message:
Disabling a push button after being under pressure for some time?

I need to disable a button where the user is pressing for a time it is disabled.

Code:

    int ledPin = 13;

    int inPin = 7;

    int val = 0;

    void setup() {

    pinMode(ledPin, OUTPUT);

    pinMode(inPin, INPUT);

    }

    void loop(){

    val = digitalRead(inPin);

    if (val == HIGH) {

    digitalWrite(ledPin, LOW);

    } else {

    digitalWrite(ledPin, HIGH);

    }

    }

body:
    int ledPin = 13;
    int inPin = 7;
    int val = 0;
    int oldVal = 0;

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(inPin, INPUT);
    }

    void loop(){
      val = digitalRead(inPin);
      if (val == HIGH && oldVal == LOW) {
        digitalWrite(ledPin, LOW);
        oldVal = HIGH;
      } else if (val == LOW && oldVal == HIGH) {
        digitalWrite(ledPin, HIGH);
        oldVal = LOW;
      }
    }


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

I think the question is about activating something on a switch push, but only for x seconds. For example, you press a button to sound an alarm, but it stops after 5 seconds.

---

This should do it:

    const byte ledPin = 13;
    const byte inPin = 7;

    const unsigned long MAX_PUSH_TIME = 2000;  // ms
    const unsigned long DEBOUNCE_TIME = 20;    // ms
    unsigned long whenPushed;

    bool switchState;
    bool awaitingRelease;

    void setup()
      {
      pinMode(ledPin, OUTPUT);
      pinMode(inPin, INPUT_PULLUP);
      }  // end of setup

    void switchPushed ()
      {
      // we want them to let go now, ignore it
      if (awaitingRelease)
        return;

      // is LED already on?
      if (digitalRead (ledPin) == HIGH)
        {
        // held for too long? turn off LED, remember it
        if (millis () - whenPushed >= MAX_PUSH_TIME)
          {
          awaitingRelease = true;
          digitalWrite(ledPin, LOW);
          }
        return;  // all done
        }

      // turn LED on, remember when
      digitalWrite(ledPin, HIGH);
      whenPushed = millis ();
      delay (DEBOUNCE_TIME);
      }  // end of switchPushed

    void switchReleased ()
      {
      digitalWrite(ledPin, LOW);
      awaitingRelease = false;  // they released it!
      delay (DEBOUNCE_TIME);
      }  // end of switchReleased

    void loop()
      {
      switchState = digitalRead(inPin);
      if (switchState == LOW)
        switchPushed ();
      else
        switchReleased ();
      }  // end of loop

---

**Note:** I used an input pull-up resistor on the switch to avoid having to use extra components. Thus the switch is wired between pin 7 and **ground**. That is why the test for the switch being pressed is for it to be LOW.

---

## Reference

* [Switches tutorial](http://www.gammon.com.au/switches)


message:
arduino boards manager configuration

I installed the Arduino IDE 1.6.4, and used the "boards manager" to install the package for Arduino Due.

I am using c++11 in my project so i need to add the `compiler.cpp.extra_flags=-std=gnu++11` like i did in the `/Applications/Arduino.app/Contents/Java/hardware/arduino/platform.txt` file (i am on MacOSX).
It seems that arduino is ignoring that file and using a configuration coming from somewhere else.

Where is the downloaded package installed? Can it be configured?

body: Ok, as @IgnacioVazquez-Abrams suggested: the configuration files for the plugins can be found in the Arduino ide preferences directory. Click the menu Arduino->Preferences (under macosx) at the bottom of the window there is the clickable path of the `preferences.txt` file. In the same folder as that file you will find a `packages` folder, where the plugins are downloaded.


message:
ISP - Wrong direction frying ATmega

I tried to flash my ATmega328P-PU not over the Arduino but over a self-made programming board and an USBasp. The problem is, I made the board a while ago and didn't mark which direction the 10-pin connector has to go.

My question is, can I fry the ATmega if I connect the 10-pin connector the wrong way around? Also, can this harm the USBasp in any way?

Connecting it the wrong way around would give me the following connections:

    USBasp  ---  ATmega

    MOSI    -|
    NC      -|-  GND
    RST     -|
    SCK     -|

    MISO    ---  Vcc
    Vcc     ---  MISO

             |-  MOSI
    GND     -|-  NC
             |-  RST
             |-  SCK

body:
No, connecting it backwards shouldn't do any damage, it just won't work.  The clue is in these two connections:

    NC      -|-  GND
    GND     -|-  NC

With it backwards the ground connection doesn't go anywhere.  Without that ground connection there's no circuit.  With no circuit, no current flows.

The only possible danger is to the protection diodes in the IO pins when you try and operate the programmer.  The lack of a ground connection could cause some current to flow the wrong way through the circuit (in through the ATMega's MISO pin and out through the MCU's Vcc pin) through the ESD protection diode.  That could cause damage to that diode and maybe the rest of the MISO pin's logic, but it's not that likely since the currents involved would be somewhat limited by the route the power then takes through the MISO pin of the programmer.


message:
Arduino Mega 2560 R3 with Shield Model Wireless SD R3 not working

Recently I've bought an Arduino Mega 2560 R3 and a Shield Model Wireless SD R3 from http://www.amazon.de/Arduino-A000065-Netzwerkkarte-Wireless-SD-Shield/dp/B00L1FO860. I try to run the example from https://www.arduino.cc/en/Tutorial/ConnectWithWPA

Before running the sketch I turn the DIP switch to the position USB.
It seems like the WIfi Shield is correct connected to the Arduino since the LEDs TX and RX are blinking during upload the Sketch.

Sadly as output I got only:
    WiFi shield not present

Currently I'm not sure if the hardware itself provide Wifi functionality. Does somebody know if it should work with this hardware?

body:
You see that double row of 10 pin headers?  That's an XBee connector.

https://www.sparkfun.com/pages/xbee_guide

You use it to connect your XBee module of choice (there's a few to choose from) to communicate wirelessly between Arduinos using the special XBee system.

Note that XBee is not WiFi, it's Wireless.  The two are very different things (Wireless refers to any wire-free communication system, WiFi is one specific protocol on one specific set of frequencies using a specific set of encodings, etc).  XBee *cannot* talk WiFi in the same way that I can't talk Chinese.

For WiFi you need a WiFi shield.

https://www.arduino.cc/en/Main/ArduinoWiFiShield


message:
Hi-speed external ADC

I would like to detect signals in nanosecond scale. For that, an ADC with at least 500 MSPS is required.

My question is if its possible to use an external ADC with 500 MSPS with a 16MHz Arduino Mega? If not, is there any additional hardware like FIFO buffer to overcome this problem?

Please help, thanks!

body:
No, it's certainly not possible to directly sample at 500Msps on an Arduino using an external ADC.  Simple maths:

* The Arduino can perform 16 million instructions (best case) per second
* The ADC performs 500 million samples per second.
* 500 / 16 = 31.25

Therefore the ADC would be generating 31.25 samples for every clock of the Arduino, so unless you can build in a time compressor (maybe with a flux capacitor too), it just ain't gonna do it.

So you will have to think creatively instead.  A possible solution would involve:

* A high speed *flash* or *pipelined* ADC, ideally with parallel output.
* A large chunk of memory to act as a buffer.
* A high speed clock source to set the timing (500MHz?).
* Glue logic and counters to take one sample, store it in the buffer, and increment the buffer address.
* More glue logic and interfacing to allow the Arduino access to the buffer memory and to control the operation of the sampling system.

This, to me, sounds like a job for an FPGA, and at 500MHz, quite a fast FPGA.  You should investigate some of the FPGA development boards from Xilinx and Altera.


body:
From the Arduino reference on AnalogRead:
"It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate is about 10,000 times a second."

500msps is an awfully high rate - my first instinct is, perhaps you need to revisit what you are after, and why.

There are indeed chips that will do this for you. It is still not possible with an Arduino, since the Arduino can't even receive the data this fast, let alone process it. Assuming 8-bit sampling, this would generate a stream of data at 4gigabits/second - I doubt any disk drive could write that fast (SATA3 is 4.8gbit/sec, which is 20% more, I suspect that the 20% would be eaten up by overhead - you can't just send raw data to a drive, you also have to tell it where to put it. That just accounts for getting the data to the drive circuitry, not actually storing it).

Perhaps what you're looking for is an oscilloscope. An oscilloscope takes high speed readings and displays them. Oscilloscopes are often used for testing circuits (e.g. looking at what an Arduino puts out/reads in when it's being programmed). Looking on National Instruments' websites, their cheapest one I could find that does > 500msps is worth about US$8,000 (ballpark). You will still not be able to store this to disk, or process it in any meaningful way, in realtime - a board like this will typically capture data (based on a trigger, sample until the memory is full, then slowly move the data to the PC to process.


message:
Updating a sketch to work with IDE 1.6.6

I've got a MAX7456 chip and I am using [this (this is the unmodified one)][1] library with it.
There's a sketch inside the examples folder (Max7456WriteTable) that I need to get to work to update the character table.

I modified three lines and then I got really stuck as I do not know how to continue. [This][2] is the modified one.

    In file included from Max7456Write.ino:2:0:
    /tmp/build4608284042510222737.tmp/sketch/Max7456WriteTable.h:29:69153: warning: narrowing conversion of '243' from 'int' to 'const char' inside { } is ill-formed in C++11 [-Wnarrowing]

This happens for every item in the array. But that is not the only problem. (I'll skip a few hundred lines)

    /tmp/build8855411239666100148.tmp/sketch/Max7456Write.cpp.o: In function `setup':
    /home/t/Max7456Write.ino:13: undefined reference to `Max7456::Max7456(unsigned char)'
    /home/t/Max7456Write.ino:19: undefined reference to `Max7456::activateOSD(bool)'
    /home/t/Max7456Write.ino:44: undefined reference to `Max7456::getCARACFromProgMem(char const*, unsigned char, unsigned char*)'
    /home/t/Max7456Write.ino:46: undefined reference to `Max7456::sendCharacter(unsigned char const*, unsigned char, unsigned char)'
    collect2: error: ld returned 1 exit status
    Error compiling.

It takes a huge amount of time for it to abort the compilation.

  [1]: https://www.dropbox.com/s/3cp4am1f271odcm/max7456.tar?dl=1
  [2]: https://www.dropbox.com/s/sljvyngc27zver4/max7456_new.tar?dl=1

body:
If I change `prog_uchar` to `unsigned char` in both max7456.h and max7456.cpp the hello world example sketch compiles.

In Max7456WriteTable change

 Max7456::getCARACFromProgMem(i,currentChar); //Because the table is too big for ram memory

 osd->sendCharacter(currentChar,i); //We send currentChar at address i.

to

 Max7456::getCARACFromProgMem(tableOfAllCharacters, i,currentChar); //Because the table is too big for ram memory

 osd->sendCharacter(currentChar,i, 0); //We send currentChar at address i.

`0` is probably the wrong value, but at least it compiles.


message:
Better method for PROGMEM data access with multiple indirection?

-edit-
This is a simplified recreation of personal learning project I have ongoing.  My issue is in accessing data in flash, the path to which includes multiple layers of indirection.  When the data was in RAM I found accessing it easy and all worked as expected.

In flash I have created a struct mylist, aa in the example, containing a pointer to an char* array (item_list[ ])(in flash) pointing to char[ ] (in flash).

Problem: (refer to example) Given a pointer to struct aa (pml) and an index into item_list[] (ndx), how to correctly retrieve the string from flash.  My example illustrates the only method I can find that works. It seems kludgy at best, in particular needing to twice read pointers from flash as well as calculating the array item offset.  Have I missed a proper cast or perhaps become confused about 32 vs 16 bit pointers? Or, as strange as it seems, is this the correct and/or best approach?

All help and constructive criticism will be appreciated.

Code:

<!-- language: c -->

    #include "Arduino.h"
    #include <avr/pgmspace.h>

    const char x[] PROGMEM = {"Item x"};
    const char y[] PROGMEM = {"Item y"};
    const char* const item_list[] PROGMEM = {x, y};

    struct mylist {
      uint8_t nitems;
      const char** const list;
    };
    const mylist aa PROGMEM = {2,(const char** const)item_list};

    const mylist* pml = &aa;

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

      char cbuf[11] = {"__________"};

      // two line with declared intermediate pointer
      uint8_t ndx = 0;
      const char* pitem = (const char*)pgm_read_ptr_near(&pml->list) + (ndx * sizeof(const char*));
      strcpy_P(cbuf, (const char*)pgm_read_ptr_near(pitem));
      Serial.print("item[0]: /");
      Serial.print(cbuf);
      Serial.println("/");

      // one line without declared intermediate pointer
      ndx++;
      strcpy_P(cbuf, (const char*)pgm_read_ptr_near(pgm_read_ptr_near(&pml->list)
                                                    + (ndx * sizeof(const char*))));
      Serial.print("item[1]: /");
      Serial.print(cbuf);
      Serial.println("/");
    }

    void loop() {
      // put your main code here, to run repeatedly:

    }

Output:

    item[0]: /Item x/
    item[1]: /Item y/

-edit-

After many more hours trying many more variations, I feel the approach shown in the following example is workable for me. I have chosen to keep the extra level of indirection to maintain all the flash data for a particular Field in one struct ‘package’. @NickGammon and his excellent examples greatly helped my understanding and comfort level with pointers in and to flash.

The listing is meant to give context to my point in question and is summarized in the method _copyitem( ) (hope the underscore is ok):

    void Field::_copyitem(uint8_t ndx){
      PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
      PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
      strlcpy_P(_value, pitem, getLength());
    }

This listing recreates a very small subset of the overall codebase, but the one part that has stopped my progress.

    #include "Arduino.h"
    #include <avr/pgmspace.h>

    struct FieldDefinition {
      uint8_t nitems;
      const char** list;
      uint8_t row;
      uint8_t column;
      uint8_t length;
      // etc, etc
    };

    class Field {
    public:
      Field(const FieldDefinition*  /* other parameters */);
      ~Field();  // -edit-
      char * selectItem(uint8_t);
      uint8_t getLength();
      char * selectItem(uint8_t);
      uint8_t getLength();
    private:
      const FieldDefinition * _fp;
      char * _value;
      uint8_t _ndx;
      void _copyitem(uint8_t);
    };

    Field::Field(const FieldDefinition* fp ) : _fp(fp) {
      _ndx = 0;
      char * _value = new char[getLength()];
     _copyitem(_ndx);
    };
    Field::~Field(){  // -edit-
      delete _value;
    };
    char * Field::selectItem(uint8_t ndx){
      _ndx = ndx;
      _copyitem(_ndx);
      // display item
      // do more here . . .
     return _value;
    }
    uint8_t Field::getLength(){
      return pgm_read_byte(&_fp->length);
    }
    void Field::_copyitem(uint8_t ndx){
      PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
      PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
      strlcpy_P(_value, pitem, getLength());
    }

    // Setup flash data
    // selection list
    const char f1_0[] PROGMEM = {"Item 0"};
    const char f1_1[] PROGMEM = {"Item 1"};
    const char f1_2[] PROGMEM = {"Item 2"};
    const char* const f1_list[] PROGMEM = {f1_0, f1_1, f1_2};
    // create in-flash struct
    const FieldDefinition f1 PROGMEM = {4,(const char**)f1_list,1,1,10};
    // global instance and pointer to Field
    Field * s1f1 = new Field(&f1);

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

      Serial.println();
      Serial.print("Field Length: ");
      Serial.println(s1f1->getLength());
      Serial.println();
      for (uint8_t i = 0 ; i < 3; i++) {
        Serial.print("Selection at index ");
        Serial.print(i); Serial.print(" : ");
        Serial.println(s1f1->selectItem(i));
      }
    }

    void loop() {
      // put your main code here, to run repeatedly:

    }

Output

    Field Length: 10

    Selection at index 0 : Item 0
    Selection at index 1 : Item 1
    Selection at index 2 : Item 2

I could very wrong (as previously demonstrated) so comments please.

-edit-

Point taken and completely understood.  Destructor added for completeness.  In my actual application, multiple fields are constructed by a screen class when a screen is displayed, user interaction accepted, configuration data stored in EEPROM (my next endeavor), then destroyed on screen exit. Selecting from a list is one method available to populate the field value. The whole interface consists of multiple fields, for multiple screens, driven by an underlying state engine, stepped during each ‘loop’ to minimize impact. It functions as expected in an Xcode simulation, and has been a wonderful learning experience moving it to Arduino.  I thought all this was non sequitur to my question and regret any confusion I may have caused.

To restate my issue: how to get from

    // ram based
    strcpy(value, _fp->list[ndx]);

to

    // flash based
    PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
    PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
    strcpy_P(value, pitem);

using best/correct form with multiple layers of indirection as posted. Is it possible I have missed a proper cast or other mechanism that would allow the compiler to handle the ‘pointer magic’? It appears I have not. @NickGammon I greatly appreciate your input.

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

    const char x[] PROGMEM = {"Item x"};
    const char y[] PROGMEM = {"Item y"};
    const char* const item_list[] PROGMEM = {x, y};

    struct mylist {
      uint8_t nitems;
      const char** const list;
    };
    const mylist aa PROGMEM = {2,(const char** const)item_list};

It seems to me this is way too wordy for what appears to be trying to store a list of a couple of strings.

---

First:

    const char* const item_list[] PROGMEM = {x, y};

You have a array of pointers to strings. OK.

---

Now:

    struct mylist {
      uint8_t nitems;
      const char** const list;
    };
    const mylist aa PROGMEM = {2,(const char** const)item_list};

Now you have a *list* of an *array*? This is where I am confused.

---

Compare to an adaptation of the code on [Putting constant data into program memory (PROGMEM)](http://www.gammon.com.au/progmem):

    const int NUMBER_OF_ELEMENTS = 2;

    const char Message0000 [] PROGMEM = "Item X";
    const char Message0001 [] PROGMEM = "Item Y";

    const char * const messages[NUMBER_OF_ELEMENTS] PROGMEM =
       {
       Message0000,
       Message0001,
       };

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

      for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
        {
        char * ptr = (char *) pgm_read_word (&messages [i]);
        char buffer [80]; // must be large enough!
        strcpy_P (buffer, ptr);
        Serial.println (buffer);
        }   // end of for loop

      }  // end of setup

    void loop () { }

---

## Edited to comment on new code

You have a major problem here:

    Field::Field(const FieldDefinition* fp ) : _fp(fp) {
      _ndx = 0;
      char * _value = new char[getLength()];
     _copyitem(_ndx);
    };
    char * Field::selectItem(uint8_t ndx){
      _ndx = ndx;
      _copyitem(_ndx);
      // display item
      // do more here . . .
     return _value;
    }
    uint8_t Field::getLength(){
      return pgm_read_byte(&_fp->length);
    }
    void Field::_copyitem(uint8_t ndx){
      PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
      PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
      strlcpy_P(_value, pitem, getLength());
    }

What I gather you are doing here is, to get the string for an item (for printing) doing a `new` (which allocates memory), copying from PROGMEM into that memory, displaying that item, and then ignoring the allocated memory. Well, you can't do that. You will run out of RAM very quickly.

The code doesn't even have the word `delete` in it. Every `new` should have a corresponding `delete`. It's a fundamental principle.

It looks too complex still. Make a function that just displays the item (menu or whatever it is) without actually making a copy of it. Certainly don't allocate memory and not free it.


message:
LininoIO running "partially"

I installed LininoIO (OS dated 02 06 2015).

Everything seems to work fine - but nothing works as expected.

I have a running Linux - but when I try to use GPIO, as described on Lilino.org -[GPIO on lininoIO][1], I run into the first problems.

D13 doesn't exist (this should be the little red LED on board of the Yún).

Next I tested reading the analog inputs.

I can for example use `cat /sys/bus/iio/devices/iio:device0/in_voltage_A0_raw`. There are no errors, but I always get the value `0`.

Checking with `/etc/linino/test_avrdude.sh` shows:

    Testing AVRDUDE on ATMEL 32U4 ...

    avrdude: Version 6.1-20140519, compiled on Jun  2 2015 at 12:34:59
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "/etc/avrdude.conf"
             User configuration file is "/root/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : unknown
             Using Programmer              : linuxgpio
    Can't export GPIO 11, already exported/busy?: Device or resource busy
    avrdude done.  Thank you.

Maybe this is "by design" or another sign of an error.

By the way - when I start a serial console I get the message:

    avr-uart: switched to uart mode: mcuio

Further in kernel log I found:

    [   42.480000] fuse init (API version 7.18)
    [   42.620000] spi_tty_plain spi1.0: spi_tty_probe
    [   45.380000] No need to change console settings
    [   49.550000] mcuio-hc 0:0.0: unexpected reply
    [   49.600000] gpiochip_add: registered GPIOs 100 to 139 on device: generic
    [   49.630000] mcuio adc is 0:1:1
    [   49.750000] mcuio-adc 0:1.1: 6 input channels detected
    [   49.910000] mcuio-hc 0:0.0: unexpected reply
    [   49.970000] mcuio pwm is 0:1:2
    [   49.970000] mcuio-pwm 0:1.2: 6 pwm outputs detected
    [   55.790000] busybox: sending ioctl 5310 to a partition!
    [   55.800000] busybox: sending ioctl 5310 to a partition!
    [   55.820000] busybox: sending ioctl 5310 to a partition!
    [   55.830000] busybox: sending ioctl 5310 to a partition!
    [   56.290000] EXT4-fs (sda2): couldn't mount as ext3 due to feature incompatibilities
    [   56.310000] EXT4-fs (sda2): couldn't mount as ext2 due to feature incompatibilities
    [   56.360000] EXT4-fs (sda2): mounted filesystem with ordered data mode. Opts: (null)
    [   58.520000] cfg80211: Calling CRDA for country: AT

It seems as if there are problems with `mcuio-hc`.

Last thing - when I ran `run-avrdude /etc/linino/bathos-one.hex`
I get an error when comparing the written data (I found information that this can be ignored).

How can I fix this / find out what to fix / what's going wrong?

  [1]: http://wiki.linino.org/doku.php?id=wiki:lininoio_sysfs

body:
finally I got it (somehow) working.
After a reset and another run of run-avrdude /etc/linino/bathos-yun.hex (the first was a mistake by copy and past - not bathos-one I already ran bathos-yun before) and a reboot again I was able to read analog IO.

But still the digitals were missing.
Than I found the command gpioexport an ran it.
After that the correct entries (D13, D14...) were present in sys/class...

But an echo out > D13/direction resulted in a timeout error message.
Again reboot - again the Dxxx entries were gone.
Another gpioexport made them appear again.

And this time not timeouts - instead I could turn on / of D13 (for test).

I guess all I have to do to make the things better is include gpioexport in "startup code" so that it runs after a reboot.


body:
Have a look at the schematics of the YUN https://www.arduino.cc/en/uploads/Main/arduino-Yun-schematic.pdf

You will notice that most of the GPIO pins on the Atheros is not available to you. You only have access to the GPIO pins of the atmega.


body:
LininoIO has a part which runs on the microcontroller and make the Atheros enable to use the mcu pinout as linux gpios. So you are right, you need to flash the bathos to the mcu.

In general to enable/disable lininoIO run:

    > lininoio start
    > lininoio stop

those commands do everything for you.
have also a look [here][2]

Anyway your Linino version seems old, try to upgrade it: http://www.arduino.org/learning/tutorials/advanced-guides/how-to-upgrade-the-linino-distribution-for-arduino-yun-and-yun-mini

  [1]: http://www.arduino.org/learning/tutorials/advanced-guides/linino-gpio-configuration
  [2]: http://www.arduino.org/learning/tutorials/advanced-guides/how-to-pilot-gpio-on-lininoio-2


message:
Getting values from multiple thermistors - one value glitches all over the place

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

  [1]: https://i.stack.imgur.com/xNSRT.png
I have a circuit with preferably long wires that get data from thermistors. The Arduino sends this data (formatted in JSON) to a web server where it can be collected by another program.
Some of these values appear correct, while others do not.

    [
    {
        "dht11": {
            "temperature": 73.4,
            "humidity": 41,
            "heat-index": 77.15
        },
        "thermistors": {
            "therm1": {
                "temp": 71.21,
                "resistance": 12727.27
            },
            "therm2": {
                "temp": 76.22,
                "resistance": 12045.51
            },
            "therm3": {
                "temp": nan,
                "resistance": -19393.41
            }
        }
    }
    ]
code:

    #define THERMISTORPIN A0
    #define THERMISTORNOMINAL 10000
    #define TEMPERATURENOMINAL 25
    #define NUMSAMPLES 25
    #define BCOEFFICIENT 4050
    #define SERIESRESISTOR 10000
    #define THERMISTORPIN2 A5
    #define THERMISTORPIN3 A3
    #define DHTPIN 2
    #define PHOTORESISTOR 3
    #define DHTTYPE DHT11
    int samples[NUMSAMPLES];
    int samples_two[NUMSAMPLES];
    int samples_three[NUMSAMPLES];
    int stuckintime;
    #include <SPI.h>
    #include <Ethernet.h>
    #include "DHT.h"
    byte mac[] = {
      0x00, 0x00, 0x00, 0x00, 0x00, 0xEE
    };
    IPAddress ip(192, 168, 1, 3);
    EthernetServer server(80);
    DHT dht(DHTPIN, DHTTYPE);
    void setup() {
      Serial.begin(9600);
      Ethernet.begin(mac, ip);
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());
      dht.begin();
      analogReference(EXTERNAL);
    }

    void loop() {
      uint8_t i;
              float average;
              float average_two;
              float average_three;
              float stuckintime;
              for (i = 0; i < NUMSAMPLES; i++) {
                samples[i] = analogRead(THERMISTORPIN);
                samples_two[i] = analogRead(THERMISTORPIN2);
                samples_three[i] = analogRead(THERMISTORPIN3);
                delay(10);
              }
              for (i = 0; i < NUMSAMPLES; i++) {
                average += samples[i];
                average_two += samples_two[i];
                average_three += samples_three[i];
              }
              average /= NUMSAMPLES;
              average = 1023 / average - 1;
              average = SERIESRESISTOR / average;
              float tempreading;
              tempreading = average / 10975;
              tempreading = log(tempreading);
              tempreading /= BCOEFFICIENT;
              tempreading += 1.0 / (TEMPERATURENOMINAL + 273.15);
              tempreading = 1.0 / tempreading;
              tempreading -= 273.15;
              tempreading = tempreading * 9 / 5 + 32;
              average_two /= NUMSAMPLES;
              average_two = 1023 / average_two - 1;
              average_two = SERIESRESISTOR / average_two;
              average_two = average_two;
              float tempreadtwo;
              tempreadtwo = average_two / 11811;
              tempreadtwo = log(tempreadtwo);
              tempreadtwo /= BCOEFFICIENT;
              tempreadtwo += 1.0 / (TEMPERATURENOMINAL + 273.15);
              tempreadtwo = 1.0 / tempreadtwo;
              tempreadtwo -= 273.15;
              tempreadtwo = tempreadtwo * 9 / 5 + 32;
              average_three /= NUMSAMPLES;
              average_three = 1023 / average_three - 1;
              average_three = SERIESRESISTOR / average_three;
              float tempreadthree;
              tempreadthree = average_three / THERMISTORNOMINAL;
              tempreadthree = log(tempreadthree);
              tempreadthree /= BCOEFFICIENT;
              tempreadthree += 1.0 / (TEMPERATURENOMINAL + 273.15);
              tempreadthree = 1.0 / tempreadthree;
              tempreadthree -= 273.15;
              tempreadthree = tempreadthree * 9 / 5 + 32;
              float h = dht.readHumidity();
              float t = dht.readTemperature();
              float f = dht.readTemperature(true);
              float hif = dht.computeHeatIndex(f, h);
      EthernetClient client = server.available();
      if (client) {
        boolean currentLineIsBlank = true;
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();
            if (c == '\n' && currentLineIsBlank) {
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: application/json");
              client.println("Connection: close");
              client.println("Refresh: 0");
              client.println("");
        client.println("[");
        client.println("   {");
        client.println("    \"dht11\": {");
        client.print("          \"temperature\": ");  client.print(f);   client.println(",");
              client.print("          \"humidity\": ");   client.print(h);   client.println(",");
        client.print("          \"heat-index\": ");  client.print(hif);  client.println("");
        client.println("     },");
        client.println("    \"thermistors\": {");
        client.println("        \"under-bed\": {");
           client.print("             \"temp\": ");    client.print(tempreading);   client.println(",");
        client.print("             \"resistance\": ");  client.print(average);  client.println("");
        client.println("       },");
        client.println("        \"side-bed\": {");
        client.print("             \"temp\": ");    client.print(tempreadtwo);   client.println(",");
           client.print("             \"resistance\": ");  client.print(average_two);  client.println("");
        client.println("       },");
        client.println("        \"top-bed\": {");
        client.print("             \"temp\": ");    client.print(tempreadthree);   client.println(",");
           client.print("             \"resistance\": ");  client.print(average_three);  client.println("");
        client.println("       }");
        client.println("     }");
        client.println("   }");
        client.println("]");
              break;
            }
            if (c == '\n') {
              currentLineIsBlank = true;
            }
            else if (c != '\r') {
              currentLineIsBlank = false;
            }
          }
        }
        delay(1);
        client.stop();
      }
    }

I have no idea what is causing this to happen - pushing RESET doesn't fix it at all, reconnecting wires does not fix it, any help?
(Please tell me what else to include if you need it.)

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

Here's a major problem:

    void loop() {

      uint8_t i;
              float average;
              float average_two;
              float average_three;
              float stuckintime;
              for (i = 0; i < NUMSAMPLES; i++) {
                samples[i] = analogRead(THERMISTORPIN);
                samples_two[i] = analogRead(THERMISTORPIN2);
                samples_three[i] = analogRead(THERMISTORPIN3);
                delay(10);
              }
              for (i = 0; i < NUMSAMPLES; i++) {
                average += samples[i];
                average_two += samples_two[i];
                average_three += samples_three[i];
              }

The variables *average*, *average_two*, and *average_three* have **undefined** values. Thus it isn't surprising that when you add something to them, they are still undefined.

Local variables must be initialized (eg. to zero in your case).

Also, you have two variables named *stuckintime* - I would do something about that.


message:
Reducing read time for reading DS18B20 temp sensors

I have a number of temperature sensors connected up to an Arduino - I've split it into 3 sections, with each section having a 2-4 sensors on it (due to distances).   This works, but the code I'm using would seem to me to be very inefficient - particularly with respect of how long it takes to read all the sensors.

I've got 3 code blocks one after each other (which are modified from some code online) which look as below - save, of-course, for the name of the 1wire class.

    // Dallas 1 Wire (Main Area):

     //  ds.reset_search();
     //  delay(250);
      while (ds.search(addr))
      {
        for( i = 0; i < 8; i++) {
          Serial.print(addr[i], HEX);
        }

        if (OneWire::crc8(addr, 7) != addr[7]) {
            Serial.println("CRC is not valid!");
            return;
        }

        ds.reset();
        ds.select(addr);
        ds.write(0x44, 0);        // start conversion, with parasite power on at the end

        delay(1000);     // maybe 750ms is enough, maybe not
        // we might do a ds.depower() here, but the reset will take care of it.

        present = ds.reset();
        ds.select(addr);
        ds.write(0xBE);         // Read Scratchpad

        for ( i = 0; i < 9; i++) {           // we need 9 bytes
          data[i] = ds.read();
        }
        raw = (data[1] << 8) | data[0];
        if (type_s) {
          raw = raw << 3; // 9 bit resolution default
          if (data[7] == 0x10) {
            // "count remain" gives full 12 bit resolution
            raw = (raw & 0xFFF0) + 12 - data[6];
          }
        } else {
          byte cfg = (data[4] & 0x60);
          // at lower res, the low bits are undefined, so let's zero them
          if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
          else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
          else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
          //// default is 12 bit resolution, 750 ms conversion time
        }
        celsius = (float)raw / 16.0;
        Serial.print(":");
        Serial.print(celsius);
        Serial.print(",");
      }

I note that there is a 1000ms delay after each sensor is read, and I'm wondering if I can reduce this to a single 750ms delay for all the sensors.  My initial attempts to do this did not meet with success - but I confess that I can't quite get my head around the ds.reset, ds.select etc - and my initial attempts to do this have all failed.

Is it possible to remove this delay after reading each sensor ?

body:
Doing a search every time is quite inefficient. The search function is for if you don't know the device address - and it takes a while to do. In your case, presumably the addresses will never change. Find the addresses and hard-code them into your code. Or if that isn't practical, store them in EEPROM. And if even that isn't practical find the addresses once in setup.

---

Next, you need a delay while you take the temperature readings. Why not parallel those up? In a loop, tell all the devices to take a reading. Then wait one second. Then read them all (in another loop). That way the one-second delay is shared between all your sensors.

However from [the page Gerben linked](http://milesburton.com/Main_Page?title=Dallas_Temperature_Control_Library):

> And it is NOT possible to run DS1820 sensors on a simple pull-up resistor. During the "Conversion" phase, it needs more power. And there are Application Note discussing this in length.

That suggest that if you are using parasitic power, my suggestion won't work too well (having multiple devices taking readings would make it worse).

---

I found this code on my disk from a couple of years ago. There don't seem to be any delays between reading sensors. There is a delay at the end of the main loop, mainly to stop spamming the serial monitor.

Notice the comment:

> Call sensors.requestTemperatures() to issue a global temperature request to all devices on the bus

See if that works for you.

    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include <Streaming.h>

    // Data wire is plugged into port 10 on the Arduino
    const byte ONE_WIRE_BUS = 10;
    const byte TEMPERATURE_PRECISION = 10;
    // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
    OneWire oneWire(ONE_WIRE_BUS);

    // Pass our oneWire reference to Dallas Temperature.
    DallasTemperature sensors(&oneWire);

    // arrays to hold device addresses
    DeviceAddress myThermometer [10];
    int deviceCount;

    void setup(void)
    {

      // start serial port
      Serial.begin (115200);
      Serial << "Dallas Temperature IC Control Library Demo" << endl;

      // Start up the library
      sensors.begin();

      // locate devices on the bus
      Serial << "Locating devices..." << endl;
      deviceCount = sensors.getDeviceCount();

      Serial << "Found " << deviceCount << " devices." << endl;

      // report parasite power requirements
      Serial << "Parasite power is: " << (sensors.isParasitePowerMode() ? "ON" : "OFF") << endl;

      // method 1: by index

      for (int i = 0; i < deviceCount; i++)
      {
        if (sensors.getAddress(myThermometer [i], i))
        {
          Serial << "Device " << i << " Address: ";
          printAddress(myThermometer [i]);
          Serial << endl;
          sensors.setResolution(myThermometer [i], TEMPERATURE_PRECISION);
        }
        else
          Serial << "Unable to find address for Device " << i << endl;
      }  // end of for loop

    }

    // function to print a device address
    void printAddress(DeviceAddress deviceAddress)
    {
      for (uint8_t i = 0; i < 8; i++)
      {
        // zero pad the address if necessary
        if (deviceAddress[i] < 16) Serial.print("0");
        Serial.print(deviceAddress[i], HEX);
      }
    }

    void loop(void)
    {

      // call sensors.requestTemperatures() to issue a global temperature
      // request to all devices on the bus
      sensors.requestTemperatures();

      // now get all temperatures
      for (int i = 0; i < deviceCount; i++)
      {
        float tempC = sensors.getTempC(myThermometer [i]);
        if (tempC > -80)
        {
          Serial << "Device " << i << " Temperature: " << tempC << endl;
        }
        else
          Serial << "Unable to find temperature for Device " << i << endl;
      }  // end of for loop

      delay (1000);
    }


body:
After nearly a year and a number of experiments later, I've learned a little bit more about using these devices:

Issuing the sensors a Skip ROM command followed by Convert T command starts all devices converting temperature at once (pg.11 of the datasheet). Then you need only wait one delay period of {750,375,188,94}ms for a {12,11,10,9}-bit conversion, respectively, before you can start reading back the temperatures.

If the devices are being powered parasitically, the bus will need a strong pullup during the conversion; the 4.7KOhm pullup is not sufficient (pg.5 of the datasheet).

An arduino pin can source 40mA and I've found that a second pin directly bypassing the 4.7K pullup without the suggested transistor, will source enough current for at least 3 sensors (as many as I've tried so far) and I assume the technique could be extended to more pins. The strong pullup must be switched on within 10uSec after the Convert T command and kept on for the duration of the conversion. The 10uSec spec pretty much means you have to do this in the library.

I keep an abbreviated DS18B20 library around in which I assume the sensors on the bus are related, so it sets all of their resolutions at once and starts their conversions at once, and assumes that the bus is parasite-powered, which mine are, so it switches a specified pin as a strong pullup. I give up some flexibility that the full DSTemperature library would allow but it satisfies my temperature measuring requirements (so far) and simplifies my application code by black-boxing the above techniques.


body:
In case the "Temperature Conversion Time (tCONV)" of each resolution is not fast enough ([MAX] 9-bit: 93.75ms; 10-bit: 187.5ms; 11-bit resolution: 375ms; 12-bit: 750ms), you can use more sensors.

For example, to get a half time (for 9-bit): 47ms:
- You can use two sensors at the same measurement point, (they can operate in parallel , as long as the software can operate with each one of them) when reading one, the software starts converting the other.

Each one has its normal conversion time, but when doing the readings in an interleaved way, a shorter reading time can be obtained.

For 8 sensors, a time below 11.75ms can be achieved (for 9-bit).


message:
Arduino ,How I can see the value (0 or 5) on my screen, where I connected my sensors output to analog input A0,A1.. pins

I am working in my project and I want to see the output of my sensors as (0 or 5).
The maximum read was 770 and the minimum read was 0. So, how can I see the  value (0 or 5) on my screen, where I connected my sensors output to analog input A0, A1 pins.
I did the following code, but it didn't work:

<!-- language: c -->

    void setup(){
    Serial.begin(9600);
    }
    void loop()
    {
    if (analogRead(0)<385)
          Serial.print("0");
     else
          Serial.print("5");
          Serial.print('  ');

    if (analogRead(1)<385)
          Serial.print("0");
       else
          Serial.print("5");
          Serial.print('  ');

    if (analogRead(2)<385)
          Serial.print("0");
      else
          Serial.print("5");
          Serial.print('  ');

    if (analogRead(3)<385)
          Serial.print("0");
      else
          Serial.print("5");
          Serial.print('  ');

    if (analogRead(4)<385)
          Serial.print("0");
      else
          Serial.print("5");
          Serial.print('  ');

    if (analogRead(5)<385)
          Serial.print("0");
      else
          Serial.print("5");
          Serial.print('  ');

    delay(1500);
    }

Note: I have 5 light sensors in my circuit.

body: You can use DigitaRead command instead of analogread. It will give result in only 1 or 0. Hopefully this will help you.


body:
Try this code - it should help you see what is going on more clearly:

    const int threshold = 385;

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

    void loop()
    {
      int reading = analogRead(0);
      Serial.print("Analog 0 reads ");
      Serial.print(reading);
      Serial.print(" - this maps to ");
      if (reading < threshold){
        Serial.println("0");
      } else {
        Serial.println("5");
      }

      reading = analogRead(1);
      Serial.print("Analog 1 reads ");
      Serial.print(reading);
      Serial.print(" - this maps to ");
      if (reading < threshold){
        Serial.println("0");
      } else {
        Serial.println("5");
      }

      reading = analogRead(2);
      Serial.print("Analog 2 reads ");
      Serial.print(reading);
      Serial.print(" - this maps to ");
      if (reading < threshold){
        Serial.println("0");
      } else {
        Serial.println("5");
      }

      reading = analogRead(3);
      Serial.print("Analog 3 reads ");
      Serial.print(reading);
      Serial.print(" - this maps to ");
      if (reading < threshold){
        Serial.println("0");
      } else {
        Serial.println("5");
      }

      reading = analogRead(4);
      Serial.print("Analog 4 reads ");
      Serial.print(reading);
      Serial.print(" - this maps to ");
      if (reading < threshold){
        Serial.println("0");
      } else {
        Serial.println("5");
      }

      reading = analogRead(5);
      Serial.print("Analog 5 reads ");
      Serial.print(reading);
      Serial.print(" - this maps to ");
      if (reading < threshold){
        Serial.println("0");
      } else {
        Serial.println("5");
      }

      Serial.println();

      delay(1500);
    }


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

Your code has multiple issues.

    if (analogRead(1)<385)
          Serial.print("0");
       else
          Serial.print("5");
          Serial.print('  ');

Note that `Serial.print('  ');` is not at all the same as `Serial.print("  ");`

---

Also, by the indentation it looks like you should be using braces. Amended code:

    if (analogRead(1)<385)
          Serial.print("0");
       else
          {
          Serial.print("5");
          Serial.print("  ");
          }

Without the braces only the first statement after the *else* is conditionally executed.

If I am wrong about that, you should indent differently, eg.

    if (analogRead(1)<385)
          Serial.print("0");
       else
          Serial.print("5");
    Serial.print("  ");


message:
Why does the standard Arduino IDE not include the CH341G USB Drivers?

Can anyone explain why the standard Arduino IDE 1.6 distribution does not include support for the popular CH341G USB/serial drivers?

I am using these USB/serial chips in several teaching projects for CoderDojo and it is somewhat difficult to have each student download the drivers and reboot their PCs for each class. It seems like both Mac and PC users would benefit from having these drivers loaded directly into the standard Arduino IDE.

Is there possibly some security concern? I know that the latest Mac requires that the drivers are digitally signed. In fact for many modern Macs to use the drivers we have to disable the digital signature checks.

Here is the link to [the official drivers][1].

Here is [a good article][2] on how to download the drivers.

BTW, the command to disable the digital signature check on the mac we need to do the following:

In the Mac "Terminal" application enter:

    sudo nvram boot-args="kext-dev-mode=1"

Then we must reboot the mac. Then when we want to re-enable the checks change the 1 to 0:

    sudo nvram boot-args="kext-dev-mode=0"

If we don't do this command, the Arduino App will not show the serial ports. Do to this go to Tools -> Port Menu within the Arduino application.

    /dev/tty.SerialPort
    /dev/cu.SerialPort

I should mention that the CH340G are also used in many "Arduino Nano" clones from China. Perhaps that is why the drivers are not included?

Tags: Driver CH340 Setup Installation

  [1]: http://www.wch.cn/download/CH341SER_MAC_ZIP.html
  [2]: http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

body:
This is simply because the CH340G is not supported officially. The Arduino IDE is meant primarily for genuine Arduinos.

What you could do is repackage the Arduino zip file with the required library and create a basic script file to install the drivers with just a couple of clicks.

Or you could shift to another board that uses the ATMEGA32u4 as this **might** not require anything special. Have a look [here](http://www.aliexpress.com/item/Mini-Leonardo-Pro-Micro-ATmega32U4-5V-16MHz-Module-For-Arduino-Best-Quality/32284746884.html). I don't have tested this board so you will need to check the quality and whether it works with your projects.


body:
> I should mention that the CH340G are also used in many "Arduino Nano" clones from China.

I believe that the Arduino company already has concerns about the number of unofficial clones (many pretending to be genuine) and have lost a considerable amount of revenue to those knock-off products.

I imagine they are not going to make things worse for themselves by including drivers for unofficial boards, so that the job of the clone-makers is even easier.


message:
Arduino in Eclipse IDE: How to add SPI library (core library already added)?

I want to use eclipse for arduino programming, so I followed the guides to set up a static project for the arduino core library. Then I added the library file (.a) and the .h and .cpp files to my new project in the settings.
So far, so good.
But now I am trying to add the SPI library to my project without success (I only have the .h and .cpp files, **no** .a)!

My sample code

    #include <Arduino.h>
    #include <SPI.h>

    int main(void) {
        init();
        pinMode(13, OUTPUT);
        for (;;) {
         digitalWrite(13,1);
         SPI.setBitOrder(0);
        }
    }

The pinMode and digitalWrite parts work, but with the SPI method I get an error:

    05:33:26 **** Build of configuration Debug for project ArduinoTestProject ****
    make all
    Building file: ../main.cpp
    Invoking: AVR C++ Compiler
    avr-g++ -I/home/fabio/Workspace/arduinoLIB/SPI -I/home/fabio/Workspace/arduinoCORE -Wall -g2 -gstabs -Os -ffunction-sections -fdata-sections -fno-exceptions -mmcu=atmega328p -DF_CPU=16000000UL -MMD -MP -MF"main.d" -MT"main.d" -c -o "main.o" "../main.cpp"
    Finished building: ../main.cpp

    Building target: ArduinoTestProject.elf
    Invoking: AVR C++ Linker
    avr-gcc -s -Os -o"ArduinoTestProject.elf"  ./main.o   -l"arduinoUNO" -l"m" -lm -Wl,-Map,ArduinoTestProject.map,--cref -mrelax -Wl,--gc-sections -L/home/fabio/Workspace/arduinoCORE/lib -mmcu=atmega328p; avr-nm -C -n "ArduinoTestProject.elf" >ArduinoTestProject.symbol
    ./main.o: In function `main':
    ../main.cpp:38: undefined reference to `SPIClass::setBitOrder(unsigned char)'
    collect2: error: ld returned 1 exit status
    avr-nm: 'ArduinoTestProject.elf': No such file
    make: *** [ArduinoTestProject.elf] Error 1

    05:33:26 Build Finished (took 72ms)

Does anyone see the problem?

body:
As far as I understand you are using eclipse CDT directly. (I mean you are not using an "arduino eclipse plugin" that does the stuff below for you)

The first thing to understand is that a arduino library is not treated as a library when compiling a arduino sketch.

In other words in the Arduino IDE, a arduino library is compiled like standard source code just like your .ino files.

As such there is no SPI.a file created during the compilation process.
In CDT you can have both options (with or  without .a file) but the Arduino IDE way is the easiest, by far.

So lets first assume you want to compile the "Arduino way" aka without SPI.a.
What you need to do is simply drag and drop the files in your project. If you want to drop in a subfolder (like libraries/SPI) you will need to add those folders to your include path.
That is all there is to it.

If you want to treat the library as a real library (saying you want a SPI.a) the best thing I can think of is to create a new library project for each sketch-project . Drag and drop the SPI code in that project (like above) and make your project dependent on the library project. There are probably some include path issues but the .a file should be found and included in the build

Note that the second approach makes that you will need a SPI project for each and every (arduino) board you have. If you want to use project defines it is even more difficult.

I would strongly advise to start your arduino eclipse development with [my arduino eclipse plugin][1] because it is simply easier. Later you can evolve to the full freedom of CDT.

If you want to drag and drop folders instead of the .h and .cpp files you will have to add exclusion rules to your include path. This because otherwise all the examples of the library will be in your project making you have multiple setup and loop functions.

  [1]: http://eclipse.baeyens.it


message:
How to measure the state of charge of a battery in arduino

This questions has been formulated several times with not clear answer, and I wonder if there is one.

it is well stablished from several sources that measuring the voltage of a battery alone is not good indicator of the State of Charge (SOC) of the battery because voltage does not decline proportional to the soc.

Another solution (http://fritzing.org/projects/battery-charge-level/) suggest measuring the voltage (with analogread) between two resistors connected to the gnd and vcc of the circuit (I presume this constantly draw power) and then choose what is the critical voltage of the circuit.

However, my question is how to measure the SOC of a battery using units of 0 to 100% in arduino?

body:
To do it correctly, you need a coulomb counter. Something like [this][1].

Even that is not fully sufficient, as the charge that can be obtained from a battery depends on various factors, such as temperature and ageing.

More recent batteries have somewhat flat discharge curve, when it comes to voltage, till they run flat, then the voltage drops significantly.
Which means that you would need a very accurate voltage meter.

However the starting point is that you must be able to count how much charge is going in and out.

  [1]: http://www.maximintegrated.com/en/products/power/battery-management/DS2740.html


message:
Timer 2 interrupt with ATmega328p and make measurement in ISR

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

I am working in my project and i want to use Timer2 interrupt every 100ms to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5.

I read in some article that using delay instruction is not as good as using timers'Interruptions so, I tried this code put it didn't work properly :

    void setup(){

    cli();

      TCCR2A = 0;
      TCCR2B = 0;
      TCNT2  = 0;
      OCR2A = 99;
      TCCR2A |= (1 << WGM21);
      TCCR2B |= (1 << CS21);
      TIMSK2 |= (1 << OCIE2A);
    sei();

    Serial.begin(9600);
    }
    void loop()
    {
    Serial.print(digitalRead(1));
    Serial.print(' ');
    Serial.print(digitalRead(2));
    Serial.print(' ');
    Serial.print(digitalRead(3));
    Serial.print(' ');
    Serial.print(digitalRead(4));
    Serial.print(' ');
    Serial.print(digitalRead(5));
    Serial.println(' ');

    }

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

Well let's start from the start ...

---

## Analog readings

> to get new measurement from the output of my 5 sensors which connected to pins A1,A2,A3,A4,A5.

    Serial.print(digitalRead(1));

That is not reading **analog** pin A1, it is reading **digital** pin 1. If you want to read A1 you need:

    Serial.print(analogRead(1));

---

## Check the time

By far the simplest thing would be to simply check the time and take a reading when 100 ms is up.

Example:

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

    unsigned long lastReading;
    const unsigned long INTERVAL = 100;  // ms

    void loop()
    {

      // is time up?
      if (millis () - lastReading >= INTERVAL)
        {
        lastReading = millis ();  // when we took this reading
        Serial.print(analogRead(1));
        Serial.print(" ");
        Serial.print(analogRead(2));
        Serial.print(" ");
        Serial.print(analogRead(3));
        Serial.print(" ");
        Serial.print(analogRead(4));
        Serial.print(" ");
        Serial.print(analogRead(5));
        Serial.println();
        }  // end of if time up

      // do other things here

    }  // end of loop

I increased the baud rate to 115200. Why use 9600 when you are trying to print 5 x 4 characters every 100 ms?

---

## Using timers

If you really want to use timers (and I don't see what they achieve here) I have a [page about timers](http://www.gammon.com.au/timers) that describes using them, and interrupts, in some depth.

The very least you would need is a timer 2 "compare A" interrupt like this:

    ISR (TIMER2_COMPA_vect)
      {
      // Timer 2 has reached its comparison value
      }


message:
Connect multiple modules to arduino micro

I have an Arduino Micro and I want to connect an LCD and Bluetooth module to it. The problem I face is that there are not enough power pins for them both.

I understand that I probably need some external power supply for them, but I have no idea how to do this properly.

body:
You can design/build/deploy a power supply that provides to each board (arduino included) the voltage it needs (but it's advisable to have modules working at the same voltage level) and that should be sufficient.
As long as you have a shared Vcc-to-GND reference, it's enough.

To verify that the power supply you choose is ok, do the following:

  - check that the modules are compatible with its voltage (ex: all at 5V)
  - check that the combined power consumption of each module (you get that from the datasheet) is lower than the total power output of the power supply.

Additional checks:

  - check that the maximum voltage ripple provided by the power supply is lower than what the modules can tolerate
  - check that the peak current the power supply can provide is larger than the combined peak current of all the other devices.


message:
HC-06 module versus 1sheeld

Why would someone buy a [1sheeld](http://1sheeld.com/)?

Why not connect an Arduino to their smartphone using HC-06 bluetooth module and find an appropriate Android app, like for example RoboRemo. What is the advantage of using a 1sheeld?

body:
Why would you buy a car when you can cobble something together from some old pram wheels, a lawnmower engine, some old scaffolding, gaffer tape and chewing gum?

Because buying a car is considerably easier and more reliable.  Plus your "friends" don't laugh at you when they see you trying to drive it to work.

Yes, you could cobble something together that might work using random components and other bits of software, but the work involved would be considerably more than plugging in a shield and downloading an app that is guaranteed to work perfectly with that shield.


body:
Giving an equally biased answer as @Majenko, from the other side:

Because they're lazy, they don't know anything about electronics, and they don't want to. And they have more money than they know what to do with.

I am horrified at people shelling out for an "Arduino Temperature Sensor", "Arduino Shift Register", or "Arduino LED", each of which is a generic component soldered on to a board, with pins, at a 1000% markup

I also question the claim that "cobbled together" items are more reliable, or are less likely to have people laugh at you - if you want it to look nice, put it in a nice box (this applies both to "pre-made" items, and to cobbled together).

You will also learn a lot more from making it yourself; you will learn how things work, and you have a better idea and have the opportunity to fix when things go wrong. Your projects will also be a lot smaller.

If you want something that "just works", go buy an ipad. Then, when it doesn't work, throw it in the rubbish and buy a new one. And if you want it to do something it doesn't do, tough luck.


message:
Help choosing a servo motor

I am struggling to choose servo motor for my project. There are two servos on ebay. Th First one is named Only "Towerpro micro 9g servo" and the second one that is cheaper is named as a "Towerpro 9g Digital servo".
The Links are:

Servo1: http://www.ebay.in/itm/TowerPro-SG90-9g-Mini-Servo-9-gram-Servo-RC-Robotics-/201386256243?hash=item2ee38e6773

Servo2: http://www.ebay.in/itm/251928442829?aff_source=Sok-Goog

My Problem is that **I am confused with the name "Digital Servo"**. Its cheaper but I a afraid that will it work as normal.
Please help me.

Are both the **same** product, but with a different name?

body:
Servos are digital by definition.  All you have there is two sellers that are selling the same product, but they are describing them slightly differently.  They are both SG90 servos. They are both digital (they require a digital PWM signal to control them, hence they are digital).

However, here's a little hint: Add the postage costs on to the cost of the servo - you'll see there's not that much difference in price - only 3 rupees between them.  That's about ¢5 or 3p.


message:
Is it correct to use pulseIn() in ISRs?

Since it is not right to use millis() in an ISR to calculate duration of the input, Is it correct to use pulseIn()?

body:
You shouldn't really use anything much in interrupts.  Using anything that runs for a period of time is usually bad since no other interrupts can happen at the same time.

It is more normal to use the interrupt to set a flag that is then checked within your main loop to determine what should be done.


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

It is quite OK to use `millis()` or `micros()` inside an ISR. In fact that is an excellent time to do it, because you are recording the time of the event shortly after it happened. Make sure the variable you are saving it to is `unsigned long` and `volatile`. Eg.

    volatile unsigned long whenItHappened;
    volatile bool eventHappened;

    void myISR ()
      {
      whenItHappened = millis ();
      eventHappened = true;
      }

Now in your main loop you can test the `eventHappened` flag, so you will know if this event has happened, and `whenItHappened` is when.

It is **not** a good idea to use `pulseIn()` because that can wait quite a long time for a pulse. The default timeout for `pulseIn` is 1 second, which is far too long to wait inside an ISR.

If you want to time something (eg. how long it takes a ball to cross a sensor) use the interrupt twice, once to find the first event, and again to find the second.

---

## Example

Example code which times how long a ball passes a sensor:

    const byte LED = 12;
    const byte photoTransistor = 2;

    unsigned long startTime;
    volatile unsigned long elapsedTime;
    volatile boolean done;

    void ballPasses ()
    {
      // if low, ball is in front of light
      if (digitalRead (photoTransistor) == LOW)
        {
        startTime = micros ();
        }
      else
        {
        elapsedTime = micros () - startTime;
        done = true;
        }

      digitalWrite (LED, !digitalRead (LED));
    }

    void setup ()
    {
      Serial.begin (115200);
      Serial.println ("Timer sketch started.");
      pinMode (LED, OUTPUT);
      attachInterrupt (0, ballPasses, CHANGE);
    }

    void loop ()
      {
      if (!done)
        return;

      Serial.print ("Time taken = ");
      Serial.print (elapsedTime);
      Serial.println (" uS");
      done = false;
      }

That code used `micros()` for a more accurate timing.

---

## Reference

* [Interrupts](http://www.gammon.com.au/interrupts)


message:
Help with LCD's menu and seeing values continuously

I want to see the voltage data using `void volt();`, when I go to the "Item2SubItem3" within `void menuChanged`. Now I can only see the data *at that time*: how can I refresh the value every second?

    void setup()
    {
     // setup()...
    }

    void loop()
    {
     //loop()...
    }

    // DC Voltometer
    float vPow = 4.7;
    float r1 = 100000;
    float r2 = 10000;

    void volt()
    {
     lcd.clear();
     float v = (analogRead(0) * vPow) / 1024.0;
     float v2 = v / (r2 / (r1 + r2));
     lcd.setCursor(0, 0);
     lcd.print("DC VOLTOMETER");
     lcd.setCursor(0, 1);
     lcd.print(v2);
     delay(1000);
    }

    void menuChanged(MenuChangeEvent changed)
    {
     MenuItem newMenuItem = changed.to; // get the destination menu
     lcd.setCursor(0, 1);            // set start position for lcd
             // printing to the second row

     if (newMenuItem.getName() == menu.getRoot())
     {
      lcd.print("Main Menu       ");
     }
     else if (newMenuItem.getName() == "Item1")
     {
      lcd.print("Item1           ");
     }
     else if (newMenuItem.getName() == "Item1SubItem1")
     {
      lcd.print("Item1SubItem1");
     }
     else if (newMenuItem.getName() == "Item1SubItem2")
     {
      lcd.print("Item1SubItem2   ");
     }
     else if (newMenuItem.getName() == "Item2")
     {
      lcd.print("Item2           ");
     }
     else if (newMenuItem.getName() == "Item2SubItem1")
     {
      lcd.print("Item2SubItem1   ");
     }
     else if (newMenuItem.getName() == "Item2SubItem2")
     {
      lcd.print("Item2SubItem2   ");
     }
     else if (newMenuItem.getName() == "Item2SubItem3")
     {
      lcd.print("Item2SubItem3   ");
      delay(2000);
      volt();
     }
     else if (newMenuItem.getName() == "Item3")
     {
      lcd.print("Item3           ");
     }
     else if (newMenuItem.getName() == "Item4")
     {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Item4           ");
     }
    }

body:
As Gerben implied in a comment, `menuChangeEvent` is called only when the menu selection changes.  Thus, your voltmeter readout will print only whenever you change the menu selection to Item2SubItem3.  The code shown below illustrates how to modify your `loop()` so that it checks the menu selection once per second.  Each second the main loop will do whatever function is currently selected, such as displaying a current voltmeter reading.  Note, you can make the menu decoding shorter and less tedious as shown in the answer, and can put variable declarations near where they are used instead of in random places.

    void setup() {
    }  // setup()...

    // DC voltmeter reading
    void volt () {
      const float vPow = 4.7, r1 = 100000, r2 = 10000;
      lcd.clear();
      float v = (analogRead(0) * vPow) / 1024.0;
      float v2 = v / (r2 / (r1 + r2));
      lcd.setCursor (0,0);
      lcd.print("DC Voltmeter");
      lcd.setCursor (0,1);
      lcd.print (v2);
      // Don't delay(1000) since loop() takes care of delay.
    }

    long int second = 0;
    uint8_t itemcode = 0; // Will be number nm for Item n, Subitem m
    int passnumber = 0;
    void menuChanged(MenuChangeEvent changed) {
      MenuItem menuitem = changed.to; //get the destination menu
      String itemname = menuitem.getName();
      lcd.clear();       // Make printing spaces at line ends unnecessary
      lcd.setCursor(0,1);       //set lcd printing position = second row
      if(newMenuItem.getName() == menu.getRoot()){
        lcd.print("Main Menu");
        itemcode = 0;
      } else {
        lcd.print(itemname);
        itemcode = 10*(itemname[4] & 7);
        if (itemname.length() > 5)
          itemcode += itemname[itemname.length()-1] & 7;
      }
      passnumber = 0; // Actions can test passnumber if they like
      second = 0; // Cause actions to take place now
    }

    void loop() {
      long int now = millis()/1000; // Get elapsed-seconds
      if (now == second) return; // Only do stuff once per second
      // Update to current second and do chosen menu item
      second = now;
      switch (itemcode) {
      case  0: break;
      case 10: break;
      case 11: break; // Fill in with code for different cases
      case 12: break;
      case 20: break;
      case 21: break;
      case 22: break;
      case 23:   // Item 2, subitem 3, read voltmeter
        volt();
        break;
      case 30: break;
      case 40: break;
      }
      // You can test passnumber to control for cases that only go once
      ++passnumber;
    } // end of loop()

*Edit:* I moved the declaration of `second` and added `second = 0` within `menuChanged()` to decrease latency between a menu item being selected and its action taking place.  Without `second` being zeroed in `menuChanged()`, up to a second could pass between an item's selection and its action; latency would average 0.5 seconds, which is undesirable in a user interface.


message:
Help Connecting Arduino Uno To Computer

I am A Newbie to Arduino

I have a Windows 7 PC. Last Time I bought an Arduino Uno Clone but after working for a day, it stopped detecting on the port. So I bought a new Clone Of different brand. Now I Want in which sequence should I install its drivers, Coonect it, Unzip Arduino IDE...Reboot??

I dont want a problem this time. Another question is Should I first connect the clone and then Install its drivers Or first install drivers and then plug the board? When Is the reboot required?

Product Link : https://m.ebay.in/itm?itemId=121708881208

Please Explain...
Thanks In Advance

body:
I would like to start by pointing out that you are using a clone. The arduino IDE by default does support clones. Just install your port drivers that's far enough.

The reason your board got spoilt the last time definitely was not cause you did not install the drivers in the right order. It could be due to many reasons, few listed below:

1. Poor PCB quality
2. Humidity
3. Cheap USB to UART converter.
4. Short circuit in your connection

So what I recommend is the either the use of genuine arduino boards if you can afford.

**Note:** Most likely its only the USB to UART (CH340G) that has been destroyed, you could buy a hot air station and replace the IC, it is a much cheaper solution.

  [1]: http://arduino.stackexchange.com/questions/14264/why-does-the-standard-arduino-ide-not-include-the-ch341g-usb-drivers/


body: I have shorted my bords a few time and they always came back to "life" after a minute. Maybe you should be more concern about the voltage you supply to the board. Even if it can take up to 12 volt I never use more then 9 volt on the board. And if you run motors on them its always good to supply them with an external power source and use something like a H bridge to power your devices. I made mistakes and my board are still in mint conditions.


body:
I just checked the link and the item is not available anymore. That way it is impossible to say which driver you should install.

I agree with the answers and comments so far, get the real board. I've heard of people who fried their USB ports because of Arduino clones and their terrible/absent circuit protection.

If you can't afford the original board, what will you do if it damages your computer?