message:
Can you access the EEPROM of an ATtiny with Arduino Code?

I'm attempting to reduce the amount of RAM being used by my program by writing some values to the EEPROM of my micro controller. I'm currently programming on the ATtiny85 which has 512 Bytes of EEPROM. According to the documentation this is how you write to EEPROM:

    #include <EEPROM.h>

    void setup() {
      EEPROM.write(0, 1);
      EEPROM.write(1, 0);
      EEPROM.write(2, 3);
      EEPROM.write(3, 2);
      EEPROM.write(4, 1);

    }

For some reason this isn't working for me and I can't seem to find the error. Am I programming this wrong or can the EEPROM of the ATtiny simply NOT be accessed with Arduino Code?

Here is the Datasheet: http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet-Summary.pdf

Here is the second sketch I'm using to test the EEPROM:

        #include <EEPROM.h>

    void setup() {
      EEPROM.write(0, 1);
      EEPROM.write(1, 0);
      EEPROM.write(2, A3);
      EEPROM.write(3, A2);
      EEPROM.write(4, A1);

    byte CLK = EEPROM.read(0);

    }

    void loop() {

      if(CLK == 1)
      {
        for(int i = 0; i < 3; i++)
        {
        digitalWrite(0, HIGH);
        delay(1000);
        digitalWrite(0, LOW);
        delay(1000);
        }
        exit(0);
      }
      else
      {
        for(int i = 0; i < 100; i++)
        {
        digitalWrite(0, HIGH);
        delay(1000);
        digitalWrite(0, LOW);
        delay(1000);
        }
        exit(0);
      }

      exit(0);

    }

body:
When you upload a new sketch with the default settings, the EEPROM will be cleared.

"The -e option instructs avrdude to perform a chip-erase before programming; this is almost always necessary before programming the flash."

If you're using the Arduino IDE, the -e option is enabled by default. This is probably why it's not working for you.

See also the question [Is there a way to preserve EEPROM contents in AVR Atmega when burning a new firmware to flash with avrdude?][1]

  [1]: https://electronics.stackexchange.com/questions/98891/is-there-a-way-to-preserve-eeprom-contents-in-avr-atmega-when-burning-a-new-firm


sender: user

sender: assistant

body:
The Arduino EEPROM library is compatible with the ATTiny range of AVR microcontrollers as the library itself is built on the standard Atmel AVR avr/eeprom.h 'library' so it is compatible with all the AVR microcontrollers.

The EEPROM also doesn't take to being written or read to often as EEPROM can wear very quickly. Reading though does not cause much damage though.

Also note that using `exit(0);` **will stop the ATTiny from doing anything else** after it is called so I hope your intention is to only run the loop once, if not this would account for either not seeing anything or it only ever running the blinking cycle once.

To answer your follow up question. Yes you can run one sketch to set you values in EEPROM and then use another sketch to read those. That us usually the point of EEPROM it is a memory type that "keeps its value while there is no power".

Also you need to make sure the ATTiny is set to preserve EEPROM during upload with the ISP, this is done with the fuse settings. You need to look for a tutorial on fuse calculators for the AVRs. To set the `EESAVE` you need to set the High fuse to `0xD7`, you can change this in the `boards.txt` file. [Here is a fuse calculator.][1]

If the code that is on your question at the moment is being used you won't be seeing anything as it needs the pins to be set with `pinMode`. That's a note for others that see this.

Next what you can do is run a basic test code which blinks the LED without anything else going on.

Basically:

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

    void setup(){

     pinMode(0, OUTPUT);

    }

    void loop(){

     digitalWrite(0, HIGH);
     delay(1000);
     digitalWrite(0, LOW);
     delay(1000);

    }

Below is the code you have written, it works I have it running in front of me.
I have commented it and changed a few things to make it work as intended, although the intention is not clear.

    #include <EEPROM.h>

    byte CLK = 0; //This is a global variable with an initial value

    void setup() {
      // put your setup code here, to run once:

      EEPROM.write(0, 1); //set the pin to D1
      delay(5);

      //read from EEPROM address 0
      //this sets the value of the global variable CLK
      CLK = EEPROM.read(0); //place this inside a function

      //just to give an example...
      byte PIN = CLK;   //PIN variable is a local variable

      pinMode(PIN ,OUTPUT); //using that local variable

    }

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

      // Note: the below if() will always be true as the value
      // of CLK is never change and shouldn't be changed as
      // it will change the pin number of the output

      if (CLK == 1) {
        for (int a = 0; a < 3; a++) {
          digitalWrite(CLK, HIGH);  //this uses the global variable
          delay(1000);
          digitalWrite(CLK, LOW);
          delay(1000);
        }
        //putting exit(0); will actually stop the program
        //remove it
    //    exit(0);
      }
      else {
        for (int a = 0; a < 100; a++) {
          digitalWrite(0, HIGH);  //this has a predefined pin no.
          delay(500);
          digitalWrite(0, LOW);   //this has a predefined pin no.
          delay(500);
        }
        //putting exit(0); will actually stop the program
        //remove it
    //    exit(0);
      }
    }

  [1]: http://eleccelerator.com/fusecalc/fusecalc.php?chip=attiny85&LOW=E2&HIGH=D7&EXTENDED=FF&LOCKBIT=FF


body:
Not sure if things have changed so significantly since the question was asked originally but I'll answer using the Atmel AVR libraries.

Don't assign the EEPROM value to a variable as then you are wasting precious SRAM again. EEPROM has unlimited read cycles.

I can't find any current references to `EEPROM.read()` as a Macro or function in the Arduino IDE. Instead there is the AVR EEPROM library which uses `eeprom_read_byte()` as shown below.

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

    #include  <avr/eeprom.h>

    // the setup routine runs once when you press reset:
    void setup() {
    /* The "131" value is used to prevent damaging excess EEPROM writes on every restart.
       If you want to try setting a different GPIO pin for LED blink change the test value in
       both the read and following write to EEPROM address 511 */

        if (eeprom_read_byte((uint8_t*)511) != 131) {
           eeprom_write_byte((uint8_t*)511,131);
    // Store the GPIO pin number in EEPROM address 1
           eeprom_write_byte((uint8_t*)1,1);
        };
    // initialize the digital pin as an output.
        pinMode(eeprom_read_byte((uint8_t*)1), OUTPUT); // LED pin value stored in EEPROM address 1
    }

    // the loop routine runs over and over again forever:

    void loop() {
        digitalWrite(eeprom_read_byte((uint8_t*)1), HIGH);
        delay(1000);               // wait for a second
        digitalWrite(eeprom_read_byte((uint8_t*)1), LOW);

        delay(1000);               // wait for a second
    }


body:
It is now very common to read from EEPROM in an ATTiny, particularly an OSCCAL value. It has also been the case for some embedded devices to perform a superfluous write and read back to external EEPROM during POST. Every boot.

    > ---snip---
    >     current tick:1 sec
    >     EEPROM Init...
    >     Write EE_TEST ==0x7cf u8EEData1=0xaa
    >     Read EE_TEST ==0x7cf u8EEData1=0xaa
    >     [EEPROM 24c16 found!]
    >     EEPROM: Data valid
    >     Restore Configuration from EEPROM to Device...
    >     Show MY MAC Address(from 24c16): (0x00:92:58:01:45:4d)
    >     _24c16_eeprom_word_read: EE_DHCPEN: (01)
    > --- end snip ---

In addition, available cores include options to suppress EEPROM erase in programming, this is fuseable.

In ancient times AVRDUDE would write flash counts to the four bytes terminated by E2END. (the -y option).

You need to include the header.  You can check, peek and poke, the contents with a sketch or by using avrdude in terminal mode (-t) with "dump ee".

And yes, it is normal for Arduino work to have a dedicated temporary sketch to load EEPROM data.
So SRAM (or FLASH) does not matter, there is a lot of FLASH compared to EEPROM.

Keep it simple and test your results. Depending upon the library or core, it is best to avoid crossing page boundaries as addressing may wrap around to the beginning of the page due to 6 bit truncation as for I2C external EEPROM. Don't trust, verify.


message:
I2C multi sensors reading on Arduino

I have several sensors (Grove multichannel gas sensor, Air Pressure Sensor MPX4115A, Temperature and Humidity Sensor DHT11) where most of them uses I2C communication.
I wonder if it is possible to read all of them using the I2C communication on a single Arduino board?

body:
Should be easy enough.  Do you already know how to connect and communicate with one I2C device?  If so, connecting multiple should be simply a case of connecting them in parallel.

If you don't know how to communicate with a single I2C device, then...

For the Arduino software you can use [Wire][1] to talk to devices over I2C.

For the hardware, connect the I2C clock and data lines from the Arduino to the I2C devices.  More on that [here][2].

  [1]: https://www.arduino.cc/en/Reference/Wire
  [2]: https://learn.sparkfun.com/tutorials/i2c/why-use-i2c


body:
It is possible to use multiple I²C devices, all is needed is for each one to have a different address and the ability to set up the wiring(the [other answer][1] points to wriring info).

Of the sensors you listed only one is an I2C device(Grove sensor).

The DHT11 uses a single digital wire to communicate and the air pressure sensor is an analog device. Although you do mention having several devices, the only thing you need to be sure of is if there are no address conflicts, i.e. there being two devices with the same address on the I²C bus.

If address conflicts are an issue most devices provide a way of changing that address, often there are solder jumpers on the board. This allows you to change a devices address to a unique one.

  [1]: https://arduino.stackexchange.com/a/25087/2944


message:
MG2639 CELL AND GPS LIBRARIES

I'm using a [MG2639 Cell Module][1] with the SMS and GPS functionality.
I have a sketch that sends through SMS the location of the arduino UNO.

This is my code:

    #include <SoftwareSerial.h> //to communicate with mg2639 cell module.
    #include <SFE_MG2639_CellShield.h> //basic librarie of the module.
    #include <AltSoftSerial.h>   //to communicate with the GPS module
    #include <TinyGPS++.h>    //to acquire the NMEA codes.

    TinyGPSPlus gps;

    AltSoftSerial ALTS(9, 8);
    char celprim[11]="4423337388";
    uint8_t GPStatus=0;
    long temp=0;

     void configurado()
    {
      sms.start(celprim);
      sms.print("Transmitiendo GPS Tracking....");
      sms.send();
      delay (6000);
    }

         void GPSTracking()
    {
       do
          {
            if (ALTS.available()>0)
              if (gps.encode(ALTS.read()))
          {
            if (gps.date.isValid() && gps.location.isValid() && gps.time.isValid()){
              sms.start(celprim);
              sms.print("Fecha/Hora/Ubicacion: ");
              sms.print(gps.date.day());
              sms.print("-");
              sms.print (gps.date.month());
              sms.print("-");
              sms.print(gps.date.year());
              sms.print(" ");
              if ((gps.time.hour()-5) < 10) sms.print("0");
              sms.print(gps.time.hour()-5);
              sms.print(":");
              if (gps.time.minute() < 10) sms.print("0");
              sms.print(gps.time.minute());
              sms.print(":");
              if (gps.time.second() < 10) sms.print("0");
              sms.print(gps.time.second());
        sms.print("https://www.google.com.mx/maps/dir/19.4161748,-99.1664011/");
              sms.print(gps.location.lat(), 6);
              sms.print(",");
              sms.print(gps.location.lng(), 6);
              sms.print("/@");
              sms.print(gps.location.lat(), 6);
              sms.print(",");
              sms.print(gps.location.lng(), 6);
              sms.print(",19z");
              sms.send();
              GPStatus=1;
            }
        }
          if ((millis()-temp) > 30000 && GPStatus==0)
          {
            GPStatus=1;
            sms.start(celprim);
            sms.print("Imposible ubicar equipo, intente mas tarde...");
            sms.send();
          }
        }while (GPStatus ==0);
    }

    void setup()
    {
      delay (5000);
      int beginStatus = cell.begin();
      if (beginStatus <= 0)
      {
         while(1)
          ;
      }
      delay (10000);
      sms.setMode(SMS_TEXT_MODE);   //Se pone al modulo en modo de recepción y envio de sms
      ALTS.begin(115200); // Or whatever rate the GPS uses
      configurado();
    }

    void loop()
    {
      if (GPStatus==0)
      {
        temp = millis();
        GPSTracking();
      }
    }

Is it possible to use only AltSoftSerial to create 2 serial ports and communicate with both cell and GPS in order to reduce program storage and global variables space? If it's possible, what changes should do in the [MG2639 library][2] to make it work?
Or what could i do to reduce space.

  [1]: https://learn.sparkfun.com/tutorials/mg2639-cellular-shield-hookup-guide
  [2]: https://github.com/sparkfun/SparkFun_MG2639_Cellular_Shield_Arduino_Library/

body:
> Is it possible to use only AltSoftSerial to create 2 serial ports and communicate with both cell and GPS in order to reduce program storage and global variables space?

The question is a little vague.

`AltSoftSerial` only works on pins 8 & 9, so I thought you were asking if you could connect both the cell and the GPS to pins 8 & 9 (using jumper pads on the back of the board), and use one `AltSoftSerial` instance to talk to both devices.  If it were possible, this would save RAM (just one instance) and program space (you wouldn't need two link in another software serial class, like `SoftwareSerial`).  However, this is not possible.  Serial connections are always point-to-point.  Although two "things" can listen to one RX line, the TX line cannot be shared by two devices.

If you were asking if you can have two instances of `AltSoftSerial` on two separate pairs of pins (e.g., 2/3 and 8/9), the answer is again "No", because... `AltSoftSerial` only works on pins 8 & 9.  Also, the SparkFun library only uses SoftwareSerial to talk to the cell.

> what could i do to reduce space.

Use [NeoGPS](https://github.com/SlashDevin/NeoGPS) instead, and use the F macro around double-quoted strings that you print:

        sms.print( F("Imposible ubicar equipo, intente mas tarde...") );

That will save several hundred bytes of RAM.

Also, you may be sending multiple SMS's per second.  It depends on what sentences the GPS emits.  As it is, your sketch will send one SMS per sentence (i.e., one for each `encode`).  Even if you don't use NeoGPS, look at the example program `NMEAloc.ino` et al for the correct program structure.  The Troubleshooting section also contains some tips.


message:
Arduino Uno - ESP 8266: sending AT commands via Code

I bought a ESP 8266 & I am able to send AT commands and receive response via serial monitor when I upload a empty sketch. I changed the baud rate from 115200 to 9600 by using `AT+CIOBAUD=9600` and am able to run AT commands at 9600 baud rate.

**Empty Sketch:**

    void setup()
    {

    }
    void loop()
    {

    }

Here is how my circuit looks:
[![Diagram][1]][1]

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

**Problem**

The problem is when I create a custom sketch to run AT commands it doesn't work. Here is how my sketch looks:

    #include <SoftwareSerial.h>
    SoftwareSerial esp8266(0,1); //RX,TX

    void setup()
    {

      Serial.begin(9600);
      esp8266.begin(9600);

      Serial.println("Run AT Command");

       esp8266.print("AT\r\n");

    }

    void loop(){
       String response = "";
       while(esp8266.available())     {
            char c = esp8266.read();
            response+=c;
            Serial.print(c);
          }

          if(response != ""){
            Serial.println(response);
          }

    }

ESP8266 is receiving 3.3V but I have read TX and RX sends 5V, and they also need to be 3.3V. Don't know if thats what is causing it, but I am able to run AT commands on empty sketch, so this is a bit weird.

> UPDATE:

**My sketch is:**

    #include <SoftwareSerial.h>
    SoftwareSerial esp8266(2, 3); //RX,TX

    void setup()
    {

      Serial.begin(9600);
      esp8266.begin(9600);

      esp8266.print("AT\r\n");

    }

    void loop() {
      String response = "";
      while (esp8266.available())     {
        char c = esp8266.read();
        response += c;
      }

        if (response != "") {
          Serial.println("Response: " + response);
        }

    }

**Serial Monitor shows this:**

    Response: A
    Response: T

    OK
    Response:

**OUTPUT when I run AT+CIFSR command:**

    Response: A
    Response: T+CIFSR

    Response:
    +CIFSR:APIP
    Response: ,"192.168.4.1
    Response: "
    +CIFSR:APMA
    Response: C,"5e:cf:7f:80
    Response: :f7:74"

    OK

**Question now is:** How do I store the string being returned from the esp8266. I thought my response string was suppose to store the "OK" but that did not happen.

body:
Of course you cannot use the same pins for both hardware and software serial, but that part seems to have been solved in comments.

>Question now is: How do I store the string being returned from the esp8266. I thought my response string was suppose to store the "OK" but that did not happen.

     while (esp8266.available())     {
        char c = esp8266.read();
        response += c;
     }

This will only read as long as characters are available, but the ATmega is able to run this loop much more quickly than characters are received, so unless the entire message was previously transferred it will likely only get a character or two before the receive buffer is found (temporarily) empty and it terminates.

You should instead read until a terminating condition is found, such as a newline character.  For safety you might also put in a "give up and try again" timeout, but make it long.

Some would try to solve this problem by inserting short delays before trying to read, but that is unwise - depending on delays creates unreliability as the necessary delay can easily change due to conditions that may on the surface seem to have little relevance, for example the esp866 might respond more slowly if it is seeing a lot of broadcast traffic on a network, or if the firmware version changes.


body:
There is another technique that you can use, instead of hanging around waiting for more characters from the ESP8266. Your code starts:

    void loop() {
        String response = "";
        while (esp8266.available())     {
            char c = esp8266.read();
            response += c;
        } // while

This has the effect of creating a new `String` every time `loop()` is entered, and you accumulate the data from the ESP8266 in that - but it's lost if you leave `loop()`. So it may be better to do it differently:

    const char EOL = '\n'; // End of line
    String response = ""; // Create String once, outside loop()

    void loop() {
        char c = '\0'; // Initialise to NUL
        while (esp8266.available() && c!=EOL) { // Wait for End of Line
            c = esp8266.read();
            response += c;
        } // while
        if (c==EOL) {
            Serial.print("Response: "); // Don't use '+' if you can help it!!!
            Serial.println(response);
            // Do other processing
            response = ""; // Clear response for next string
        } // if

This has three effects:

1. It keeps an incomplete `response` between calls to `loop()`.
2. It only processes `response` once the end-of-line is read.
3. It keeps `loop()` running nicely (important on other Arduino), rather than hanging around


body:
Just check if this answer helps.
Here is the thing, For AT commands from serial monitor, RX or arduino should be connected to RX of ESP and TX of arduino to TX of ESP. That is the reason you are able to enter AT commands with your circuit when empty program is uploaded.

Now for arduino to communicate with ESP using program, you have to connect RX of arduino to TX of ESP and TX of Arduino to RX of ESP. In your case if using software serial 2 & 3, then pin2 to TX of Esp and pin3 to RX of ESP.

To read "OK" from ESP, try below code:

    if(esp8266.find("OK"))

Also you may try this code to read:

    esp8266.find("pin="); //this acts like a pointer.
    int value = esp8266.read(); //returns ASCII Code. this will read value which comes after pin=

Refer : https://www.arduino.cc/en/Serial/read


message:
Hooking up the Arduino to a car's 12v

I am planning an uno based tachometer for my truck, which doesn't have a tachometer. With nothing in place for me to get a reliable signal, I started looking at other sources to read the rpm from the engine.

It seems to me that an engine should affect the power every time a cylinder fires --the power should spike in some way. So in theory I should be able to hook up to the 12v cigar lighter, count the spikes, and calculate the rpm. It would only need to be accurate within 500 rpm or so.

This is a two part question.

1. How would I hook up the arduino to the 12v system? As in, what should I do to protect the io of the arduino?

2. How would I gather the test data to see if this is possible? Is there a way to hook the arduino up to the truck via the 12v and my computer via usb and send data back that I can record or monitor?

body:
> How would I hook up the arduino to the 12v system? As in, what should I do to protect the io of the arduino?

First you're going to need to do some investigative work. You're going to need to beg, steel, borrow (or use your own if you have one) an oscilloscope. You can then use that to examine the 12V power coming from the cigarette lighter.  Armed with that you can then tell:

1. If there is any power fluctuation from the engine, and
2. What form that fluctuation takes.

If there is any fluctuation it will appear as an AC component imposed on top of the 12V DC voltage. Removing the 12V DC offset is simple enough. All you need to do is pass the power through a *high pass* filter. That's simply a capacitor and a resistor. You need to ensure that the cut-off frequency of the filter is below the lowest frequency you want to measure (idle frequency) yet high enough to cut out the DC component effectively.

Once you have done that you can then clip the waveform using a diode to protect against negative voltage, and a resistor and zenner diode to limit the positive voltage.

For instance, something similar to the following (it's not exact - the source isn't creating spikes, but an offset low duty cycle PWM, which is kind of similar for demonstration purposes):

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

The first point measured is the 12V signal with big high voltage spikes. Next the power has been high-pass filtered by the RC network and the lower portion of the waveform clipped by the reverse biased diode. Following that the zenner diode clips the upper portion of the waveform to within safe limits for the Arduino. The 100Ω resistor with the zenner is there to limit the current through the zenner.

Don't take any of those values as gospel, since the signal I am filtering there is not your signal. You need to know your signal first before you can work out exactly how it should be filtered, but that gives you the basic idea of how it can be done.

> How would I gather the test data to see if this is possible? Is there a way to hook the arduino up to the truck via the 12v and my computer via usb and send data back that I can record or monitor?

Connect the filtered and clipped signal to an interrupt input on the Arduino. Count the pulses within a given time period (1 second, 5 seconds, whatever you choose) and multiply up for number of pulses in a minute. Don't forget to then divide by 4 for a 4-cylinder engine, since I would expect you would see 4 sparks per revolution. How you then gather the data is up to you. It might be simplest to add an SD card shield to your Arduino and record the data onto an SD card. You can then place that card into your computer to process the data at your leisure.

The best way to power your Arduino is, of course, direct from the truck's power. The safest way, because of all those nasty spikes in the power, is to use car USB phone charger adapter. Plug that into the USB of the Arduino and all should be nice and happy.

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


message:
Can I connect a remote control relay to a arduino uno board by disabling the remote control in the relay?

I was making a home automation system by making some of the appliances in the home like fans and lights voice activated. But by mistake I bought a remote controlled relay in place of a normal relay from a shop and return does not seems possible. So I want to know if I will be able to use that remote controlled relay in this project?

body:
I don't like to work with mains, so I use those outlets and connect a [433MHz transmitter](http://www.ebay.com/itm/NEW-433Mhz-RF-transmitter-link-kit-for-Arduino-ARM-MC-U-Remote-control-Sale-/321975775117?hash=item4af7406f8d:g:ed8AAOSwFqJWlzgA) to the arduino to activate the outlets.

You'd have to check the frequency of the unit, and see if anyone have decoded the transmitted data package.

If that doesn't float you're boat, you could open up the unit, and remove/desolder the relay. Add a transistor, and flyback diode and you're done. Just be careful with mains power.


message:
Difference between Arduino IDE giving me headaches

For some time now I've been playing around with the latest version of Arduino IDE and my UNO and ATTiny with simple 433 RF links with the Manchester Library. It all worked fine, but for my next project I want to take the step up and use a better wireless thingy... like the nRF24l01 or the nfm12b.

And then starts the pain. Attiny does not have hardware serial, but people seems to have solved this by implementing software-serial. But then they have to use some other boards for ATTiny, because when I try to run the examples I get error messages that it could not find <SPI.h> and so on. I use the ATTiny boards I found over at [google code][1].

Regarding the RFM12B I got something to compile. If I went back and downloaded Arduino IDE 1.5.0 (no other!) it actually work with the JeeLib - hurray! Why is this, why can't I use the latest version of the Arduino IDE?

Regarding the NRF24 chip this case is unresolved. I have not found the correct combination of boards, IDE and library versions. Could anyone point me in the right direction?

What are the difference between the Arduino IDE's? Why can I get stuff to work on 1.5.0 but not the latest 1.6.x?

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

body:
To get RF24 working:

 1. Download the latest IDE (not 1.0*)
 2. Use the library manager to download the
    latest RF24.
 3. See https://github.com/TMRh20/RF24/issues/236#issuecomment-205354077
    about what core to use.
 4. Don't forget to define ATTiny in the sketch
    Ex: `#define __AVR_ATtiny84__`
(84, 44, 24 are the choices)

ATTiny* do not have SPI, that's why it can't find SPI.h (SPI library).


body:
As far as I know, there was an internal dispute in the Arduino company. So now there are two companies selling under the Arduino name.

www.arduino.cc 's latest ide is 1.5.x and that has more features than www.arduino.org 's ide 1.6.x. So make sure you use arduino.cc's version only because they do the major development of the IDE.


message:
Arduino: Sending SD CSV file online at specific time of the day

I intend to perform data logging from sensors and store it on SD card as CSV format. The data is related to weather and I would like to send it at the end of the day/
Any available codes how to deploy the SD files from Arduino to the cloud/online at specific time of the day?
Thank you in advance.

body: You should use arduino as an ftp client, then stream the csv file to the site in binary mode. You should find examples on the web.


body:
Well for CSV, you might as well do `dataFile.print(",");`. It will log a comma and thus separating your values with a comma.

For **logging** your data at the end of the day, you have multiple ways.

1- Use a delay (worst idea EVER! Don't do this!). This will require you putting `delay(86400000);`. Yes that is indeed a 24h delay!

2- Use the `millis()` function. This function returns the number of milliseconds since the programmed started running. There is an example code called `blinkWithOutDelay`(or something like that). This method is somewhat "ok" but after 49 days there is a rollover which makes things complicated. To solve that rollover, see [here][1].

3- Use a RTC. RTC stands for Real Time Clock. It is pretty much a module that keeps actual time even if the power to your project is disconnected. There are many popular models out there such as the DS3231. There are many libraries for it. You can do so that each day, at a specific time, it logs the data to your SD card.

Now to **send** the data. You have may options for this too.

1- Use an Arduino Ethernet shield. This will connect your Arduino to the Ethernet via an Ethernet cable. From there, you can either log your data to a Google Sheets file or a custom web server. Many tutorials out there for you.

2- Use an ESP8266. With this Wifi module, you can easily host your own web server with it. Note that This makes it somewhat harder for your code then simply using an Ethernet cable but it makes you project wireless. Note that if you do use an ESP8266, you can put the Arduino aside. The ESP has many GPIOs that can be used to do many things, but I'll still suggest keeping the Arduino for sake of simplicity. Again, many tutorials out there.

Note that there are many cloud services out there. A quick Arduino IOT search will bring out many result and interresting projects ideas for you.

  [1]: https://arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover


message:
Setting the frequency of a timer interrupt

**The concept:**

Play a sine wave saved as a character array in PROGMEM through an 8-bit DAC connected to the PORTC pins on the Arduino Mega.

**This works:**

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

    // File just defines an array and a size

    #include "sine440.h"

    int i = 0;
    void setup() {
      DDRC = B11111111;
    }

    void loop() {
      PORTC = pgm_read_byte(&sine[i++]);
      if(i >= sine_size){
        i = i - sine_size;
      }

      delayMicroseconds(60);
    }

The above code produces a sine wave of about 440 Hz, exactly what I wanted. Now, I'd like to move this into an interrupt routine, as follows:

### This doesn't work

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

    #include "sine440.h"

    int i = 0;
    void setup() {
      DDRC = B11111111;
      TCCR5B = (1 << WGM52) | (1 << CS50 );
      OCR5A =  16000000/16000;
      TIMSK5 = (1 << OCIE5A);
    }

    ISR(TIMER5_COMPA_vect){
      PORTC = pgm_read_byte(&sine[i++]);
      if(i >= sine_size){
        i = i - sine_size;
      }
    }

    void loop() {

    }

The above code produces a sine wave of 1721 Hz. I know that this means it's iterating through the array too fast, but I don't know how to change it. In order for it to produce 440 Hz, it needs to be preforming 16,000 iterations per second, which is what I believe ` OCR5A =  16000000/16000;` does. **But** it doesn't appear that changing the value of OCR5A does anything at all. Giving it the max value of 65,535 still produces a 1721 Hz sine wave...

So what am I doing wrong here? How do I change the speed of this timer interrupt?

body:
I second BrettAM's comment. The Arduino IDE sets most of all the timers up for PWM, and I had to comment out a section once to use my own ISR with Timer 3 on a 32u4, because no matter where or how I set it, the CTC interrupt never went. The `WGM50` and `CS51` are set at the start of the Arduino files basically, so that messes with your settings.

You will need go into the Arduino core files. This is `$install_path/arduino-1.x.x/hardware/arduino/avr/cores/arduino/`, and under that directory you need to find file `wiring.c`. This file contains all the setup of the timers for PWM and the `millis()` or `micros()` functions.

Go to line 342. Located there is this:

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

    #if defined(TCCR5B) && defined(CS51) && defined(WGM50)

      sbi(TCCR5B, CS51);           //set ter 5 prescale factor to 64
      sbi(TCCR5B, CS50);
      sbi(TCCR5A, WGM50);         // put timer 5 in 8-bit phase correct pwm mode

    #endif

Here you can place another `#if defined()` macro around this, resulting in:

    #if !defined(doNotSetTimer5)

      #if defined(TCCR5B) && defined(CS51) && defined(WGM50)

        sbi(TCCR5B, CS51);           //set ter 5 prescale factor to 64
        sbi(TCCR5B, CS50);
        sbi(TCCR5A, WGM50);         // put timer 5 in 8-bit phase correct pwm mode

      #endif

    #endif

Now when you want to use your custom settings, you will put the following at the top of your .ino file:

    #define doNotSetTimer5
    #include <wiring.c>

That does not block the Arduino environment from setting up Timer 5 when compiled with other code, but only when you want to use custom settings (changed because of @Gerben's suggestion). When you change these settings you will lose PWM on 3 pins: `44 45 46`. But you will be able to make use of setting your own PWM up or a CTC `ISR()`.

This doesn't mess with anything else and is the easiest way to do it.


message:
Arduino Nano Update failure - avrdude: stk500_recv(): programmer is not responding

Before I tear all my hair and teeth out, can anyone please help. I have tried googling an answer and have not found anything.

My Setup:

1. Win7 64bit
2. Arduino 1.6.9 IDE freshly reinstalled
3. COM14 port in Arduino IDE checked
4. Under Device Manager COM14 shows as: "USB Serial Port (COM14)". Not as "Arduino...(COM14)" as some pages have shown
5. I am not sure if I have a real or copy of the Arduino. As far as I can figure out I have a real one, on the back I have the FT232RL chip
6. I have bought 2 Arduino Nanos and both show same error
7. Both Nanos came pre-soldered, (no noob soldering by me)
8. I have tried uploading sketches on my Win7 platform AND over a Raspberry Pi, both same error

Now perhaps most importantly I previously ordered an Arduino from the same retailer and that one worked. The two I have now dont work.

The problem:

1. When I try upload I get the same message every time: **avrdude: stk500_recv(): programmer is not responding**

   a. it does this 10 times and then fails

   b. Rx and Tx LED's are ON and do NOT blink at all at any point in time

   c. Green power LED is always ON, no blinking

   d. Pin13 LED blinks consistently

   e. I have tried the extreemly annoying reset "trick" before uploading, after uploading, at the same time, during uploading, and nothing works

I am seriously at a loss here. I have had an Arduino Nano work on my pc.

Any help would be greatly appreciated please.

body:
Sorry for posting this as an answer, I don't have enough rep to write comments yet.

1) Have you tried different USB cables? A dodgy USB cable could power the Nano just fine, giving the impression that it's properly connected, without not actually supporting the data rate required for programming. The fact that something shows up on a USB port on your computer makes this explanation less plausible, though.

2) I notice that there are different versions of the Nano, some with ATmega168 and some with ATmega328. If you have the ATmega328, maybe try selecting "Arduino Uno" in the IDE? If you have the ATmega168, maybe try "Arduino Mini"?


body: The baudrate for those is 57600. Try checking for an error in your boards.txt .


body: try a different COM port. I had a corrupted COM3 and it gave the exact same error message that you got


body: The Arduino.cc developers changed the bootloader on official Arduino Nanos to communicate at a different speed. Try setting Tools → Processor → ATmega328P (Old Bootloader)


message:
74HC595N shift register with separate power supply

I have wired up a 74HC595N with an Uno, and the standard 8 LEDs and resistors, per the usual youtube "shift register tutorial" and written a sketch that works.  For example, I wrote a routine to walk from values 0 through 255 and light up the LEDs as a hex number.  So my wiring and code are correct.

As an experiment, I tried disconnecting the pin on my breadboard's power rail that goes to the Arduino 5V, and the pin that goes to Arduino ground, and instead plugged in a breakout (if that's the right word) that plugs into the breadboard and provides 5V on the power rail when a 9V battery is plugged into it.  (It's been checked with a multimeter, it's just under 5V.)  The only pins still going to the Arduino are for DS, SHCP and STCP.

Things sort of work, but not really.  It seems clear to me that the shift register keeps getting reset. (All of the LEDs briefly light back up in each iteration as I'm running my hex number display routine.) All of the other wiring remains the same; specifically OE-bar is still connected to ground on the power rail.  But it still seems to reset.

Can someone explain why the shift register keeps resetting?  Also, am I doing anything that might burn up the Arduino and/or shift register?

body: All ground connections except those which are explicitly isolated must be connected together in order to provide a common voltage reference for the circuit. Any breaks in the ground connection can result in gross misbehavior such as what you are experiencing.


message:
Why do I get "invalid operands of types 'const char*'" error?

I am making an Arduino alarm. This is the error:

    exit status 1
    invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

Here is the code that triggers it:

    lcd.print("0"+hours+":"+minutes);

This code is similar, but worked before:

    String none="00";
    lcd.print(none+":"+none+":"+minutes);

I can post the full code if you need it. How can this be fixed?

body:
Your first code took a `String` object, then added other strings (note lowercase) to it - which are characters enclosed in quotes. It is legal to add strings to `String` objects.

Your new code doesn't have any `String` objects at all - and you're not allowed to add strings to strings (both lowercase).

It will work if you change your new code to:

`lcd.print(String("0")+hours+":"+minutes);`

That turns the original string `"0"` into a `String` object, and then adds more strings to it.


message:
Why does my lcd screen work fine and then display random characters?

It works as expected for a few seconds and then random letters appear on the second row. The wiring and the programming should be correct. I wired it according to an Arduino Starter Kit Book and coded it myself.

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

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

Code:

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    int hours=23;
    int minutes=0;
    String none="00";
    unsigned long timer;
    void setup() {
    lcd.begin(16, 2);
    lcd.setCursor(6, 0);
    lcd.print("Time:");
    lcd.setCursor(6, 1);
    lcd.print("23:00");
    }

    void loop() {
    timer=millis();
    if(timer`0==0){
       minutes++;
      if(minutes==60){
          minutes=0;
          hours++;
          }
       if(hours==24){
          hours=0;
       }
      lcd.clear();
      lcd.setCursor(6, 0);
      lcd.print("Time:");
      lcd.setCursor(6, 1);
      if(minutes<10){
        if(hours<10){
          lcd.print(String("0")+hours+":"+"0"+minutes);
        }
        else{
          lcd.print(hours+String(":")+"0"+minutes);
        }
      }
      else{
        if(hours<10){
           lcd.print(String("0")+hours+":"+minutes);
        }
        else{
           lcd.print(hours+":"+minutes);
        }

      }
      delay(200);
      }
    }

  [1]: https://i.stack.imgur.com/DvX0B.jpg
  [2]: https://i.stack.imgur.com/XJ0OI.jpg

I was able to narrow down the problem. I was testing what happens when it hits 24 hours so I set hours to 23 in the beginning and made the time 600 ms. Once it hits 10 seconds, the characters appear. If the hour is a 2 digit number, the issue happens. I made the hours 9, and the issue disappeared. What can I do?

body:
The problem was that I was adding ":" to the printed string on the lcd without making it a String object. That only occurred if I had double digit hours and minutes.

Incorrect way:

    lcd.print(hours+":"+minutes);

Correct way:

    lcd.print(hours+String(":")+minutes);


message:
RC Car Hack Issue

I am trying to hack a cheap RC car as to be able to control it using my Arduino. I took apart the cars remote controller and found the pins that make it go forwards, backwards, left, and right. So I soldered 4 jumper wires to these pins and connected them to the Arduino as follows:
Pin 8 - Left
Pin 9 - Right
Pin 10 - Forwards
Pin 11 - Backwards
I found the remote controller is controlled by a chip called TX-2E, I checked the data sheet online and found that if any of the pins that control the pins motion are ground, the car will move in that corresponding direction. So if the forwards pin is grounded the car is supposed to move forwards.
To test this, I connected each jumper wire to ground on the Arduino individually and found that it worked as described on the datasheet.

Then I decided to create a sketch that makes the car move forwards for 1 second and backwards for 1 second, it worked as expected.

Then I wrote a sketch that makes the wheels turn left for 1 second and then turn right for 1 second. But it didn't work as expected instead the wheel turned left for 1 second, went to neutral for a second.

I wasn't sure what was wrong, but I decided to run a sketch that should move the car forwards for 1 second, move it backwards for 1 second, turn the wheels left for 1 second, and then turn right for 1 second. But all it actually did was just turn left for 1 second every couple of seconds. I removed the jumper wire connected to pin 8 that is supposed to control the wheels turning left, while the sketch was running and everything worked as expected except the turning left part. it moved forwards for 1 second, moved back for a second, waited at neutral for a second, and then turned right for a second.
When I connected back the jumper wire that controls the car moving left everything stops working again. I am not sure whats wrong, I even connected a multimeter to each pin and found they were pulsing between 0V and 5V as expected but for some reason they weren't moving the car, it was only moving left, in this case at least.
Any help to get this working, ideas to why its not working, or any troubleshooting tips would be greatly appreciated.
Below you can find the code for the sketch, that is supposed to move the car      forwards, backwards, left and right.

    const int LEFT = 8;
    const int RIGHT = 9;
    const int FWD = 10;
    const int BWD = 11;

    void reset () {
      //Sets all pins to HIGH as the car moves when the pins are grounded.
      //And we want the car to start out by not moving.

      digitalWrite(LEFT, HIGH); //For some reason everything works when I remove this
      digitalWrite(RIGHT, HIGH);
      digitalWrite(FWD, HIGH);
      digitalWrite(BWD, HIGH);
    }

    void setup() {
      // put your setup code here, to run once:

      pinMode(RIGHT, OUTPUT);
      pinMode(FWD, OUTPUT);
      pinMode(BWD, OUTPUT);
      pinMode(LEFT, OUTPUT);
      reset();
    }

    void Forward(){

      digitalWrite(FWD, LOW);
      delay(1000);
      digitalWrite(FWD,HIGH);
      delay(1000);
    }

    void Backward(){
      digitalWrite(BWD, LOW);
      delay(1000);
      digitalWrite(BWD, HIGH);
      delay(1000);
    }

    void Left(){
      digitalWrite(LEFT, LOW);
      delay(1000);
      digitalWrite(LEFT, HIGH);
      delay(1000);
    }

    void Right(){
      digitalWrite(RIGHT, LOW);
      delay(1000);
      digitalWrite(RIGHT, HIGH);
      delay(1000);
    }

    void loop() {

      Forward();
      Backward();
      Left();
      Right();

    }

body:
Without details of the car's circuitry one can't say with certainty what the problem is.  However, from the description given, one thing sticks out:  The TX-2E spec sheet says to ground a control pin to select a motion.  But besides grounding pins at times, you are also taking them high.

Instead, try leaving pins open when not active, and pulled down for active.  Eg, try code like:

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

    void motion(const int pin) {
      pinMode(FWD, OUTPUT);
      digitalWrite(pin, LOW);
      delay(1000);
      pinMode(pin, INPUT);
      delay(1000);
    }
    void Forward() {
      motion(FWD);
    }
    void Backward() {
      motion(BWD);
    }
    void Left() {
      motion(LEFT);
    }
    void Right() {
      motion(RIGHT);
    }


message:
how can i fix the error ? stk500v2_getsync(): timeout communicating with programmer

I bought [this Chinese Arduino Mega 2560 16AU][1].

This was the first time to deal with Arduino boards. When I try to upload a sketch I always get this error:

`stk500v2_getsync(): timeout communicating with programmer`

I successfully burnt a bootloader to it using an Arduino uno,
but the same error is there.

Finally I discovered the the loop test is not working, and only the LX LED flashes once  when I enter a letter in the serial monitor.

  [1]: http://www.aliexpress.com/item/MEGA-2560-R3-ATmega2560-R3-AVR-USB-board-Free-USB-Cable-for-Arduino-2560-MEGA2560/32437126167.html

body:
It's our old friend the CH340G again, isn't it?

You've been sold a dud, I'm afraid. The USB chip used there is dead. It happens a lot with those cheap Chinese boards. You should still be able to use the board with an external FTDI adapter by wiring it in to TX->RX, RX->TX and DTR->RESET (via a 100nF capacitor) with power and ground connected of course.

There is also a slim chance that the CH340G may interfere with the TX/RX pins, in which case you may need to remove it. Simply cutting the pins on it with an xacto knife then removing the stumps with a soldering iron and tweezers would do the job.


body:
If You Downloaded the driver it should be fine!

https://github.com/jimaobian/CH34x_Install_V1.3


message:
avrdude: ser_open(): can't set com-state for "\\.\COM2"

I have an unofficial Arduino Uno.

I've tested these:

> - Testing on USB 2.0 and USB 3.0
> - Changing Port (COM XX)
> - Updating drivers for the Unknown device to Arduino Uno (COM XX)
> - Resetting Arduino Board
> - Plug/Unplug
> - 1x PC Reboot
> - Burning bootloader
> - Changing 'Programmer'
> - Uninstalling-Reinstalling device
> - Holding the "Reset" button while I Upload
> - Testing different examples (Blinking/Voltage Serial Read)
> - Testing different "Board" in Arduino software (just in case, you never know)
> - Removing jump wires

Does anyone have any suggestion more than I just tried?

body:
The board you have uses the CH340G chip instead of an ATMega16U2 or FTDI FT232R chip.

It requires special drivers, not the ones that come with the IDE.

Why do they use that chip instead of the proper one? Simply because it's dirt cheap. They are the cheapest of the cheapest of the cheapest USB chips around. They frequently die. You might want to save up and invest in a genuine Arduino at some point, because that one may well die out of the blue.


body:
I had the same problem with the cheap nano from Amazon Longrunner. At first, it worked, I could program it. Then, I farted around with my COM port numbers because I was tired of being in the COM14 area.
Since that moment, it stopped working. IDE couldn't find the port COM3. After reading you guys, I also noticed that the device was identified RAMPS which it wasn't before. I updated the driver which didn't work; it told me I was already with latest driver.
So I deleted that driver and reconnected my Nano and lord and behold, the new driver USB-SERIAL CH340 installed and everything was fine. El cheapo still works. I don't care to pay more just for the USB chip which I will use only once. The uP is still up to par.


message:
programming via ISP

A short question:

I wonder weather I can program an AVR chip *(ATMega328, ATMega664, ATMega1284, ATTiny etc.)* using the Arduino IDE, via ISP, **without needing to bootload first.**

Does programming via ISP clear the bootload, if installed previously in the chip?

body:
As Ignacio mentioned, using ISP does not require a bootloader, however, it is also very nearly mutually exclusive with retaining one.

> Does programming via ISP clear the bootload, if installed previously in the chip?

Indeed, it does.  The ISP interface on the ATmega [cannot erase individual pages][1] but only the entire chip.  This is distinct from the [SPM instruction][2] used by a bootloader running on the chip itself, which can perform a partial erase.  It is also distinct from the ATxmega, which does apparently offer an ISP page erase capability.

So in order to end up with both a bootloader and sketch on the ATmega, you would need to erase the full chip, and then load both the bootloader and the sketch, either in a unified hex file or by loading one and then the other to distinct already-blank memory regions *while using the -D option to tell avrdude not to perform an automatic erase*.

I do not believe the the Arduino IDE supports this, rather its menu option to program a sketch via a programmer is intended to set up a chip for operation with a sketch alone and no bootloader.  There does not appear to be any way at GUI-level to configure it to do otherwise.

Someone determined enough could probably craft a customized board configuration that built a functional bootloader into every sketch (or merged or additionally programmed a pre-built one), allowing one shot installation of both an operable sketch and an operable bootloader that could field upgrade it.  However, the Arduino IDE would be a poor choice for production programming...

  [1]: http://www.avrfreaks.net/forum/isp-programming-preserve-bootloader
  [2]: http://www.atmel.com/webdoc/avrassembler/avrassembler.wb_SPM.html


message:
Getting POST data into a char array

I'm using Energia to program TI's CC3200 MCU. Since Energia is based off the Arduino IDE, I'm hoping someone can help me here.

I'm trying to get the CC3200 to act as a Webserver which when successfully starts up serves up a page with two fields for the username and password that the user needs to fill. Now I'm able to see that the two fields are being successfully POST'd (through Serial.write but only when the code to get it into `buffer` is not present) but I was hoping someone can help me get this content into a character array (called buffer declared before the setup loop begins).

The code in the section `//Here is where the POST data is` does not seem to be working as I see garbage values in `buffer` and in the `Serial.write`. How do I get these POST values into `buffer` OR even better how do I split the two field values and store them into two separate character arrays?

    void loop()
    {
      // listen for incoming clients
      WiFiClient client = server.available();

      if (client) {
        //Serial.println("Client connected");
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;

        while (client.connected()) {
          while(client.available()) {
            char c = client.read();
            // if you've gotten to the end of the line (received a newline
            // character) and the line is blank, the http request has ended,
            // so you can send a reply
            if (c == '\n' && currentLineIsBlank) {

             // Here is where the POST data is.
             Serial.println("Post data: ");
             int ctr = 0;
             while(client.available())
             {
          Serial.write(client.read());
          buffer[ctr] = client.read();
          ctr++;
         }
         Serial.println("Buffer: ");
         Serial.write(buffer);
         Serial.println();

         //Serial.println("Sending response");
         // send a standard http response header
         client.println("HTTP/1.0 200 OK");
         client.println("Content-Type: text/html");
         client.println("Connection: keep-alive");
         client.println();

         //form added to send data from browser and view received data in serial monitor
         client.println();
         client.println("<!DOCTYPE html>");
         client.println("");
         client.println("");
         client.println(" <FORM action=\"\" method=\"POST\">");
         client.println("
");
         client.println("    Username:");
         client.println("    <INPUT type=\"text\" name=\"uname\">

");
         client.println("    Password:");
         client.println("    <INPUT type=\"text\" name=\"pwd\">

");
         client.println("    <INPUT type=\"submit\" value=\"Submit\">");
         client.println("
");
         client.println(" </FORM>");
         client.println("");
         client.println("");

         client.println();

         client.stop();
            }
            else if (c == '\n') {
              // you're starting a new line
              currentLineIsBlank = true;
            }
            else if (c != '\r') {
              // you've gotten a character on the current line
              currentLineIsBlank = false;
            }
          }
        }
        //Serial.println("Disconnected");
        Serial.println();
      }
    }

body:
In this loop

    while(client.available()) {
        Serial.write(client.read());
        buffer[ctr] = client.read();

you're using `client.read()` twice, so the `buffer` gets only every second character.

A solution could be:

    while(client.available()) {
        int c = client.read();
        Serial.write(c);
        buffer[ctr] = c;


message:
How can I make push buttons react to being pressed instantly?

I am making an Arduino alarm clock. I am checking for the state of a button. If it is clicked, I increment the button counter. If the counter is divisible by 2, it is mode 0, if not, it is mode 1. I have small delays in the code for each mode to help the lcd clear itself. Those delays are preventing the buttons to reacting to my touch, because there is likely a delay during that time.

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    int hours=0;
    int minutes=0;
    const int modePin=6; //button
    int prevModeState=0; //prev state of button
    unsigned long timer;
    int modeState;//current state
    int mode=0;//mode of alarm
    int buttonCounter=0;
    void setup() {
    lcd.begin(16, 2);
    lcd.setCursor(6, 0);
    lcd.print("Time:");
    lcd.setCursor(6, 1);
    lcd.print("00:00");
    pinMode(modePin, INPUT);
    }

    void loop() {
    modeState=digitalRead(modePin);
    if(prevModeState!=modeState){    //this is the part where I check for the state
      if(modeState==HIGH){
        buttonCounter++;
      }
    }
    prevModeState=modeState;
    if(buttonCounter%2==0){
      mode=0;
    }
    else{
      mode=1;
    }

    if(mode==0){
      timer=millis();
      if(timer`0==0){
         minutes++;
        if(minutes==60){
            minutes=0;
            hours++;
            }
         if(hours==24){
            hours=0;
         }
        lcd.clear();
        lcd.setCursor(6, 0);
        lcd.print("Time:");
        lcd.setCursor(6, 1);
        writeTime();
        delay(200); //delay
        }
    }
    else if(mode==1){
      lcd.clear();
      lcd.setCursor(4, 0);
      lcd.print("Set Time:");
      lcd.setCursor(6, 1);
      writeTime();
      delay(500); //delays

    }
    }

    void writeTime(){
    if(minutes<10){

          if(hours<10){
            lcd.print(String("0")+hours+":"+"0"+minutes);
          }
          else{
            lcd.print(hours+String(":")+"0"+minutes);
          }
        }
        else{
          if(hours<10){
             lcd.print(String("0")+hours+":"+minutes);
          }
          else{
             lcd.print(hours+String(":")+minutes);//possibly split if problems arise
          }

        }
    }

How can I edit my code?

body:
You have a few options, including using interrupts. But I believe the most important thing is: "do not use delay()" and you might not even need to use interrupts...

Have a look on this nice post from Nick Gammon: [http://www.gammon.com.au/blink][1] with some tips about non-blocking coding.

Also a very simple "Blink LED" example: [https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay][2]

  [1]: http://www.gammon.com.au/blink
  [2]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


body:
The simple answer is, of course, don't use any `delay()` calls. There is no need for them in your code.

> I cannot remove delays since lcd.clear(); would be done very often and nothing would be visible on the lcd.

So don't clear the LCD. There is no reason to clear the LCD. Just over-print the existing text with new text. Go on, have a go. Just remove the `lcd.clear()` calls and the delays from your program and see just how smoothly the screen updates.

On an LCD a cell can only hold one character at a time. Printing one thing and then printing something else in the same place replaces the characters that are already there with the new ones. There is rarely any need to use `lcd.clear()` for normal screen updates - only if you really need to clear the *entire* screen should you use it. Just updating a bit of text on the screen does not require clearing of the entire screen.

In fact, you don't even need to print `Time:` or `Set Time:` every loop - you only need to do that once when you change mode. If you are going to clear the screen that is the time to do it.  So a quick outline:

* When button pressed:
   * Set mode
   * Clear screen
   * Print static text (`Time:` etc)
* Every iteration:
   * Print the mode's dynamic text

You see the heavyweight screen clearing is only done once when you change mode. All the rest of the time it's just updating small portions of the screen. Not only does it look nicer (no flicker) but it's also considerably more efficient and allows your program to do more.


message:
How can i receive data from Mega2560 on PC with Visual C#

How can i receive the data from my Arduino Mega 2560 with Visual C# on my PC.

I send a short databyte (2 bytes) and a timestamp (4 bytes) over USB to PC

    //initialization

    const int RX = 0;
    const int TX = 1;

    void setup(){

    pinMode(RX, INPUT);   //readpin for USB
    pinMode(TX, OUTPUT);  //writepin for USB
    ...

    Serial.begin(28800);   //open interface
    }

     //loop()

     Serial.print(incomingByte, BIN); //sending databyte

     sendBinary(currentMillis);   //send timestamp

    //method for timestamp

    void sendBinary(long currnetMillis)
     {
      int temp = currentMillis&0xFFFF;  //16 bit of the low-byte
      sendBinary(temp);
      temp = currentMillis >> 16;       //16 bit of the high-byte
      sendBinary(temp);
     }

I have surched in the internet for an example but i didn´t find a good. So i ask here what ist the best way with Visual Studio C# to receive the incoming data?
An example code will be nice because i´m a beginner and didn´t understand the jargon.

With frindly wishes sniffi

body:
I haven't tried the code below, but it should point you in the right direction.

All you have to do is write a C# program that opens the Serial port that your Arduino is connected to and read and write from there like you would from a file.

 1. Open Visual Studio, create a C# command line project.

 2. Paste this code inside main()

            System.IO.Ports.SerialPort port = new SerialPort("COM1", 9600);
            try
            {
                while (true)
                {
                    int readData = port.ReadByte();
                    System.Console.WriteLine("Read {0} from the port", readData);
                }
            }
            catch(Exception)  // Press CTRL-C to exit.
            {
            }
            port.Close();

 3. Compile the code and run it.


message:
Thermometer project shows fluctuation due to varying sensor value and voltage

I built this thermometer that reads the sensor value from the temperature sensor and displays it on the LCD display. It basically works fine, but the displayed temperature shows a fluctuation between +/-2 degrees due to varying sensor value and voltage every second.
(This is my very first Arduino project and I am pretty new to electronics.)
The Arduino gets the power via my Mac through USB.

When I check the sensor value and voltage, it slightly differs each second (or whatever delay interval I use in my code). Sensor value is between 123-125 and voltage usually 0.7, but also changes slightly, which causes the temperature calculation to vary around 2 degrees, which for a "thermometer" is quite a lot.

Is there any way to stabilize it? Should I use a capacitor or another resistor?

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

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

Code:

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    const float powerSupply = 5.0;
    const int sensorPin = A0;
    const float baselineTemp = 23;

    void setup() {
      Serial.begin(9600);
      lcd.begin(16, 2);
      lcd.print("Temperature:");
    }

    void loop() {
      int sensorVal = analogRead(sensorPin);
      Serial.print("Sensor Value: ");
      Serial.print(sensorVal);

      float voltage = (sensorVal/1024.0)*powerSupply;
      Serial.print(", Volts: ");
      Serial.print(voltage);

      Serial.print(", degrees C: ");
      float temperature = (voltage - .5)*100;
      Serial.println(temperature);

      // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      lcd.print(temperature);
      // lcd.print(String(sensorVal) + ", " + String(voltage) + ", " + String(temperature));
      delay(1000);
    }

  [1]: https://i.stack.imgur.com/PLbKf.jpg
  [2]: https://i.stack.imgur.com/AYl3W.png

body:
There are a few things you might try to stabilize your readings.

1. Add a small ceramic capacitor, say 22pF between the analog signal from the temp sensor (green on your example) and ground;

2. Perform multiple reading from your analog, let's say 10, discard max. and min. values and calculate the average. Use this instead of a single reading;

3. User the "internal" voltage as reference. It's normally more stable than using the external 5V. Just bear in mind that you might need to use a voltage divider as the "interval" voltage reference max value is 1.1V (https://www.arduino.cc/en/Reference/AnalogReference);
4. Reduce the wire sizes and make sure all connections are OK.

Probably just by using technique number "2" listed above you'll get much more stable results and don't need any hardware, just a small looping. Also adding the capacitor would be quite simple.

Hope it helps. Cheers!


body:
What you need to do is take an averaged reading, this is because the sensor is always fluctuating, noise on the 5V line or the signal line. There are possible hardware solutions.

 - Adding a capacitor between `Vcc` and `Gnd` near the sensor, 0.1µf
 - Adding a [low-pass filter][1] on the signal line of the LM35 to Arduino
 - heatsink on the LM35(they are very sensitive to movement, giving odd readings)

The capacitor on the `Vcc` and `Gnd` will lessen the effects of voltage spikes from the rest of the Arduino's circuitry.

The low-pass filter will help give a more filtered output from the sensor with a better response over time.

        2.2k
    LM35>---------/\/\/\-0------<Arduino
          |
          |
          |
            === 1µF
             |
          |
            GND

The heatsink will allow the LM35 to get a better reading of the general temperature and not the temperature of the breeze from a window.

All three of the above solutions will probably give the best results.

What you could do in software too is to have an averaging algorithm/function in your code and actually take the averaged reading across the whole second that you delay the MCU.

An example of this would be:

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

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    const float powerSupply = 5.0;
    const int sensorPin = A0;
    const float baselineTemp = 23;
    int sensorVal = 0;

    //these are NEW
    unsigned long lastTime = 0;     // last time reading taken
    unsigned long currTime = 0;     //current time variable intialised
    float AverageReading = 0;

    float _readingAv = 0;   // static variable for keeping the averaged reading
    int _readingsCount = 0;
    int _readings = 100;     //the number of readings to take

    void setup() {
      Serial.begin(9600);
      //  lcd.begin(16, 2);
      //  lcd.print("Temperature:");
    }

    void loop() {
      currTime = millis();

      if ((currTime - lastTime) < 1000) {  //checks to see if a second has passed
        sensorVal = analogRead(sensorPin);

        if (_readingsCount < _readings) {
          _readingAv += sensorVal; //add the current value to the last
          _readingsCount++;
        }
        else {
          AverageReading = _readingAv / _readings; //get the average
        }
      }
      else {
        Serial.print("Sensor Value: ");
        Serial.print(sensorVal);

        float voltage = (AverageReading / 1024.0) * powerSupply;
        Serial.print(", Volts: ");
        Serial.print(voltage);

        Serial.print(", degrees C: ");
        float temperature = (voltage - .5) * 100;
        Serial.println(temperature);

        //~ reset the values used by the previous function
        _readingsCount = 0;
        lastTime = currTime;
        _readingAv = 0; //Important to set this back to 0 so not to get odd values

        // set the cursor to column 0, line 1
        // (note: line 1 is the second row, since counting begins with 0):
        lcd.setCursor(0, 1);
       // print the number of seconds since reset:
        lcd.print(temperature);
        // lcd.print(String(sensorVal) + ", " + String(voltage) + ", " + String(temperature));
      }

    }

Probably a better version of making [filtering code][2] of the LM35.

  [1]: https://en.wikipedia.org/wiki/Low-pass_filter
  [2]: http://www.elcojacobs.com/eleminating-noise-from-sensor-readings-on-arduino-with-digital-filtering/


message:
Arduino Wireless SD Shield

Is it possible to use the Wireless SD shield without the wireless function, or XBEE Module? I do not need it to be wireless it simply was cheaper than any other I could find, so I was wondering if it was possible to use it just like a normal, non-wireless SD Shield? Thanks!

body:
In general, on a combined "Something plus SD card" shield like this the SD card is a completely separate section to the rest of it. The only real exception is on some audio shields (mp3) where the SD card is directly controlled by the audio CODEC chip.

So yes, you can pick and choose which portions of the shield you actually use in your code. Just by not using the bits you don't want to use.


message:
Which relay should I use to control the power from mains?

I was making a home automation project in which I want to control appliances like a fan and a bulb through voice commands with the help of an arduino uno and a relay but I am confused which relay to use. Please tell me the specifications of a 4 channel relay fit for this project.

body:
There are two factors you need to consider when choosing a relay:

1. Can it power the devices I want it to power without the contacts melting?
2. Can I control it?

The first one is simple enough. Find out the current requirements for each of the devices and add them together. Make sure that the relay is capable of switching *at least* that much at the *AC* voltage of your country's mains supply.  If in doubt go slightly higher.

For the second point you need to consider the interfacing circuitry and what DC power supply you are using in your system. For instance, if you have a 12V power supply for the Arduino you might consider a 12V coil relay and use the 12V power as the switching power. If you are running from 9V then you might consider a 5V relay and use the Arduino's regulated 5V pin as the switching power source. Either way you need a driving circuit. That could be as simple as an NPN transistor, two resistors, and a diode (the circuit can be found throughout the web if you Google "Arduino Relay"), or more complex involving an opto-isolator.

The simplest solution is to find an all-in-one module - a relay with driver circuit all as a single product. There are many of these around directly targeted at the Arduino, and most are the slightly more complex (and thus better) opto-isolator driving circuit. You still have to consider the same two points - switching capacity and coil voltage - but you don't then need to worry about making your own driving circuit for them.


body:
In the US there is a set of products - plug-in modules - collectively known as X10, which uses signals sent over the house wiring to control devices elsewhere in the house. If they are available where you are, **this is the safest way to control mains-powered devices with an Arduino** because the Arduino needs no connection to the house wiring.

The Wireless Transceiver module receive X10 commands over RF and transmit them onto the power wiring. Using this and a small RF transmitter known here as "X10 Firecracker CM17A", your Arduino can be completely isolated from the house wiring, sending its control commands over the air instead. Amazon shows both products on [this page][1]; the CM17A (which you use by removing its circuit board from the plastic package), and the RF control module, of which you only need one. The transceiver module can directly control one fan or light; for additional devices you'd use any other, non-RF (read "less expensive") X10 module, which will "hear" whatever the transceiver module sends.

There is an Arduino library already written for X10 communication.

  [1]: https://www.amazon.com/s?ie=UTF8&page=1&rh=i:aps,k:x10 firecracker


message:
HTTP Requests using Arduino

I use this simple HTTP Post request to post some values on my API from Arduino using Switch. each time I push the switch it send a different values to API.

    void switch_led() {
    bool SwitchReading = digitalRead(SWITCH);
    if (SwitchReading == HIGH) {
    Serial.println("Now pressed....");
    state = state + 1;
    if (state % 2 != 0) {
      digitalWrite(LED, HIGH);
      char data1[] = "{""LDRValue"": 88888888}";
      Serial.println("\nStarting connection to led server...");
      if (client.connect(server, 8040)) {
        Serial.println("connected to post server");
        client.println("POST /api/sensor HTTP/1.1");
        client.println("Host: 192.168.2.116:8040");
        client.println("Content-Type: application/json");
        client.print("Content-Length: ");
        client.println(sizeof(data1));
        client.println();
        client.print(data1);
        Serial.println("1.finish");
      }
      Serial.println("2.finish");
    }
    else {
      digitalWrite(LED, LOW);
      char data2[] = "{""LDRValue"": 1111111111}";
      Serial.println("\nStarting connection to led server...");
      if (client.connect(server, 8040)) {
        Serial.println("connected to post server");
        client.println("POST /api/sensor HTTP/1.1");
        client.println("Host: 192.168.2.116:8040");
        client.println("Content-Type: application/json");
        client.print("Content-Length: ");
        client.println(sizeof(data2));
        client.println();
        client.print(data2);
        Serial.println("3.finish");
      }
      Serial.println("4.finish");
    }
    delay(500);
       }
    }

It works perfect for the first and second posts in both Arduino and API but at the third post it works fine on Arduino but it takes long time on the API(about 2 minutes to get the post).
The fourth and the fifth posts also works fine but the sixth is same as the third.
Knowing that my API works 100% with Raspberry Pi and it has no errors.

The same thing for PUT and GET.

After Edition:
After I remove the port number from the host line and using strlen(data)instead of sizeof(data), the POST request works but only for first 7th posts. The output of serial monitor on Arduino is like that:

    Attempting to connect to WPA SSID: WiFi-Repeater1

    WiFi connected
    SSID: WiFi-Repeater1
    IP Address: 192.168.2.149
    signal strength (RSSI):-66 dBm

    Starting connection to post server...
    connected to post server

    Starting connection to post server...
    connected to post server

    Starting connection to post server...
    connected to post server

    Starting connection to post server...
    connected to post server

    Starting connection to post server...
    connected to post server

    Starting connection to post server...
    connected to post server

    Starting connection to post server...
    connected to post server

    Starting connection to post server...

    Starting connection to post server...

    Starting connection to post server...

Before the Editing, it was always giving me "connected to post server" and It always posts but as I told you before It takes a lot of time at the 3rd 6th 9th 12th ..... Now after the 7th post it will not posts.

body:
I _THINK_ the problem might be the `client.println()` statement.  I believe REST messages should be terminated with a \r\n and I think println just does \n.  So if you change it to `client.println("\r")` it should start working on every message.

Also you might want to consider moving creating the message into a function to reduce the amount of code you have.


body:
I figure out the problem.

To solve the session between Arduino and the server must ended after each Post using  `client.stop();`

    void switch_led() {
          bool SwitchReading = digitalRead(SWITCH);
          if (SwitchReading == HIGH) {
            state = state + 1;
            if (state % 2 != 0) {
              digitalWrite(LED, HIGH);
              char data1[] = "{""LDRValue"": 88888888}";
              Serial.println("\nStarting connection to post server...");
              if (client.connect(server, 8040)) {
                Serial.println("connected to post server");
                client.println("POST /api/sensor HTTP/1.1");
                client.println("Host: 192.168.2.116");
                client.println("Content-Type: application/json");
                client.print("Content-Length: ");
                client.println(strlen(data1));
                client.println();
                client.print(data1);
              }
              client.stop();
            }
            else {
              digitalWrite(LED, LOW);
              char data2[] = "{""LDRValue"": 11111111111}";
              Serial.println("\nStarting connection to post server...");
              if (client.connect(server, 8040)) {
                Serial.println("connected to post server");
                client.println("POST /api/sensor HTTP/1.1");
                client.println("Host: 192.168.2.116");
                client.println("Content-Type: application/json");
                client.print("Content-Length: ");
                client.println(strlen(data2));
                client.println();
                client.print(data2);
              }
              client.stop();
            }
           }


body:
you may wish to do more than just client.stop:

    // ensure the client is clean
    while (client.connected()) { while (client.available()) client.flush(); }
    client.stop();

also; if you are using a WiFi shield; you may want to take a look at a known issue where on a failed connection; the socket isn't released. i simple patch is required to make it work flawlessly:

https://github.com/arduino-libraries/WiFi/issues/5


message:
how do you capture the top value in a fallen edge in analogs data (flex sensor)

Guys i'm working with a flex sensor and I'm trying to capture a specific value which is the moment before the user lets go of a flexed flex sensor and its represented as the top point of a falling edge as sub picture A in the picture I included. using an array I tried two methods, which can produce a close value at times but at other it will give me wrong values
first I tried the following logic, whenever I detect a value below a certain threshold it indicates that a fallen edge has occurred so get me the value that came right before it as shown in sub picture C but depending on the delay this can be quite unpredictable.

the second method is to store the maximum value of but this returns the peak and it's not always the top of the fallen edge as shown in subpicture B

what do you guys suggest to capture those values?
this is my code so far

    bool loaded = false;
    int threshold = 760;
    int index = 0 ;
    int _max=0;
    int values[4];
    int values_size = 4;
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      int data = analogRead(A0);

      if (loaded) {
        values[index] = data;
        if(data>_max){
          _max=data;
          }

        if (data < threshold) {
          loaded = false;
          Serial.flush();
          Serial.print('a');
          Serial.print(',');
          Serial.print(_max);
          Serial.println();
          _max=0;
          delay(300);
        }
        index++;
        index %= values_size;
      }
      else if ( data > threshold && !loaded) {

        loaded = true;
      }

      delay(20);

    }

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

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

body:
I suggest you consider as “top value of the falling edge” the maximum of
the values you have read during a specified time window before the edge
is detected. This means you have to compute the maximum at the time you
detect the edge. If you instead continuously compute a running maximum,
then you are going to get a global maximum. Amended source:

    bool loaded = false;
    int threshold = 760;
    int index = 0 ;
    const int values_size = 4;  // this controls the time window
    int values[values_size];

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

    void loop() {
      int data = analogRead(A0);

      if (loaded) {
        // Store the reading.
        values[index] = data;
        index = (index + 1) % values_size;

        // Detect falling edge.
        if (data < threshold) {
          loaded = false;

          // Find the max.
          int _max = 0;
          for (int i = 0; i < values_size; i++) {
            if (values[i] > _max) _max = values[i];
            values[i] = 0;  // clear, for next time
          }

          // Report it.
          Serial.flush();
          Serial.print('a');
          Serial.print(',');
          Serial.print(_max);
          Serial.println();
          delay(300);
        }
      }

      // Detect rising edge.
      else if (!loaded && data > threshold) {
        loaded = true;
      }
      delay(20);
    }

Notice the line `values[i] = 0;`. It is intended to avoid the reading of
one falling edge being seen on the next one.


message:
Using only Rx pin to receive data from HC 05 and attiny85 (Arduino IDE)

I was building a Bluetooth car with attiny85 (Arduino IDE) and HC05 bluetooth module. I need 4 IO pins to control the car. Since attiny have only 5vIO's, I am left with only 1 pin to connect to HC05. I would only be receiving data from HC05. So, I want to use that leftover pin as RxD to receive data.

#include //the software serial library
#define RxD 4

SoftwareSerial blueToothSerial(RxD);

But when I do this It gives the following error

No matching function for call to 'SoftwareSerial::SoftwareSerial(int)'

Though it works fine, when I also define a TxD pin. But I want to use only one pin (RxD). Please help.

body:
The constructor for the SoftwareSerial object expects to be given both a TX and and RX pin (and, optionally, a boolean value representing whether or not it should use inverse logic.) From SoftwareSerial.h, see:

    SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

If you want to use the library in the way you've written, you'll need to either modify the existing constructor or write a new one into the library.

As a quick test, I've added the following lines to each of the listed source files:

**SoftwareSerial.h**

    SoftwareSerial(uint8_t receivePin, bool inverse_logic = false);

**SoftwareSerial.cpp**

    SoftwareSerial::SoftwareSerial(uint8_t receivePin, bool inverse_logic /* = false */) :
    _rx_delay_centering(0),
    _rx_delay_intrabit(0),
    _rx_delay_stopbit(0),
    _tx_delay(0),
    _buffer_overflow(false),
    _inverse_logic(inverse_logic)
    {
      setRX(receivePin);
    }

Now there's a constructor that allows for a single RX pin argument like you've outlined in your initial example. The problem is that this is likely to break anytime the Arduino codebase gets updated and your changes get blown away.

Best practice may dictate writing your own driver to use the serial functionality of your ATTiny without the possibility of accidentally using the TX functions, but if this is a one-off then maybe Bence Kaulics' suggestion of just feeding it a nonsense pin would be the least time-consuming.


body:
I suggest you get rid of SoftwareSerial and use instead this [Simple
ATtiny USI UART](http://www.technoblogy.com/show?VSX). This is a driver
for a receive-only UART that uses the USI port of the ATtiny85. It is
superior to a software-only UART as it makes good use of the hardware,
leaving more time for the CPU to do more useful things (or sleep and
save battery). Also, unlike SoftwareSerial, it does not need to block
interrupts for long periods, which is a good thing.


message:
Wired IoT sensor network with PoE?

**Objective:** Maybe I'm a bad Googler, but I am finding very little on ***wired*** Internet of Things sensor networks using Arduino.

**Project Goals:**

 - Arduino based sensor nodes that connect to the local network (not out to the internet)
 - All the benefits of adding adding/removing nodes, moving nodes, adding new routers for more ports.
 - Black box sensors that don't take any soldering to plug into the network (although they contain soldered components in the black box.
 - Using a master Raspberry Pi on the network to identify the nodes and read data from them.
 - Using Power over Ethernet (PoE) to power my sensor nodes.
 - Don't want to actually connect to the outside internet, just want the convenience of assembling a network with node names and such.

**Why not use wireless solutions (e.g. XBee):**

Currently, it seems Xbee is the way to go, but I don't want a wireless solution.

- I want the reliability of a wired connection.
- I don't want to have to worry about batteries

**What I'm doing right now:**

Currently, I have all my sensors wired to a central Arduino MEGA using 4-conductor security cable (Vcc, GND, and two signal conductors). The MEGA communicates over serial with a Raspberry Pi. This is annoying for the following reasons:

- I have to solder/unsolder every time I want to change something.
- I have to figure out which digital I/O pins are available on the MEGA and have to write down which signal conductor goes to which pin on the MEGA and means what on the sensor.
- There is a finite number of pins.
- Each sensor is its own unique project. I want to start standardizing these sensors to clean up the code.

**What I have found so far:**

I've been looking at XPort sensors; however they are very expensive (i.e. $60 ea.) and don't support PoE. If there is a solution using Arduino and an Ethernet Shield, it brings down the base cost of a sensor by a lot.

**Request:**

Where can I find out more information about *wired* Arduino sensors? Are there any prebuilt solutions that already do what I am looking for?

body:
I think I am using a setup like you wish at my home:

1. PoE Switch (for example Cisco SG300-28P)
2. Arduino Ethernet's with PoE Module (https://www.arduino.cc/en/Main/ArduinoBoardEthernet) I bought one for every room ;-)
3. Use DHCP-Server on raspberry PI
4. Put your sensors on your Arduino ethernet board
5. I am also using MQTT as protokoll for example http://pubsubclient.knolleary.net/
6. Use MQTT broker Mosquitto on raspberry pi

For the case that you want to use your switch also for internet connectivity, define a vlan (search wikipedia) for your arduino sensor network.

Hope that helps.


body:
Enviromon.net has [PoE sensors][1] that are plug and play with their base units. The base unit is then connected to your internal network.

If your a bit more experienced (which it seems you are) their base units can also be integrated into other systems like network monitoring apps, and SCADA programs.

You could most likely configure the base unit to slave to your raspberry pi, and bonus, no soldering. All their sensors are PoE. Although unfortunately they are not for the Arduino.

But you mentioned if anyone knew if there was a prebuilt solution.

Heres a link to their sensors you might be interested in http://www.enviromon.net/environmental-monitoring-sensors/

  [1]: http://www.enviromon.net/environmental-monitoring-sensors/


message:
How can I control 4 DC motors with an Arduino?

In a few months, I am planning to construct an Arduino robot with multiple sensors etc. I will use an arduino mega and a 4wd chassis like the one here: [Chassis. ][1] The chassis uses 4 DC motors. I was planning to use a motor shield, but I realized that it only fits an Arduino Uno(not Mega) and it controls only 2 DC motors. What can I do to make all 4 DC motors move forward and backward? If I use a motor driver board that controls 2 motors, can I connect the 2 right and 2 left motors in parallel together and the control it through the Arduino?

  [1]: http://www.ebay.com/itm/NEW-4WD-Robot-Smart-Car-Chassis-Kits-car-with-Speed-Encoder-for-Arduino-M26/201561877173?_trksid=p2047675.c100009.m1982&_trkparms=aid=777000&algo=ABA.MBE&ao=1&asc=36860&meid=c76077722d4348e88152fa6c7f32c005&pid=100009&rk=1&rkt=1&sd=181329341315

body: Yes, you can actually do this, but you have to consider the current of the motors and the motor driver. For example, if you have 12V, 2 Amps motors, then you need a 2-channel motor driver that is able to output a little higher that 4 Amps (2*2 Amps) for each channel at 12V. You will need to connect each two motors on the same side in parallel to one channel.


body:
Yes, you can do this using 2 L293D motor drivers, each motor driver can run 2 motors and it is very easy to use.
[![enter image description here][1]][1]

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

You should connect Vcc 1(used to power on the chip) to 5V and Vcc 2 to a power supply that is needed to run your motors, Enable 1,2 and Enable 3,4 are used to enable the 2 sides of the chip and should be connected to 5V. Outputs 1-4 are the outputs to 2 motors and Inputs 1-4 are the inputs from the micro-controller.


message:
Why doesn't my 1602A LCD display text with this code?

<!-- language: c++ -->

    #include <SPI.h>
    #include <MFRC522.h>
    #include <LiquidCrystal.h>
    #include <Servo.h>

    #define RST_PIN 9 // Configurable, see typical pin layout above
    #define SS_PIN 10 // Configurable, see typical pin layout above

    MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    Servo myservo; // create servo object to control a servo

    String read_rfid;
    String ok_rfid_1 = "6722323b";
    String ok_rfid_2 = "99be859e";
    int posClosed = 180; // variable to store the servo position for locked
    int posOpen = 0; //same for open...

    /*
      Initialize.
    */
    void setup() {
      Serial.begin(9600); // Initialize serial communications with the PC
      while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
      SPI.begin(); // Init SPI bus
      mfrc522.PCD_Init(); // Init MFRC522 card
      lcd.begin(16, 2);
      lcd.clear();
      lcd.print("Scan your card:");
      Serial.println("Scan your card:");
      //Choose which lock below:
      myservo.attach(7); // attaches the servo on pin 7 to the servo object
    }

    /*
      Helper routine to dump a byte array as hex values to Serial.
    */
    void dump_byte_array(byte *buffer, byte bufferSize) {
      read_rfid = "";
      for (byte i = 0; i < bufferSize; i++) {
        read_rfid = read_rfid + String(buffer[i], HEX);
      }
    }

    void open_lock() {
      //Use this routine when working with Servos.
      lcd.print("Servo Unlocking");
      myservo.write(posOpen);
      Serial.println("Servo Unlocking");
      delay(10000);
      myservo.write(posClosed);
      lcd.clear();
      lcd.print("Servo Locking");
      Serial.println("Servo Locking");
    }

    void loop() {
      lcd.clear();
      lcd.print("test");
      // Look for new cards
      if (!mfrc522.PICC_IsNewCardPresent())
        return;
      // Select one of the cards
      if (!mfrc522.PICC_ReadCardSerial())
        return;
      dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
      if (read_rfid == ok_rfid_1) {
        open_lock();
        lcd.clear();
        lcd.print(read_rfid + " (FRED FARMER)" + " -Access Granted");
        Serial.println(read_rfid + " (FRED FARMER)" + " -Access Granted");
        delay(10000);
        lcd.clear();
        lcd.print("Scan a card:");
        Serial.println("Scan a card:");
      }
      if (read_rfid == ok_rfid_2) {
        open_lock();
        lcd.clear();
        lcd.print(read_rfid + " (JOHN DOE) " + " -Access Granted");
        Serial.println(read_rfid + " (JOHN DOE) " + " -Access Granted");
        delay(10000);
        lcd.clear();
        lcd.print("Scan a card:");
        Serial.println("Scan a card:");
      } else {
        lcd.clear();
        lcd.print(read_rfid + " -Access Denied");
        Serial.println(read_rfid + " -Access Denied");
        delay(10000);
        lcd.clear();
        lcd.print("Scan your card:");
        Serial.println("Scan your card:");
      }
    }

I have tried running the Arduino library's "Hello World" example, and it successfully runs the text onto the screen. Therefore I have determined that it is not a hardware problem, rather a code problem. It occasionally does display "ff" on the LCD, but that's it.

body:
Pins number 12, 11 are used by some other library in your code. And that's the reason there is no LCD output. Change pins/connections from 12, 11 to 7, 6.

Then your code uses `lcd.clear()` too often, so whatever data you display vanishes before you were able to read. Don't clear the display unnecessarily.


message:
How can I made my Arduino follow the time exactly?

I am making an Arduino clock. You can set time to it, and then it keeps on going. The problem is that it is always within a minute off. It is not a major issue, but one that I would like to fix. I use the millis function. The program checks if millis is evenly divisible by 60,000(1 minute). After I set the time, millis is NOT at 0, meaning that is ahead of what I set by a number of seconds. How can I fix this? Code:

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    int hours=0;
    int minutes=0;
    const int modePin=6; //button
    int prevModeState=HIGH; //prev state of button
    unsigned long timer;
    int modeState;//current state
    int mode=0;//mode of alarm
    int buttonCounter=0;
    const int incrementPin=9;
    const int switchPin=7;
    int incrementState;
    int switchState;
    int prevIncrementState=HIGH;
    int prevSwitchState=HIGH;
    int switching=0;

    void setup() {
    lcd.begin(16, 2);
    lcd.setCursor(6, 0);
    lcd.print("Time:");
    lcd.setCursor(6, 1);
    lcd.print("00:00");
    pinMode(modePin, INPUT_PULLUP);
    pinMode(incrementPin, INPUT_PULLUP);
    pinMode(switchPin, INPUT_PULLUP);
    }

    void loop() {
    modeState=digitalRead(modePin);
    if(prevModeState!=modeState){
          prevModeState=modeState;
       if(modeState==LOW){
        buttonCounter++;
      if(buttonCounter%2==0){
        mode=0;
        lcd.clear();
        lcd.setCursor(6, 0);
        lcd.print("Time:");
        writeTime();
    }
      else{
        mode=1;
        switching=0;
        lcd.clear();
        lcd.setCursor(4, 0);
        lcd.print("Set Time:");
    }

       }
      }
    if(mode==0){
      timer=millis();
      if(timer`000==0){
         minutes++;
        writeTime();
        }
    }
    else if(mode==1){
     incrementState=digitalRead(incrementPin);
      switchState=digitalRead(switchPin);
      if(prevSwitchState!=switchState){
        prevSwitchState=switchState;
        if(switchState==LOW){
        switching++;
        }
        if(switching==4){
          switching=0;
        }

        }

      if(prevIncrementState!=incrementState){
        prevIncrementState=incrementState;
        if(incrementState==LOW){
          if(switching==0){
            if(hours<14){
            hours+=10;
            }
            else if((hours>=14)&&(hours<20)){
            hours-=10;
            }
            else{
              hours-=20;
            }
            }

            else if(switching==1){
              if((hours==9)||(hours==19)){
                hours-=9;
              }
              else if(hours==23){
                hours-=3;
              }
              else{
              hours++;
              }
            }

            else if(switching==2){
              if(minutes<50){
                 minutes+=10;
              }
              else{
                minutes-=50;
              }

            }
            else if(switching==3){
              if(minutes==9){
                minutes-=9;
              }
              else{
              minutes++;
              }
            }

        }

      }

      writeTime();
    }
    }

    void writeTime(){
      lcd.setCursor(6, 1);
       if(minutes>=60){
            minutes=0;
            hours++;
            }
         if(hours>=24){
            hours=0;
         }
    if(minutes<10){

          if(hours<10){
            lcd.print(String("0")+hours+":"+"0"+minutes);
          }
          else{
            lcd.print(hours+String(":")+"0"+minutes);
          }
        }
        else{
          if(hours<10){
             lcd.print(String("0")+hours+":"+minutes);
          }
          else{
             lcd.print(hours+String(":")+minutes);//possibly split if problems arise
          }

        }
    }

body:
Three things you can do - any combination of these is good, but the more the better:

1. Use an RTC module to keep more accurate track of the time.
2. Connect the Arduino to the internet and use NTP to get the exact time.
3. Use the time provided by GPS.

The RTC chip can keep track of time when there is no external power, using just a very small button cell.
The GPS and internet time are both very accurate.

Using either or both of those sources to set and maintain the correct time in the RTC chip is the best and most accurate way of keeping the right time on the Arduino.

To increase the accuracy of your existing method you should count seconds, not minutes.

Start by recording the current millis. When 1000 of them have passed you can increase your seconds.  Don't rely on `millis() % 1000` since you may miss it whilst doing other things. Also don't rely on your millisecond counter check executing at exactly 1000ms intervals - work on the principle of "at least 1000ms" and move the next check to 1000ms from where it *should* have happened, not where it *did* happen.  This can help to combat some clock drift.

    static unsigned long mscount = millis();

    if (millis() - mscount >= 1000) {
        mscount += 1000;
        seconds ++;
    }

Then every 60 seconds you can increase your minutes:

    if (seconds == 60) {
        seconds = 0;
        minutes ++;
    }


body:
First of all, let me second Majenko in suggesting the use of an RTC. The
Arduino Uno is clocked from a ceramic resonator, and these are nowhere
accurate enough for proper timekeeping. C.f. the answers to [How do I
get an accurate time?](https://arduino.stackexchange.com/questions/27).

Next, instead of counting seconds, I suggest you instead count
_milliseconds_. I know it sounds like overkill, but it's actually
simpler because you already have `millis()` returning a millisecond
count:

    void loop()
    {
        uint32_t now = millis();
        static uint32_t last_minute;

        // Increment the time every minute.
        if (now - last_minute >= 60000) {
            last_minute += 60000;
            if (++minutes >= 60) {
                minutes = 0;
                if (++hours >= 24)
                    hours = 0;
            }
        }

        // Do not advance the seconds when the user sets the time.
        if (time_is_being_set_by_the_user()) {
            last_minute = now;
        }
    }

Oh, wait! No! Do not count milliseconds, instead **count microseconds**:

    void loop()
    {
        uint32_t now = micros();
        static uint32_t last_minute;

        // Increment the time every minute.
        if (now - last_minute >= 60000000) {
            last_minute += 60000000;

            // The rest does not change...
        }
    }

Why? Because, as I said before, the ceramic resonator of your Arduino is
not very accurate. You will eventually find out that it drifts
significantly. However, if you compare to a good reference, you will be
able to _calibrate_ the drift. If, for example, you find that it drifts
forward by 0.0025% (about 15 seconds per week, quite optimistic), you
will be able to fix it simply by replacing 60000000 by 60001500. The
same would work if counting milliseconds, except that you would only be
able to do a coarse tuning. Oh, and do [not worry about `micros()`
overflowing](https://arduino.stackexchange.com/a/12588).