message:
How do I use Microduino (mCookie) on Linux?

I'm interested in getting the [mCookie][1] working in Linux — specifically, in Fedora 23. The Arduino IDE (version 1.6.4) is already available. I'm very familiar with Linux, fine with C, and completely new to Arduino.

The tutorials for [Windows][2] or [Mac][3] describe installing a customized version of the IDE along with drivers. Do I _need_ special drivers on Linux? On the projects' GitHub site, I found [the examples](https://github.com/wasdpkj/Microduino-IDE-Support/tree/master/arduino-ide-Support/[1.6.x]-hardware(library)/examples/00.mCookie) and [a directory called 'avr'](https://github.com/wasdpkj/Microduino-IDE-Support/tree/master/arduino-ide-Support/[1.6.x]-hardware(library)/hardware/Microduino/avr) which has promising subdirectories like "bootloaders" and "libraries", along with files `boards.txt` and `platform.txt`.

Can I download this stuff and add it to the existing "system" arduino package somehow? How, and what will I need?

  [1]: https://wiki.microduino.cc/index.php/MCookie_Series
  [2]: https://wiki.microduino.cc/index.php/Getting_started:_Windows
  [3]: https://wiki.microduino.cc/index.php/Getting_started:_Mac

body:
First you will need the `arduino` 1.6.x package from `updates`, not the 1.0.x package from `fedora`. Then:

> You will be adding a URL to the new Additional Boards Manager URLs option: https://github.com/wasdpkj/Microduino-IDE-Support/raw/master/package_Microduino_index.json

source

This tutorial tells you where and how to add that URL to the preferences, as well as how to actually install the required support files.

----
As of this writing, the platform configuration supplied as part of the above won't work out of the box in Linux; you will also have to edit `~/.arduino15/packages/Microduino/hardware/avr/1.6.7/platform.txt` to:

* replace `compiler.path={runtime.tools.avr-gcc.path}/bin/` with just `compiler.path=/usr/bin/`
* on the line starting `recipe.ar.pattern=`, change `{archive_file_path}` to `{build.path}/{archive_file}`

Hopefully this will be fixed in future versions.

----
You probably also want to prevent ModemManager from probing the serial device with this udev rule, just replace the vendor and product IDs as appropriate:

    SUBSYSTEM=="usb-serial", ATTRS{idVendor}=="xxxx", ATTRS{idProduct}=="xxxx", ENV{ID_MM_DEVICE_IGNORE}="1"


sender: user

message:
How to serve multiple connections with an ESP8266 and an Adruino?

I want to make a server using an ESP8266 (12e) and an Arduino Nano.
I have got everything hooked and I created a minimal "Hello World" example, based on a number of samples found on the web, which is working fine... as long as the ESP does not receive multiple requests simultaneously.

I am using SoftwareSerial on pins 8 and 9 of my Arduino Nano.

As long as I send one request at the time, things work fine.
If I use two browsers and send two requests with little interval, things go wrong, and that figures: the `sendData()` method just reads from the serial connection. It will consume the new request while waiting for an "OK" from the initial request...

Is there any sample code or library (for ESP + Arduino (nano)) that can handle correctly multiple concurrent connections?

Thanks

My code:

    /*
      Software serial multple serial test
     */
    #include <SoftwareSerial.h>

    #define DEBUG true

    SoftwareSerial esp8266(8, 9); // RX, TX

    void setup() {

      Serial.begin(9600);
      esp8266.begin(9600); // your esp's baud rate might be different : 115200

      Serial.println("Setup...");

      /*
      sendData("AT+RST\r\n",2000,DEBUG); // reset module
      sendData("AT+GMR\r\n",1000,DEBUG); // get version
      sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
      sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
      sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
      sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
      */

      sendData("AT+RST\r\n", 2000,DEBUG);
      sendData("AT+GMR\r\n", 1000, DEBUG);

      sendData("AT+CWMODE=1\r\n",1000,DEBUG); // configure as station
      sendData("AT+CWJAP=\"******\",\"*******\"\r\n", 6000, DEBUG);
      sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
      sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
      sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

      Serial.println("Setup ready.");
    }

    //WIRE RESET TO HIGH!!?

    void loop() { // run over and over

    if(esp8266.available()) // check if the esp is sending a message
      {

        if(esp8266.find("+IPD,"))
        {
         delay(1000);

         int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                               // the ASCII decimal value and 0 (the first decimal number) starts at 48

         String webpage = "
Hello World!
";

         String cipSend = "AT+CIPSEND=";
         cipSend += connectionId;
         cipSend += ",";
         cipSend +=webpage.length();
         cipSend +="\r\n";

         sendData(cipSend,1000,DEBUG);
         sendData(webpage,1000,DEBUG);

         String closeCommand = "AT+CIPCLOSE=";
         closeCommand+= connectionId; // append connection id
         closeCommand+="\r\n";

         sendData(closeCommand,250,DEBUG);
        }
      }

    }

    String sendData(String command, const int timeout, boolean debug)
    {
        String response = "?";
        int pos = -5;

        Serial.println("--------------");
        Serial.println(" sending "+command);

        esp8266.print(command); // send the read character to the esp8266

        long int _timeout = timeout + millis();

        while( (_timeout) > millis())
        {
          while(esp8266.available())
          {
            // The esp has data so display its output to the serial window
            char c = esp8266.read(); // read the next character.
            response+=c;
            pos+=1;
            if(pos>=0 && response.substring(pos) == "\r\nOK\r\n"){
              //WE GOT OK -> stop waiting
              _timeout=0;
            }
          }
        }

        if(debug)
        {
          Serial.println(" response: "+response);
        }

        return response;
    }

sender: assistant

body:
I might not have understood what you are trying to do, but if it is to use the ESP8266 to allow the Nano to connect to WIFI and act as a web server then I believe you are doing this the hard way.

The ESP8266 is an 80 or 160MHz microprocessor with 64KB Program Ram + 96KB data RAM.  You are using a 16/32MHz microprocessor to generate pages and pass them to it.  I would recommend that you investigate using the Arduino IDE to program the ESP8266 in "Arduino C" it comes with a set of examples that include webservers (which is what I think you are trying to do).  Keep the Nano if the ESP8266s 10 digital and one analogue ports aren't enough to interface to you hardware.


body:
I had the same experience. When you send data by an AT command and receive something from another connection at the same time, then the ESP chip starts to behave unexpectedly. Sometimes it sends the data but does not respond with OK. Sometimes it does not send. And sometimes it ignores received data (missing +IPD message).

The AT firmware works only well with single telnet-style connections. I mean half-duplex communication where it never happens that more than one sender is "talking" at the same time.

I hoped that this issue becomes solved over time, but the modules that I bought recently (with AT Firmware 1.4) are still not better. However, I did not notice any unexpected auto-reset or hangup anymore in my 2-Week test loop. At least that became better.


message:
Arduino shuts off and doesn't turn on after couple hours

I use a mega 2560, pir sensor and a SG90 9g Servo motor in my project. Basically while the pir outputs high, the Servo Motor rotates from 0 to 180 degrees.

Here is how everything is wired up:

**PIR sensor:**

Data: pin 24

Vcc: 5 volt

Gnd: Ground

**Servo:**

PWM pin: pin 11

Vcc: 5 volt

Ground: ground

The arduino mega has two 5 volt and ground pins, one next to the analog pins and other at tho bottom bar of pin, where pins 22 and up are. I connected the Servo to the first 5v and gnd and the pir to the second.

My power source is my nexus 5 charger(5v 1.8 or 2 A).

My code:

    Servo myservo;

        void setup() {
          myservo.attach(11);
         pinMode(24, INPUT);
        }

        void loop() {
         if(digitalRead(24) == HIGH){
           myservo.write(0);
           delay(500);
           myservo.write(180);
           delay(500);
         }
        }

All of this works fine for the first ~10 hours. After that the arduino just shuts down. The power led of the arduino isn't lit up. Disconnecting the adapter and reconnecting it or pressing the reset button of the arduino doesn't work.  I Have to wait for a couple of minutes with the adapter disconnected and reconnect it. After that it works fine for the next ~10 hours.

Seems like a hardware issue, but I'm not sure what exactly fails and why.

body:
`The power led of the arduino isn't lit up.`

The power LED is implemented in hardware, basically, if it's not lit, it won't work.

**Find the problems' (power?)source**

After the 10h operation, your Arduino isn't on anymore.

Does the power supply still have 5V available at that point? Or does your Arduino's chips get hot or short-circuit the supply?

**Exclude as much variables as possible**

You don't know what the problem is, it could be:

 - The supply
 - The Arduino
 - The Servo
 - The PIR

Try another supply (preferably through the barrel jack, since it's regulated) (The supply may have some "protection" to avoid it being on too long).

Try another Arduino (unlikely?).

Try no servo & pir connected. (They may draw too much current, so the Arduino shuts down or create electrical noise.)


body:
I assume your charger is connecting to the USB port of the Mega2560.

That USB port has a *polyfuse* (actually a special type of positive-coefficient thermistor) which is normally rated at around 500mA (polyfuses are a bit woolly with their ratings since they are heat based).

If you are drawing near that limit of current the fuse will be gradually heating up. I would think that after 10 hours it may have reached its threshold temperature and thus switches the power off.

Disconnecting the power and allowing it to cool down would then make the board work again.

How can you test it?  Well, next time it switches itself off try bypassing the polyfuse (tweezers would be good to do that with) to see if the power LED turns on again.

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

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


body:
I'm just going to hazard a guess: Your 5v line isn't staying at 5v because of the servo. They draw massive amounts of power quickly, and can wreck a lot of havoc. Many times electronics "kinda" work after voltage drops, but will lock up or glitch eventually.  (To get confirmation that this is the problem, monitor your 5v power with an oscilloscope. Set a trigger at 4.5v and try to capture the voltage drops.)

If that is the problem, you need better isolation on your digital power (running the arduino) and your analog power (running the servo.)  Two ideas to try (you may need both):

1)  Get a big cap (say 100 uF or more), then put it across your power to the arduino. If it's big enough, it will prevent your 5v from sagging. It may be expensive to get a big enough cap.

2) Instead of connecting your servo directly to 5v, put a small resistor (say 10 ohm) between them.  Now when he tries to suck all the power, it will get resistance, which will limit the current. The bigger the resistor the better the isolation, but too big will prevent your servo from working. (And may heat up your resistor).


message:
How to convert voltage to current from ACS712-20A?

I've been used the ACS712-20A to measure the current flow. Actually I used LIFA program (LabVIEW interface for Arduino).

I used this equation:

current = ((analog read)-2.5 )/ 0.1

But I am still not sure with the result.

Any suggestion?

body:
According to the datasheet you have 100mV per ampere, and a zero offset voltage of Vcc × 0.5.

So assuming you are correctly converting the ADC reading into a floating point voltage the instantaneous current can be calculated with the formula

    i = (Vadc - 2.5) × 10

Or for milliamps,

    i = (Vadc - 2.5) × 10000

If you are measuring a DC current that is then all well and good.  However, if you are measuring an AC current things get considerably more complex.

To work out an AC current you need to have the peak-to-peak voltage, not the instantaneous voltage.  To get that you need to sample the ADC over a number of cycles and find both the maximum and minimum values.  You can then subtract the minimum from the maximum to give you the peak-to-peak voltage.  That can then give you the peak-to-peak current.

From that you can then calculate the RMS current.


message:
Arduino Nano clone doesn't fit into breadboard. How can I work around this?

I have bought an arduino nano clone (called funduino) and upon trying to place it into my breadboard to work with it I realised that the pins do not line up with the holes on the breadboard so I simply can't use the funduino...

[![Nano Clone][1]][1]

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

Does anyone have any recommendations on how I can get around this?

body:
You might be able to use [these female to female jumper][1] wires and [these headers][2] and hook up the board and breadboard like this:

[![enter image description here][3]][3]

Note, the square female cable ends may not fit closer than 0.1 inches on center.

A more compact and (possibly) mechanically difficult solution may be implemented using wire-wrap sockets.  You may be able to leave the sockets intact and deform the pins to match the breadboard.  Or you may need to remove the pins from the plastic in order to accommodate your (different) Nano:

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

  [1]: https://www.adafruit.com/product/266
  [2]: https://www.adafruit.com/products/400
  [3]: https://i.stack.imgur.com/5XVIP.jpg
  [4]: https://i.stack.imgur.com/EgfPZ.jpg


body:
Because of the same issue, I use mine with a miniature breadboard:

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

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


message:
upload real time ultrasonic sensor data to pubnub using arduino and esp8266

I want to upload the real time data of ultrasonic sensor attached to my Arduino  Uno and I have been using esp8266 module for the WiFi connection.

I want to upload to [PubNub][1] but I don't know how to start writing the code for PubNub and where do I have to write the code.

I have the code working on my Arduino using the ultrasonic sensor in C++ language, printing the readings on the serial monitor. However, the code will be definitely changed in order to upload the sensor readings to PubNub.

On PubNub the most used SDK is JavaScript and I'm not very familiar to it. For C++ the most used SDK is Posix but it seems way more difficult more than JavaScript. So how I have to translate the code from C++ to JavaScript to get it published on PubNub?

Sorry, I am completely new to this stuff therefore I don't know much about it.

  [1]: https://www.pubnub.com/

body:
The PubNub website has a link to an Arduino library:

[https://github.com/pubnub/arduino][1]

Although it doesn't have specific support for the ESP8266 per se, it does support the [Arduino Ethernet Shield][2], [Arduino Wifi Shield][3] and [Arduino Wifi101 Shield][4], so I would imagine it wouldn't be hard to adapt the code.

Be aware that for the Arduino Uno, the SRAM will be fairly limited, where as the  ESP8266 contains [96 KB of DRAM][5].

  [1]: https://github.com/pubnub/arduino
  [2]: https://www.arduino.cc/en/Main/ArduinoEthernetShield
  [3]: https://www.arduino.cc/en/Main/ArduinoWiFiShield
  [4]: https://www.arduino.cc/en/Main/ArduinoWiFiShield101
  [5]: https://www.espressif.com/en/products/hardware/esp8266ex/resources


message:
Are there any online data analysis websites for arduino IoT projects?

I am planning on making a system where multiple arduinos monitor the conditions of certain type of plant. (Each arduino monitors its own plant, but the plants are of the same species). Each plant would have a different placement in the yard(varies the light). The plants are watered as normal, without an exact amount of water. The arduinos would measure light, temperature, and soil water content. Each would send it to the cloud. My question is: Is their a cloud service that can analyze and "find" the best conditions(amount of water,light,temperature,etc) for type a plant, based on how healthy the plants are?(The health of the plants would be entered in manually by the person using the system). (Sorry if my question doesn't make sense, please ask me any questions you have ,Thanks.)

body:
To send data to cloud you will need an internet shield and given that the individual plants are far apart, you will need a wifi shield for each plant that you want to monitor most likely the yun shield.
Now for online services, there are a few like Temboo, Pushingbox, Initial State, Cayenne, Xively.
Each of them works differently and you will need to choose which best suit you.


message:
Can you pass params to an arduino sketch?

I was wondering if there is a way to pass parameters to an arduino sketch at the upload step.

Edit: The reason this would be helpful is because I have a bunch of esp8266 units that need to have details about their specific location but changing variables around per upload feels tedious.

If this is not possible the other solution that I am probably going to try is to have a sketch to just flash these details to eeprom and then read it from there whenever it is needed. Also storing them in eeprom feels a bit better than as literals in these sketches.

body:
Every ESP8266 has a unique MAC address. You could that information to distinguish between the different units.

Something like `if( mac='00:0a:95:9d:68:16' ){ ... }`


body: Another option, if you can afford the pins, is to install DIP switches or ground-jumpers on a few pins and set / wire a different n-bit code onto each board. Set those pins to INPUT_PULLUP, read them at setup, and wallah! each board is unique. You can put the lookup table (binary number -> parameter string, f/ex) in Flash so it doesn't take up scarce RAM.


message:
Sending binary data to HTTP server

I am new to low level programming.I am trying to send binary data to the http server.At the moment i just fill up the byte array with numbers and send them to the server(eventually i want to send image file). I can see the request in the server log as `
2016-05-18T23:30:26.688040+00:00 heroku[router]: at=info method=POST path="/api/users" host=myapp.herokuapp.com request_id=ed2b7852-7021-4642-a663-f9709e1aea70 fwd="99.89.114.63" dyno=web.1 connect=0ms service=2ms status=404 bytes=221`

**Questions**

1.My question is as you can see in the log, what is `bytes=221` i thought if i sent byte array of length 32 i should see 32 bytes(or around 40s).And i made the buffer of length 1024 byte array, still in the server log is `bytes=221`.Are my bytes are even being sent?

2.How would i handle the bytes received on the server side just to be sure `client.write` actually succeeded?(Just in high level...doesn't matter you can guide me in any language,Java,ruby,C,NodeJS)

Here is my code.Thank you in advance.

    #include <ESP8266WiFi.h>
    #define SSID "ssid"
    #define PASS_SSID "password"
    #define HOST "myapp.herokuapp.com"
    WiFiClient client;

    byte buffer[32];
    int bufOffset = 0;
    byte startByte = 0;
    byte nextByte = 0;

    void setup() {
        Serial.begin(115200);
        checkConnection();
    }

    void loop() {

      if (client.connect(HOST,80)) {
               Serial.begin(115200);
               Serial.println("conected to the server");
               String start_request = "";
               String end_request = "";
               start_request = start_request  + "--AaB03x" + "\n"
                                       + "Content-Disposition: form-data; name=\"picture\"; filename=\"cam.jpg\"" + "\n"
                                       + "Content-Type: image/jpeg" + "\n" + "Content-Transfer-Encoding: binary";
              end_request = end_request + "\n" + "--AaB03x--" + "\n";
              client.println("POST /api/users HTTP/1.1");
              client.println("Accept: */*");
              client.print("Content-Type: multipart/form-data; boundary=AaB03x");
              client.println(start_request);

             //Fill the buffer with values
                nextByte = startByte++;
                for(int ii = 0; ii < sizeof(buffer); ii++) {
                buffer[ii] = nextByte++;
            }

              //write it to the server
            int count = client.write(&buffer[bufOffset], sizeof(buffer));

           //end the request
           client.println(end_request);
            client.stop();
           }
          }

body:
You should forget about MIME, that is only needed if you are sending *multiple* files to the server. Your best bet is to just send these headers, then a blank line, then your data:

    POST /api/users HTTP/1.1
    Accept: */*
    Content-Type: application/octet-stream
    Content-Length: 123

On the other end, you just look at "request.body" and it should have your binary data. (Replace 123 with `sizeof(buffer)`)


message:
Inherent delay running EEPROM.read()

I'm using EEPROM to store long term data for use in sketches (thanks to DarthRubik for the guidance).  I store stuff like a location ("Garden") and a device name ("Greenhouse Monitor 02") plus whatever else I'd need to store to help filter through data.

When this information is stored in the sketch itself it is recalled quickly and accurately, is passed via wifi to my PHP, that then posts the data to the relevant fields in my AWS db.  Piece o' cake!  When I store it in the EEPROM, the extra time required to find it in EEPROM, pull it through the sketch, and then push it through to the db corrupts the data sourced from EEPROM and posts a jumbled mess of characters...if it even makes it to the db at all.

My question is actually simple (I think):<br>
Is it possible to "stage" strings from EEPROM in flash or SRAM vs. pulling cold from EEPROM?

I think PROGMEM plays a role here and I'm looking at examples oh how other sketched employ PROGMEM to better understand how to use it.

I am withholding the code for now because I want to try to implement concepts people may describe before I am just shown the solution...although that would be easier.  If I can't figure it out I'll post the code for more direct answers.

body:
> When I store it in the EEPROM, the extra time required to find it in EEPROM, pull it through the sketch, and then push it through to the db corrupts the data sourced from EEPROM and posts a jumbled mess of characters...if it even makes it to the db at all.

Are you certain of that? It is incredibly unlikely that mere time will corrupt characters and data as they are read and sent - especially the minuscule amounts of time we are talking here.

> Is it possible to "stage" strings from EEPROM in flash or SRAM vs. pulling cold from EEPROM?

Yes, and you are already doing so, since you can't send direct from EEPROM to WiFi - you have to go via SRAM. You read from EEPROM into SRAM then send from SRAM through WiFi. You just won't be doing it an entire string at once.

> I think PROGMEM plays a role here and I'm looking at examples oh how other sketched employ PROGMEM to better understand how to use it.

No, it doesn't. PROGMEM is for storing strings and other data within your sketch. It has nothing at all to do with EEPROM.

> I am withholding the code for now because I want to try to implement concepts people may describe before I am just shown the solution...although that would be easier. If I can't figure it out I'll post the code for more direct answers.

Without seeing your code no one is really going to be able to help you. I suspect (although I am stabbing wildly in the dark) that your EEPROM reading/writing code is completely wrong and you aren't actually storing the data you expect in the EEPROM, nor reading it back properly. Unless we see your code we can't know what is going on, and so we don't have a cat's hope in hell of diagnosing your problem.


message:
Low byte fuse programming of atmega328 of arduino uno

I want to use the atmega328 of my arduino uno board to clock TDC 1000, using the clkout bit of atmega328, but this requires fuse programming of the low byte, Can any one tell me how to do it ??

body:
Do you have another arduino? if so check this video and you can set the fuses with AVRDUDESS. Be carefull, if you set the fuses the wrong way you kinda "brick" the chip, and depending on the mess, you can only recover with a high voltage programmer. One advantage is that you can never ruin the chip with the fuses, just make it hard to reset to some defaults :)

> https://www.youtube.com/watch?v=tzGLoqvSJdw&t=194s&pp=ygUJYXZyZHVkZXNz


message:
How do I turn off the blinking cursor/caret in the Arduino IDE?

I just purchased a RedBoard, knowing that it would work on Linux, and knowing that it could allow me to easily interface with some electronics project. I am aware of the `ino` command line tool but I wanted to try interfacing with my board using the Arduino IDE because the latter seems to be somewhat standard. However, when I open the IDE I see a blinking cursor and for whatever reason I can't deal with this. How do I turn off the blinking cursor in the IDE?

I've managed to fix the blinking cursor problem in Firefox, GNOME, KDE, and my terminal... just not sure what to do with Java applications like Arduino IDE.

body:
**Note:** does not work with version 1.6.11. Works with 1.0.6

- Open the Arduino IDE
- Go to File
- Then go to Preferences
- At the bottom of the page is the file location you can enter to set additional preferences
- Exit the Arduino IDE
- Go to the preferences file location then set `editor.caret.blink=false`
- Then save
- Then restart the IDE and the **caret** will not flash


body:
As suggested by Gerben, you can go into Preferences and check the box "Use external editor":

[![Arduino Preferences][1]][1]

Now you can edit with your favourite editing program.

With this option active the IDE will show your sketch but in a non-editable way, and with a blue (cyan?) backwash:

[![External editor][2]][2]

Whenever you save the file in your external editor the IDE will detect the change and refresh the code shown in the internal editor.

Effectively you have replaced the IDE's editor with your own, but still use the IDE to compile and upload your sketches.

  [1]: https://i.stack.imgur.com/Ib32x.png
  [2]: https://i.stack.imgur.com/dHYJB.png


message:
Can't store time over 9 hours and 10 minutes

I am making a clock on my Arduino Uno using the time library http://playground.arduino.cc/Code/Time

I let the user set a time. Which is then converted to seconds and used in the

    setTime(s);
function.
When the value is over 9:10h, the seconds evaluate to 4 294 941 360 seconds (=
1 193 039.27 hours)

A code snippet:

    void timeChange() {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Change time");
      lcd.setCursor(0, 1);
      lcd.print("00:00");
      int hoursSet    = 0; //Stores the hours added.
      int minutesSet  = 0; //Stores the minutes added.
      String printTime;
      bool timeComplete = false;
      while (!timeComplete) {
        int buttonVal = analogRead(A0);
        if (buttonVal >= 490 && buttonVal <= 520) { //Indicates button 3 is pressed. It's function is to add one hour to the time.
          hoursSet = (hoursSet + 1) % 24; //Adds one hour to the hours.
          delay(100);
        } else if (buttonVal >= 5 && buttonVal <= 10) { //Indicates button 4 is pressed. It's function si to add 5 minutes to the time.
          minutesSet = (minutesSet + 5) % 60; //Adds minutes to the minutes.
          delay(100);
        }

        lcd.setCursor(0,1);
        String strHr = String(hoursSet);
        String strMn = String(minutesSet);
        if(strHr.length() == 2){
          lcd.print(hoursSet);
        } else if(strHr.length() == 1) {
          lcd.print("0");
          lcd.setCursor(1, 1);
          lcd.print(hoursSet);
        }

        lcd.setCursor(2,1);
        lcd.print(":");
        lcd.setCursor(3,1);
        if(strMn.length() == 2){
          lcd.print(minutesSet);
        } else if(strMn.length() == 1) {
          lcd.print("0");
          lcd.setCursor(4, 1);
          lcd.print(minutesSet);
        }
        delay(100);

        if (buttonVal >= 990 && buttonVal <= 1010) { //if button 2 is pressed again, the timecomeplete is set to true, and the script continues.
          timeIsSet = true;
          timeComplete = true;
        }
      }
      lcd.clear(); //Clear the screen
      lcd.setCursor(0, 0);
      lcd.print("The time"); //Print text, move cursor and print the time
      lcd.setCursor(0, 1);
      String strHr = String(hoursSet);
      String strMn = String(minutesSet);
      if(strHr.length() == 2){
        lcd.print(hoursSet);
      } else if(strHr.length() == 1) {
        lcd.print("0");
        lcd.setCursor(1, 1);
        lcd.print(hoursSet);
      }
      lcd.setCursor(2,1);
      lcd.print(":");
      lcd.setCursor(3,1);
      if(strMn.length() == 2){
        lcd.print(minutesSet);
      } else if(strMn.length() == 1) {
        lcd.print("0");
        lcd.setCursor(4, 1);
        lcd.print(minutesSet);
      }
      lcd.print(" is saved!");
      setTime((hoursSet * 3600) + (minutesSet * 60));
      timeIsSet = true;
      delay(5000); //Wait five, seconds then proceed
}

Added this to the code:

          Serial.print("hours ");
      Serial.println(hoursSet);
      Serial.print("hours in s ");
      Serial.println(hoursSet * 3600);
      Serial.print("minutes ");
      Serial.println(minutesSet);
      Serial.print("minutes in s ");
      Serial.println(minutesSet * 60);
      Serial.print("Combined:  ");
      Serial.println( (hoursSet * 3600) + (minutesSet * 60) );

When I input 5:15 it results in:

> hours 5
hours in s 18000
minutes 15
minutes in s 900
Combined:  18900

When I input 9:15 it results in:

> hours 9
hours in s 32400
minutes 15
minutes in s 900
Combined:  -32236

So, it looks like the library only holds an Int. But that seems odd, as the function expects seconds.

body:
Here's a hint: 32767 seconds is 9 hours, 6 minutes and 7 seconds.

What is the largest value that an `int` can hold?

---

EDIT: I can't add comments on this computer (old browser), so I have to respond to your question here.
`time_t` is an unsigned 32-bit value, but all of your input values are signed 16-bit values. When you take a product like 3600*10, you get a bit pattern of `1000110010100000`, which is 36000 when interpreted as an unsigned value, but is -29536 when interpreted as a signed value.

When assigned to a `time_t`, the value is sign-extended to 32 bits, which makes it `11111111111111111000110010100000`, which is 4294937760 when interpreted as an unsigned value.

If you want to write a statement like

    time_t x = (hoursSet * 3600) + (minutesSet * 60);

you need to type-cast your input arguments to the correct type first:

    time_t x = ((time_t)hoursSet * 3600) + ((time_t)minutesSet * 60);


body:
Changing this:

      time_t x = (hoursSet * 3600) + (minutesSet * 60);

To this:

      time_t x = ((unsigned long)hoursSet * 3600) + (minutesSet * 60);

Has solved the problem


message:
Trying to print text on LCD display from Arduino trinket

I'm trying to simply program an Arduino trinket to display some text on an LCD display.

I'm basically trying to follow [this][1], except connect it to a Trinket rather than an Arduino Uno. The background color of the LCD display is changing as expected from the `loop` function in my Arduino code, but it's just displaying some o's and arrow's for text on the LCD display.

I'm new to Arduino's (and EE in general), but am a computer programmer.

What am I doing wrong that the sample code in the above link doesn't print text on my LCD display?

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

[![enter image description here][3]][3]

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

  [1]: https://learn.adafruit.com/usb-plus-serial-backpack/testing-with-ttl-serial
  [2]: https://i.stack.imgur.com/sSr1t.jpg
  [3]: https://i.stack.imgur.com/7Wc9S.jpg
  [4]: https://i.stack.imgur.com/TE3Hg.jpg

body:
Warning: I do not have a ATtiny85 nor the lcd so this is purely based on what I found after some reading up on this mcu.

What I would do in your situation:
As the trinket is using a ATtiny85 it does not have hardware serial. So a software variant is needed.
You opted for software serial (which is the most obvous in Arduino world) but which seems to be the hardest solution.
According to this source [Serial communication with the Tiny's][1] is is possible (And I quote)

> you might have to tune the internal oscillator to get a stable
> connection.

Assuming your lcd does not need to send data back; I would try the TinyDebugSerial.

  [1]: http://www.ernstc.dk/arduino/tinycom.html


body:
Operating this display should not be out of the range of the ATTiny85 abilities. I have one using a two-way serial connection for a setup routine, that modifies EEPROM values.

----------

First off connect to the LCD Backpack using the [USB connector][1] and test it through there to rule out it being faulty.

At the bottom of that page:

> For more commands, check the github repository (see the Downloads tab) for a python script that will test all commands on the display.

----------

__Testing Trinket Serial:__

What you can do is take your trinket and run a basic Serial connection program to test if the Trinket is sending the right info out.

Trinket:

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

    #include <SoftwareSerial.h>
    // Create a software serial port!
    SoftwareSerial comm = SoftwareSerial(0, 1); //RX,TX
    #define LEDPIN  PINB2
    void setup() {
      //set baud
      comm.begin(9600);
      DDRB |= (1 << LEDPIN);  // set LED pin to output mode
    }

    void loop() {
      //print a specific character once a second

      comm.println('a');
      PORTB |= (1 << LEDPIN); // turn on LED
      delay(500);            // 0.5 second delay
      PORTB &= ~(1 << LEDPIN); // turn off LED
      delay(1000);
    }

Then you need another Arduino, like an Uno, Leonardo:

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

    // For leonardo use Serial1 for the connection to trinket
    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.println("Ready...");

      // set the data rate for the SoftwareSerial port
      Serial1.begin(9600);
    }

    void loop() { // run over and over
      if (Serial1.available()) {
        char incoming = Serial.read();
        Serial.println(incoming);
      }

    }

Or the stock balnk sketch and connect the Trinket Serial out to Arduino `TX-> 1`.

If using an UNO you can set up a SoftwareSerial style of the above.

I recommend this rather, a USB-Serial converter as it will be quicker and cleaner.

Next you need to see what is coming out. If the received data is correct then there is an issue in the LCD display, try re-flashing the LCD board with new firmware.

If the data comes through correctly then move onto using the Adafruit  code and still connecting it to the other Arduino boards serial connection, replacing the `Serial.println(Serial1.read());` with `Serial.println(Serial1.read(),HEX);`.

If the data still comes through correctly then the data is not being received properly by the LCD backpack.

----------

**LCD Backpack**

You should test the display board with another Arduino, UNO or Leonardo (32u4).

Run the Adafruit tutorial code and see the results. If the code works then there is a problem with the Trinket and the SoftwareSerial library.

If there are again errors that happen with the LCD backpack when used with a 'normal' Arduino then it is the problem.

----------

**Recomendations**

Download the ATTiny core from High-Low Tech and burn the 'bootloader' to reset the fuses to 8MHZ setting, also this is a good core to use if you want more space on the ATTiny.

Possibly re-flash the trinket bootloader and make sure the internal clock is 8MHz; the SoftwareSerial library is touchie I believe.

----------

  [1]: https://learn.adafruit.com/usb-plus-serial-backpack/testing-with-usb


message:
Range of Offset Value in pH sensor module?

In finding the pH value of a liquid/Soil, what is the range of Offset voltage value that I can use in my code?

https://arduino.stackexchange.com/questions/17436/using-calibrating-ph-sensor-module/24362?noredirect=1#comment46498_24362

I considered the above link as a reference. But I didn't come to know the range of Offset Value...

Here is the logic below to find the value of pH right...

    avgValue = 0;
    for (int i=2;i<8;i++)       // take the average value of 6 center sample
    avgValue+=buf[i];

    float phValue = (float)avgValue*5.0/1024/6; // convert the analog into millivolt
    phValue=3.5*phValue+Offset;
What is the range of Offset value can I use in the above/my code?

Thanks in Advance

body:
When converting real world sensor measurements into usable data there are several issues to consider:

1. Noise from any number of sources such as (unavoidable?) long cables and power supplies to name two.  Consider using exponential averaging to minimize the effects of noise.  If the noise if predictable consider sampling only when the noise is absent.

2. Slope of the data is important when converting to known scales.  For example the slop of the resistance of a thermistor verses heat may not have the same slope as the temperature in Celsius verses heat.  Simply multiply by the appropriate constant to correct for slope error.

3. After you correct for slope the values may still not be correct.  When all values are equally less or more then the expected values an offset is required.  Simply add or subtract the appropriate constant to correct for offset error.

4. Linearity is often corrected using lookup tables.  Linearity is a measure of how closely the sensor tracks the physical value being measured.  For example, after slope and offset corrections, a thermistor measurement may appeared curved when compared to the actual temperature in Celsius.  For this final correction the sensor measured value is used to index into a lookup table which returns a correction value.  Interpolation is used to control the size of the lookup table when space is a consideration.


message:
IO Control and Configuration

I am using Eclipse to program a ATMega2560 and would like to stay away from the Arduino library, While looking through AVR Examples I have seen the syntax

    #include <avr/io.h>

    PORTD.0 = 1

    or

    PORTD.DIR = 1;

instead of

    PORTD = 0b11111111;

To define and control the Inputs/Outputs when I try to use this syntax I get compiler errors:

    error: request for member 'DIR' in '*34u', which is of non-class type 'volatile uint8_t {aka volatile unsigned char}'

I am sure that I am simply missing a include file or something but I can't figure out what I am doing wrong.

body: What you're doing wrong is that you're using the wrong compiler. That syntax is for CodeVision or mikroC, but the Arduino IDE uses GCC. Which follows global standards rather than making syntax up.


message:
Getting Firmata to control WS2801 LEDs

I am trying to control a strip of WS2801 LEDs through an arduino uno running firmata from Python on my laptop.

I've written some basic code based on adafruit's library [here][1] (from line 187):

    from pymata_aio.pymata3 import PyMata3
    from pymata_aio.constants import Constants
    import time

    leds = [(255, 255, 0), (255, 255, 0), (0, 255, 255)]

    uno = PyMata3()

    uno.set_pin_mode(2, Constants.OUTPUT)  # signal
    uno.set_pin_mode(3, Constants.OUTPUT)  # clock

    def show(leds):
        for pixel in leds:
            for channel in pixel:
                i = 0b1
                for x in range(0,8):
                    if i & channel:
                        uno.digital_write(2, 1)
                    else:
                        uno.digital_write(2, 0)
                    uno.digital_write(3, 1)
                    uno.digital_write(3, 0)

                    i = i << 1

        uno.digital_write(3, 0)
        time.sleep(0.001)

When I run the code it seems to run ok, but only the first LED will light up. I think (too quick to be certain) that it flashes through all the colours - ie displaying each colour rather than passing them through.

I'm wondering if there is something wrong with the timing for the clock pin making it latch, but I'm grasping here.

  [1]: https://github.com/adafruit/Adafruit-WS2801-Library/blob/master/Adafruit_WS2801.cpp

body:
It's possible that time.sleep is causing a latching issue. You should instead use pymata-aio's sleep function:

    uno.sleep(0.001)

The documentation for it can be found here: http://htmlpreview.github.io/?https://github.com/MrYsLab/pymata-aio/blob/master/documentation/html/pymata_aio.html#module-pymata_aio.pymata3

You could also try a different pin and see if you still have the issue?


body:
You cannot do precise timing of I/O mediated by USB like that. Regardless of the serial baud rate in use, the USB mode utilized basically puts a 1ms minimum interval between any two distinct *communication* operations.

Providing there are no intervening reads, if firmata is coded to deliver its data to the host's serial API in buffers matching or exceeding the USB packet size rather than individual writes for each command, it is possible that "keeping the pipe full" may mean that commands are able to be executed without such gaps, but any little interruption could introduce a problematic delay.

The key problem with delay is this part of the data sheet:

>CLK pin keeps low more than 500uS will make the WS2801 internal status register reset, and at this moment, the gray scale data
in the data shift registers will be latched.

Basically, that says that you need a clock low pulse of more than a half millisecond to start the process, but by extension it also means that all of the subsequent clock pulses have to be shorter than that or you will inadvertently reset the process, and this is not something you can easily achieve reliability of with a USB bus of the type utilized here mediating your software manipulation of the clock line.

**Essentially, don't try to bit-bang things with Firmata.**  You should send the desired intensity values across the USB as byte data, and then have software running on the Uno clock this data out in accordance with the WS2801 timing requirements.

Personally, I'd just write that as an ordinary sketch reading the Serial input - no need for firmata.  You can still feed the data from python on the host if you like, or anything else that can push data over a serial port.


message:
How to write IF/Else using a threshold range of values

basically I am trying to write an IF/ELSE statement that triggers a light when a pressure sensor is between two values.

In other words, I want the light to respond ONLY if the analog read is between 400 and 600, as opposed to, say, only being above 400.

Here is the code, any suggestions?

    int sensor=0;
    int threshold=200;

    void setup (){
      pinMode(2, OUTPUT);
      digitalWrite(2, LOW);
      Serial.begin(9600);
    }

    void loop() {
      sensor=analogRead(0);
      Serial.println(sensor);
      if (sensor > threshold) {
        digitalWrite(2, HIGH);
      }
      else {
        digitalWrite(2, LOW);
      }
    }

body:
To get the light to turn on only when the sensor reading is between two numbers, you should test if the reading is between the two numbers, and if it is, turn on the light.

To test if a value is between two numbers, you could use the `&&` AND operator to see if both conditions are met.  For example:

    if (sensor > loLimit && sensor < hiLimit) {
        digitalWrite(2, HIGH);
    } else {
        digitalWrite(2, LOW);
    }

Here's a shorter way to write that:

    digitalWrite(2, (sensor > loLimit && sensor < hiLimit));

In this form, the expression evaluates to 1, or HIGH, if it is true, and to 0, or LOW, if it is false.

Another approach is to test if `abs(sensor-midLimit) < halfGap`, where `midLimit` is `(loLimit+hiLimit)/2` and `halfGap` is `(hiLimit-loLimit)/2`.  Turn on the light if `abs(sensor-midLimit) < halfGap`, else turn it off.


message:
Question about number of sensors for Arduino Mega

What is a good max number of sensors for an Arduino Mega? Since it has like -- 2? -- ground connections, is it better to keep the number of sensors to a minimum amount?

body:
It depends on what you want the Arduino to do with them. There is no (not much) penalty for having many sensors connected. Where it begins to matter is when you need to read at rates which, collectively, tax the speed of the processor to meet the total demand. Your project specs will really determine how many sensors make sense. The other place that sensor count might matter is if your project is to be battery powered, and the sensors draw some amount of current even when they're not being used. In a battery powered project, you'll want to be able to power-down everything that isn't being used at a given time, to maximize the system's overall run-time on battery.

The Mega, and I'm assuming you mean Mega 2560, has 50-some odd I/O pins available, so you have a lot of potential connectivity, and I think it's safe to say, the designers intended for them to be used.


message:
No Response to AT commands

I'm unable to communicate with my nodemcu ESP8266 module using the AT commands. The module does not return 'ready'  on the serial monitor and entering AT commands has no effect at all. I am able to upload programs onto the module and even receive messages onto the serial monitor. But not for the AT commands.  Please help....

body:
AT commands require the installation of firmware that responds to AT commands.

A plain ESP module normally comes with that firmware installed. A nodemcu doesn't. A nodemcu comes with Lua installed instead.


body:
The bare chip knows nothing, just as an Arduino would. The AT+ command set is provided by an interpreter running on the 8266 processor. The AI Thinker modules and others, come with that interpreter already loaded. Your module does not have it installed. And any time you load a program into it, the previous one is over-written.

You can find the AT+ interpreter available for download and upload it to the module, after which it will be able to execute AT+... commands.


message:
GPS timestamping of digitized voltages from geophones

I wonder if anyone has written a code for GPS time stamping of voltages from seismic geophone (or any other sensors) digitized by internal or better external ADC connected to Arduino? Since the accuracy of at least 1 millisecond is required I believe using 1 PPS signal of the GPS is the only solution.

body:
I doubt anyone has written software for your exact situation but you should be able to cobble something together if we break down the problem.

 1. You want to read a value from an Analog port (or external ADC)
 2. You want to read the time from a GPS.
 3. You want to write these two readings to 'somewhere'.

Looking at the Arduino IDE tutorials there are some Analog ones that would be relevant.  But the only line you need is `int sensorValue = analogRead(analogInPin);` which reads a value between 0 and 1024 which relates to the output range of your sensor.

Now you want to read from a GPS, looking at the Software Serial Library Examples there is an example of how to setup a second serial port to read the GPS data. The GPS data will arrive once every 2 seconds.  The PPS signal will arrive once every 1 second.  So I'm not sure how you are going to use this to get millisecond accuracy.  To get millisecond accuracy I would use the GPS data to correct a Real Time Clock connected over either the I2C or SPI bus.  There are lots of example programs on reading from an RTC over these busses.

Write them to somewhere, well initially I would write them to the hardware serial port, back to you PC via USB, but then you might want to start looking at writing them to a SD card or via WIFI or GSM to a cloud storage solution.

Here are a list of the examples I looked at:

https://www.arduino.cc/en/Tutorial/AnalogInOutSerial#
https://www.arduino.cc/en/Tutorial/SoftwareSerialExample#
https://www.arduino.cc/en/Tutorial/Datalogger

Hope that helps


body:
To tackle the time resolution and accuracy issue you could:

1. Attach the 1PPS signal to an interrupt pin
2. In the interrupt routine record the `millis()` value at the time the 1PPS signal is activated
3. In the main loop do a non-blocking read of the GPS data to find and build up the time string as it is sent from the GPS (shortly after the 1PPS is triggered).

You now know what the `millis()` count was the last time a 1PPS pulse arrived, and you know the current time to within a second. The 1PPS pulse will be at `HH:MM:SS.000` (or as near as damnit) so if you subtract the current `millis()` from your recorded 1PPS `millis()` value it gives you the number of milliseconds since the 1PPS pulse. Add that to the current time, and you have 1ms accuracy in the time: `HH:MM:SS.iii`.


message:
Use doorbell output (12VDC) to power arduino?

Not sure if this is possible, but could I use my existing doorbell setup to power an Arduino? I'd also like to preserve the existing chime's functionality either through the existing button or triggering it through the arduino.

My doorbell chime is made by Nicor and its input is 120VAC, but outputs 12VDC. This seems to be a very unconventional setup, but I've confirmed its output with a multimeter (it's also printed on the chime itself). The chime is very similar to this: http://www.amazon.com/Nicor-18888-Door-Chimes/dp/B006T38PTU (only difference I can see is the output). The 12V line runs to my front door where it's connected to a light up button. Here is a picture of the button's circuitry: https://i.stack.imgur.com/YsSu0.jpg

What I'd like to do is use the chime's 12VDC output to power the arduino so I don't have to rely on another power source or batteries. I will be adding smart features to the doorbell via the arduino, but my main hangup is getting power to the arduino. I've tried connecting the doorbell wires to VIN and ground, which successfully powers on the Arduino, but it also triggers the chime. It appears closing the circuit triggers the chime to play.

Is this possible to do?

body:
You need to find the transformer for your doorbell system and take the power from there. It seems like somehow you are using the signal wires for the door bell instead of the power wires.

The door bell transformer should/could be in a utility room, closet, by your heating and air unit. once you find that look at the output of the transformer. I know some are AC 12 volts, and I feel like that arduino will not like that...


body:
If your extra features only need to sense the button press, then your arduino can go at the chime and use the 12V source that also powers the chime.

You put an opti-isolator's led side in series with either leads of the button loop. A digital input with high pull-up can read the state of the detector side of the opto-isolator.

This assumes that your extra features do not include providing some kind of visual or auditory output **at the button**. But remember that just because you want to read the button state, you need not detect it at the button physically--just electrically.


body:
This seemingly simple task is actually quite complicated; a good challenge that's not impossible or easy to overcome.

The AC/DC transformer in your link only provides "12VDC/6mA"; not enough to run the Arduino, chime, and button LED; so it likely needs upgraded to something beefier; you can't have too many amps on such a transformer.

Then there's your chime, which could use a lot of current (buzzer/bell) or a little bit (speaker-based chime tones). If it uses a lot, you should replace it to simplify the other connections. Remember that power goes through the chime to get to the button; otherwise the circuit would be incomplete and the ringer's LED would be dark.

The chime is activated by the resistance of the button lowering itself to the point where the chime gets enough power, no longer being current-limited by the diode, 2.2k resistor, and small LED. Very simple design, but not ideal for easily intercepting.

So what's the easiest way to accomplish your task?

Looking at it closely, it seems the basic circuit is there for you already; you have a power-consuming node on the network in the form of the button's LED.

You need to replace/augment the LED on the ringer with the Arduino. The 2.2k _R19_ could/should be replaced with the Arduino as well; just make sure your LED isn't over-drawn when the Arduino is chugging at full-steam, and add additional inline resistance as needed to keep it safe.

The other problem is powering the MCU while ringing. You'll notice the LED goes out while ringing. While that's nice feedback to the user, it's not because the circuit designers were UX-focused, it's because the chime's simple circuit  pulls all the current out from under the LED, just as it will an MCU in the same slot.

You can get around this using a super capacitor. I would use an LM7805 in front of the Uno to deliver VIN +5 V instead of 12 V. Then you can "short" the Uno's GND to VIN with a 1 F 5.5 V capacitor ("F", NOT "uF"). Those caps are (amazingly) available for just a few dollars on eBay.

So, at the end of the day, you basically just need to "upgrade the LED" and maybe upgrade the transformer. You could also re-create the switching pattern on your ringer with diodes if you're handy with circuit design, but if i were you, i would just "bodge" a few wires onto the existing PCB, and possibly alter that resistor.

Good luck; sounds like a fun project and a good challenge.

EDIT:
I realized you might not need any circuit mods at all; a hall-effect current sensor anywhere the line, or just paralleling the chime terminals with a voltage-divider input to the Uno might suffice, if you didn't need the MCU physically at the button. Heck, a microphone sensor taped inside the chime could accomplish the task of detecting doorbell rings...


message:
Serial Communication to WPF (Windows Presentation Foundation) giving me odd results. How do I clear up the Strings I am receiving?

I'm trying to make a voltage/temp logger that will post to SQL. I'm using a WPF to make kind of a UI for people to measure the voltage of a cell, and take the temp of the battery acid in the battery. My end goal is to have the Arduino Bluetooth to a computer. the computer will handle all the SQL. The Arduino will have a physical button to post or save the data to my SQL server. Also the Arduino will have a little display to display the battery S/N, Voltage, Temp. (Side Question: Am I going to be able to do the screen and access the serial, with also sending the serial data over Bluetooth?)

My problem is that when I call my function to get that data sometimes it comes out messed up. Sometimes I get, for example: "3.1234 V=" Or "V= 3.123V=" It also happens with the temperature, sometimes I get the voltage in the temp box and vice versa.

More times than not I get a bad result. When I run it in the Serial Monitor with the Arduino IDE It looks fine. Does anyone have any advice how I can clean up the communication and get more reliable results?

Thanks for any help!

I'm using to place the serial port string into a textbox.

    txt_Volt.Text = sp.ReadExisting();

I tried using the `Serial.flush();` to clear out any old stuff to no avail.

The Arduino code:

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

    else if (c == '3')
     {
       int analog_value = analogRead(A0);
       volt = (analog_value * 5.0) / 1024.0;
       Serial.print("v= ");
       Serial.print(volt, 5);
       Serial.flush();
    }

Arduino `loop()`:

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

    void loop() {
      if (Serial.available() > 0)
      { Serial.flush();
        char c = Serial.read();
        if (c == '1')
        {
          digitalWrite(13, HIGH);
          Serial.println("LED is On");
          Serial.flush();
        }

        else if (c == '0')
        {
          digitalWrite(13, LOW);
          Serial.println("LED is off");
          Serial.flush();
        }
        else if (c == '3')
        {
          int analog_value = analogRead(A0);
          volt = (analog_value * 5.0) / 1024.0;
          Serial.print("v= ");
          Serial.print(volt, 5);
          Serial.flush();
        }
        else if (c == '4')
        {
          //Temp Function go HERE
          getTemp();
        }

C# CODE:

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

             private void Connect_Click(object sender, RoutedEventArgs e)
             {
               while (portNum >= 0) //automaticly connect to correct port.
               {
                try
                {
                    String portName = "COM" + portNum;
                    comportno.Text = portName;
                    //String portName = comportno.Text;
                    sp.PortName = portName;
                    sp.BaudRate = 9600;
                    sp.Open();
                    status.Text = "Connected";
                }
                catch (Exception)
                {
                    portNum--;
                    // MessageBox.Show("Please give a valid port number or check your connection");
                    if (portNum == -1)
                    {
                        MessageBox.Show("Could not find Arduino\nCheck Connection");
                    }
                }
            }

        }

        private void Disconnect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                sp.Close();
                status.Text = "Disconnected";
            }
            catch (Exception)
            {

                MessageBox.Show("First Connect and then disconnect");
            }
        }

        private void on_Click(object sender, RoutedEventArgs e)
        {
            sp.Write("1");
            rect_LED.Fill = new SolidColorBrush(Color.FromRgb(0, 255, 0));
            // DebugWindow.Text = sp.ReadExisting();
            //  readingStuff();
        }

        private void Of_Click(object sender, RoutedEventArgs e)
        {
            sp.Write("0");
            rect_LED.Fill = new SolidColorBrush(Color.FromRgb(0, 0, 0));
            //  DebugWindow.Text = sp.ReadExisting();
            //  readingStuff();
        }

        private void Get_Volt_On_Click(object sender, RoutedEventArgs e)
        {

            sp.Write("3");
            string volts = sp.ReadExisting();
            int volt_length = volts.Length;

            bool isLetter = !String.IsNullOrEmpty(volts) && Char.IsLetter(volts[0]) && Char.IsDigit(volts[volt_length - 1]);

            if (isLetter)
            {
                DebugWindow.Text = volts;
            }
            else
            {
                DebugWindow.Text = "Error";
                sp.Write("3");
            }
        }

        private void Get_Temp_On_Click(object sender, RoutedEventArgs e)
        {
            sp.Write("4");
            txt_Volt.Text = sp.ReadExisting();
        }

        void readingStuff()
        {
            String comdata = sp.ReadLine();
            Dispatcher.Invoke((Action)(() => DebugWindow.Text += "Data\n" + comdata + "\n"));
        }

What a bad result looks like:

[![Bad Results][1]][1]

A Good result:

[![Good][2]][2]

  [1]: https://i.stack.imgur.com/KGg2o.png
  [2]: https://i.stack.imgur.com/wOkU3.png

body:
Your problem arises from a mix of newline-terminated and un-terminated messages.

The newline terminated values probably would work by themselves as you can use a `ReadLine()` type method to wait until they have been completely transferred.

But the non-terminated attempts such as your use of the `ReadExisting()` method cause a problem - these likely fetch whatever has been received *up to the time of the call* but that will not necessarily be the full message sent (or even anything at all).   Whatever is left over (had not been received by the time of the call) will become the beginning of the data achieved during the next partial or until-newline read.

As a solution you should probably either:

 - Terminate each message with a newline

or else

 - Always read only complete lines, and then *parse* individual messages out of them

or

- Always read until you find some delimiter character such as a space or comma, *or* a newline.  You may have to write your own read method to accomplish this.

*Using delays to try to fix a problem like this is bad practice as it is fragile and can easily break if there is an unexpected delay on the other side, or if the execution speed of one of the components changes*.  A number of fragile techniques that generally worked with true serial ports subsequently broke when USB converters were introduced in the middle, as USB bunches data into packets with gaps in between, a behavior not necessarily previously seen in many pure serial implementations.


message:
Replacement for #include <pins_arduino.h> on particle photon

I've run into this a couple of times when trying to use libraries written for Arduino on a particle photon. Many have the line:

     #include <pins_arduino.h>

which returns the error on the photon compiler:

     fatal error: pins_arduino.h: No such file or directory

I had similar trouble with:

     #include <WProgram.h>

and found an easy fix was to replace that with

     #include "application.h"

I'm wondering if there's a similar easy fix for pins_arduino?

body:
There are some Arduino libraries, that just implements functionalities that do not depend on hardware. Example of these are almost all those libraries that deal with data structures/types (strings, arrays, trees, lists, etc), or particular algorithms.
If such libraries do not depend on other Arduino-specific libraries, you can use them almost certainly.

Other libraries, instead, heavily depend on the hardware currently used on the Arduino boards. In those cases, the library must access the hardware, therefore they will include verious headers, such as pins_arduino.h (in particular, pin_arduino.h .

These won't work without heavy modification of such libraries and/or the creation of a wrapper header to "emulate" the required functionalities and define the required macros/constants, according to your hardware.


message:
Arduino tool to enumerate where RAM is being used?

In a sketch I have, I use a few libraries and have discovered that a large amount of RAM is being consumed.

Is there a tool that can identify how this RAM is being allocated, e.g. which libraries, which piece of code?

body:
I use this code for Heap memory of AVR (UNO, Mega, etc.):

    int freeRam()
    {
         extern int __heap_start, *__brkval;
         int v;
         return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
    }

To show heap memory just use `Serial.print("Write here a name of the function from which you print it"); Serial.println(freeRam());` anywhere in the code.

Compiler shows stack memory but not the heap, so this code helps me to find exact place where my program uses too much of heap memory. I just print it in every suspicious place in my code.

I hope this will help.


message:
Trouble using lcd.readButtons() in RGBLCDShield library

I am trying to create a state machine that loops in whatever state it's in until a button is pressed.  I am using the **Adafruit_RGBLCDShield** library along with the LCD shield and 16x2 display.  For some reason the buttons aren't being detected at all.  Here is the code for one of the states:

        case STANDBY_MODE:
      lcd.clear();
      lcd.setBacklight(0x0);
      delay(100);
      noInterrupts();
      digitalWrite(fire, LOW);
      digitalWrite(chg, LOW);
      digitalWrite(trig, LOW);
      analogWrite(eprgm, 0);
      // Wait for button press
      while(1)
      {
        button = lcd.readButtons();
        if(button)
        {
          showLCD();
          t0 = millis();
          state = NO_CHARGE;
          analogWrite(eprgm, (vSet*0.0204)/5);
          interrupts();
          return;
        }
      }
    break;

In this state, the system turns off all outputs and display and waits for a button to be pressed.  For some reason, though, it doesn't respond when I press the button.  Is there something missing here?

body:
IMO, your post doesn't provide enough information to allow definitive problem diagnosis.

Why do you say `noInterrupts();` at line 5?  Some versions of the Wire library might be interrupt driven[1].  If interrupts were off, such a library wouldn't detect any button presses on a TWI-interfaced shield like [Adafruit's RGBLCDShield](https://www.adafruit.com/product/714).

[1]: Per [arduino.cc's WireLibraryDetailedReference](http://playground.arduino.cc/Main/WireLibraryDetailedReference) page,  “"The AVR TWI is byte-oriented and interrupt based...." (section 21.6 on p. 224) ... The TWI module sends an interrupt when it finishes, to notify the processor of the change in conditions ... However, notice that the Wire library has blocking I/O. ” [Ie, the usual Wire library doesn't take advantage of TWI interrupts.]


message:
why are there odd spikes in the USB serial data transfer rates?

I'm trying to use an Arduino for data collection, and hoping to get a consistent sampling rate.

I looked into the serial communication using the simplest program I could, but it produces odd results.

    void setup() { Serial.begin(9600); }
    void loop() { Serial.println("00000"); }

I use a python script to read the data and create a text file and write the time in seconds before the five zeros.

Using the seconds as a marker, I then count the number of data lines for each second.  for example:

    44 00000  // recorded at time 44 seconds
    44 00000
    44 00000
    45 00000  // recorded at time 45 seconds, etc

I was expecting that there would be a somewhat stable value for this.  Using 10 bits per character, printing the 5 zeros should be able to be done about 190 times per second.  When analyzed, it turns out to be lower, which isn't surprising due to overhead, but also unexpectedly variable.

Collecting the zeros for 5000 seconds produced the following results:
most often, there were 137 sets of 00000 collected per second, followed by 138 sets of 00000.  This is easily explainable by not being equally spaced per second, and having one second with 137 followed by one second with 138.

What is harder to explain is when it jumps to 139, 140, 141 and 142 sets of 00000 per second.

Out of the 5000 seconds of data, there were 25 seconds where 140 sets of 00000 were created.  That isn't too bad and could be due to timing.

But, out of the 5000 seconds, there were 203 seconds where 142 sets of 00000 were created.

The percent breakdown is as follows:

    137 sets of 00000:  79.15%
    138 sets of 00000:  13.8%
    139 sets of 00000:  0.39%
    140 sets of 00000:  0.51%
    141 sets of 00000:  2.05%
    142 sets of 00000:  4.11%

the first 4 could be explainable with minor timing errors, the last ones are very hard to explain.  with 137 sets of 00000 there are 685 characters sent serially in one second.

with 142 sets of 00000 there are 710 characters sent serially in one second.

What I am trying to figure out is why the variability is so wide and also so consistent - as in the pattern, which can be seen in the graph.

![frequency of characters sent per second](https://i.stack.imgur.com/nETxJ.jpg)
![pattern of characters sent](https://i.stack.imgur.com/70pxx.jpg)

Is there any explanation for the variability?

Because of the variability in the transfer, it is very hard to sync up data or filters or other uses when a constant sample rate is needed.

I've also added delays in the main loop from 1ms to 7ms, 7ms was the maximum because that would not cause the loop to run slower than the free running speed at 142 loops/transmissions per second (1sec/7ms = 142.8 loops per second discounting all other overhead) and found the same patterns.

Using a delay of 8ms produced another interesting result:
with a delay of 8ms, most of the data was transmitted at 123 or 124 sets of 00000 per second, but every 12 seconds there would be a burst of 128 sets of characters.  this makes sense because the delays add up to less than one second for 11 loops, then get an extra loop for that second, but that adds 15 characters, not just 5.

After re-reading this, it dawned on me that there might be some loop timing/buffering errors, so instead of a delay, I used Serial.flush() to pause the loop until the data was sent.

This resulted in a free-running result of 137 sets transmitted per second for the most common, followed by 138 sets.  The new issue is that every 25 seconds there is a drop down to 133 sets of characters transmitted per second, which seems to be the same issue only causing slowing instead of speeding up.

I thought I found the answer with Serial.flush() but there is still something causing huge changes in the sent characters per second.  What could be causing this? and what can be done to make the transfer rates more constant?

body:
While a serial port "kept busy" can potentially produce data with jitter comparable to its clock's jitter reduced by the number of clocks per word, a USB serial converter introduces a bunching of data into packets that is effectively entirely asynchronous.

As a result, once the data has gone through the USB, you really can't determine much of anything about the timing of its *origin* just by looking at the timing of its *arrival*.  That remains true even if you are claiming it via a serial-type API on the host, because the USB bus has already irreversibly de-synchronized it in transit.

A more meaningful experiment would be to timestamp the data at the source, ie, on the Arduino.  That could potentially be more regular, but if you use a high enough resolution timestamp, you will still find that it is irregular, as by default the Arduino's foreground thread of execution is periodically interrupted by the timer, which produces a brief delay.

If you are sending serial data into the Arduino or using other hardware peripherals, those may cause additional sporadic delay-inducing interrupts.


message:
Possible to condense this if statement?

I have this if statement:

    if (now.hour() == 5 && now.minute() == 10 && now.second() == 0 && now.dayOfTheWeek() != 1 && now.dayOfTheWeek() != 7){

Is there a way to condense that for the purposes of saving on some bytes?

Ultimately trying to say "At 5:10 every weekday do X"

body:
Yes. The method now() Returns the current time as seconds since Jan 1 1970. Simply keep tract of all your time this way and you only need to test this one value.

The [Arduino is not a good source of time over long periods][1].  Consider using an [RTC][2] (Real Time Clock) chip.  [This][3] Arduino page links to [this][4] page which talks about an RTC.  (I will leave it up to you to research any compatibility issues.)

Many RTCs contain a register set specifically designed to handle tasks such as you outlined above. For example, setting alarms off on weekdays only or on specific days of the month.

If absolute time is not important in your application I would try the following code outline.  Each test only has 2 operands:

    // Turn on Arduino on Monday at the time task is to be performed.  Task
    // should be performed at that time on Monday, Tuesday, ... Friday.
    // Nothing should happen on Saturday & Sunday.  Then cycle repeats.

    // Set time to zero.

    // Count through days (0, 1, 2, ...).

    // Wait each day until number-of-seconds is greater then seconds-in-a-day
    // times the day number.

    // If day number is 4 or less do activity.  Else skip activity.

    // If day number is more than 6 set the day counter to 0 and set the time
    // to zero.

If you want to start the Arduino at arbitrary times, set the initial Arduino clock value to the number of seconds from the time the activity would have been performed on Monday and initialize the day counter to the appropriate value.  For example if you started the Arduino on Tuesday 23 hours after the time the activity should have happened on Monday set the Arduino clock to 23 * 60 * 60 seconds and initialize the day counter to 2.  Of course you can calculate the initial day counter value using  = initial_number_of_seconds / 60 * 60 * 24.

  [1]: https://arduino.stackexchange.com/questions/242/arduino-time-clock-accuracy
  [2]: https://en.wikipedia.org/wiki/Real-time_clock
  [3]: http://playground.arduino.cc/Code/Time
  [4]: http://www.pjrc.com/teensy/td_libs_DS1307RTC.html


body:
The following saves a couple of program bytes (but no RAM) when `now` is a structure with a byte called `DayofWeek`:

     if ((byte)(now.DayofWeek+249)>250) ...
       -vs-
     if ((now.DayofWeek != 1 && now.DayofWeek != 7)) ...

It might save slightly more than that in your case, where `now.dayOfTheWeek()` appears to be a function reference.  This technique will work if function `now.dayOfTheWeek()` returns a `byte`, that is, an `unsigned char`.  The technique depends on value 7+249 overflowing to zero <strike>in byte arithmetic</strike> when truncated to a byte, because 7+249 is 0 modulo 256.

The cast to `byte` [or `uint8_t`] of `now.DayofWeek+249` is needed because of `int` promotion as Edgar Bonet pointed out.


message:
Refactor to save bytes?

I'm a painful 128 bytes of my max for this Trinket. Any refactoring I could do to get down the size?

<!-- language: c -->

    #include <Adafruit_NeoPixel.h>
    #include <Wire.h>
    #include <RTClib.h>

    #define LEDPIN 1
    #define TONE 4
    #define BTNPIN 3

    RTC_DS1307 rtc;
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(5, LEDPIN, NEO_RGB);

    const long fadeTime = 10 * 60000L; // X minutes
    const int colorStops = 255;
    const int delaySpeed = fadeTime / colorStops;
    const int notes[] = {262,294,330,349};
    const uint32_t alarmLength = 5 * 60000L; // 5 minutes

    void setup() {
      rtc.begin();
      rtc.adjust(DateTime(__DATE__, __TIME__));

      pinMode(TONE,OUTPUT);
      pinMode(BTNPIN, INPUT);
      digitalWrite(BTNPIN, HIGH);

      strip.begin();
      strip.show();
    }

    void loop() {
      DateTime now = rtc.now();

      // If it's 5:10 am on a week day, start the fade in
      if (now.hour() == 5 && now.minute() == 10 && now.second() == 0 && now.dayOfTheWeek() != 1 && now.dayOfTheWeek() != 7){
        // Fade in light
        for(int i = 1; i<colorStops; i++){
          if (kill() == true){ break; }

          for(int np = 0;np<strip.numPixels(); np++){
            strip.setPixelColor(np, strip.Color(i,i,i));
          }
          strip.show();
          delay(delaySpeed);
        }

        // Play tone after light fully bright
        for( uint32_t tStart = millis();  (millis()-tStart) < alarmLength; ){
          if (kill() == true){ break; }

          for(int np = 0;np<strip.numPixels(); np++){
             strip.setPixelColor(np, strip.Color(random(50,255),random(50,255),random(50,255)));
          }
          strip.show();

          beep(notes[random(0,3)]);
          delay(100);
        }

        turnOffPixels();
      }
    }

    void beep(int delayAmount)
    {
      for (uint16_t t = 0; t < 30*1000/2; t += delayAmount)
      {
        digitalWrite(TONE,HIGH);
        delayMicroseconds(delayAmount);
        digitalWrite(TONE,LOW);
        delayMicroseconds(delayAmount);
      }
    }

    void turnOffPixels() {
      for(int np = 0;np<strip.numPixels(); np++){
        strip.setPixelColor(np, strip.Color(0,0,0));
      }
      strip.show();
    }

    bool kill() {
      if (! digitalRead(BTNPIN)) {
        turnOffPixels();
        return true;
      } else {
        return false;
      }
    }

Error...

    Sketch uses 5,438 bytes (102%) of program storage space. Maximum is 5,310 bytes.
    Global variables use 97 bytes of dynamic memory.

body:
For refactoring, consider using a `for` loop that executes twice, once for the  “// Fade in light” section of code, and once for the  “// Play tone after light fully bright” section.  For parts of the code that differ, test the loop index and do one action or the other.

Here are two ways to get rid of a few (eg 54) bytes of code:

1. Instead of

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

     Adafruit_NeoPixel strip = Adafruit_NeoPixel(5, LEDPIN, NEO_RGB);
     ...
     for(int np = 0;np<strip.numPixels(); np++){
     ...

(with three instances of the latter), say something like

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

    enum {numPixels = 5 };
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(numPixels, LEDPIN, NEO_RGB);
    ...
    for (byte np=0; np<numPixels; ++np){
    ...

This will save about 40 bytes (10 bytes per `for`, and another 10 probably due to `strip.numPixels()` code not linking).  (Note, the savings is due to getting rid of function calls; the change from `int` to `byte` apparently makes no difference in program size, probably because the compiler optimizes `int` to `byte` where its analysis shows it can do so.)

2. Instead of

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

    if (... && now.dayOfTheWeek() != 1 && now.dayOfTheWeek() != 7){

say

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

    if (... && now.dayOfTheWeek()+250>250){

which will save 14 bytes.  This works as explained in my answer to your previous question.  However, I've written `+250>250` here instead of the `+249>250` there because according to `RTClib` documentation and `RTClib.cpp` code, `.dayOfTheWeek()` returns 0 for Saturday, rather than 1 as you seem to expect.

3. Possibly inline `beep()`, since you call it only once.


body:
On a quick test build for an ATmega328p type Arduino, the implementation of random() and its unique dependencies seems to be about 180 bytes, so you might see if there's a more compact way of achieving your need there, perhaps using the low byte of some mathematical expression of the time, and just retrying until you get an in-range value.

Of course if you get really stuck, you could remove the bootloader and program it with ISP from an ordinary Arduino or something like that.


body:
Remove the `rtc.adjust(DateTime(__DATE__, __TIME__));`. You only need to set the RTC once, after e.g. you insert the backup battery.

Change

    pinMode(BTNPIN, INPUT);
    digitalWrite(BTNPIN, HIGH);

to

    pinMode(BTNPIN, INPUT_PULLUP);

Inline the beep function using the `inline` hint:

    inline void beep(int delayAmount)
    ...

Shorter `beep` function:

    inline void beep(int delayAmount)
    {
      for (uint16_t t = 0; t < 30*1000; t += delayAmount)
      {
        digitalWrite(TONE,t & 0x01);// HIGH is odd, LOW if even
        delayMicroseconds(delayAmount);
      }
    }


body:
Very good suggestions so far. I have only one to add: instead of
`strip.Color(0,0,0)` use just the constant number 0. This saves a
function call.


message:
Removing CH340g chip from Arduino Nano clone.. any issues?

In trying to figure out how to solve another [problem with Arduino Nano clone using CH340 chip][1], I was just now wondering, would there be any issues if I were to simply remove the CH340 chip? As it stands, I have the slight suspicion that the chip itself might be causing some problems with communicating using only the Tx Rx pins, could this be the case? More importantly, can I just remove the chip with no issues (other than the already lacking ability to use it as USB-Serial bridge)? In a working board, would removing the chip cause any other problems?

  [1]: https://arduino.stackexchange.com/questions/23750/nano-clone-not-working-over-usb-no-data-no-power-but-can-power-via-vin-schot

body:
No problem whatsoever as long as you aren't powering the board over USB. You may still be able to do that though depending on what role the CH has in managing the power.

Personally I think all CH chip should be removed from all boards. They are horrible chips and cause no end of problems.

I assume you have an FT232 adapter board (or similar) to then use for the programming of your Arduino.


body:
Looking at the datasheet, I see no problem with removing it.

I'd suggest using a sharp knife and cut all the pins, one at a time, right where they come out of the black epoxy. Make sure you don't accidentally stab into the PCB. Remove the main body of the chip. After that, remove the legs still attached to the PCB, one by one, using a soldering iron.


body: Once I removed a burned ch340 from a dysfunctional uno, and it didn't brought it back to life, I couldn't program it by other means, because reset remained shorted to ground. It might have other problems, but I still recommend digging more into the problem (eg. Check the diagram for your board)


body:
You could probably get away with just removing 3 legs - Tx, Rx, and DTR. The rest don't anything.
The pins are rather far apart, you could heat them one at a time gently pry/lify up with tweezers too. Better than a knife I would think.


message:
DC Motor Speed Measurement using Rotary Encoder

I have written the following code to measure the speed of a unidirectional DC Motor.I have attempted to measure the time between successive interrupts in order to calculate speed.

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

    boolean check;
    boolean start;
    unsigned int angle = 5;   //angle moved per encoder tick
    unsigned long volatile time1;
    unsigned long volatile time_11;
    unsigned long interrupt_time;

    void setup() {
      Serial.begin(9600);
      while (!Serial) ;
      pinMode(21, INPUT);  //Pin#21=interrupt pin, matched to interrupt#2
      attachInterrupt(digitalPinToInterrupt(2), speed, FALLING);
      time1 = 0;
      time_11 = 0;
      interrupt_time = 0;
      check = true;
      start = false;
      time_11 = millis(); //Start Clock
    }

    void loop() {
      if(time1 == interrupt_time && start) //Both times same , hence bool start.
      {
        if(check)
        {
          Serial.print(millis());  //Time taken to rise to steady speed.
          check = false;
        }
        Serial.println((angle/time1)*1000);   //Display Speed.
      }
      interrupt_time = time1;
      start = false;
      while(!start)
        {}
    }

    void speed(void) {
      start = true;
      time1 = millis()-time_11;
      time_11 = millis();
    }

I want the code to be as efficient as possible.I have around 100 ticks per 360 degrees from my encoder.Is there any chance of "missing" an interrupt?

body:
Just a couple of remarks:

1. `start` should be volatile, but you can remove it and simply check
   that `time1 != 0`.

2. there is no point in calling `millis()` twice inside the interrupt
   service routine:

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

    void speed(void) {
      unsigned long now = millis();
      time1 = now - time_11;
      time_11 = now;
    }


body:
Thank you for the feedback!
This is my attempt at calculating speed using the averaging method.

    unsigned long volatile encodercount;
    unsigned long encodercount_previous;
    unsigned long volatile timer;
    unsigned int angle;
    boolean first;
    boolean firstencodertick;
    void setup() {
          angle=3;
          encodercount=0;
          encodercount_previous=0;
          Serial.begin(9600);
          while (!Serial);
          pinMode(21,INPUT);  //Pin#21=interrupt pin, matched to interrupt#2
          attachInterrupt(digitalPinToInterrupt(2),speed,FALLING);
          first=true;
          firstecnodertick=true;
            }

      void loop() {
         delay(100);

       if(encodercount==encodercount_previous&&encodercount!=0)
        {
       if(first)
         {
       Serial.println(millis()-timer);  //Steady State Time Taken
       first=false;
         }
      Serial.println((encodercount); //Angle Moved in 0.1second.
        }
      encodercount_previous=encodercount;
      encodercount=0;
       }

      void speed(void)
     {
     if(firstencodertick)
     {
     timer=millis();
     firstencodertick=false;
      }
     encodercount++;
    }


message:
How to switch on an AC bulb using arduino as well as regular switch?

I'm trying to build a GSM based AC Power ON/OFF switch using Arduino. I've successfully completed the ON/OFF mechanism using SMS with the help of 240v 100amps relay to control the circuit. Apparently I don't want to disturb the regular on/off switch's operation. I want both of them to be operational. When I'm not at home arduino should be the switch control and the regular one should be preferred while at home. I'm actually a noob in this topic, and want your precious help to solve this issue.

body:
This can be done (to a certain extent) using a SPDT (Single-Pole-Double-Throw) relay and an SPDT switch.

The basic principle is the same as when you have two light switches controlling the same light (such as on a staircase - one switch at the top and one at the bottom).  The two switches alternate between one of two different paths for the current. When both switches are routed to the same path the light is on.

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

Both the Arduino and the switch can turn the light on and off at will. The only problem, though, is that the Arduino has no clue if the light is on or off. To know if the light is on you will need some kind of feedback mechanism.  That might be a simple LDR that looks to see if it's light or dark, or some kind of current monitoring system (current transformer, hall effect current monitor, etc) which the Arduino can use to see if current is actually flowing through the lamp circuit or not.

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


body:
A safer approach is to optically link the Arduino to an [IR remote control light switch][1].  Such an approach is discussed in [this thread][2]. The technical specifications appear to be [here][3] for the Lutron light switch remote controls.  From this document one could construct an [Arduino IR transmitter][4] to send out these code.

  [1]: http://www.lutron.com/en-US/Products/Pages/StandAloneControls/Dimmers-Switches/MaestroIRDimmer/Overview.aspx
  [2]: http://forum.arduino.cc/index.php?topic=155114.0
  [3]: http://www.lutron.com/TechnicalDocumentLibrary/048158.doc
  [4]: https://learn.adafruit.com/using-an-infrared-library/sending-ir-codes


message:
calling a random function number

I have a recurring problem that when I'm controlling leds, I make several different functions for different fx and just want to trigger them randomly but having a hard time to formulate it in an intelligent way and end up hardcoding every function call.

ex: I have let's say 10 functions called anim1();, anim2();, anim3(); etc
and would like to called them randomly in that fashion :

    randNumber = random(1,11);
    anim[randNumber]();

I know that it's not that type of brackets I need to use but I can't find the proper syntax and I'm wondering if it's possible to do that..
I'm sure there must be a way ;)

thanks for your help

body:
What you want is an *array of function pointers*.

    void anim1() {
        // blah blah
    }

    void anim2() {
        // blah blah
    }
    // ... etc ...

    typedef void (*animptr)();

    animptr anims[10] = {
        anim1,
        anim2,
        anim3,
        // ... etc ...
        anim10
    };

Then you can use:

    anims[animNumber]();


body:
I end up using another way and just wanted to share it here for anybody that would want a bit less efficient but simpler way of doing that  ;) it's cleaner with Majenko's solution for sure but this gets the job done and is pretty easy to understand and troubleshoot. cheers!

    int randNumber;

    void loop(){
    randNumber = random(1,14);

    if (button is pressed or something){
    callAnim(randNumber);
    }
    }

    void callAnim(int randNumber){
    if (randNumber==1){
    anim1();
    }
    if (randNumber==2){
    anim2();
    }
    }
    // ... etc ...

    void anim1() {
    // blah blah
    }

    void anim2() {
    // blah blah
    }
    // ... etc ...


message:
convert String to unsigned long long

i want to convert string for example
"68976543210" to unsigned long long(64 bit) in mega2560,
 do is possible?

    String x="68976543210";
    unsigned long long y=?;

body:
avr-libc lacks `strtoull()` that I would normally use for such a conversion. You will have to do it manually.

Fortunately it's quite simple - just start with y=0 and, for each character in the string, multiply y by 10 then add the numeric value of the character in the string:

 String x = "68976543210";
 unsigned long long y = 0;

 for (int i = 0; i < x.length(); i++) {
  char c = x.charAt(i);
       if (c < '0' || c > '9') break;
       y *= 10;
       y += (c - '0');
 }

Note that the Arduino Print API has no method for printing a 64-bit integer.


message:
ESP8266 Battery Monitor

Is there a way to monitor the battery that feeds an esp8266 in a portable project?

I have been meaning to implement that feature into my project so that i can be warned when the battery runs low on juice but i don't know if the esp has some kind of onboard sensor to do that.

body:
There are two things you need to measure the battery of the system that is doing the measuring of the battery:

1. An analog-to-digital converter
2. Some form of fixed voltage reference to compare the battery voltage against.

Some ESP8266 modules have a single analog input available, and some don't. You need to check which module you have and which pins are available on it.

Then you need to use the ADC to measure the fixed known voltage. That could be from a small LDO voltage regulator that is below the voltage of the minimum voltage you will care about from your battery, or something like the forward voltage drop of a silicon diode (~0.7V) - something where you know what the voltage is.

From that reading you can then back-track what the supply voltage must be in order to give you the reading it has given you.  As the battery voltage drops the voltage range the ADC will be measuring will be reduced, and so the fixed voltage will rise within that range giving you higher readings from the ADC.

Here is a snippet of code I use with the 1.1V internal voltage reference of the ATMega328P to calculate the supply voltage:

    long readVcc() {
      long result;
      // Read 1.1V reference against AVcc
      ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
      delay(2); // Wait for Vref to settle
      ADCSRA |= _BV(ADSC); // Convert
      while (bit_is_set(ADCSRA,ADSC));
      result = ADCL;
      result |= ADCH<<8;
      result = 1125300L / result; // Back-calculate AVcc in mV
      return result;
    }

Of course, you need to change that to use the analog input of the ESP8266 instead (probably just using analogRead()). And of course change the ADC-scaled voltage.  The formula is basically:

    Vref * ADCmax / ADCreading

So if you have the 1.1V reference as above, and the ADC can read 0-1023, then it's:

    1.1 * 1023 / reading

Or, pre-calculate the first half of the sum:

    1125.3 / reading

To keep it as integer mathematics work in millivolts instead of volts by multiplying the reference voltage by 1000:

    1125300 / reading

And that, as you can see, is what is in the function above.


message:
Pin toggle speed

If I use direct port manipulation, what is the average number of clock cycles it takes to flip a pin on the arduino

ie.

    void loop(){
      PORTB |=  0b00010000;
      PORTB &= ~0b00010000;
    }

So how fast is this generally?

body:
If you compile the code and examine the results you can see how many instructions it will take, and thus how many clock cycles.

It's slightly more complex because of what else happens in main() to call loop, but basically you have:

    for (;;) {
    loop();
      aa:0e 94 49 00 call 0x92; 0x92 <loop>
    if (serialEventRun) serialEventRun();
      ae:20 97       sbi wr28, 0x00; 0
      b0:e1 f3       breq.-8      ; 0xaa <main+0x10>

    00000092 <loop>:
      92:2c 9a       sbi0x05, 4; 5
      94:2c 98       cbi0x05, 4; 5
      96:08 95       ret

So you can see there is:

    Operation                            Cycles
    Call loop()                          4
    Check if serialEventRun exists       2
    Since it doesn't, got start of loop  2

Then in loop:

    Set bit                              2
    Clear bit                            2
    Return                               4

So in total you have 16 clock cycles. At 16MHz that gives you a frequency of 1MHz - however that won't be a square wave of 50% duty cycle since there is much less time between set and clear than between clear and set.  The full 16 cycles, mapped to the state of the IO pin, would look like this:

                 _
     _ _ _ _ _ |   | _ _ _ _ _ _ _ _
    | call  |sbi|cbi|  ret  |chk|bra|
     . . . . . . . . . . . . . . . .

You can get a much tighter operation by wrapping the pin manipulation in a `while (1)` loop:

    void loop(){
      while(1) {
        PORTB |=  0b00010000;
        PORTB &= ~0b00010000;
      }
    }

That reduces down to just:

    00000092 <loop>:
      92:2c 9a       sbi 0x05, 4; 5
      94:2c 98       cbi 0x05, 4; 5
      96:fd cf       rjmp .-6      ; 0x92 <loop>

That's `sbi` (2) `cbi` (2) and `rjmp` (2). A total of 6 clock cycles.  At 16MHz that's 2.667MHz. Again, though, not a 50% duty cycle, since the `rjmp` takes two extra clock cycles:

         _
     _ |   | _ _
    |sbi|cbi|jmp|
     . . . . . .

By inserting a pair of 1-cycle `NOP` instructions you can even out the duty cycle and make it 50%:

    void loop(){
      while(1) {
        PORTB |=  0b00010000;
        asm volatile("nop");
        asm volatile("nop");
        PORTB &= ~0b00010000;
      }
    }

    00000092 <loop>:
      92:2c 9a       sbi 0x05, 4; 5
      94:00 00       nop
      96:00 00       nop
      98:2c 98       cbi 0x05, 4; 5
      9a:fb cf       rjmp.-10     ; 0x92 <loop>

         _ _ _
     _ |       | _ _
    |sbi|n|n|cbi|jmp|
     . . . . . . . .

Now, of course, it's 8 clock cycles, so at 16MHz that's 2MHz output, but with 50% duty cycle.

Incidentally, all these instruction timings are available in the Instruction Set Summary chapter of the ATMega328P data sheet.


message:
Where could I find the "Serial.find()" source code?

As written in the title, could you tell me where to find the source code of the function "Serial.find()"?

I haven' t installed the Arduino IDE, so I'm glad if you could me link a web resource, or if you directly copy the source code here .

Thanks for your time.

body:
It is part of the Stream class which the Serial class inherits from.

* https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Stream.cpp#L93

It just calls `findUntil()` which is a little further down in the same file:

* https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Stream.cpp#L114

That itself calls `findMulti()` which is where all the magic happens:

* https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Stream.cpp#L256

----

    int Stream::findMulti( struct Stream::MultiTarget *targets, int tCount) {
      // any zero length target string automatically matches and would make
      // a mess of the rest of the algorithm.
      for (struct MultiTarget *t = targets; t < targets+tCount; ++t) {
        if (t->len <= 0)
          return t - targets;
      }

      while (1) {
        int c = timedRead();
        if (c < 0)
          return -1;

        for (struct MultiTarget *t = targets; t < targets+tCount; ++t) {
          // the simple case is if we match, deal with that first.
          if (c == t->str[t->index]) {
            if (++t->index == t->len)
              return t - targets;
            else
              continue;
          }

          // if not we need to walk back and see if we could have matched further
          // down the stream (ie '1112' doesn't match the first position in '11112'
          // but it will match the second position so we can't just reset the current
          // index to 0 when we find a mismatch.
          if (t->index == 0)
            continue;

          int origIndex = t->index;
          do {
            --t->index;
            // first check if current char works against the new current index
            if (c != t->str[t->index])
              continue;

            // if it's the only char then we're good, nothing more to check
            if (t->index == 0) {
              t->index++;
              break;
            }

            // otherwise we need to check the rest of the found string
            int diff = origIndex - t->index;
            size_t i;
            for (i = 0; i < t->index; ++i) {
              if (t->str[i] != t->str[i + diff])
                break;
            }

            // if we successfully got through the previous loop then our current
            // index is good.
            if (i == t->index) {
              t->index++;
              break;
            }

            // otherwise we just try the next index
          } while (t->index);
        }
      }
      // unreachable
      return -1;
    }