text:
Store TinyGPS++ latitude value into a variable of type string or float
I want to get the GPS ordinates in degrees with 6 decimal accuracy. I can obtain this by creating a gps object with TinyGPS library. but In the TinyGPS example codes, its written
Serial.println(gps.location.lat(), 6);

But I actually want to store this latitude degrees in a variable of type string or float. when i write this;
double Tiny_latitude = (gps.location.lat());
Serial.print("Tiny lat:");
Serial.println(Tiny_latitude);

it returns me Tiny lat:33.55 on serial monitor. But i want 33.546600.
How do I do that ?

"double lat = gps.location.lat();" but I think there is more to this question?

double and float , both are not working. both giving me 33.55 as an answer. check my updated question ...

double and float are the same on AVR. The answer to the number of decimals printed is here https://www.arduino.cc/en/Serial/Print. The default is two.

Try Serial.println(Tiny_latitude, 6); But remember the max number of digits is 6-7. https://www.arduino.cc/en/Reference/Float

O man, You're a life saver ! Thanks a bunch :) Serial.println(Tiny_latitude, 6); worked like charm.

One last thing, Now if i want to make a String "your location is \nlat:33.546600 \nlong: 75.456912" ,  i.e. my String variable are stored in Tiny_latitude and Tiny_longitude and want to make a string my_Location. How do i do that ? Thanks in advance :)

it returns me Tiny lat:33.55 on serial monitor. But i want 33.546600. How do I do that?

The issue is simply the number of decimal places. That can be added to the Serial.println().
double Tiny_latitude = (gps.location.lat());
Serial.print("Tiny lat:");
Serial.println(Tiny_latitude, 6);

Now if i want to make a String "your location is \nlat:33.546600 \nlong: 75.456912" , i.e. my String variable are stored in Tiny_latitude and Tiny_longitude and want to make a string my_Location. How do i do that?

I would use sprintf() for that but as that requires some additional build parameters the easiest way is to use String. Some special care is needed to increase the number of decimal places.
void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  String buf;
  buf += F("your location is \nlat:");
  buf += String(latitude, 6);
  buf += F("\nlong:");
  buf += String(longitude, 6);
  Serial.println(buf);
  ...
}

Cheers!


text:
ESP8266 sends webpage to client, but html codes appears in browser instead of webpage?
I am using ESP8266 with Arduino MEGA. ESP8266 is powered 3.3v via voltage divider, which is taking 5v from arduino and converting it down to 3.3v with the help of 5K and 10K resistors. AT commands seems to be working OK. I am using SD_card reader and kept my index.html file in SD_card. I am able to make a successful connection and esp also sends the whole index.html file, But the issue is my browser does not shows the page in html format, instead the whole html code appears on the browser. Can anyone help me to sort this issue ?
Herez the whole code;
    #include <SPI.h>
    #include <SD.h>

     #define SSID "Maxcotec"   // change this to match your WiFi SSID
     #define PASS "qamar0334" // change this to match your WiFi password
     #define PORT "80"      // using port 80 by default
    #define DEBUG true
     #define BUFFER_SIZE 1024
     char buffer[BUFFER_SIZE];
    //SoftwareSerial Serial2(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                                 // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                                 // and the RX line from the esp to the Arduino's pin 3
    File webFile, CSS_file;
    String webpage;
     // By default we are looking for OK\r\n
     char OKrn[] = "OK\r\n";
     byte wait_for_esp_response(int timeout, char* term=OKrn) {
      unsigned long t=millis();
      bool found=false;
      int i=0;
      int len=strlen(term);
      // wait for at most timeout milliseconds
      // or if OK\r\n is found
      while(millis()<t+timeout) {
       if(Serial2.available()) {
        buffer[i++]=Serial2.read();
        if(i>=len) {
         if(strncmp(buffer+i-len, term, len)==0) {
          found=true;
          break;
         }
        }
       }
      }
      buffer[i]=0;
      Serial.print(buffer);
      return found;
     }

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

       setupWiFi();
      // print device IP address
      Serial.print("device ip addr:");
      //esp.println("AT+CIFSR");

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

        // initialize SD card
        Serial.println("Initializing SD card...");
        if (!SD.begin(53)) {
            Serial.println("ERROR - SD card initialization failed!");
            return;    // init failed
        }
        Serial.println("SUCCESS - SD card initialized.");
        // check for index.htm file
        if (!SD.exists("index.htm")) {
            Serial.println("ERROR - Can't find index.htm file!");
            return;  // can't find index file
        }
        Serial.println("SUCCESS - Found index.htm file.");

             // send web page
        webFile = SD.open("index.htm");        // open web page file
        if (webFile) {
            while(webFile.available()> 0) {
                //client.write(webFile.read()); // send web page to client
               char ch = webFile.read(); // Read a character
               webpage += ch; // Add it
            }
            webFile.close();
        }
         Serial.print("file contents>>>");
         //Serial.println(webpage);
         //delay(20000);
    }

    void loop()
    {
      if(Serial2.available()) // check if the esp is sending a message
      {
        /*
        while(Serial2.available())
        {
          // The esp has data so display its output to the serial window
          char c = Serial2.read(); // read the next character.
          Serial.write(c);
        } */

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

         int connectionId = Serial2.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!
<button id=\"11\">Toggle Pin 11</button>";//<button>LED1</button>";

         //Serial.print("file contents>>>");
         //Serial.println(webpage);
         //delay(20000);
         String cipSend = "AT+CIPSEND=";
         cipSend += connectionId;
         cipSend += ",";
         cipSend +=webpage.length();
         cipSend +="\r\n";

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

         //webpage="<button>LED2</button>";

    //     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,3000,DEBUG);
        }
      }
    }

    void setupWiFi() {
      // try empty AT command
      Serial2.println("AT");
      wait_for_esp_response(2000);
      // set mode 1 (client)
      Serial2.println("AT+CWMODE=1");
      wait_for_esp_response(2000);
      // reset WiFi module
     /*
      esp.print("AT+RST\r\n");
      wait_for_esp_response(3000);
      delay(5000);
      */
      // join AP
      Serial2.print("AT+CWJAP=\"");
      Serial2.print("xxxxxxx");
      Serial2.print("\",\"");
      Serial2.print("xxxxxxx");
      Serial2.println("\"");
      // this may take a while, so wait for 5 seconds
      wait_for_esp_response(5000);
      Serial2.println("AT+CIPSTO=30");
      wait_for_esp_response(1000);
      // start server
      Serial2.println("AT+CIPMUX=1");
      wait_for_esp_response(1000);
      Serial2.print("AT+CIPSERVER=1,"); // turn on TCP service
      Serial2.println(PORT);
      wait_for_esp_response(1000);
     }

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

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

        long int time = millis();

        while( (time+timeout) > millis())
        {
          while(Serial2.available())
          {

            // The esp has data so display its output to the serial window
            char c = Serial2.read(); // read the next character.
            response+=c;
          }
        }

        if(debug)
        {
          Serial.print(response);
        }

        return response;
    }

And this is what I am getting in web browser;
I am using Opera browser but I have tried in Chrome and firefox aswell. when I open this index.html page in my laptop with the same browser, it opens perfectly.

Did you tell the browser that you're sending it HTML?

Looks like you're lacking the whole of the header portion to me...

I am following link this tutorials. Its seems like he is also not sending the header portion.

@AnumSheraz try using the developer tools to get the headers. To do this for instance in Chrome press F12, go to the network tab, load the page and look at the files being retrieved. Find the index.html file, right click on it and press "Copy response headers"; then post them in your question: this way we'll be able to see what are the missing ones

Also, please get a proper 3.3V regulator.

You need to send the header Content-Type: text/html before the html.

I'm trying to use the program and now I have achieved good results. Now I am trying to send a txt file to a client that connects to the webserver.
When the client sends a request to: IP\data.txt, it should directly receive the txt file to download.
Have you any advice for me? Thank you, Riccardo

Why are you using the 5 V and not the 3.v V from Arduino?  Using a divider is not a good idea. Yout voltage will not stay constant and you are liminting the current with voiltage deviding.

It looks like you did not send the HTTP headers. Before sending any of the HTML content send following lines:
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n\r\n"

Make sure you send all the \r\n !

See the text from "'HTTP/1.1 200 OK'" until "'DOCTYPE html'" in the following couple of links which say the same, and you might like to read the rest of those pages:

https://www.arduino.cc/en/Tutorial/WebServer
http://www.allaboutcircuits.com/projects/using-an-arduino-as-a-web-server

this is an html question, not an arduino question. What is it doing here? Sending html from an esp8266 is no different than sending it from any other device.

Before asking the question, I didn't knew that its could be html problem, I thought it might the voltage issue (as many ppl have this issue with there esp8266).

Slightly off-topic, as this is not the source of your problem, but as jBot42 says, you need a proper regulator. When you use a voltage divider, your load (the ESP8266) is connected in parallel with one of the resistors (the 10K one) and effectively changes the output voltage of the regulator. As the consumption of power in the ESP8266 changes (e.g. when the wifi circuit transfers data), the voltage will also change.
At the very least you should place an electrolytic capacitor in parallel with the 10K resistor, but even this is not a good solution.

Make sure you save the SD card file as index.htm.
That is what you are calling for in your code. Your description has a reference to index.html. You will get the result you see.

Whilst you are correct, in that there is a mismatch between the source code calling a .htm file and the OP saying that the file on the SD card is a .html file, this is most likely a typo, in the question, on the part of the OP. The Arduino is clearly accessing the file correctly. So, unfortunately, this will not fix the issue that the OP is experiencing. The correct answer has already been provided, which is that the HTTP headers were missing.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Requesting references for learning about the upload process
I would like to know of references that discuss the process of uploading code onto an Arduino board. I have read this reference on hacking the Arduino and an outline of the build process. I also found this segment on creating Arduino libraries informative.
Overall I am interested in tracing through an upload process to learn more detail about how the programming works. I would like to understand which C-libraries are used. I would like to understand how the code is uploaded onto the Arduino. One example that I would like to see is an direct upload of C or C++ code without using the IDE gui. I want to see kind of the "bare-minimum" necessary for programming the Arduino (in C/C++). I would ideally like to read about something like this which makes use of the Arduino libraries.
Looking forward to hearing back responses, and being a part of this community. Any references and comments appreciated.

Edit #1 (request for more information from the accepted answer):
How does the main sketch trace through the C/C++ code?
For example, in the make file shown in the accepted answer:
$(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
$(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
$(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o

Does part of the main sketch transfer through in the compilation of malloc.c and realloc.c (as well as the c/c++ files)?
I would think so, being that it is compiled every time we change the main sketch.
Lastly, how is the outputted .hex file uploaded to the board?

Edit #2 Trouble compiling with make method
I am having issues with the manual compiling process, I am using Arduino 1.6.5 r5. It seems that malloc.c and realloc.c are not in the same place as they were in IDE 1.0.6.. Here is the makefile.
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015
#
# Edited by: Kyle Lawlor
# Date: 30th October 2015

$H# where you installed the Arduino app
ARDUINO_DIR = /home/wiz/programs/arduino-1.6.5-r5/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

# create a file called Blink.cpp in same base dir
MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/avr/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
#   $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
#   $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
#   $(AR) rcs core.a malloc.c.o
#   $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

The build fails unless the lines involving those two functions are commented out. I searched in the directories but had no luck in finding the libraries, so I decided to move forward in testing things out.
Here is the file I am using as Blink.cpp.
#include <Arduino.h>

void setup(){
    pinMode(13, OUTPUT);
}

void loop(){
    digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(1000);              // wait for a second
    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    delay(1000);              // wait for a second
}

Again, the build does compile ignoring malloc and realloc. I am unsure of whether these are critical libraries as I am not very familiar with C/C++. While the libraries do compile, there is an error derived from the delay() function in Blink.cpp.
Here is that:
"/home/wiz/programs/arduino-1.6.5-r5/hardware/tools/avr/bin/avr-gcc" -Os -Wl,--gc-sections -mmcu=atmega328p -o Blink.cpp.elf Blink.cpp.o core.a -lm
core.a(wiring.c.o): In function `delay':
/home/wiz/programs/arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/wiring.c:113: undefined reference to `yield'
collect2: error: ld returned 1 exit status
make: *** [build] Error 1

I am unsure at this point whether or not this error is related to the fact that malloc and realloc have not been compiled. I have traced back into the wiring.c file to find out where yield() was. That file starts with an #include "wiring_private.h" and here is the delay function and yield:
void delay(unsigned long ms)
{
        uint16_t start = (uint16_t)micros();

        while (ms > 0) {
                yield();
                if (((uint16_t)micros() - start) >= 1000) {
                        ms--;
                        start += 1000;
                }
        }
}

Here are the include statements from the wiring_private.h header.
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include <stdarg.h>

#include "Arduino.h"

Perhaps on of these contain the yield() function, which is not being seen correctly?
Does anyone have any advice for what I am doing wrong regarding building manually with 1.6.5? Any comments or further comments will be appreciated.

Edit #3 Identified where yield() function is located.
Project directory:
.
├── abi.cpp
├── Arduino.h
├── binary.h
├── Blink.cpp
├── Blink.cpp.d
├── Blink.cpp.o
├── CDC.cpp
├── CDC.cpp.d
├── CDC.cpp.o
├── Client.h
├── core.a
├── HardwareSerial0.cpp
├── HardwareSerial1.cpp
├── HardwareSerial2.cpp
├── HardwareSerial3.cpp
├── HardwareSerial.cpp
├── HardwareSerial.cpp.d
├── HardwareSerial.cpp.o
├── HardwareSerial.h
├── HardwareSerial_private.h
├── HID.cpp
├── HID.cpp.d
├── HID.cpp.o
├── hooks.c
├── IPAddress.cpp
├── IPAddress.cpp.d
├── IPAddress.cpp.o
├── IPAddress.h
├── main.cpp
├── main.cpp.d
├── main.cpp.o
├── new.cpp
├── new.cpp.d
├── new.cpp.o
├── new.h
├── Printable.h
├── Print.cpp
├── Print.cpp.d
├── Print.cpp.o
├── Print.h
├── run.mk
├── run.mk~
├── Server.h
├── Stream.cpp
├── Stream.cpp.d
├── Stream.cpp.o
├── Stream.h
├── Tone.cpp
├── Tone.cpp.d
├── Tone.cpp.o
├── Udp.h
├── USBAPI.h
├── USBCore.cpp
├── USBCore.cpp.d
├── USBCore.cpp.o
├── USBCore.h
├── USBDesc.h
├── WCharacter.h
├── WInterrupts.c
├── WInterrupts.c.d
├── WInterrupts.c.o
├── wiring_analog.c
├── wiring_analog.c.d
├── wiring_analog.c.o
├── wiring.c
├── wiring.c.d
├── wiring.c.o
├── wiring_digital.c
├── wiring_digital.c.d
├── wiring_digital.c.o
├── wiring_private.h
├── wiring_pulse.c
├── wiring_pulse.c.d
├── wiring_pulse.c.o
├── wiring_pulse.S
├── wiring_shift.c
├── wiring_shift.c.d
├── wiring_shift.c.o
├── WMath.cpp
├── WMath.cpp.d
├── WMath.cpp.o
├── WString.cpp
├── WString.cpp.d
├── WString.cpp.o
└── WString.h

yield() is located in hooks.c. I do not understand why the function is not available to wiring.c.

Edit #4 Compilation working
Structure of arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino:
.
├── abi.cpp
├── Arduino.h
├── binary.h
├── CDC.cpp
├── Client.h
├── HardwareSerial0.cpp
├── HardwareSerial1.cpp
├── HardwareSerial2.cpp
├── HardwareSerial3.cpp
├── HardwareSerial.cpp
├── HardwareSerial.h
├── HardwareSerial_private.h
├── HID.cpp
├── hooks.c
├── IPAddress.cpp
├── IPAddress.h
├── main.cpp
├── new.cpp
├── new.h
├── Printable.h
├── Print.cpp
├── Print.h
├── Server.h
├── Stream.cpp
├── Stream.h
├── Tone.cpp
├── Udp.h
├── USBAPI.h
├── USBCore.cpp
├── USBCore.h
├── USBDesc.h
├── WCharacter.h
├── WInterrupts.c
├── wiring_analog.c
├── wiring.c
├── wiring_digital.c
├── wiring_private.h
├── wiring_pulse.c
├── wiring_pulse.S
├── wiring_shift.c
├── WMath.cpp
├── WString.cpp
└── WString.h

The reason the yield() function was not recognized was because I was not compiling with 1.6.5 correctly. Below is an updated makefile that compiles the Blink.cpp seemingly correct. I have yet to verify the sketch works on upload to the Arduino (via avrdude). The mistake was that I did not compile abi.cpp, HardwareSerialx.cpp(0-3), and hooks.c. hooks.c is where the yield() is located.
Updated makefile:
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015
#
# Edited by: Kyle Lawlor
# Date: 30th October 2015

$H# where you installed the Arduino app
ARDUINO_DIR = /home/wiz/programs/arduino-1.6.5-r5/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

# create a file called Blink.cpp in same base dir
MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/avr/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
#   $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
#   $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)hooks.c -o hooks.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)abi.cpp -o abi.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial0.cpp -o HardwareSerial0.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial1.cpp -o HardwareSerial1.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial2.cpp -o HardwareSerial2.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial3.cpp -o HardwareSerial3.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
#   $(AR) rcs core.a malloc.c.o
#   $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a hooks.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a abi.cpp.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HardwareSerial0.cpp.o
    $(AR) rcs core.a HardwareSerial1.cpp.o
    $(AR) rcs core.a HardwareSerial2.cpp.o
    $(AR) rcs core.a HardwareSerial3.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

Are malloc.c and realloc.c being used anymore? I searched across 1.6.5 for a directory similar to avr-libc, I couldn't find anything. I'm guessing they are no longer in use.

Edit #5 Upload via avrdude
Basically this command worked for my board (Arduino Uno SMD):
avrdude -v -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:w:/path/to/Blink.cpp.hex:i

This is all to say that the latter makefile in this post correctly builds the .hex file. Which can then successfully be uploaded onto the board. (Using Arduino 1.6.5).

I am interested in tracing through an upload process to learn more detail ...

I covered the uploading process in some detail here: What happens when code is uploaded using the bootloader?

I would like to understand which C-libraries are used

See my post about How the IDE organizes things

One example that I would like to see is an direct upload of C or C++ code without using the IDE gui.

I wrote a simple Makefile on the Arduino Forum:
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

There are quite a few more complex ones around.

I want to see kind of the "bare-minimum" necessary for programming the Arduino (in C/C++).

Here:
int main ()
 {
 }

Does part of the main sketch transfer through in the compilation of malloc.c and realloc.c (as well as the c/c++ files)?
I would think so, being that it is compiled every time we change the main sketch.

I'm not sure I understand the part about "transfer through" but basically functions which are needed in the main sketch are linked into the combined file by the linker.
Effectively these are the main parts:
# Compile main sketch
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o

# Compile libraries
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
...

# Remove temporary "combined libraries" file
    rm core.a

# Add compiled libraries into combined file "core.a"
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
...

# Link main sketch to combined libraries (linker will discard things not needed)
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm

# Make an .eep (EEPROM) file
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep

# Make the main .hex file
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

Lastly, how is the outputted .hex file uploaded to the board?

There are various ways of achieving this. The IDE calls the program avrdude which is designed to upload a .hex file to a processor. You can also just copy the .hex file to an SD card and upload it using a board programmer.

Are malloc.c and realloc.c being used anymore?

They are being used, the trick is to find them.
I can't see them being directly linked in a 1.6.5 compiler output, so I am assuming (I can't prove it right now) that they are linked in by default from libc.a (the default C library). Being a default library it is not mentioned on the linker line.
In my (Linux) installation I found that library here:
~/Development/arduino-1.6.5-r5/hardware/tools/avr/avr/lib/libc.a

If you do a nm on it you find this (amongst other things):
malloc.o:
00000002 C __brkval
         U __do_clear_bss
         U __do_copy_data
00000002 C __flp
00000146 T free
         U __heap_end
         U __heap_start
00000000 T malloc
00000000 D __malloc_heap_end
00000002 D __malloc_heap_start
00000004 D __malloc_margin
0000003e a __SP_H__
0000003d a __SP_L__
0000003f a __SREG__
00000000 a __tmp_reg__
00000001 a __zero_reg__

From man nm:
  "D"
  "d" The symbol is in the initialized data section.
 ...
  "T"
  "t" The symbol is in the text (code) section.

See http://www.linuxtopia.org/online_books/an_introduction_to_gcc/gccintro_17.html :

The C standard library itself is stored in '/usr/lib/libc.a' and contains functions specified in the ANSI/ISO C standard, such as 'printf'---this library is linked by default for every C program.

I am guessing here that malloc and free moved into the standard (default) library since version 1.0.6 (or they wanted to override it with a bugfix) and it is now being found, by default, in the standard C library as described above.
You should be able to find more about AVR libc at its page: http://www.nongnu.org/avr-libc/

Please see my edits. I am looking for a bit more information. Thank you for the answer. It is very helpful.

See amended reply.

I am not too familiar with C terminology. Are the INCLUDE_FILES in reference to the headers? While the LIBRARY_DIR is in reference to the c and cpp file? I've looked in the directories and see those types of files. I just want to understand the distinction. I also found some assembly code (.S), is that file used in INCLUDE_FILES or LIBRARY_DIR?

The INCLUDE_FILES is the path to the .h files used in the compilation process (eg. Arduino.h). If you include other libraries (like SPI) more include files paths are added to the compile line for the main sketch. These locations may vary a bit from IDE to IDE, I think the one I quoted was form IDE 1.0.6. Assembly code would be assembled as a separate compilation unit (ie. another compile) since one compiler doesn't compile both C++ and assembler. The best way to examine this is to turn on verbose compiling, try some compiles, and see what gets generated.

Hi, again. Please see the edits to my post. I hope the forums don't mind me amending the post as much as I have.

See my amended reply.

I figured that they likely were moved. Thanks for confirming this. The build process works for my setup now. The gcc reference will be helpful. Thanks, again.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

authors: Мишаков Максим


text:
How to extract number from a string?
Using LabVIEW I am sending string of data through Xbee like,

u123
r64
r89
u34
r179

And my arduino is receiving this data.
I want my arduino to read this data as a string
and I want to extract numbers from these strings and feed it into two different servos.
For example from u123 I want to extract 123 and feed it to servo1 and from r64 I want to extract 64 and feed it to servo2 and so on.
Arduino IDE Serial Monitor is showing nothing but Arduino's Xbee is receiving and sending data. Don't know why :(

It's not clear what you're asking. Is "Arduino IDE Serial Monitor is showing nothing..." an additional question or did my answer not address your question? What are you expecting to happen? What did you try to accomplish that? What happened instead?

First collect all of the characters up to the new-line (`\n' or line-feed) into an array of characters, and put a zero byte after the last one.
Since It looks like all of the strings you need to parse consist of one a single letter followed by the value you want, value = atoi(inputArray[1]; will return the value as a 16-bit int. If it could be larger than 32767 but less than 65536 (probably not if you're driving a servo with it), then cast the value to unsigned.
If there might be an unknown number of characters (non-digits) preceeding the value, the C function size_t strcspn(const char *string, const char *cset) will return the length of the leading sub-string of string that does not contain characters in cset. So value = atoi(inputArray[strcspn(inputArray, "0123456789")]); will do the same thing, but calculating the array index of the first digit in the string.
(For completeness, note there is a companion function, size_t strspn(const char *str, const char *cset);, that returns the leading sub-string of 'string' consisting only of characters in cset).


text:
How to access parse cloud functions using arduino?
I have created rest service using .js file on Parse.com.
I want to access cloud function from arduino.
i tried this
client.get(https://myAppID:javascript-key=myJavaScriptKey@api.parse.com/1/functions/hello");
i am getting error "Method not allowed".
Solution :
Somehow i got the answer which is as follows.I hope it will help others.
 ParseCloudFunction cloudFunction;
 cloudFunction.setFunctionName(function_name);  //string ("hello")
 cloudFunction.add("light_sensor", light); //pass parameter to cloud

 ParseResponse response = cloudFunction.send();
 Serial.println(response.getJSONBody());

What is a rest service?

REST api i have written on Parse side that i want to access from Arduino sketch.

I read api of Parse and there i got the class to call cloud function from
Arduino.I hope it will help others.
 ParseCloudFunction cloudFunction;
 cloudFunction.setFunctionName(fnname); //String ("hello")
 cloudFunction.add("light_sensor", 139); //parameter

 ParseResponse response = cloudFunction.send();
 Serial.println(response.getJSONBody());


text:
Arduino sending keystrokes via push-buttons. Proper bouncing and manually setting buttons?
I have a simple set of 8 push buttons wired to a Teensy 3.2 board (which uses Arduino via Teensyduino plugin). The 8 buttons are on pins 1-8 and their common ground line (one line soldered to each of them) is on the GND pin. I have code to get any one button working that works. It's currently set to make pressing the second button type "A."
I'd like to make push buttons 1 through 8 type out A,B,C...etc respectively as you press them. I've been told of two problems with my setup, the first being that copying the code for every button is a bad way to go about it and second that it's subject to bouncing issues (creates a keystroke once every 5 presses or so.) I'd also like to set this up so in the future I can write a 3rd party app that configures the keys based on the user's preference.
Adding those needs up I'm not sure where to go next. I'm beginner enough that I'm not sure how to properly incorporate the bounce class or if that's the right way to go given the needs.
Is a matrix the way to go or is there an elegant way to manual set each button and compensate for bounce? I'd really appreciate a small example if anyone has done this. Thanks~ Current code follows:
#define CHECK_EVERY_MS 20
#define MIN_STABLE_VALS 5

unsigned long previousMillis;
char stableVals;
char buttonPressed;

void setup() {
  // make pin 2 an input and turn on the
  // pullup resistor so it goes high unless
  // connected to ground:
  pinMode(2, INPUT_PULLUP);
  Keyboard.begin();
}

void  loop() {
    if ((millis() - previousMillis) > CHECK_EVERY_MS)
    {
        previousMillis += CHECK_EVERY_MS;
        if (digitalRead(2) != buttonPressed)
        {
            stableVals++;
            if (stableVals >= MIN_STABLE_VALS)
            {
                buttonPressed = !buttonPressed;
                stableVals = 0;

                if (buttonPressed)
                {
                    //Send an ASCII 'A',
                    Keyboard.write(65);
                }
            }
        }
        else
            stableVals = 0;
    }
}

-------
Edit: WORKING CODE FOLLOWS
/*  jw - 3 Nov 2015 - Program for button debounce demo
Ref: http://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin
*/

//--------------------------------------------------------
enum { sw0=3, sw1=4, sw2=5, sw3=6, sw4=7, sw5=8, sw6=9, sw7=10}; // Switchbutton lines
enum { nSwitches=8, bounceMillis=42}; // # of switches; debounce delay
struct ButtonStruct {
  unsigned long int bounceEnd;  // Debouncing-flag and end-time
  // Switch number, press-action, release-action, and prev reading
  byte swiNum, swiActP, swiActR, swiPrev;
};

struct ButtonStruct buttons[nSwitches] = {
  {0, sw0, 'A'},
  {0, sw1, 'B'},
  {0, sw2, 'C'},
  {0, sw3, 'D'},
  {0, sw4, 'E'},
  {0, sw5, 'F'},
  {0, sw6, 'G'},
  {0, sw7, 'H'}};
//--------------------------------------------------------
void setup() {
  for (int i=0; i<nSwitches; ++i)
    pinMode(buttons[i].swiNum, INPUT_PULLUP);
Keyboard.begin();
}
//--------------------------------------------------------
byte readSwitch (byte swiNum) {
  // Following inverts the pin reading (assumes pulldown = pressed)
  return 1 - digitalRead(swiNum);
}
//--------------------------------------------------------
void doAction(byte swin, char code, char action) {
  Keyboard.write(action);
}
//--------------------------------------------------------
void doButton(byte bn) {
  struct ButtonStruct *b = buttons + bn;
  if (b->bounceEnd) { // Was button changing?
    // It was changing, see if debounce time is done.
      if (b->bounceEnd < millis()) {
    b->bounceEnd = 0;    // Debounce time is done, so clear flag
    // See if the change was real, or a glitch
    if (readSwitch(b->swiNum) == b->swiPrev) {
      // Current reading is same as trigger reading, so do it
      if (b->swiPrev) {
        doAction(b->swiNum, 'P', b->swiActP);
      } else {
        doAction(b->swiNum, 'R', b->swiActR);
      }
    }
      }
  } else {  // It wasn't changing; but see if it's changing now
    if (b->swiPrev != readSwitch(b->swiNum)) {
      b->swiPrev = readSwitch(b->swiNum);
      b->bounceEnd = millis()+bounceMillis; // Set the Debounce flag
    }
  }
}
//--------------------------------------------------------
long int seconds, prevSec=0;
void loop() {
  for (int i=0; i<nSwitches; ++i)
    doButton(i);
}

You already have it working with one button. Just replicate it for all the others. This could be a good time to learn about arrays and loops.

Yes but it suffers from only sending a keystroke once ever 5-10 clicks, one of the things I'm trying to learn to fix.  The other is how to loop this correctly, as I can't find a tutorial online~

I'm not sure what you mean by “Is a matrix the way to go”, so will ignore that question.
Shown below is a way of using an array of structs (one of C's ways of organizing a collection of items) to keep data for several buttons, such that it's straightforward to use one subroutine to process each button the same way, using a for-loop to call the routine for each button.
Each element of the array buttons is a ButtonStruct, and each ButtonStruct contains five items: bounceEnd, swiNum, swiActP, swiActR, swiPrev, which respectively represent a debouncing-flag and end-time; a switch number [ie a pin number]; a code for action to take on a press; a code for action to take on a release; and previous state of button.  (In many special cases, some of these items will be irrelevant and you can leave them out of the ButtonStruct.)  The form b->x that is used in the doButton() routine says to access element x of the struct that b points to.
At the start of each loop() pass, doButton() is called once for each button.  It first tests if debouncing was underway for the button.  If so, it sees if enough time has gone by to suppose button bounce is over.  If so, it reads the button's state, and if different from previous state, does an action for whichever way the button changed.  (If the button state is unchanged after a debounce delay, the program supposes there was a glitch.)  If debouncing was not underway, the program checks if the button state is different from most recent pass.  In that case, it sets up a debounce test for the button.
The buttons are tested and debounced individually, as you can see in the sample output that is shown following the program.  (This program was tested on an Uno, with four independent buttons used in the test. Edit: Made corrections to handle 32-bit overflow, 2016.10.17)
/*  jw - 3 Nov 2015 - Program for button debounce demo
Ref: http://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin
*/

//--------------------------------------------------------
enum { sw0=8, sw1=9, sw2=10, sw3=11}; // Switchbutton lines
enum { nSwitches=4, bounceMillis=42}; // # of switches; debounce delay
struct ButtonStruct {
  unsigned long int bounceGo;   // Debouncing-flag and end-time
  // Switch number, press-action, release-action, and prev reading
  byte swiNum, swiActP, swiActR, swiPrev;
};

struct ButtonStruct buttons[nSwitches] = {
  {0, sw0, 'A','a', 0}, {0, sw1, 'B','b', 0}, {0, sw2, 'C','c', 0}, {0, sw3, 'D','d', 0}};
//--------------------------------------------------------
void setup() {
  for (int i=0; i<nSwitches; ++i)
    pinMode(buttons[i].swiNum, INPUT_PULLUP);
  Serial.begin(115200);
  Serial.println("Starting");
}
//--------------------------------------------------------
byte readSwitch (byte swiNum) {
  // Following inverts the pin reading (assumes pulldown = pressed)
  return 1 - digitalRead(swiNum);
}
//--------------------------------------------------------
void doAction(byte swin, char code, char action) {
  Serial.print("Switch ");
  Serial.print(swin);
  Serial.print(code);
  Serial.print(' ');
  Serial.print(action);
  Serial.print(" at t=");
  Serial.print(millis());
  Serial.println();
}
//--------------------------------------------------------
void doButton(byte bn) {
  struct ButtonStruct *b = buttons + bn;
  if (b->bounceGo) { // Was button changing?
    // It was changing, see if debounce time is done.
      if (millis() - b->bounceGo > bounceMillis) {
    b->bounceGo = 0;    // Debounce time is done, so clear flag
    // See if the change was real, or a glitch
    if (readSwitch(b->swiNum) == b->swiPrev) {
      // Current reading is same as trigger reading, so do it
      if (b->swiPrev) {
        doAction(b->swiNum, 'P', b->swiActP);
      } else {
        doAction(b->swiNum, 'R', b->swiActR);
      }
    }
      }
  } else {  // It wasn't changing; but see if it's changing now
    if (b->swiPrev != readSwitch(b->swiNum)) {
      b->swiPrev = readSwitch(b->swiNum);
      b->bounceGo = millis();   // Set the Debounce flag
    }
  }
}
//--------------------------------------------------------
long int seconds, prevSec=0;
void loop() {
  for (int i=0; i<nSwitches; ++i)
    doButton(i);
}

In the sample output below, a P line indicates a button press, detected at given millis() time, and an R line indicates a button release.   Observe, near the end, overlaps among separate button presses and releases.
Starting
Switch 8P A at t=2170
Switch 8R a at t=2322
Switch 9P B at t=2789
Switch 9R b at t=2969
Switch 10P C at t=3395
Switch 10R c at t=3562
Switch 11P D at t=4087
Switch 11R d at t=4260
Switch 11P D at t=6518
Switch 10P C at t=6961
Switch 8P A at t=7070
Switch 10R c at t=7112
Switch 11R d at t=7427
Switch 8R a at t=7598
Switch 10P C at t=8502
Switch 9P B at t=8642
Switch 10R c at t=8961
Switch 9R b at t=9054
Switch 9P B at t=9954
Switch 11P D at t=10073
Switch 8P A at t=10164
Switch 8R a at t=10215
Switch 9R b at t=10315
Switch 11R d at t=10354

This is great information...I'm just confused as using it exactly as shown displays nothing when I press any of my buttons...

For the moment, adjust the pin numbers in the enum { sw0=8, sw1=9, sw2=10, sw3=11} line, eg change to sw0=3, sw1=4, sw2=5, sw3=6 to test the buttons on pins 3, 4, 5, 6.  I don't have a teensy.  For the longer run, if your buttons are on  "pins 1-8" make 8 entries in buttons with the swiNum values from 1 to 8, and set nSwitch to 8.  Note, since pin 1 is TX1, having a button on it may conflict with Serial.

Aye I've set to try different pins even to get 4 work and nothing shows.  I attached some other switches I know work in case and still nothing.  I'm generally keeping the buttons' common wire on gnd but I've tried changing that around too with no avail

If it helps to see, here's a pic of my current simple wiring to test buttons on 3,4,5,6: http://tinyurl.com/px6rezv and here's the button set I'll eventually use (all have been tested working individually with my first bit of code) http://tinyurl.com/oajbpck

I should have mentioned I'm testing in notepad, not console. An update, I swapped all the serial commands for a simple Keyboard.write(action); which now prints Aa, Bb, etc... I think I follow this now, standby~

You are a marvel! I've posted the final code in an edit above. Please let me know if that is suitable or if I've done something problematic, but it works wonderfully!  Thanks so much for all your help!

Your code adaptation looks ok.  If you don't need to track button releases, for code cleanup you can remove swiActR from the struct, and the else {  doAction(b->swiNum, 'R', b->swiActR); } statement and the first two params to doAction().  (Or delete the def of doAction() and in place of  doAction(b->swiNum, 'P', b->swiActP); just say Keyboard.write(b->swiActP);)

Hey there! I know the question is closed, but I thought I'd ask in case you were still around. How do I pass something like a ctrl-z command into that? (for like a button press = undo).  I tried {0, sw0, KEY_LEFT_CTRL + 'Z'}, but I think that's banking on a mathematical operand and displays nothing.  KEY_LEFT_CTRL's hex value is 0x80. Is there a way to combine that with z inside the array there?

Might as well ask additionally, I'm curious also how to make a press and hold act like a regular keyboard. (Example, you press and hold the button, it delivers one keystroke, waits a moment, then starts repeating the stroke until you let go.

See the four  "Linked" questions in the right sidebar, above.   If they don't answer those two questions, you may need to start a new question.   . . . .


text:
Arduino + TMP36 + DC Motor
I made this circuit:

The part with the DC motor is from this tutorial: https://learn.sparkfun.com/tutorials/sik-experiment-guide-for-arduino---v32/experiment-12-driving-a-motor ( I only use another resistor, with 220 OHM)
As you can see, I also have a TMP36 sensor attached. What I would like to do is this:
When the temperature is 25 degrees or more, the motor should turn on.
I have this code:
//TMP36 Pin Variables
int sensorPin = 0; //the analog pin the TMP36's Vout (sense) pin is connected to
                        //the resolution is 10 mV / degree centigrade with a
                        //500 mV offset to allow for negative temperatures

/*
 * setup() - this function runs once when you turn your Arduino on
 * We initialize the serial connection with the computer
 */
void setup()
{
  Serial.begin(9600);  //Start the serial connection with the computer
                       //to view the result open the serial monitor
}

void loop()                     // run over and over again
{
 //getting the voltage reading from the temperature sensor
 int reading = analogRead(sensorPin);

 // converting that reading to voltage, for 3.3v arduino use 3.3
 float voltage = reading * 5.0;
 voltage /= 1024.0;

 // print out the voltage
 Serial.print(voltage); Serial.println(" volts");

 // now print out the temperature
 float temperatureC = (voltage - 0.5) * 100 ;  //converting from 10 mv per degree wit 500 mV offset
                                               //to degrees ((voltage - 500mV) times 100)
 Serial.print(temperatureC); Serial.println(" degrees C");

 if(temperatureC >= 25){
  analogWrite(9, 250);
 }

 delay(1000);                                     //waiting a second
}

But I get this result:
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.75 volts
25.20 degrees C <------
0.87 volts
36.91 degrees C
0.66 volts
16.41 degrees C
0.78 volts
27.64 degrees C
0.77 volts
26.66 degrees C
0.84 volts
34.47 degrees C

The point where the sensor measures > 25 degrees, the motor turns on but the circuit gets "poluted" and the temp sensor starts to send all kinds of strange values.
How do I solve this?
Thanks in advance!

I got it to work in with the following: https://i.sstatic.net/4GFPH.png

Motors tend to use more current than the arduino can supply, try hooking up the motor to a different power supply than the arduino 5V. What most likely is happening, is that when the motor turns on, it alters the value of the voltage, which the temperature sensor is using to tell the arduino what the temperature is. You need to have the temperature sensor hooked up to the arduino to have the reference at the right voltage, so the motor should be on a different power supply. That should fix things.

Thank you rocketman412. I can't figure out how to add a battery to the circuit. I've removed the red + and black - wires from the bottom and changed the circuit to this:
http://i.imgur.com/2haaNqd.png
But it's not working.

I would think connecting the ground of the arduino to the ground of the battery should help. Other than that, I'm not entirely sure why it wouldn't work.

I've just tried it, but still not working :(

Did you get the motor to work without the temperature sensor? That may be the issue. What transistor are you using as well? 2n2222s aren't as available now, so if you switched it out for a different one, the different properties of that new transistor could cause it to act the way it is.

I did get it to work without the temperature sensor. As the 2n222's are unavailable, I've used the following: BC547B.
The Diode I'm using is 1N4001 50V 1A.

I rechecked everything, it turns out that the solution you provided worked! I didn't propperly connect the ground of the arduino wit the ground of the battery. I'll update the question with a proper drawing. Thanks rocketman412!

You're very welcome! Glad to hear it works now!


text:
Algorithm to detect motion using ultrasonic sensor
I have a PIR sensor which sometimes give false readings and I have added a ultrasonic sensor to compensate for that. I think my algorithm can work, however currently it is very prone to give false positives.
Algorithm theory
My idea is to have an arduino which will obtain six samples and wait 25 milliseconds between each sample and then calculate the variance. If the variance exceeds a specific threshold, which I have set to a thousnad, it will send an motion event over the serial bus.
Problem with the algorithm
Ultrasonic sensors can give faulty responds which usually isn't hard to detect. My HC-SR04 sensor can only accurately read the distance between 2 cm and 400 cm. All the faulty readings are usually way over 400 cm or lower than 2 cm, therefore if is not within these boundaries a new try will be made to get a value within the boundaries, if it fails for three times it will assume the distance is exactly 400 cm.
It is redundant to wait for more than 23280 µs because 400*29.1*2 is the corresponding microseconds it would take for the distance to be 400 cm. pulseIn has a timeout value which can be used for this.
In theory this sounds great to me but very often this algorithm will erroneously send motion events. My belief for this is that when the ultrasonic sensor transmitts a wave and wait for it come back, pulseIn will timeout and retry and yet again ask the sensor to send a wave. This happens before the first wave has come back thus the distance will be incorrect and vary from time to time making the variance higher than my threshold.
If the distance is much lower than 4 metres my algorithm works very well.
What I tried
I figured I might be able to block for some time until the echo pin on the ultrasonic sensor turns low or a time of 100ms has passed. The code hanged and I couldn't communicate with my arduino any more. I can't see the problem with my code to obtain the distance pursuant to the ultrasonic sensor.
for(tries=3;tries;--tries) {
  digitalWrite(TRIG_PIN), LOW); // Set trigger pin low.
  delayMicroseconds(2); // Let signal settle.
  digitalWrite(TRIG_PIN, HIGH); // Set trigger pin high.
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW); // Ping has now been sent.
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 23280); // Duration is in microseconds
  unsigned long time = micros();
  while(!(PINB & 0b00000010)) { // ECHO_PIN is PB1 or digital pin 9
    if((micros() - time) >= 100000) {
      continue;
    }
  }
  if(duration >= 116L && duration <= 23280L) { // Is duration within boundaries?
    return ((float)(duration)/2.0) / 29.1;
  }
}
return 400.0f;

This just blocks my program indefinently and I had to upload a new program removing that code for my arduino to respond again.
So my question boils down to: how can I resolve this issue where my algorithm very frequently sends motion events erroneously? Is there a better way to detect motion with an ultrasonic sensor?
(EDIT: I was really tired when I wrote the code above and Majenko corrected me, I changed the code for this
for(tries=3;tries;--tries) {
  digitalWrite(TRIG_PIN), LOW); // Set trigger pin low.
  delayMicroseconds(2); // Let signal settle.
  digitalWrite(TRIG_PIN, HIGH); // Set trigger pin high.
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW); // Ping has now been sent.
  unsigned long duration = pulseIn(ECHO_PIN, HIGH, 23280); // Duration is in microseconds
  unsigned long time = micros();
  while(PINB & 0b00000010) { // ECHO_PIN is PB1 or digital pin 9
    if((micros() - time) >= 100000) {
      goto retry;
    }
  }
  if(duration >= 116L && duration <= 23280L) { // Is duration within boundaries?
    return ((float)(duration)/2.0) / 29.1;
  }
  retry:
  continue;
}
return 400.0f;

The main blocking part of your code is this bit:
while(!(PINB & 0b00000010)) { // ECHO_PIN is PB1 or digital pin 9
  if((micros() - time) >= 100000) {
    continue;
  }
}

That is saying "While the echo pin is low, check the time.  If too much time has passed then carry on with the loop".
So basically that will loop until the echo pin goes high, regardless of the time.
The continue command means to jump back to the beginning of the loop that it's in, be that a while, for, or do loop.  In this case it jumps back to the beginning of the while loop it's in.
Instead you should consider using break, which means "Terminate this loop and carry on with what comes next".

Ultrasound sensing with pulseIn(), while simple to perform is rarely particularly accurate.  Any interrupts that occur during the sensing will affect the outcome, and it's only as accurate as the micros() function allows it to be.
If you need a more precise and reliable measurement you should consider using one of the Input Capture modules in the ATMega.  I don't know if there is a library to do it off hand, but programming it through the registers shouldn't be that difficult - just read the datasheet to find out how it all works.
Briefly the operation of IC is:

Send trigger pulse
Start IC timer counting
Pulse arrives
IC stops counting automatically and interrupt is triggered
Read counter value and convert to microseconds.
Set flag to indicate a result is available

The timing source is the main system clock and counting happens in the background completely parallel to the operation of the CPU, so nothing can interrupt it or delay it. Even if the execution of the IC interrupt routine is delayed by another interrupt running the counter value will have already stopped incrementing, so it will have been "captured" and give the correct result every time.

Thanks it didn't give me any better results though, see my updated question please.

@Linus I have added an edit to my answer about doing more reliable and accurate measurements.

Thanks, I'll definently look in to Input Capture modules. Is it gauranteed to never give faulty values? Should I still check the boundaries and clamp to 116 and 23280 ?

@Linus It can't hurt to check the boundaries.  It should always give good results, but of course it's somewhat dependant on the reliability of the ultrasound module. It will certainly give more reliable results than pulseIn().


text:
Is it possible to run emulator from IC? and how?
I have an Emulator and Roms I would like to create a portable device to allow me to connect via RCA to a TV and play. Only I have no prior knowledge of how Integrated Circuits function or what they are capable of. If a IC would work, how does one go about programming one to load up the emulator? What other components aside from RCA and USB would I need? Any direction with this would be great and sorry in case I am not asking the proper questions.
I figured arduino is similar to what I am building in regards to circuitry/ electronics. Thanks in advance.
This is the only bit of information I have found online in 4 days thats not store bought.   CLICK HERE

Not a chance, I am afraid.  The Arduino cannot do what you think it does.
Yes, you could program the Arduino to act like some of the simple old video games, but there is no way it can run a pre-existing emulator program like your computer can.
You need something more like a Raspberry Pi - in fact there is an interesting project that might be just what you want: RetroPie


text:
Occasional incorrect time returned by NTP
I have an Uno with CC3000 wifi shield and am trying to use the sntp.h library to get NTP time. I have been experimenting with a modified version of the ntpTest code from the library which fetches the time every minute. In the serial monitor I get the correct time MOST of the time. However at random intervals, the time will display 3 hours and 14 minutes ahead of the current MST time.
the SNTP client constructor looks like this:
sntp mysntp = sntp(NULL,"time.nist.gov", (short)(-7 * 60),(short)(-7 * 60), true);

The time will display correctly for two to ten minutes and then display one of the erroneous times once then revert to correct time.
EDIT
Here is the pared down code from the Adafruit CC3000 WIFI shield ntpTest example. Note that the only reason I was getting the time so often was just teaching myself how it worked and I noticed this odd behavior. My intent was not to make an application that would, in the end, access NTP servers more than once per day.
    /***************************************************
  This is an example for the Adafruit CC3000 Wifi Breakout & Shield

  Designed specifically to work with the Adafruit WiFi products:
  ----> https://www.adafruit.com/products/1469

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Kevin Townsend & Limor Fried & Rick Lesniak for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ****************************************************/

/*

This example does a test of the SNTP (Simple Network Time Protocol) client:
* Initialization
* SSID Scan
* AP connection
* DHCP printout
* SNTP time synchronization
* Extract and print current time and date information

*/

#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
//#include "utility/NetTime.h"
#include <string.h>
#include "utility/debug.h"
#include "sntp.h"

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                                         SPI_CLOCK_DIVIDER); // you can change this clock speed but DI

#define WLAN_SSID       "CompsciWifi"   // cannot be longer than 32 characters!
#define WLAN_PASS       "005276DA"
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

//Arguments to SNTP client constructor:
//  1 - Primary Network Time Server URL (can be NULL)
//  2 - Secondary Network Time Server URL (also can be NULL)
//  3 - Local UTC offset in minutes (US Eastern Time is UTC - 5:00
//  4 - Local UTC offset in minutes for Daylight Savings Time (US Eastern DST is UTC - 4:00
//  5 - Enable Daylight Savings Time adjustment (not implemented yet)
//
//sntp mysntp = sntp(NULL, "time.nist.gov", (short)(-7 * 60), (short)(-7 * 60), true);
sntp mysntp = sntp(NULL, "time-a.timefreq.bldrdoc.gov", (short)(-7 * 60), (short)(-7 * 60), true);

// Type SNTP_Timestamp is 64-bit NTP time. High-order 32-bits is seconds since 1/1/1900
//   Low order 32-bits is fractional seconds
SNTP_Timestamp_t now;

// Type NetTime_t contains NTP time broken out to human-oriented values:
//  uint16_t millis; ///< Milliseconds after the second (0..999)
//  uint8_t  sec;    ///< Seconds after the minute (0..59)
//  uint8_t  min;    ///< Minutes after the hour (0..59)
//  uint8_t  hour;   ///< Hours since midnight (0..23)
//  uint8_t  mday;   ///< Day of the month (1..31)
//  uint8_t  mon;    ///< Months since January (0..11)
//  uint16_t year;   ///< Year.
//  uint8_t  wday;   ///< Days since Sunday (0..6)
//  uint8_t  yday;   ///< Days since January 1 (0..365)
//  bool     isdst;  ///< Daylight savings time flag, currently not supported
NetTime_t timeExtract;

#define pF(string_pointer) (reinterpret_cast<const __FlashStringHelper *>(pgm_read_word(string_pointer)))

const prog_char   janStr[] PROGMEM = "January";
const prog_char   febStr[] PROGMEM = "February";
const prog_char   marStr[] PROGMEM = "March";
const prog_char   aprStr[] PROGMEM = "April";
const prog_char   mayStr[] PROGMEM = "May";
const prog_char   junStr[] PROGMEM = "June";
const prog_char   julStr[] PROGMEM = "July";
const prog_char   augStr[] PROGMEM = "August";
const prog_char   sepStr[] PROGMEM = "September";
const prog_char   octStr[] PROGMEM = "October";
const prog_char   novStr[] PROGMEM = "November";
const prog_char   decStr[] PROGMEM = "December";

PROGMEM const char* const monthStrs[] = { janStr, febStr, marStr, aprStr, mayStr, junStr,
                                          julStr, augStr, sepStr, octStr, novStr, decStr};

const prog_char   sunStr[] PROGMEM = "Sunday";
const prog_char   monStr[] PROGMEM = "Monday";
const prog_char   tueStr[] PROGMEM = "Tuesday";
const prog_char   wedStr[] PROGMEM = "Wednesday";
const prog_char   thuStr[] PROGMEM = "Thursday";
const prog_char   friStr[] PROGMEM = "Friday";
const prog_char   satStr[] PROGMEM = "Saturday";

PROGMEM const char* const dayStrs[] = { sunStr, monStr, tueStr,  wedStr,
                                        thuStr, friStr, satStr};

/**************************************************************************/
/*!
    @brief  Sets up the HW and the CC3000 module (called automatically
            on startup)
*/
/**************************************************************************/
void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  //Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

  /* Initialise the module */
  Serial.println(F("\nInitialising the CC3000 ..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
    while(1);
  }

  /* Optional: Update the Mac Address to a known value */
/*
  uint8_t macAddress[6] = { 0x08, 0x00, 0x28, 0x01, 0x79, 0xB7 };
   if (!cc3000.setMacAddress(macAddress))
   {
     Serial.println(F("Failed trying to update the MAC address"));
     while(1);
   }
*/

  /* Delete any old connection data on the module */
  Serial.println(F("\nDeleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  /* Attempt to connect to an access point */
  char *ssid = WLAN_SSID;             /* Max 32 chars */
  Serial.print(F("\nAttempting to connect to ")); Serial.println(ssid);

  /* NOTE: Secure connections are not available in 'Tiny' mode! */
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  /*Serial.println(F("UpdateNTPTime"));
  if (mysntp.UpdateNTPTime())
  {
    Serial.println(F("Current local time is:"));
    mysntp.ExtractNTPTime(mysntp.NTPGetTime(&now, true), &timeExtract);*/

    /*Serial.print(timeExtract.hour); Serial.print(F(":")); Serial.print(timeExtract.min); Serial.print(F(":"));Serial.print(timeExtract.sec); Serial.print(F("."));Serial.println(timeExtract.millis);
    Serial.print(pF(&dayStrs[timeExtract.wday])); Serial.print(F(", ")); Serial.print(pF(&monthStrs[timeExtract.mon])); Serial.print(F(" ")); Serial.print(timeExtract.mday); Serial.print(F(", "));Serial.println(timeExtract.year);
    Serial.println(timeExtract.yday + 1);
  }

  /* You need to make sure to clean up after yourself or the CC3000 can freak out */
  /* the next time you try to connect ... */
  /*Serial.println(F("\n\nClosing the connection"));
  cc3000.disconnect(); */

    mysntp.UpdateNTPTime();
    mysntp.ExtractNTPTime(mysntp.NTPGetTime(&now, true), &timeExtract);
    Serial.print(pF(&dayStrs[timeExtract.wday])); Serial.print(F(", ")); Serial.print(pF(&monthStrs[timeExtract.mon])); Serial.print(F(" ")); Serial.print(timeExtract.mday); Serial.print(F(", "));Serial.println(timeExtract.year);
}

void loop(void)
{
    mysntp.UpdateNTPTime();
    mysntp.ExtractNTPTime(mysntp.NTPGetTime(&now, true), &timeExtract);
    Serial.print(timeExtract.hour); Serial.print(F(":")); Serial.print(timeExtract.min);

    delay(60000);
    Serial.println();
}

Try to figure out if it is either corrupted data, or a math overflow.  3 hours and 14 minutes isn't quite as interesting a number as four hours and 15 minutes would be, but could still be intriguing.  Are you certain the intervals are truly random?  It would be great if you could somehow monitor the data directly from the wifi shield (or else at at the access point) and even better if you could set up a fake server to repeatedly cycle through the same times and see if it is repeatable.  But the real solution may be careful inspection of the whole chain of operations.

Here's what I suggest you do: Make a copy of your code, and remove, a little at a time, any code not directly related to your sntp issue. There are two possible outcomes: either the problem will vanish, in which case, find the minimum change to make the problem vanish. If the problem does not vanish, post the remaining code here - I would expect you would have maybe 10-20 lines left (if you get that far).

PS - you probably shouldn't be polling time servers too often - unless your device powers down, you should be keeping a local clock. NTP is for stopping your clock from drifting, not to save you from having to keep a local clock. I would not expect an Arduino to need to poll NTP more than once a day. By keeping a local clock, you can also check if the clock is off - it shouldn't drift 3 hours, between polls.

@AMADANON-inc I I think the code is pretty minimal already but I will try removing what I can and see what happens. I agree that the end product has to be using NTP as intended. This was just a weird phenomenon I  observed while exploring the use of a wifi shield. It made me concerned that I must be missing something that would be important when eventually using NTP to correct time drift.

@ChrisStratton that sounds a little above my skill set. It might be good to try but I am going to try and eliminate other possibilities first. Thanks for the insight though.

@techkilljoy, once you are down to minimal code, post it here, so we can try to reproduce the problem. Usually in a case like this, there is a subtle problem with code; when you are working on the code, it's often hard to see exactly what's wrong.

@AMADANON-inc, sorry for the holiday-induced delay but here is the pared down code listed below the EDIT line above

It may be easier to start by building the minimum NTP application and confirming that that works. Use just the NTP library and a sample sketch or an example from the NTP library. Start with something that is as simple as possible or that is known to be good.

The updated NTP test sketch assumes that the communication with the NTP server will not fail but as the NTP protocol is based on UDP the reply package can be lost. A possible correction to the updated sketch is to check the return value from UpdateNTPTime().
void loop(void)
{
    if (mysntp.UpdateNTPTime()) {
        mysntp.ExtractNTPTime(mysntp.NTPGetTime(&now, true), &timeExtract);
        Serial.print(timeExtract.hour);
        Serial.print(F(":"));
        Serial.println(timeExtract.min);
        delay(60000);
        Serial.println();
    }
}

Cheers!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Arduino Mega LCD
I am interfacing an LCD with an Arduino. Sometimes it shows nothing after uploading the program. What should I do?

From what Isee, it does not show "nothing" but it shows entirely black points which is different. If you could post the code you u;load that might help people here trying to find out what happens.

Cannot exactly see from the image, but check your soldering. I feel like some of the pins might be in contact. Also, try changing the contrast with a potentiometer and see what happens.

An LCD will show blocks like that if it isn't initialized correctly.  You may have an intermittently-bad connection on one or more of the control lines.  [But see edit 1, below, regarding contrast adjustment.]
To diagnose intermittent connections, you could run a sketch that repeatedly initializes the LCD and then displays different sets of characters for a few seconds.  This will allow you to wiggle different pins and find out which is responsible for the bad connection.
To avoid intermittent connections, you could use a shield with soldered pins, or could get multipin shells to replace the single-pin shells of the Dupont-type connectors shown in the photograph.  Having adjacent connectors fixed in a single multipin shell results in more-stable connections.

Edit 1: As noted in a comment, blocks appearing on both lines is typical of contrast adjustment problems or missing contrast voltage.  On the other hand,  blocks appearing on just the first line is typical of incorrect  initialization, which could be caused by poor connections or by software errors.

Below is a sketch that repeatedly initializes the LCD and then displays different sets of characters for a few seconds each.
Note, if you don't have  the Streaming.h contributed library installed, you can get Streaming5.zip from arduiniana.org.
Note, if not using an I2C-interfaced LCD, change the included LCD library .h from LiquidCrystal_I2C.h to whatever is appropriate, and remove I2C-address-related stuff from the sketch.  If you are using an I2C-interfaced LCD on a known fixed address, remove the lcd.setAddress(address); and lcd.getAddress(address); stuff.  Those routines are not part of the usual LCD libraries; they probably can be added by subclassing LiquidCrystal_I2C, but on my system I added code as shown after the sketch.

/* Screen-test sketch for PCF8574/PCF8574A/PCF8574T I2C LCD Backpack
Uses library from https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads GNU General Public License, version 3 (GPL-3.0) */
#include <Streaming.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

enum { LCDcols=16, LCDrows=2 };        // # of rows and cols on LCD
enum { LCDaddr2=0x27, LCDaddr3=0x3F}; // For TI PCF8754 or PCF8754A
LiquidCrystal_I2C lcd(LCDaddr2,2,1,0,4,5,6,7);

void initLCD(byte address) {
  byte cdata[8];
  Serial << "initLCD(" << _HEX(address) << ')' << endl;
  lcd.setAddress(address);       // Set LCD I2C address
  Serial << "LCD address ... " << _HEX(lcd.getAddress()) << endl;
  // activate LCD module
  lcd.begin(LCDcols, LCDrows);
  lcd.setBacklightPin(3,POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.noCursor();

  // Load custom characters
  for (int c=0; c<8; ++c) {
    unsigned int d = ((c+4)<<12 | (c|3)<<9 | (c|2)<<6 | (c|1)<<3 | c) ^ 0x5555;
    //Serial << "c=" << c << "  d=" << _HEX(d) << endl;
    for (byte k=0; k<8; ++k)
      cdata[k] = d >> k;
    lcd.createChar(c, cdata);
  }
  lcd.home ();
  lcd.print("Initialized");
  delay(1000);
}

void setup() {
  Serial.begin(115200);
  Serial << "Starting up" << endl;
  Wire.begin();                 // Setup to wirescan to check for 8754 addr
  Serial << "after Wire.begin()" << endl;
  TWBR = 152;  // 50 kHz, use if it works, or use slower rate
  TWBR = 158;  // 12.5 kHz, = slower rate
  TWSR |= bit (TWPS0);  // change prescaler
  Serial << "after TWBR / TWSR" << endl;
  Wire.beginTransmission (LCDaddr2);
  Serial << "after Wire.beginTransmission()" << endl;
  if (Wire.endTransmission() == 0) // Does 0x27 succeed?
    initLCD(LCDaddr2);          // Set up with 0x27 address
  else
    initLCD(LCDaddr3);          // Set up with 0x3F address
  Serial << "after initLCD()" << endl;
}

void show(char base, byte delt) {
  enum {MD=2000};
  byte k, ro;
  for (ro=0; ro<LCDrows; ++ro) {
    lcd.setCursor(0, ro);
    for (k=0; k<LCDcols; ++k) {
      lcd.print(base);
      base += delt;
    }
  }
  if (base==' ') {
    lcd.setCursor(1, 1);
    lcd << "LCD @" << _HEX(lcd.getAddress()) << " =" << lcd.getAddress();
  }
  delay(MD);
}

long p=0;
void loop() {
  byte c;
  Serial << "Pass " << p++ << " on " << _HEX(lcd.getAddress()) << " at t=" << millis() << endl;
  lcd.home ();          // Set cursor to 0,0
  show('#', 0);         // Screen of # characters
  show(' ', 0);         // Screen of ' ' characters
  show('@', 0);         // Screen of @ characters
  show( 0,  1);         // lo specials + ' '...'/'
  for (c=' '; c < '~'; c+=16)
    show(c, 1);

  lcd.setBacklight(HIGH);
  while (Serial.available()) {
    c = Serial.read();
    if (c == '2') initLCD(LCDaddr2);
    if (c == '3') initLCD(LCDaddr3);
  }
}

To add lcd.setAddress(address); and lcd.getAddress(address); routines:
// add after void setBacklight(...); in LiquidCrystal_I2C.h
void setAddress(uint8_t addr);
uint8_t getAddress();

and
// add after void setBacklight(...); in LiquidCrystal_I2C.cpp
void LiquidCrystal_I2C::setAddress(uint8_t addr) {
  LiquidCrystal_I2C::_Addr = addr;
}
uint8_t LiquidCrystal_I2C::getAddress() {
  return LiquidCrystal_I2C::_Addr;
}

Blocks on the first line means it's incorrectly initialized. But blocks on the both lines means more likely bad contrast voltage.

@KIIV, that sounds correct


text:
Do I use an LED or a pullup resistor for stopping "floating" or "ghosting" for a matrix keypad?
I know this sounds simple, but I have an Arduino Mega 2560 and I am making a matrix keypad for a claw machine. It's a 3*4 matrix keypad. Let's just say, I am making this keypad for the claw machine to reduce the number of I/O pins. I have tried to use a mux, but that has failed me because it has a single input/output pin and can only read ONE button at a time. So, I have come up with the solution to use a matrix keypad because: A. It is the most common method and B. It is smaller on a PCB design rather than that CD4067BE chip. The reason why I was trying to use that chip in the first place was because it included all my thirteen buttons. Basically, what I am wanting to know is if I should use a resistor or an LED to stop either "floating" or "ghosting." I still don't really know the difference between the two terms, but if somebody could clarify that, that would be great. And also when I should use an LED or a resistor. Or do they serve the same purpose? Tutorials: LED "ghosting" Pullup Resistor "floating" (I am not sure how to make a schematic of the "floating" pin).  (Credit to EasyEDA for the schematic). Thanks,
Austin

An LED is a diode, but a diode isn't an LED. Note also that matrix keyboards also scan (each row, for example, in the example you link to). I'm still puzzled what human you're targeting that can push buttons faster than an Arduino can scan them.

But, isn't this approach faster? Won't I get a smoother stepper motor ride from them? So, what am I supposed to do about reducing the number of I/O pins from the claw machine?

Thanks for the fast reply, too.

... You're talking about a difference of microseconds. There are a million microseconds in a second. Humans operate in tenths of seconds. A tenth of a second is one hundred thousand microseconds. No human can even perceive, let alone care about, the difference. There are hundreds of examples on making keyboards--just follow one.

Should I go back to the way I had it before? Just the buttons and the INPUT_PULLUP?

failed me because it has a single input/output pin and can only read ONE button at a time ... the matrix keypad is also read one button at a time ... it is like that for almost every device that you use in everyday life, like computer keyboards, TV remote controls, microwave ovens, etc. etc. ... one button is read at a time

Oh, sorry. I wasn't sure.

I really think I should go back to the way I had the PCB before, besides I have a Mega. What could go wrong, right?

I thought I could reduce the most number of I/O pins and complexity of the claw machine buttons. Apparently, I was wrong, it just made things more complex.

Although, I think I could use the matrix design because my code shows that it only reads one button at a time anyway. (For the claw machine). Also, I was using the CD4067BE.

try going with the matrix arrangement ... if it does not work as expected, then go to direct connection, one switch, one pin .... https://playground.arduino.cc/Code/Keypad/

Let us continue this discussion in chat.

First some clarification:

Floating is where an input isn't connected to a defined logic state. It's neither in one state or the other and is free to "float" between them at will. Basically a floating input is an antenna.
Ghosting is where you press two buttons in a matrix together and it causes unwanted short or crossed circuits in the matrix making it appear that other keys are pressed when they aren't.

The Keypad.h library deals with any pullups that may be needed.  To prevent ghosting you need to use diodes (not LEDs) to separate the buttons from each other.
Nick Gammon has a fantastic tutorial where he describes the problems and solutions to ghosting.

So, why can't I use LEDs, does it have to "absorb" more, I guess? Does the Keypad library have internal pullup resistors?

How come the row pins don't have a resistor?

@Austin Libraries have code; hardware has pullup resistors. Because the rows are outputs--only the columns are read. A press is determined by outputting a value on a row and reading all the columns. Read all the way to the bottom :)

That is a good article!

So, how come I can't use LEDs?

LEDs have a massive forward voltage compared to proper diodes. They're also bigger, more power hungry and more expensive.


text:
esp8266 r1 mini stops serial print during execution
The setup includes an WEMOS/ESP8266 R1 mini compatible board, a DHT11, a photo resistor and a magnetic reed.
The libs used are:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "DHT.h"

Compilation/loading is successful and the code starts normally, publishes and subscribes correctly.
Executable segment sizes:
ICACHE : 32768           - flash instruction cache
IROM   : 259412          - code in flash         (default or ICACHE_FLASH_ATTR)
IRAM   : 27337   / 32768 - code in IRAM          (IRAM_ATTR, ISRs...)
DATA   : 1524  )         - initialized variables (global, static) in RAM/HEAP
RODATA : 2300  ) / 81920 - constants             (global, static) in RAM/HEAP
BSS    : 26416 )         - zeroed variables      (global, static) in RAM/HEAP
Sketch uses 290573 bytes (27%) of program storage space. Maximum is 1044464 bytes.
Global variables use 30240 bytes (36%) of dynamic memory, leaving 51680 bytes for local variables. Maximum is 81920 bytes.
esptool.py v3.0
Serial port /dev/ttyUSB0
Connecting....
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: 5c:cf:7f:ad:11:6b
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 460800
Changed.
Configuring flash size...
Auto-detected Flash size: 4MB
Compressed 294720 bytes to 215795...
..

However the serial printing commands (ie Serial.println) in the code stop working for no apparent reason. The code/module is working, it is not dead.
I suspected json serialization but various changes that I tried didn't solve it. Then I thought that the dht lib is responsible, because serial printing stops in the dht function routine. But the adafruit stand alone examples work alright.
Here is the initial printing until it stops:
WiFi connected.
IP address:
192.168.xx.xx
ESP Mac Address: xx:xx:xx:xx:xx:xx
Subnet Mask: 255.255.255.0
Gateway IP: 192.168.xx.xx
DNS: 192.168.xx.xx
RRSI: -84
mqtt status in setup: 0
Humidity: 34.00% || Temperature: 24.00°C
before ser

This is the code function that requests dht data:

StaticJsonDocument<128> doc_dht;

void request_temp_hum() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  char  h_ch[10];
  char  t_ch[10];
  char buffer[256];
  doc_dht.clear();
  memset (h_ch, 0, sizeof(h_ch));
  memset (t_ch, 0, sizeof(t_ch));
  if (isnan(h) || isnan(t)) {
        Serial.println("Failed to read from the DHT sensor, check wiring.");
        return;
  }
  Serial.print("Humidity: ");
  Serial.print(h);
  //Print out the Temperature
  Serial.print("% || Temperature: ");
  Serial.print(t);
  Serial.println("°C ");

  dtostrf(t, 5, 2, t_ch);

  dtostrf(h, 5, 2, h_ch);

  doc_dht["sensor"] = "dht11";
  doc_dht["temp"] = t_ch;
  doc_dht["humi"] = h_ch;

  Serial.println("before serialization");
  serializeJson(doc_dht, buffer);
  Serial.println("after serialization..");
  client.publish("Home/info/dht", buffer);
  Serial.println("after publish");
  }

This is the mqtt publishes from the device:
02.05.2023 13:11:31 Home/info/dht {"sensor":"dht11","temp":"24.00","humi":"34.00"}
...
02.05.2023 13:26:38 Home/info/dht {"sensor":"dht11","temp":"25.00","humi":"34.00"}

Apart from the fact that I can't debug my code any further, it is evident that something is wrong and it might have further implications that I can't foresee. So why does serial printing stop working?

You can call Serial.flush() after each println() to make sure the log is sent before moving to the next line.

Thank you for the suggestion, I used Serial.flush() is various points in the program and I was able  to move on and further debug. The issue must be the fact that I used GPIO1 (TX) for controlling a relay module.


text:
Why does my Arduino show weird characters with my code?
When I had the code run just the LCD it worked perfectly fine, but when I added an HC-SR04 without changing the text it showed weird characters. All I had the code do with the HC-SR04 was print it in the serial monitor.
// include the library code:
#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 5, e = 4, d4 = 3, d5 = 2, d6 = 1, d7 = 0;
const int trigPin = A0;
const int echoPin = A1;
LiquidCrystal lcd(rs, e, d4, d5, d6, d7);

void setup() {
  // set up the LCD's number of columns and rows:
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.print("zach is cool");
  pinMode(trigPin,OUTPUT);
  pinMode(echoPin,INPUT);
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  long duration, inches, cm;
  lcd.setCursor(0, 1);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);

  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  delay(100);
}

long microsecondsToInches(long microseconds) {
  // According to Parallax's datasheet for the PING))), there are 73.746
  // microseconds per inch (i.e. sound travels at 1130 feet per second).
  // This gives the distance travelled by the ping, outbound and return,
  // so we divide by 2 to get the distance of the obstacle.
  // See: https://www.parallax.com/package/ping-ultrasonic-distance-sensor-downloads/
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the object we
  // take half of the distance traveled.
  return microseconds / 29 / 2;
}

It looks like you have the LCD connected to pins 0 and 1.  Those are the Serial Rx and Tx pins.  When you also use Serial in your sketch it creates a conflict.  Move those two lines from the LCD to different pins and update the sketch.

it was the Tx and Rx pins Thank You!

Thanks.  Please mark as solution if it fixed the problem.

With the following code, I ran an HCSR04 and a 16x2 LCD with Arduino UNO. It ran successfully.
#define trigPin 8
#define echoPin 9
#define pinIR 7
// Define variables:
float duration=0.00;
float distance=0.00;
int visitor,sum,threshold,temp;

// declaring variables to hold the new and old IR states
boolean oldIRState = LOW;
boolean newIRState = LOW;

#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin
// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {
  // Define inputs and outputs:
  pinMode(pinIR, INPUT);
  pinMode(trigPin, OUTPUT);

  pinMode(echoPin, INPUT);
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("Visitor=");
  lcd.print(visitor);

  //Begin Serial communication at a baudrate of 9600:
  Serial.begin(9600);
}

void loop() {
  // Clear the trigPin by setting it LOW:
  newIRState = digitalRead(pinIR);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  // Trigger the sensor by setting the trigPin high for 10 microseconds:
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds:
  duration = pulseIn(echoPin, HIGH);
  // Calculate the distance:
  distance = duration /58.82 ;

  // Print the distance on the Serial Monitor (Ctrl+Shift+M):
  Serial.print("Distance = ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(1000);
  if(distance<=10 && abs(temp)>=70)
  {
    visitor++;
    lcd.clear();
    lcd.print("Visitor=");
    lcd.print(visitor);

  for(int i=0;i<500;i++)
 {

 sum +=distance;
 delay(5);

 }
 threshold = sum/500;
  }

temp=threshold-distance;

 if ( newIRState != oldIRState )
  {

    if ( newIRState == LOW && visitor>0 )
    {

        visitor--;
         lcd.clear();
    lcd.print("Visitor=");
    lcd.print(visitor);

      }

    }
    oldIRState = newIRState;

}

You can follow this code and circuit arrangement. I also suggest you check the HCSR04 and LCD separately with The Arduino. You can also check this Arduino UNO pinout configuration guideline This will be helpful for any Arduino UNO project you work on.

Thank you, I will try this. I tried simplifing the code to just the LCD and it didnt work either so that is probably the issue.

can you explain to me the IRstate and Is and extra stuff you added? I'm new to this and I don't understand the new code.

Actually, there was two sensors in my setup. One was the HCSR04, another was the IR obstacle sensor. I was making a visitor counter. The HCSR04 was counting people entering the room. IR sensor was counting people exiting the room. When you are working with the HCSR04, you do not need the variables associated with the IR sensor. You can get a simplified example here: https://www.theengineeringprojects.com/2017/08/ultrasonic-sensor-arduino-interfacing.html  This one only features an Arduino UNO and an HCSR04.


text:
Multiple symbol definition related to USART_RX_vect from Serial
When trying to compile the sketch below, I get this error when using either the IDE or the CLI:
HardwareSerial0.cpp.o (symbol from plugin):
In function `Serial':
(.text+0x0): multiple definition of `__vector_18'

This seems to have something to do with multiple definitions of  USART_RX_vect.
Since I'm not using any extra libraries, that doesn't seem to be the source of the problem (though library conflicts are the source of many similar problems I've seen on here and elsewhere).  Any suggestions on how to fix this?
Sketch:
// Listen to the Serial Port for Instructions and Print Register Values

volatile boolean start = false;  // flag to start register inspection; global

void setup() {
  Serial.begin(9600);
  if (Serial) {
    Serial.println("Arduino listening...");
    Serial.println("Enter g or s at any time");  // g = go, s = stop
  }
}

void loop() {
  while (start) {
    // print the values of some ADC registers
    Serial.print("ADMUX  register: ");
    print_bin(ADMUX);
    Serial.print("ADCSRA register: ");
    print_bin(ADCSRA);
    Serial.println(" ");
    delay(1000);
  }
}

ISR(USART_RX_vect) {
  unsigned char data;
  data = UDR0;
  if (data == 'g') {
    start = true;
  }
  if (data == 's') {
    start = false;
  }
}

void print_bin(byte aByte) {
  for (int8_t aBit = 7; aBit >= 0; aBit--) {
    if (aBit == 3) {
      Serial.print(" ");
    }
    Serial.print(bitRead(aByte, aBit) ? '1' : '0');
  }
  Serial.println(" ");
}

Using the Arduino IDE as follows:
Version: 2.3.0
Date: 2024-02-07T13:40:21.377Z
CLI Version: 0.35.2

Well the Serial is probably using the same ISR. (may differ for different boards, however Arduino Core usually occupy all related ISRs for all serial ports)

USART_RX_vect is defined by the Arduino core library. It is part of
the implementation of the Serial object. Your sketch has a second
definition of the same ISR, thus the conflict.
Basically you have two choices: either you write your own code to handle
the serial port at the I/O register level (like in your ISR above), or
you rely on the Serial implementation of the Arduino core
(Serial.available() and Serial.read() to read data). You cannot mix
the approaches like you are trying to do here.

Thanks, self-inflicted wound.  In another sketch I used ISR(ADC_vect) without such a conflict but I guess that one is not implemented in the core library.  Live and learn.

@BryanHanson: Indeed. The core busy-waits for the ADC (in analogRead()) instead of using the interrupt.