text:
Wearable GPS LED help
I'm very new to Arduino and C++ and have been playing with the Flora Wearable GPS. However, nowhere I've looked has given me any help in setting and changing the color of the LEDs. The tutorial on their site is barebones and doesn't explain how to modify code and make the colors change. I've tried mixing what I know, but none of it results in what I want: one color to show when I'm in range of a a point, and another to show when I'm not.
// Flora GPS + LED Pixel Code
//
// This code shows how to listen to the GPS module in an interrupt
// which allows the program to have more 'freedom' - just parse
// when a new NMEA sentence is available! Then access data when
// desired.
//
// Tested and works great with the Adafruit Flora GPS module
//    ------> http://adafruit.com/products/1059
// Pick one up today at the Adafruit electronics shop
// and help support open source hardware & software! -ada

#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
#include "Adafruit_NeoPixel.h"
Adafruit_GPS GPS(&Serial1);

// Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
// Set to 'true' if you want to debug and listen to the raw GPS sentences
#define GPSECHO false

#define PIN 6

// this keeps track of whether we're using the interrupt
// off by default!
boolean usingInterrupt = false;

//--------------------------------------------------|
//                    WAYPOINTS                     |
//--------------------------------------------------|
//Please enter the latitude and longitude of your   |
//desired destination:                              |
  #define GEO_LAT                44.995012
  #define GEO_LON               -93.228967
//--------------------------------------------------|

//--------------------------------------------------|
//                    DISTANCE                      |
//--------------------------------------------------|
//Please enter the distance (in meters) from your   |
//destination that you want your LEDs to light up:  |
  #define DESTINATION_DISTANCE   20
//--------------------------------------------------|

// Navigation location
float targetLat = GEO_LAT;
float targetLon = GEO_LON;

// Trip distance
float tripDistance;

boolean isStarted = false;

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(8, PIN, NEO_GRB + NEO_KHZ800);

uint8_t LED_Breathe_Table[]  = {   80,  87,  95, 103, 112, 121, 131, 141, 151, 161, 172, 182, 192, 202, 211, 220,
              228, 236, 242, 247, 251, 254, 255, 255, 254, 251, 247, 242, 236, 228, 220, 211,
              202, 192, 182, 172, 161, 151, 141, 131, 121, 112, 103,  95,  87,  80,  73,  66,
               60,  55,  50,  45,  41,  38,  34,  31,  28,  26,  24,  22,  20,  20,  20,  20,
               20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,
               20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  22,  24,  26,  28,
               31,  34,  38,  41,  45,  50,  55,  60,  66,  73 };

#define BREATHE_TABLE_SIZE (sizeof(LED_Breathe_Table))
#define BREATHE_CYCLE    5000      /*breathe cycle in milliseconds*/
#define BREATHE_UPDATE    (BREATHE_CYCLE / BREATHE_TABLE_SIZE)
uint32_t lastBreatheUpdate = 0;
uint8_t breatheIndex = 0;

void setup()
{
  // connect at 115200 so we can read the GPS fast enough and echo without dropping chars
  // also spit it out
  Serial.begin(115200);

  // 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800
  GPS.begin(9600);

  // uncomment this line to turn on RMC (recommended minimum) and GGA (fix data) including altitude
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  // uncomment this line to turn on only the "minimum recommended" data
  //GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY);
  // For parsing data, we don't suggest using anything but either RMC only or RMC+GGA since
  // the parser doesn't care about other sentences at this time

  // Set the update rate
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);   // 1 Hz update rate
  // For the parsing code to work nicely and have time to sort thru the data, and
  // print it out we don't suggest using anything higher than 1 Hz

  delay(1000);
  // Ask for firmware version
  Serial1.println(PMTK_Q_RELEASE);

    // Start up the LED strip
  strip.begin();

  // Update the strip, to start they are all 'off'
  strip.show();
}

uint32_t timer = millis();

void loop()                     // run over and over again
{
  // read data from the GPS in the 'main loop'
  char c = GPS.read();
  // if you want to debug, this is a good time to do it!
  if (GPSECHO)
      if (c) Serial.print(c);

  // if a sentence is received, we can check the checksum, parse it...
  if (GPS.newNMEAreceived()) {
    // a tricky thing here is if we print the NMEA sentence, or data
    // we end up not listening and catching other sentences!
    // so be very wary if using OUTPUT_ALLDATA and trytng to print out data
    //Serial.println(GPS.lastNMEA());   // this also sets the newNMEAreceived() flag to false

    if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag to false
      return;  // we can fail to parse a sentence in which case we should just wait for another
  }

    if (GPS.fix) {
      //Serial.print("Location: ");
      //Serial.print(GPS.latitude, 2); Serial.print(GPS.lat);
      //Serial.print(", ");
      //Serial.print(GPS.longitude, 2); Serial.println(GPS.lon);

      float fLat = decimalDegrees(GPS.latitude, GPS.lat);
      float fLon = decimalDegrees(GPS.longitude, GPS.lon);

      if (!isStarted) {
        isStarted = true;
        tripDistance = (double)calc_dist(fLat, fLon, targetLat, targetLon);
      }

      //Uncomment below if you want your Flora to navigate to a certain destination.  Then modify the headingDirection function.
      /*if ((calc_bearing(fLat, fLon, targetLat, targetLon) - GPS.angle) > 0) {
        headingDirection(calc_bearing(fLat, fLon, targetLat, targetLon)-GPS.angle);
       }
      else {
        headingDirection(calc_bearing(fLat, fLon, targetLat, targetLon)-GPS.angle+360);
      }*/

      headingDistance((double)calc_dist(fLat, fLon, targetLat, targetLon));
      //Serial.print("Distance Remaining:"); Serial.println((double)calc_dist(fLat, fLon, targetLat, targetLon));

    }
  //}

}

int calc_bearing(float flat1, float flon1, float flat2, float flon2)
{
  float calc;
  float bear_calc;

  float x = 69.1 * (flat2 - flat1);
  float y = 69.1 * (flon2 - flon1) * cos(flat1/57.3);

  calc=atan2(y,x);

  bear_calc= degrees(calc);

  if(bear_calc<=1){
    bear_calc=360+bear_calc;
  }
  return bear_calc;
}

void headingDirection(float heading)
{
  //Use this part of the code to determine which way you need to go.
  //Remember: this is not the direction you are heading, it is the direction to the destination (north = forward).
  if ((heading > 348.75)||(heading < 11.25)) {
    Serial.println("  N");
    //Serial.println("Forward");
  }

  if ((heading >= 11.25)&&(heading < 33.75)) {
    Serial.println("NNE");
    //Serial.println("Go Right");
  }

  if ((heading >= 33.75)&&(heading < 56.25)) {
    Serial.println(" NE");
    //Serial.println("Go Right");
  }

  if ((heading >= 56.25)&&(heading < 78.75)) {
    Serial.println("ENE");
    //Serial.println("Go Right");
  }

  if ((heading >= 78.75)&&(heading < 101.25)) {
    Serial.println("  E");
    //Serial.println("Go Right");
  }

  if ((heading >= 101.25)&&(heading < 123.75)) {
    Serial.println("ESE");
    //Serial.println("Go Right");
  }

  if ((heading >= 123.75)&&(heading < 146.25)) {
    Serial.println(" SE");
    //Serial.println("Go Right");
  }

  if ((heading >= 146.25)&&(heading < 168.75)) {
    Serial.println("SSE");
    //Serial.println("Go Right");
  }

  if ((heading >= 168.75)&&(heading < 191.25)) {
    Serial.println("  S");
    //Serial.println("Turn Around");
  }

  if ((heading >= 191.25)&&(heading < 213.75)) {
    Serial.println("SSW");
    //Serial.println("Go Left");
  }

  if ((heading >= 213.75)&&(heading < 236.25)) {
    Serial.println(" SW");
    //Serial.println("Go Left");
  }

  if ((heading >= 236.25)&&(heading < 258.75)) {
    Serial.println("WSW");
    //Serial.println("Go Left");
  }

  if ((heading >= 258.75)&&(heading < 281.25)) {
    Serial.println("  W");
    //Serial.println("Go Left");
  }

  if ((heading >= 281.25)&&(heading < 303.75)) {
    Serial.println("WNW");
    //Serial.println("Go Left");
  }

  if ((heading >= 303.75)&&(heading < 326.25)) {
    Serial.println(" NW");
    //Serial.println("Go Left");
  }

  if ((heading >= 326.25)&&(heading < 348.75)) {
    Serial.println("NWN");
    //Serial.println("Go Left");
  }
}

void headingDistance(float fDist)
{
  //Use this part of the code to determine how far you are away from the destination.
  //The total trip distance (from where you started) is divided into five trip segments.
 Serial.println(fDist);
 if ((fDist >= DESTINATION_DISTANCE)) { // You are now within 5 meters of your destination.
    //Serial.println("Trip Distance: 1");
    //Serial.println("Arrived at destination!");
    int i;
    for (i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, 0, 0, 0);
    }
    strip.show();   // write all the pixels out
  }

  if ((fDist < DESTINATION_DISTANCE)) { // You are now within 5 meters of your destination.
    //Serial.println("Trip Distance: 0");
    //Serial.println("Arrived at destination!");
    breath();
  }

}

unsigned long calc_dist(float flat1, float flon1, float flat2, float flon2)
{
  float dist_calc=0;
  float dist_calc2=0;
  float diflat=0;
  float diflon=0;

  diflat=radians(flat2-flat1);
  flat1=radians(flat1);
  flat2=radians(flat2);
  diflon=radians((flon2)-(flon1));

  dist_calc = (sin(diflat/2.0)*sin(diflat/2.0));
  dist_calc2= cos(flat1);
  dist_calc2*=cos(flat2);
  dist_calc2*=sin(diflon/2.0);
  dist_calc2*=sin(diflon/2.0);
  dist_calc +=dist_calc2;

  dist_calc=(2*atan2(sqrt(dist_calc),sqrt(1.0-dist_calc)));

  dist_calc*=6371000.0; //Converting to meters
  return dist_calc;
}

// Convert NMEA coordinate to decimal degrees
float decimalDegrees(float nmeaCoord, char dir) {
  uint16_t wholeDegrees = 0.01*nmeaCoord;
  int modifier = 1;

  if (dir == 'W' || dir == 'S') {
    modifier = -1;
  }

  return (wholeDegrees + (nmeaCoord - 100.0*wholeDegrees)/60.0) * modifier;
}

void breath()
{
  uniformBreathe(LED_Breathe_Table, BREATHE_TABLE_SIZE, BREATHE_UPDATE, 127, 127, 127);
}

void uniformBreathe(uint8_t* breatheTable, uint8_t breatheTableSize, uint16_t updatePeriod, uint16_t r, uint16_t g, uint16_t b)
{
  int i;

  uint8_t breatheBlu;

  if ((millis() - lastBreatheUpdate) > updatePeriod) {
    lastBreatheUpdate = millis();

    for (i=0; i < strip.numPixels(); i++) {
      breatheBlu = (b * breatheTable[breatheIndex]) / 256;
      strip.setPixelColor(i, 0, 0, breatheBlu);
    }
    strip.show();

    breatheIndex++;
    if (breatheIndex > breatheTableSize) {
      breatheIndex = 0;
    }
  }
}

What gets me the most is this part
void headingDistance(float fDist)
{
  //Use this part of the code to determine how far you are away from the destination.
  //The total trip distance (from where you started) is divided into five trip segments.
 Serial.println(fDist);
 if ((fDist >= DESTINATION_DISTANCE)) { // You are now within 5 meters of your destination.
    //Serial.println("Trip Distance: 1");
    //Serial.println("Arrived at destination!");
    int i;
    for (i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, 0, 0, 0);
    }
    strip.show();   // write all the pixels out
  }

  if ((fDist < DESTINATION_DISTANCE)) { // You are now within 5 meters of your destination.
    //Serial.println("Trip Distance: 0");
    //Serial.println("Arrived at destination!");
    breath();
  }

}

Since the comments say both are for within 5 meters but have opposite conditions and "fDist" isn't defined anywhere that I can see, I don't know which is for near or far or how to set a color to either one. I tried setting colors for the first if statement and they seemed to work, but I couldn't get it to work consistently for some reason.

I think others have addressed the need for you to modify the strip colors based on distance or bearing or... whatever you want to show.
Here's a NeoGPS version of that sketch.  I think it may be easier to understand what's going on, and where you need to focus:
// Flora GPS + LED Pixel Code
//   Modified to use NeoGPS library.
//
// Adafruit Flora GPS module
//    ------> http://adafruit.com/products/1059
// Pick one up today at the Adafruit electronics shop
// and help support open source hardware & software! -ada

#include "Adafruit_NeoPixel.h"
#include <NMEAGPS.h>

NMEAGPS gps;
gps_fix fix;
#define gpsPort Serial1

const int NEOPIXEL_PIN = 6;

//----------------------------------------------------|
//                     WAYPOINTS                      |
//----------------------------------------------------|
// Please enter the latitude and longitude of your    |
// desired destination:                               |
NeoGPS::Location_t destination( 449950120L, -932289670L );
//  To be more accurate, these are degrees * 10000000 |
//----------------------------------------------------|

//--------------------------------------------------|
//                    DISTANCE                      |
//--------------------------------------------------|
//Please enter the distance (in meters) from your   |
//destination that you want your LEDs to light up:  |
const float DESTINATION_DISTANCE = 20.0;

//--------------------------------------------------|
// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel( 8, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800 );

uint8_t LED_Breathe_Table[]  =
  {
     80,  87,  95, 103, 112, 121, 131, 141, 151, 161, 172, 182, 192, 202, 211, 220,
    228, 236, 242, 247, 251, 254, 255, 255, 254, 251, 247, 242, 236, 228, 220, 211,
    202, 192, 182, 172, 161, 151, 141, 131, 121, 112, 103,  95,  87,  80,  73,  66,
     60,  55,  50,  45,  41,  38,  34,  31,  28,  26,  24,  22,  20,  20,  20,  20,
     20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,
     20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  20,  22,  24,  26,  28,
     31,  34,  38,  41,  45,  50,  55,  60,  66,  73
  };

#define BREATHE_TABLE_SIZE (sizeof(LED_Breathe_Table))
#define BREATHE_CYCLE      5000      /*breathe cycle in milliseconds*/
#define BREATHE_UPDATE     (BREATHE_CYCLE / BREATHE_TABLE_SIZE)
uint32_t lastBreatheUpdate = 0;
size_t   breatheIndex      = 0;

void setup()
{
  Serial.begin(115200);
  gpsPort.begin(9600);  // default baud rate for Adafruit MTK GPS's - some use 4800

  gps.send_P( &gpsPort, F("PMTK314,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0") ); // RMC+GGA
  delay(100);
  gps.send_P( &gpsPort, F("PMTK220,1000") ); // 1Hz
  delay(100);
  gps.send_P( &gpsPort, F("PGCMD,33,0") ); // No antenna status

  strip.begin();
  strip.show();  // Update the strip, to start they are all 'off'
}

void loop()
{
  if (gps.available( gpsPort ) ) {
    fix = gps.read();

    const bool spoof = false; // change to true for spoofing
    if (spoof) {
      float t           = fix.dateTime.seconds / 4.0;  // 15 second cycle (60 / 4)
      float offsetAngle = (TWO_PI / 20.0) * t;         // 20 steps around circle
      float offsetDist  = 0.005 * t / NeoGPS::Location_t::EARTH_RADIUS_KM;
                           // 5m per second, 75m away or less. In RADIANS!
      fix.location = destination; // start here and step away
      fix.location.OffsetBy( offsetDist, offsetAngle );
    }

    //Serial.print( F("Location: ") );
    //Serial.print( fix.latitude(), 5 );
    //Serial.print( F(", ") );
    //Serial.print( fix.longitude(), 5 );

    if (fix.valid.location) {
      float distance = fix.location.DistanceKm( destination ) * 1000.0; // meters

      // Set below to true if you want your Flora to navigate to a
      //  certain destination.  Then modify the showDirection function.
      const bool showNavigationHints = true;

      if (showNavigationHints) {

        float bearing = fix.location.BearingToDegrees( destination );

        //  If we're moving fast enough, show the user which way to go, left or right.
        if (fix.valid.heading and (fix.valid.speed and fix.speed_kph() > 3.0)) {

          float courseCorrection = bearing - fix.heading();
          if (courseCorrection < 0.0)
            courseCorrection += 360.0;

          showDirection( courseCorrection );

        } else {
          // We're not moving very fast, show a compass direction.
          showDirection( bearing );
        }
      }

      showDistance( distance );
    }
  }
}

void showDirection( float bearing )
{
  //  Use this to show which way you need to go.
  //    Some times, it's an absolute compass direction.
  //    Other times, it's a course correction (left or right from current heading)

  const __FlashStringHelper *dir = compassDir( bearing );
  size_t dirLen = strlen_P( (const char *) dir );
  for (uint8_t i = 0; i < (3 - dirLen); i++)
    Serial.print( ' ' );
  Serial.println( dir );
}

void showDistance(float distance)
{
  Serial.println( distance );

  // Are we close enough?
  if (distance >= DESTINATION_DISTANCE) {
    // No.

    const uint8_t level = 0; // you might set this based on distance

    for (int i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor( i, level, level, level );
    }
    strip.show();   // write all the pixels out

  } else {
    // Yes!
    // Serial.println("Arrived at destination!");
    breath();
  }

}

//------------------------------------------------------------
// This is copied from the NeoGPS NMEAaverage.ino example program

const char nCD  [] PROGMEM = "N";
const char nneCD[] PROGMEM = "NNE";
const char neCD [] PROGMEM = "NE";
const char eneCD[] PROGMEM = "ENE";
const char eCD  [] PROGMEM = "E";
const char eseCD[] PROGMEM = "ESE";
const char seCD [] PROGMEM = "SE";
const char sseCD[] PROGMEM = "SSE";
const char sCD  [] PROGMEM = "S";
const char sswCD[] PROGMEM = "SSW";
const char swCD [] PROGMEM = "SW";
const char wswCD[] PROGMEM = "WSW";
const char wCD  [] PROGMEM = "W";
const char wnwCD[] PROGMEM = "WNW";
const char nwCD [] PROGMEM = "NW";
const char nnwCD[] PROGMEM = "NNW";

const char * const dirStrings[] PROGMEM =
  { nCD, nneCD, neCD, eneCD, eCD, eseCD, seCD, sseCD,
    sCD, sswCD, swCD, wswCD, wCD, wnwCD, nwCD, nnwCD };

const __FlashStringHelper *compassDir( uint16_t bearing ) // degrees CW from N
{
  const int16_t directions    = sizeof(dirStrings)/sizeof(dirStrings[0]);
  const int16_t degreesPerDir = 360 / directions;
        int8_t  dir           = (bearing + degreesPerDir/2) / degreesPerDir;

  while (dir < 0)
    dir += directions;
  while (dir >= directions)
    dir -= directions;

  return (const __FlashStringHelper *) pgm_read_ptr( &dirStrings[ dir ] );

} // compassDir

//--------------------------

void uniformBreathe
  ( uint8_t *breatheTable, size_t breatheTableSize,
    uint16_t updatePeriod,
    uint16_t r, uint16_t g, uint16_t b )
{

  if ((millis() - lastBreatheUpdate) > updatePeriod) {
    lastBreatheUpdate = millis();

    for (int i=0; i < strip.numPixels(); i++) {
      uint8_t breatheBlu = (b * breatheTable[breatheIndex]) / 256;
      strip.setPixelColor( i, 0, 0, breatheBlu );
    }
    strip.show();

    breatheIndex++;
    if (breatheIndex > breatheTableSize) {
      breatheIndex = 0;
    }
  }
}

void breath()
{
  uniformBreathe(LED_Breathe_Table, BREATHE_TABLE_SIZE, BREATHE_UPDATE, 127, 127, 127);
}

I am always amazed by how much a little whitespace can improve the readability.
 Good variable and function names are also important.  You are also being misled by bad comments.  :P
I have added some location "spoofing" code that lets you test it without having to walk around.  That spoofing section can be removed when you're done testing.
If you want to try it, NeoGPS is available from the Arduino Library Manager, under the menu Sketch-> Include Library-> Manage Libraries.  BTW, this saves about 500 bytes of RAM.
To answer your original question, the showDistance and showDirection functions should be modified to do whatever you want.

Three comments:

For someone who is new to Arduino and programming (or perhaps just new
to C / C++), you have taken on a large challenge.
It should be widely said (but it is not) that not all Arduino
libraries are compatible with one another.  And that it is up to the
user (or community) to identify conflicts.  As there are far too
many combinations for any one person to test them all.
You should ask only 1 question per post.  I think you are most
interested about programming different colors for a WS2812 LED.  So
we should not talk about GPS for now.

Most if not all Adafruit.com software source code are available free to the community at github.com.  The Adafruit_NeoPixel github repository  at github should contain all the source code for this project as well as several files of example code. In the example code is this segment of code that changes the LED color:
  switch(i){
    case 0: colorWipe(strip.Color(0, 0, 0), 50);    // Black/off
            break;
    case 1: colorWipe(strip.Color(255, 0, 0), 50);  // Red
            break;
    case 2: colorWipe(strip.Color(0, 255, 0), 50);  // Green
            break;
    case 3: colorWipe(strip.Color(0, 0, 255), 50);  // Blue
            break;
...removed some code for clarity...
    }

It is not really clear what your actual problem is. I will go with the following:

How to set the colors of the RGB LEDs: You are already using the Adafruit_NeoPixel library. The definition of Adafruit_Neopixel strip shows, that you have a strip with 8 LEDs. In setup the sketch calls strip.begin() to initiate it. After that, everytime you want to change the color/state of any number of LEDs on the strip, you can set them one by one with strip.setPixelColor(), which takes the number of the LED and the color in RGB format as parameters. To make the LEDs show your changes you have to call strip.show(), which sends the data to the LEDs.
What your sketch does: In the function headingDistance(float fDist) the colors of the LEDs are set according to the previously calculated distance. fDist comes as parameter to this function, so it is declared in the function header. The value comes from the function calc_dist(). Now you have 2 if-statements:

The first one (if you are farer away from your target) will set the color of all LEDs to black (turning them off) by calling strip.setPixelColor(i, 0, 0, 0) for every LED and then calling strip.show(). So this is easy.
The second one (if you are within the 5m radius) calls the function breath(). It will set the intensity of the blue color component for all LEDs dependent on it's parameter b and the time that passed since it set the LEDs color the last time (this is done with the millis()-if-statement). The function headingDistance() is called in loop(), whenever the fix variable of the GPS is set. Calling the breath() function (which is called from headingDistance()) very often results in a timed update of the LEDs every updatePeriod milliseconds. Refer to the BlinkWithoutDelay example in the Arduino IDE for this working principle. It leaves you time to do other things during the wait periods, because it is non-blocking. The breath() function is a more complex thing, than simply turning on and of the LEDs with the right color. If you just want to do that, replace it's call in headingDistance() with your own code, setting the LEDs like I explained above.

So:

one color to show when I'm in range of a a point, and another to show when I'm not.

Set the color values in RGB format in the first if-statement, to set for the case that your are not in the range of your GPS point. And replace the breath() function by a similar code with the color values in RGB format for the case, that you are within the range of your point.
If it still doesn't work, try if the original sketch works correctly. This would verify, that the measurement and calculation of the distance works as intended.


text:
Arduino IDE : 'tansig' was not declared in this scope
I am working on a simple NN sketch, everything looks fine and also i have added #include math.h .but when i try to compile it gives an error i-e 'tansig' is not defined in this scope
I am trying to implement neural networks on obstacle avoiding robot.
Weights(Constants) are extracted from matlab training file.
How to make tansig work with arduino IDE
#include <math.h>
byte p1,p2,p3;
float n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,s1,s2,s3,s4,s5,s6,s7,s8;

int Echo1 = A4; //LEFT_SENSOR ECHO
int Trig1 = A5; //LEFT_SENSOR TRIG
int Echo2 = A2; //MID_SENSOR ECHO
int Trig2 = A3; //MID_SENSOR TRIG
int Echo3 = A0; //RIGHT_SENSOR ECHO
int Trig3 = A1; //RIGHT_SENSOR TRIG

//Motor driver outputs

#define m11 3
#define m12 4
#define m21 5
#define m22 6

int Left_Distance = 0,Right_Distance = 0,Middle_Distance = 0 ;

/*Ultrasonic distance measurement Sub function*/
int Left_Distance_test()
{
digitalWrite(Trig1, LOW);
delayMicroseconds(2);
digitalWrite(Trig1, HIGH);
delayMicroseconds(20);
digitalWrite(Trig1, LOW);
float Fdistance = pulseIn(Echo1, HIGH);
delay(10);

Fdistance= Fdistance/ 29 / 2;
return (int)Fdistance;
}

int Middle_Distance_test()
{
digitalWrite(Trig2, LOW);
delayMicroseconds(2);
digitalWrite(Trig2, HIGH);
delayMicroseconds(20);
digitalWrite(Trig2, LOW);
float Fdistance = pulseIn(Echo2, HIGH);
delay(10);

Fdistance= Fdistance/ 29 / 2;
return (int)Fdistance;
}

int Right_Distance_test()
{
digitalWrite(Trig3, LOW);
delayMicroseconds(2);
digitalWrite(Trig3, HIGH);
delayMicroseconds(20);
digitalWrite(Trig3, LOW);
float Fdistance = pulseIn(Echo3, HIGH);
delay(10);

Fdistance= Fdistance/ 29 / 2;
return (int)Fdistance;
}

void setup()
{

pinMode(Echo1, INPUT);
pinMode(Trig1, OUTPUT);
pinMode(Echo2, INPUT);
pinMode(Trig2, OUTPUT);
pinMode(Echo3, INPUT);
pinMode(Trig3, OUTPUT);

  pinMode(m11, OUTPUT);
  pinMode(m12, OUTPUT);
  pinMode(m21, OUTPUT);
  pinMode(m22, OUTPUT);

}

void loop()
{
  Left_Distance = Left_Distance_test();
delay(10);
Middle_Distance = Middle_Distance_test();
delay(10);
Right_Distance = Right_Distance_test();
delay(10);

p1=Left_Distance;
p2=Middle_Distance;
p3=Right_Distance;

n1=(0.0588*p1)+(-2.7382*p2)+(-2.2898*p3)+(5.2586);
n2=(-3.1601*p1)+(-2.2137*p2)+(1.7397*p3)+(1.4386);
n3=(2.2931*p1)+(0.3145*p2)+(3.5053*p3)+(-1.0167);
s1=tansig(n1);
s2=tansig(n2);
s3=tansig(n3);

n4=(1.1021*s1)+(1.2825*s2)+(-1.9864*s3)+(-2.3891);
n5=(-0.5501*s1)+(1.8527*s2)+(-2.0468*s3)+(1.4314);
n6=(0.4322*s1)+(-0.2474*s2)+(-2.5017*s3)+(-0.5222);
n7=(-0.2658*s1)+(-2.0624*s2)+(-2.2511*s3)+(1.0958);
n8=(1.7401*s1)+(1.1111*s2)+(1.2254*s3)+(2.4701);
s4=tansig(n4);
s5=tansig(n5);
s6=tansig(n6);
s7=tansig(n7);
s8=tansig(n8);

n9=(1.0819*s4)+(-1.0897*s5)+(0.0658*s6)+(-0.1232*s7)+(0.3510*s8)+(1.2990);
n10=(-1.0865*s4)+(1.0899*s5)+(-0.062*s6)+(0.1241*s7)+(0.5818*s8)+(-0.7316);
n11=(-0.2292*s4)+(-0.0606*s5)+(1.0508*s6)+(-0.9711*s7)+(1.1635*s8)+(0.2269);
n12=(0.2262*s4)+(0.0607*s5)+(-1.0482*s6)+(0.9717*s7)+(-0.5215*s8)+(0.6312);

digitalWrite(m11,n9);
digitalWrite(m12,n10);
digitalWrite(m11,n11);
digitalWrite(m11,n12);

}

error: 'tansig' was not declared in this scope

Show the code and the error. We cannot guess.

Maybe we can guess -- tansig is not defined in math.h and math.h does not provide any functions for neural networks. Are you coding for an Arduino?

@josecanuc Code Added.

@jsotola Code Added and statement redefined

I'm re-opening this question because it seems clear enough. How to get the function tansig to compile?

@NickGammon Yeah i tried that, But output of tanh are not suitable to write for motor inputs. They are [ -0.xxx or 1.xxx  or 0.xxx].

If it is mathematically equivalent, wouldn't tansig be the same? What motor inputs? What numbers are you expecting? Can't you translate the range you are getting into the range needed by the motors?

@NickGammon that is what i wanted to ask,Motors get only HIGH or LOW or we can say 0,1. But i am getting range in negative and postive decimal numbers. How to translate those outputs to some other which suits motor driver

See my amended answer.

You have quite a lot of floating point math here, and the tanh() calls are going to be expensive. You will have to measure the speed of your program and make sure it is fast enough for the application. If not, you may have to replace tanh() by a cheaper alternative, or go fixed-point, or get a more capable processor.

According to: http://au.mathworks.com/help/nnet/ref/tansig.html

Algorithms
a = tansig(n) = 2/(1+exp(-2*n))-1

This is mathematically equivalent to tanh(N).

So, replace calls to tansig by tanh. Or, make a define to do it:
#define tansig(n) tanh(n)

But output of tanh are not suitable to write for motor inputs. They are [ -0.xxx or 1.xxx or 0.xxx].

...

How to translate those outputs to some other which suits motor driver

There is a map function in the IDE which lets you translate from one range to another.

map() works only on long integers (comment by Edgar Bonet)

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

OK, well write your own function that does the same thing to floats. Example:
float fmap(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

map() works only on long integers.

See amended answer.

source: Stack Exchange

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

sort: votes


text:
Optical Incremental Encoder Reading using Arduino UNO
I have a HP Optical Incremental Encoder (256 CPR) in which

Pin 1 = A,
Pin 2 = VCC,
Pin 3 = GND,
Pin 8 = B.

I already read and see tutorials for rotary encoder such this one:
https://playground.arduino.cc/Main/RotaryEncoders
I have written a program that is supposed to print out the position of my encoder, however I am only getting zeros in my serial monitor. I want to be able to use interrupts. I would like to actually return the position in degrees of my encoder as we rotate it.
I was able to get it to work. I wasn't connecting my pin properly to my Arduino.
    #include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

#define encoderPinA 2
#define encoderPinB 3
#define CPR 256
volatile int counter =0;
volatile boolean flag;

volatile int var_degrees =0;

void setup() {

  pinMode(encoderPinA, INPUT);
  pinMode(encoderPinB, INPUT);
  Serial.begin (9600);
  attachInterrupt(digitalPinToInterrupt(encoderPinA), isr, RISING);
  lcd.clear();

}

void loop() {

   if(flag == true){
        var_degrees = ((360/256.0)*counter);
        Serial.println(var_degrees);
        lcd.setCursor(0, 1);
        lcd.print("Degrees: ");
        lcd.setCursor(9, 1);
        lcd.print(var_degrees);
        flag = false;
  }

}
//Interrupts

void isr_2(){
flag = true;
  if(digitalRead(encoderPinA) == HIGH){
    if(digitalRead(encoderPinB) == LOW){
      counter = counter -1; //COUNTER CLOCK WISE
    }
    else{
      counter = counter +1; //CW
    }
  }
  else{
    if(digitalRead(encoderPinB) == LOW){
      counter = counter + 1; //CW
    }
    else{
      counter = counter - 1 ; //CCW
    }
  }
}

You are attaching your interrupt incorrectly. You should not pass in the pin number, but the interrupt number. There is also a handy function that converts a pin to the right interrupt number:
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode);

So, your code should be:
attachInterrupt(digitalPinToInterrupt(encoderPinA), isr,CHANGE);

Also, you should declare your counter variable to be volatile, since it is modified within an ISR, and thus the compiler should not assume that it doesn't change even though the loop() never changes it:
volatile int counter = 0;

Quick question for this great community. I was able to read the position of my encoder and converted that position to an angle. However when I rotate the encoder right it gives me a negative output and when I rotate it left it gives me a positive output. It is backwards, I checked my Code and I can't find the issue.
Output rotating right starting from zero:
-1
-2
-4
-5
-7
-8
-9
-11
Output rotating right starting from zero:
0
1
2
4
5
7
8
9
11

Switch the counter+1 and counter-1

what do you mean? could you more specific please?

I'm not sure I can be more specific. There are places where you add one to counter and places where you subtract one from counter. Switch the adds with the subtracts... Or just swap the two encoder phases physically, or define the pins swapped.

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


text:
Arduino RFID tag scanning problems
For a school project, I'm using an Arduino Uno and a Parallax RFID together with some other components, I used a script I got from Instructables for reading my serial input from the RFID (link: http://www.instructables.com/id/Wiring-and-programming-the-Parallax-RFID-Serial-Ca/)
To use this serial data, you need to include an if loop in your loop function to check if the scanned tag equals the previous one. If it doesn't, the tag gets used further in the program. This doesn't allow scanning the same tag twice in a row. But I need that for my project. I have tried to work around it, but I can't seem to get it working, I always create a loop of unlimited scans or some other inregularities. Here's my code:
/* Libraries that need to be manually installed:
Blynk libraries: https://github.com/blynkkk/blynk-library/releases/download/v0.5.1/Blynk_Release_v0.5.1.zip
LiquidCrystal_I2C library: https://cdn.instructables.com/ORIG/FVH/K8OQ/J8UH0B9U/FVHK8OQJ8UH0B9U.zip
 */
#define BLYNK_PRINT Serial
#include <SoftwareSerial.h>
#include <BlynkSimpleShieldEsp8266.h>
#include <ESP8266_Lib.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
//#include <ThingSpeak.h>

//Setting up the Blynk wifi connection
#define ESP8266_BAUD 9600
char auth[] = "auth";

//Setting up the virtual pins
WidgetTerminal terminal(V1);
BLYNK_WRITE(V1){}
int freeSpots = 5;
BLYNK_READ(V2)
{
  Blynk.virtualWrite(V2, freeSpots);
}

//Setting up the RFID
#define RFIDEnablePin 8
#define RFIDSerialRate 2400
String RFIDTAG=""; //Holds the RFID Code read from a tag
String DisplayTAG = ""; //Holds the last displayed RFID Tag

//Setting up the LCD
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

//Setting up the serial connection
SoftwareSerial EspSerial(2, 3);
ESP8266 wifi(&EspSerial);

//Setting up the servo
Servo slagboom;

//Tag database
char tags[7][5] = {"6196", "6753", "5655", "69EC", "9FFC"};
char owners[7][5] = {"per1", "per2", "per3", "per4", "per5"};
int statuses[7] ={0};

//unsigned long channelNumber = 461353;
//const char * APIKey = "IHFFREPE9XUNSN94";

void setup() {
  //Serial communication
  Serial.begin(RFIDSerialRate);
  EspSerial.begin(ESP8266_BAUD);
  //RFID pin setup
  pinMode(RFIDEnablePin,OUTPUT);
  digitalWrite(RFIDEnablePin, LOW);
  //Blynk startup
  Blynk.begin(auth, wifi, "ssid", "pass");
  //LCD startup
  lcd.begin(16,2);//16 kolommen, 2 rijen
  lcd.backlight();
  //Servo startup
  slagboom.attach(10);
  slagboom.write(35);

  //ThingSpeak.begin(client);

  //Blynk terminal printing test
  delay(1000);
  slagboom.detach();
  terminal.println(F("Terminal printing succesfull"));
  terminal.flush();

}

void loop() {
  if (Serial.available() > 0)
  {
    ReadSerial(RFIDTAG);
  }
  if (DisplayTAG != RFIDTAG)
  {
    DisplayTAG=RFIDTAG;
    tagCompare(RFIDTAG);
  }
}

//Function for comparing the tag to the database
void tagCompare(String tagToCompare)
{
  char lastTag[5];
  tagToCompare.toCharArray(lastTag, 5);
  int i = 0;
  while (i < 5)
    {
      if (strcmp(tags[i], lastTag) == 0)
        {
          terminal.print(owners[i]);
          if (statuses[i] == 0)
          {
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Welkom, ");
            lcd.setCursor(0,1);
            lcd.print(owners[i]);
            statuses[i] = 1;
            freeSpots--;
            digitalWrite(RFIDEnablePin, HIGH);
            slagboom.attach(10);
            slagboom.write(145);
            delay(1000);
            digitalWrite(RFIDEnablePin, LOW);
            slagboom.write(35);
            delay(500);
            slagboom.detach();
            terminal.println(F(" heeft de parking betreden."));
            terminal.flush();
          }
          else
          {
            lcd.clear();
            lcd.setCursor(0,0);
            lcd.print("Tot ziens ");
            lcd.setCursor(0,1);
            lcd.print(owners[i]);
            statuses[i] = 0;
            freeSpots++;
            digitalWrite(RFIDEnablePin, HIGH);
            slagboom.attach(10);
            slagboom.write(145);
            delay(1000);
            digitalWrite(RFIDEnablePin, LOW);
            slagboom.write(35);
            delay(500);
            slagboom.detach();
            terminal.println(F(" heeft de parking verlaten."));
            terminal.flush();
          }
          //ThingSpeak.writeField(channelNumber, 1, i, APIKey);
          Blynk.run();
        }
      i++;
      }
  i = 0;
}

//Function for reading the tag
void ReadSerial(String &ReadTagString)
{
  int bytesread = 0;
  int val = 0;
  char code[10];
  String TagCode="";

  if(Serial.available() > 0)
  {
    if((val = Serial.read()) == 10)
    {
      bytesread = 0;
      while(bytesread<10) // Reads the tag code
      {
        if( Serial.available() > 0)
        {
          val = Serial.read();
          if((val == 10)||(val == 13)) // If header or stop bytes before the 10 digit reading
          {
            break; // Stop reading
          }
          code[bytesread] = val; // Add the digit
          bytesread++; // Ready to read next digit
        }
      }
      if(bytesread == 10)  // If 10 digit read is complete
      {
        for(int x=6;x<10;x++) //Copy the Chars to a String
        {
          TagCode += code[x];
        }
        ReadTagString = TagCode; //Returns the tag ID
        while(Serial.available() > 0) //Burn off any characters still in the buffer
        {
        Serial.read();
        }

      }
      bytesread = 0;
      TagCode="";
    }
  }
}

Any help would be very much appreciated.
Thanks in advance.
Edit: here's the changes I made to the loop():
void loop() {
  if (Serial.available() > 0)
  {
    ReadSerial(RFIDTAG);
  }
  unsigned long millisScanned;
  if (DisplayTAG != RFIDTAG)
  {
    DisplayTAG=RFIDTAG;
    tagCompare(RFIDTAG);
    millisScanned = millis();
  }
  unsigned long millisReference = millisScanned + 10000;
  if ((DisplayTAG == RFIDTAG) && (millis() >= millisReference))
  {
    tagCompare(RFIDTAG);
    millisScanned = millis();
  }
}

Can you describe in more detail what you mean by "I always create a loop of unlimited scans or some other inregularities."? Also, the code you posted as "yours" doesn't seem to have had any changes that would avoid checking the new value against the previous, so what exactly did you modify to try to work around it?

I have tried using the millis function to allow the tagCompare function to be used when DisplayTAG equald RFIDTAG.  I did this using the '&&' modifier but it always seemed to ignore the millis function. I also tried changing  the previously mentioned values but that executed the function twice for every tag scanned.
I left the wrong code out of my question, but I could rewrite it for you if necessary.

Please do put in the code you tried. "using the millis function" doesn't explain how you used it, etc.

@josecanuc, I added the code to the main question.

But I need that for my project. .... what are you talking about here?

@jsotola, I need to be able to scan the same tag twice, but I can't figure it out.

If you wish to allow even for duplicate scans, but only want to check it if the RFID reader returns a new scan string, then you don't even need millis()
void loop() {
  static bool pendingTag = false;
  if (Serial.available() > 0)
  {
    ReadSerial(RFIDTAG);
    pendingTag = true;   // Indicate that this is a new scan to check
  }
  if (pendingTag)
  {
    tagCompare(RFIDTAG);
    pendingTag = false;  // The tag is checked, no need to check again
    DisplayTAG=RFIDTAG;  // Not even sure if you use this anywhere else.
  }
}

Thanks for the reply! Unfortunately this doesn't quite work. I'm able to scan the same tag twice, but it randomly opens multiple times for each tag scanned. Any way to fix this?

I can't give a fix based on that comment. You have to track down what is triggering that, because it's likely not truly random. The code in the answer says to call tagCompare() if there was data on the serial port, essentially. What else might put data on the serial port?

The only thing connected to the serial port is the RFID-reader and I have tried clearing RFIDTAG after comparing it, this nearly fixes the problem, but occasionally tagCompare() still gets called twice.

So... add some debugging statements to print what comes in on the serial port so you can figure out what's going on. No one here can guess what is happening "randomly" on your hardware setup. You have to dig deep into your setup and figure out what is going on.

I think the RFID holds the tag that was last scanned, so it just keeps on sending the same tag to the serial port, I have no clue on how to fix this, so I'm just going to require another tag to be scanned before the first one can be scanned again. Thanks for your help anyway.


text:
i586-poky-linux-g++: no such file or directory Error compiling for board Intel® Edison
I'm facing this compilation issue.
Arduino: 1.8.4 (Linux), Board: "Intel® Edison"
fork/exec /home/jimish/.arduino15/packages/Intel/tools/core2-32-poky-linux/1.6.2+1.0/i686/sysroots/pokysdk/usr/bin/i586-poky-linux/i586-poky-linux-g++: no such file or directory
Error compiling for board Intel® Edison.
Arduino IDE:

Web IDE:

please remove the two pictures and include the actual output text, so that text searches can be made. .... use the edit button

I've already pasted error there. The pictures are proof, that it's not a fault of my local machine or local ide. @jsotola

@JimishFotariya - Have you tried to access this file from the command line?  Usually its just a path issue.

@code-gorilla No i haven't tried that. But web-editor compiles on their server so I think it is a bug in original source.

This sounds like something you need to pursue with the creators of this non-Arduino toolchain.   Either you have a broken install (does the file even exist?) or (if it is there but won't run) an issue like a 32 bit executable that won't run on a 64 bit system unless you install the optional 32-bit system libraries package.

The problem here is that Intel, in their infinite wisdom* have lots of hard-coded paths to libraries in the binaries (why, heaven only knows) and then a set of scripts that munge those binaries to sort out where the libraries really are.
That script uses an option to find that was deprecated 13 years ago.
Way to keep up with the times, Intel...
So you need to make some fixes to get the toolchain to install properly.
I have created "fix" scripts for both the Edison and the Galileo that you can use to replace your broken toolchain.

https://github.com/majenkotech/IntelFixes

*i.e., sheer incompetence


text:
Fastest reading through i2c
I have an ADXL345 accelerometer and I read it with an arduino through I2C. I want to get readings at a frequency higher than 500Hz. According to the documentation this should be easily achievable, however I've downloaded and used multiple libraries and none of them was able to achieve a sampling rate higher than 100Hz. They were all based on the arduino Wire library which doesn't seen very efficient. Could someone point me to a library or give me pieces of code that will allow me to sample data at 500+Hz? I send the data to matlab, not that it probably matters.

If you want highest possible frequency, I'd use SPI instead.
With 16 MHz Arduino, SPI clock can be 4MHz.
The chip only supports I2C at 400 KHz clock, which is way slower.
http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.pdf

If you set the SPI2X: Double SPI Speed Bit, you can run at 8MHz, but the ADXL345 only support upto 5Mhz.

Yes, 16MHz Arduino can run SPI clock at 1 MHz, 2 MHz, 4 MHz (default speed), 8 MHz (and 4 additional slower speeds - but not 5 MHz). I use 8 MHz for a lot of shift register projects.

Thanks. Wouldn't SPI require to convert between 5 to 3.3V for the arduino? In any case,  400KHz would be far more than I need but I fail to reach that sampling rate with the Wire library.

5V down to 3.3V, and 3.3V up to 5V is easily down with a couple of chips. 74HC4050, sN74HC125


text:
had dice code but lost it during recovery
I had the dice code, but reset and forgot to back the code up, now I need help creating the code again, I can't get the select button to proceed to the loop when pressed here's what I have so far:
#include <LiquidCrystal.h>
// select the pins used on the LCD panel
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

//used for later
String line2 = "Press Select to roll"; // Scrolling line

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

// read the buttons
int read_LCD_buttons()
{
 adc_key_in = analogRead(0);      // read the value from the sensor

 // For V1.0 comment the other threshold and use the one below:

 if (adc_key_in > 1000) return btnNONE; // We make this the 1st option for speed reasons since it will be the most likely result
 // For V1.1 us this threshold
 if (adc_key_in < 50)   return btnRIGHT;
 if (adc_key_in < 195)  return btnUP;
 if (adc_key_in < 380)  return btnDOWN;
 if (adc_key_in < 555)  return btnLEFT;
 if (adc_key_in < 790)  return btnSELECT;

 return btnNONE;  // when all others fail, return this...
}

void setup() {
 randomSeed(analogRead(1));
 lcd.begin(16, 2);              // start the library
 lcd.setCursor(3,0);
 lcd.print ("Catan Dice");
 lcd.setCursor(0,1);
 lcd.print("Press Select to roll");
}

void loop() {
//local varables
int buttonState = read_LCD_buttons(); // read the button pad
int lastButtonState = btnNONE; // previous state of the button

//Dice
int DiceOne = random(1,7);
int DiceTwo = random(1,7);

  if (buttonState != lastButtonState) {
  // if the state has changed, increment the counter
  if (buttonState == HIGH) {
  // if the current state is HIGH then the button went from off to on:

if (btnState == btnSELECT)
  lcd.setCursor (0,4);
  lcd.print(DiceOne);

  }

}
lastButtonState = buttonState;

}

can anyone help me plz

I see you have edited the question and completely changed the sketch. What is the error message this sketch is giving you?

You know that LCD shield buttons are usually multiplexed to the analog pin A0? If I've googled correct schematics, this applies to this one too. Therefore no pin change interrupts nor external interrupts can be used.
Maybe analog comparator module with correct threshold.

can someone help me with my project, the problem is up top

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


text:
Dice is not showing the correct numbers
I've made a dice roller (to make it easier to roll the dice) using an Arduino UNO and an LCD keypad shield but I can't get the correct numbers (1, 6 (7)) to show up, I've tried using int, float and everything in between. the buttons on the shield are connected to A0, can someone help me please?
#include <LiquidCrystal.h>
// select the pins used on the LCD panel
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

#include "DFRkeypad.h"
String line2 = "Press Select to roll"; // Scrolling line

// just some reference flags
//int stringStart, stringStop = 0;
//int scrollCursor = screenWidth;

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

// read the buttons
int read_LCD_buttons()
{
  adc_key_in = analogRead(0);      // read the value from the sensor

  // For V1.0 comment the other threshold and use the one below:

  if (adc_key_in > 1000) return btnNONE; // We make this the 1st option
  for speed reasons since it will be the most likely result
  // For V1.1 us this threshold
  if (adc_key_in < 50)   return btnRIGHT;
  if (adc_key_in < 195)  return btnUP;
  if (adc_key_in < 380)  return btnDOWN;
  if (adc_key_in < 555)  return btnLEFT;
  if (adc_key_in < 790)  return btnSELECT;

  return btnNONE;  // when all others fail, return this...
}

void setup() {
  randomSeed(analogRead(1));
  lcd.begin(16, 2);              // start the library
  lcd.setCursor(3, 0);
  lcd.print ("Catan Dice");
  lcd.setCursor(0, 1);

  // while(line2)
  //
  // lcd.print(line2);
  // break;
}

void loop() {

  //Dice
  byte DiceOne = random(1, 7);
  byte DiceTwo = random(1, 7);

  //local varables
  int buttonState = read_LCD_buttons(); // read the button pad
  int lastButtonState = btnNONE; // previous state of the button

  // the following variables are unsigned longs because the time, measured in
  // milliseconds, will quickly become a bigger number than can be stored in an int.
  unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
  unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

  switch (buttonState)
  {
    case btnSELECT:
      lcd.clear();
      //Row, Colum
      lcd.setCursor (0, 4);
      lcd.print(DiceOne);
      lcd.setCursor (1, 4);
      lcd.print(DiceTwo);
      break;
  }

  DELAY(100)

  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonState);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH), and you've waited long enough
  // since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the
    debounce
    // delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;
    }
  }

UPDATE, i got it working now

what do you mean by can't get correct numbers to show up?

The question is unclear, what do you mean do not get correct number? The official Arduino documentation recommends using a "long" type variable https://www.arduino.cc/reference/en/language/functions/random-numbers/random/

i want 1 through 6 to show up insted of larger numbers

What "larger numbers" are you getting?

42, 43,62 and 55, i want it to generate numbers 1,2,3,4,5,6 at random when i push the button

You are calling setCursor() with:
//Row, Colum
lcd.setCursor (0, 4);
lcd.print(DiceOne);
lcd.setCursor (1, 4);
lcd.print(DiceTwo);

While your comment notes the order is Row, Column, there appear to be several LiquidCrystal libraries floating about, some of which use Column, Row order in the SetCursor() function. The official Arduino library source indicates the col, row order.
You are writing both values on row 4 (even though that doesn't exist on your display), and in columns 0 and 1, thus you are correctly computing the Dice values, but they are being written with no gap between.

Yes I'm writing them in the same row but different columns and I'll be away from my dice for a few days, we'll continue this when I get back, sound good?

You noted that you got it working. If you share the results, it may help others in the future who are having a possibly similar question.

all i did was switched the numbers in the
lcd.Setcusor from lcd.setCursor (0, 4);
lcd.print(DiceOne);
lcd.setCursor (1, 4);
lcd.print(DiceTwo);                                                                                to lcd.setCursor (4, 0);
lcd.print(DiceOne);
lcd.setCursor (4, 1);
lcd.print(DiceTwo);

It seems that your issue is probably connected with LCD timing. Sending data to LCD requires a precise timings, and the onboard chip of the LCD module very much like a few milliseconds of time to finish processing the data sent, instead you pass the entire clear and draw command each loop cycle.
I used the default Tinkercad LCD display example.
This code works fine:
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  randomSeed(analogRead(1));
  lcd.begin(16, 2);
  lcd.setCursor(3, 0);
  lcd.print ("Catan Dice");
  lcd.setCursor(0, 1);
}

void loop() {
  byte DiceOne = random(1, 7);
  byte DiceTwo = random(1, 7);

  lcd.clear();
  lcd.setCursor (0, 4);
  lcd.print(DiceOne);
  lcd.setCursor (1, 4);
  lcd.print(DiceTwo);
  delay(100);
}

but as soon as I remove the delay(100)
void loop() {
  byte DiceOne = random(1, 7);
  byte DiceTwo = random(1, 7);

  lcd.clear();
  lcd.setCursor (0, 4);
  lcd.print(DiceOne);
  lcd.setCursor (1, 4);
  lcd.print(DiceTwo);
  //delay(100);
}

Weird things start to show on the LCD.

Try rewriting your code that the commands are sent to LCD only once per button press.

I believe the serial LCD driver in the LiquidCrystal library is synchronous and won't return until it has finished sending the commands to display your desired characters.  The digital interface should not get confused even without delays.

My guess is that without the delay, the LCD updates so fast that the liquid crystals don't finish shifting to display a given pixel pattern before the next number is sent. (LCD displays have crystals suspended in a liquid, and when you change the pixel pattern, it takes significant time for the crystals to shift into the new patterns. If you watch the change with a high speed camera, the pixels seem to "ooze" into the new pattern.)

i have it so it generates the numbers upon a push of the right button

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


text:
Can I use 1 clock module for multiple Arduinos?
I want to connect an RTC to a master Arduino, send the time data to a slave Arduino through I2C, then connect an LCD to the slave and print it out.
can it be done? A think it would mean that the slave Arduino is a master for the LCD a the same time and it would mess up my code. Any input would be highly appreciated.

the LCD is I2C? what model?

I believe it's SPI. The model is LCD1602.

LCD1602 is just a description of the size - a 16x2 character LCD. What specific LCD is it you have?

And does it have the I2C backpack?

I2C allows for multiple masters. So you could connect the RTC to both Arduinos at the same time. Though you might have to do a bit of extra work to prevent the Arduinos from accessing the RTC at the same time. Either prevent those collisions, or gracefully handle them when they occur (which depending on how often you access the RTC, might be very rare).

From what I understood. I think you are trying to pass time to 2 ardruinos using one RTC.
m.a. = master arduino
s.a. = slave arduino
                            RTC
                            /\ (i2c)
                        m.a.  s.a.-------------(LCD)
                         L______|(spi)

No you cannot
but you can read time in master and then relay it to slave using your own protocol (i.e. "Apr  4 21:20:16 IST 2018") and let it print to LCD.
      RTC ------ m.a. ======= s.a. ++++ (lcd)
            i2c          spi
        (read reg.)  (pass string)

Humble NOTE:- If possible draw some digram while you are explaining circuit. It will be far easy to understand and answer than explaining circuit. may be draw on paper and upload to igmur/drive and add link in question or upload it here.
My ascii digrams may not be best but I think they pass message clearly.

The actual wording of the question is clear and without conflict: " connect an RTC to a master Arduino, send the time data to a slave Arduino through I2C, then connect an LCD to the slave and print it out."

there was ambiguity as in subject it was mentioned about connecting to two arduinos.

The word in the subject says "for" not "connecting to"

my mistake I misinterpreted it. But I still felt it was not very clear so mentioned it. This was my view.

The LCD is connected over SPI. The MCU can be an I2C slave and the SPI master. There is no conflict.


text:
Avrdude verification error
I use an Arduino UNO with IDE 1.8.5 and for the last few days it doesn't let me upload any code. When I try, it pops up with the following error:
avrdude: verification error, first mismatch at byte 0x0042
         0x65 != 0x8d
avrdude: verification error; content mismatch
avrdude: verification error; content mismatch

I really don't know what happened it used to work perfectly well. I even tried to upload blank code with nothing wired on and still the same error appears. I also tried with another USB cable, another PC, an older Arduino IDE but still nothing happens.
Any ideas ??
After checking so verbose output during compilation& upload it shows this:
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\kat_t\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\kat_t\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\kat_t\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10805 -build-path C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827 -warnings=none -build-cache C:\Users\kat_t\AppData\Local\Temp\arduino_cache_621253 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.1.1 -prefs=runtime.tools.avrdude.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9 -prefs=runtime.tools.avr-gcc.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2 -verbose C:\Users\kat_t\AppData\Local\Temp\untitled1895278478.tmp\sketch_may18b\sketch_may18b.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\kat_t\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\kat_t\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\kat_t\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10805 -build-path C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827 -warnings=none -build-cache C:\Users\kat_t\AppData\Local\Temp\arduino_cache_621253 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.1.1 -prefs=runtime.tools.avrdude.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9 -prefs=runtime.tools.avr-gcc.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2 -verbose C:\Users\kat_t\AppData\Local\Temp\untitled1895278478.tmp\sketch_may18b\sketch_may18b.ino
Using board 'uno' from platform in folder: C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21
Using core 'arduino' from platform in folder: C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21
Detecting libraries used...
"C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\cores\arduino" "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\variants\standard" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp" -o "nul"
Generating function prototypes...
"C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\cores\arduino" "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\variants\standard" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp" -o "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\preproc\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\cores\arduino" "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\variants\standard" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp" -o "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp.o"
Compiling libraries...
Compiling core...
Using precompiled core
Linking everything together...
"C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.elf" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp.o" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/..\arduino_cache_621253\core\core_arduino_avr_uno_7e7efc521bfa236d1e5438b10f2a9ebf.a" "-LC:\Users\kat_t\AppData\Local\Temp\arduino_build_834827" -lm
"C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.elf" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.eep"
"C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-objcopy" -O ihex -R .eeprom  "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.elf" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex"
Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/bin/avrdude -CC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: reading input file "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex"
avrdude: writing flash (444 bytes):

Writing | ################################################## | 100% 0.06s

avrdude: 444 bytes of flash written
avrdude: verifying flash memory against C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex:
avrdude: load data flash data from input file C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex:
avrdude: input file C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex contains 444 bytes
avrdude: reading on-chip flash data:

An error occurred while uploading the sketch
Reading | ################################################## | 100% 0.06s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0002
         0x6b != 0x34
avrdude: verification error; content mismatch

avrdude done.  Thank you.

Try turning on verbose messages for compiling and uploading. To do so, go to File > Preferences > Show verbose output during: and check both boxes.

i edited my question to show you the results i had after doing this.Thank you

Similar to: https://arduino.stackexchange.com/q/44965/19409 https://arduino.stackexchange.com/q/30946/19409 https://arduino.stackexchange.com/q/59837/19409

I feel there is an issue with the bootloader that you are using with your Arduino, or maybe there is a fuse bit error.
Do you have a programmer with you, such as the usbtiny or the usbasp. IF you have another Arduino which works, than you can use it as a programmer as well.
Read up about it here
https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard
Connect the programmer to the Arduino Board, and your computer.
Go to tools, select the Arduino board. Then tools>programmers>select the programmer you are using.Then tools>burn bootloader.
This will fix any fuse bit issues, while also uploading a fresh version of the Bootloader which works with your Arduino IDE.
I hope this helps.

yes i was thinking of using my second arduino as a programmer following this tutorial [link]https://www.arduino.cc/en/Tutorial/ArduinoISP


text:
Help with my project on motors using the Arduino Board
I was given the task of being able to drive two motors in the forward direction, able to drive two motors in the reverse direction, and they must be able to drive each motor independently. I was wondering if anyone can give me directions, advice, or tips on the coding for this task. All I know is that:
if(switchState == HIGH){
digitalWrite(motorPin, HIGH);
}
else{
digitalWrite(motorPin, LOW);
}
}
I know this code makes the motor turn on and off with the high and low, but what type of code do I use to make it work at a certain speed, and to move independently?

Welcome to Arduino:SE. Please be aware that this is not a free design house or an on-demand online technical encyclopedia. Please revise your question showing your work and findings so far. You might find it helpful to review the site tour and Help Centre and, in particular, [ask].

given the task .... is this school work?

There are plenty oft tutorials in the web. Google and follow one of them

you can use PWM function of digital pins (analogWrite())to control the motor speeds as desired.


text:
Is there any version of arduino that can do something like serial interruption?
I am using an Arduino to control servo MX18A by serial, and trying to use computer to communicate with the Arduino by another serial to send commands to Arduino and change the servo control mode. Once the computer send a message to Aruduino, I hope it could response in time because may be there is something emergency like the servo being out of control ,under which circumstance I have to change the control strategy in time.
However, it seems like Arduinos like UNO, MEGA does not have serial interruption, so once the message from computer comes, it could not response in time.
I know that judging serial.available() in every loop is one solution, but in my different servo control strategy there are many time delays, for loops and while loops, which means that I have to put serial.available() in every time delay or for loops, making the code hard to write and maintain.

“there are many time delays”. This is your problem. Learning to program without delays is the solution.

@EdgarBonet What about for and  while loops? They are common in code design, and both of them will takes some time and have the same effect as  explicit delay.

Then you will need a finite state machine. In a nutshell: if you have to be responsive, program in a non-blocking fashion.

While all boards support serial interrupts on their serial port, beware that `328 based boards like the Uno only have one serial port.  "Software Serial" implementations can be partially interrupt based, but tend to need a lot of the processor's attention during reception so may not fit well into an interrupt-dependent program design.

@ChrisStratton I use UNO in my platform, which has four serial ports.

@bigxiao that makes no sense at all.  An Uno only has one serial port.  If you have an application that needs four, it is not the right choice for you as even a single software serial instance adds a lot of complication.  If you need four serial ports and Arduino may not be the solution for you at all, perhaps you should re-think your overall architecture.

The Mega does have 4 hardware serial ports.

It is not a case of "An Arduino" that can do serial interupts. All Arduino boards have serial interrupts, but they are already used to receive the data and store it in a buffer for you to consume when you have the time.
The Arduino API does not define any serial interrupt handling routines. That kind of thing is designed to be handled internally by the API code, not by the user. That's the whole point of the Arduino API - to abstract away such technicalities from the user.
If you want to use the serial interrupt yourself you will have to write your own serial handling code.
Or write your code in such a way that serial interrupts aren't needed.

How to write user-defined serial handling code and replace the original default code? Is there any interface for user to do that?

@bigxiao: Locate the file named "HardwareSerial.cpp" in the Arduino installation, copy it into your sketch's directory and tweak it to your needs.

Why not use a timer to check if any data is in the serial buffer every say 2 seconds.
The DUE has interrupts available on ALL pins so that could be a viable alternative solution.
You shouldn't use blocking code anyway, e.g. whiles and delays.

Arduino DUE has serial interruption, which is open for users?

It states that ALL digital pins on DUE work with interrupts so if you set an interrupt on a serial RX line it would trigger when data was received.


text:
Arduino BMP085 Barometric sensor blank serial monitor
I am a beginner as far as arduino and microcontrollers are concerned.
I am using a BMP085 barometric pressure sensor.I have made all the necessary connections to my arduino uno board and double checked them. What I want to do is get readings from the sensor and display them on my arduino serial monitor. The code I am using compiles and uploads without any error but when I open my serial monitor, it is blank. I tried using a humidity/temperature sensor before this and that sensor returns values to the serial monitor.
The barometric sensor is new and this was my first time usage.
Here is my sketch. I took it from here.
https://www.sparkfun.com/tutorials/253
Any help would be greatly appreciated.
the code
#include <Wire.h>

#define BMP085_ADDRESS 0x77  // I2C address of BMP085

const unsigned char OSS = 0;  // Oversampling Setting

// Calibration values
int ac1;
int ac2;
int ac3;
unsigned int ac4;
unsigned int ac5;
unsigned int ac6;
int b1;
int b2;
int mb;
int mc;
int md;

// b5 is calculated in bmp085GetTemperature(...), this variable is also used in bmp085GetPressure(...)
// so ...Temperature(...) must be called before ...Pressure(...).
long b5;

short temperature;
long pressure;

// Use these for altitude conversions
const float p0 = 101325;     // Pressure at sea level (Pa)
float altitude;

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

void loop()
{
  temperature = bmp085GetTemperature(bmp085ReadUT());
  pressure = bmp085GetPressure(bmp085ReadUP());
  altitude = (float)44330 * (1 - pow(((float) pressure/p0), 0.190295));

  Serial.print("Temperature: ");
  Serial.print(temperature, DEC);
  Serial.println(" *0.1 deg C");
  Serial.print("Pressure: ");
  Serial.print(pressure, DEC);
  Serial.println(" Pa");
  Serial.print("Altitude: ");
  Serial.print(altitude, 2);
  Serial.println(" m");
  Serial.println();

  delay(1000);
}

// Stores all of the bmp085's calibration values into global variables
// Calibration values are required to calculate temp and pressure
// This function should be called at the beginning of the program
void bmp085Calibration()
{
  ac1 = bmp085ReadInt(0xAA);
  ac2 = bmp085ReadInt(0xAC);
  ac3 = bmp085ReadInt(0xAE);
  ac4 = bmp085ReadInt(0xB0);
  ac5 = bmp085ReadInt(0xB2);
  ac6 = bmp085ReadInt(0xB4);
  b1 = bmp085ReadInt(0xB6);
  b2 = bmp085ReadInt(0xB8);
  mb = bmp085ReadInt(0xBA);
  mc = bmp085ReadInt(0xBC);
  md = bmp085ReadInt(0xBE);
}

// Calculate temperature given ut.
// Value returned will be in units of 0.1 deg C
short bmp085GetTemperature(unsigned int ut)
{
  long x1, x2;

  x1 = (((long)ut - (long)ac6)*(long)ac5) >> 15;
  x2 = ((long)mc << 11)/(x1 + md);
  b5 = x1 + x2;

  return ((b5 + 8)>>4);
}

// Calculate pressure given up
// calibration values must be known
// b5 is also required so bmp085GetTemperature(...) must be called first.
// Value returned will be pressure in units of Pa.
long bmp085GetPressure(unsigned long up)
{
  long x1, x2, x3, b3, b6, p;
  unsigned long b4, b7;

  b6 = b5 - 4000;
  // Calculate B3
  x1 = (b2 * (b6 * b6)>>12)>>11;
  x2 = (ac2 * b6)>>11;
  x3 = x1 + x2;
  b3 = (((((long)ac1)*4 + x3)<<OSS) + 2)>>2;

  // Calculate B4
  x1 = (ac3 * b6)>>13;
  x2 = (b1 * ((b6 * b6)>>12))>>16;
  x3 = ((x1 + x2) + 2)>>2;
  b4 = (ac4 * (unsigned long)(x3 + 32768))>>15;

  b7 = ((unsigned long)(up - b3) * (50000>>OSS));
  if (b7 < 0x80000000)
    p = (b7<<1)/b4;
  else
    p = (b7/b4)<<1;

  x1 = (p>>8) * (p>>8);
  x1 = (x1 * 3038)>>16;
  x2 = (-7357 * p)>>16;
  p += (x1 + x2 + 3791)>>4;

  return p;
}

// Read 1 byte from the BMP085 at 'address'
char bmp085Read(unsigned char address)
{
  unsigned char data;

  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(address);
  Wire.endTransmission();

  Wire.requestFrom(BMP085_ADDRESS, 1);
  while(!Wire.available())
    ;

  return Wire.read();
}

// Read 2 bytes from the BMP085
// First byte will be from 'address'
// Second byte will be from 'address'+1
int bmp085ReadInt(unsigned char address)
{
  unsigned char msb, lsb;

  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(address);
  Wire.endTransmission();

  Wire.requestFrom(BMP085_ADDRESS, 2);
  while(Wire.available()<2)
    ;
  msb = Wire.read();
  lsb = Wire.read();

  return (int) msb<<8 | lsb;
}

// Read the uncompensated temperature value
unsigned int bmp085ReadUT()
{
  unsigned int ut;

  // Write 0x2E into Register 0xF4
  // This requests a temperature reading
  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(0xF4);
  Wire.write(0x2E);
  Wire.endTransmission();

  // Wait at least 4.5ms
  delay(5);

  // Read two bytes from registers 0xF6 and 0xF7
  ut = bmp085ReadInt(0xF6);
  return ut;
}

// Read the uncompensated pressure value
unsigned long bmp085ReadUP()
{
  unsigned char msb, lsb, xlsb;
  unsigned long up = 0;

  // Write 0x34+(OSS<<6) into register 0xF4
  // Request a pressure reading w/ oversampling setting
  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(0xF4);
  Wire.write(0x34 + (OSS<<6));
  Wire.endTransmission();

  // Wait for conversion, delay time dependent on OSS
  delay(2 + (3<<OSS));

  // Read register 0xF6 (MSB), 0xF7 (LSB), and 0xF8 (XLSB)
  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(0xF6);
  Wire.endTransmission();
  Wire.requestFrom(BMP085_ADDRESS, 3);

  // Wait for data to become available
  while(Wire.available() < 3)
    ;
  msb = Wire.read();
  lsb = Wire.read();
  xlsb = Wire.read();

  up = (((unsigned long) msb << 16) | ((unsigned long) lsb << 8) | (unsigned long) xlsb) >> (8-OSS);

  return up;
}

wirings:
https://i.sstatic.net/oRX0V.jpg

Show us your code and your wiring. That your code compiles and that you double checked the connection doesn't mean, that there cannot be any wrong coding.

That web page has several snippets of code, so please do copy/paste the code you are trying into your question.

The most simple reason: Did you set your serial monitor to use baud rate 9600? Could you also add a Serial.println("SKETCH STARTING"); after the Serial.begin() call to verify that the sketch boots up?

Could it be that my sensor is faulty? If so, how do I check if my sensor is faulty? I took the entire ino file from the tutorial, and read about what each section of code does. The site did not provide any libraries so all the mathematical calculations are a part of the code.

the baud rate is 9600. I just checked it.

@MaximilianGerhardt I added the Serial.println("SKETCH STARTING"); as you instructed. The sketch boots up. I get a "Sketch starting" on the monitor. It is all blank after that.

The reading functions are blocking the program, until something is received. Please check, if you can contact the sensor via I2C/Wire by using the (I2C scanner sketch)[https://playground.arduino.cc/Main/I2cScanner]. If no device shows up, the wiring or the sensor isn't correct. When it is found, check if the found address is equal to the one you use.

Also you should show the wiring by making a schematic (for example with the tool in this question editor) or - if it works better for you - with something like fritzing. It is very hard to see the actual wiring on your low quality images

@chrisl Here is the schematic. https://learn.adafruit.com/assets/484 .
I tried contacting the sensor by running the sketch you linked above,no device comes up. The board is unable to communicate with the sensor.

Then as artag wrote you may have fried the sensor depending on what version you have

My version is 3.3 v version. I am aware of that, which is why i connected it to the 3.3 v pin. Is it still possible that i fried the sensor? Is there no sure shot way of checking it?

Not only the supply voltage is important. The UNO will output 5V on both SDA and SCL, which can fry the I2C hardware of the board. The only way to be sure is to check with a second module, that is still OK. Be sure to use a level shifter this time

There are several versions of breakout boards for the BMP085. The device itself is 3v3. Some breakouts provide a regulator so you can supply 5V. Some also perform level-shifting so you can drive the I2C lines at 5V and work correctly with the sensor's 3v3 levels.
It isn't clear which type you have there, but you seem to be powering it from 3v3 on the arduino. A photo of the other side of the sensor board would help.
If the sensor has a regulator, sourcing it from 3v3 will drop it a little (the regulator needs some overhead). This might mean the sensor is running at too low a voltage.
If the board has no regulator, then it's correct to power it from 3v3. However, the I2C lines also need conversion. You will be driving 5V into a 3v3 input, which can damage it. You will also be receiving 3v3 levels from the sensor into the 5V arduino, which will probably work but might not.
Ideally, put level shifters in between. They need to be bidirectional, like these : https://www.adafruit.com/product/757
In some cases you can get away with resistors only, but not easily on the bidirectional I2C bus. SPI is easier as the pins are unidirectional.

my sensor
http://2.bp.blogspot.com/-rYK6t2jDt_0/VxX02W1VNzI/AAAAAAAABCk/7W83W7ufzo8Kj97Ay0ioVDxBJE3vmqiNwCK4B/s1600/BMP085.jpg
is it possible that i fried the sensor? I connected it to the 3.3v pin on the uno board.
I did some reading and found out that the sensor has a 3.3v voltage regulator. I will try to connect it to the 5v pin.

It's possible, but it would depend on whether there are also level translators to protect the 3v3 control pins from the 5v arduino pins.

Adafruit says  :   V1 of the breakout uses 3.3V power and logic level only
V2 of the breakout uses 3.3-5V power and logic level for more flexible usage.


text:
SIM800L Mini and Arduino Uno
I know there are a lot of threads about this, but i cant find answer for my problem.
I have SIM800L Mini and arduino uno. I want to create basic SMS send application, but problem is with SIM800L. I can connect it with USB-UART and communicate with it via AT terminal. I can set baud rate, send sms etc. But when I connect it with arduino, it doesnt work. Im using LM350 for powering it (4V) and voltage divider with 4k7 and 10k resistor.
Thank you for your help
EDIT:
Here is code:
#include <SoftwareSerial.h>

String Arsp, Grsp;
SoftwareSerial gsm(10, 11); // RX, TX

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

   Serial.begin(9600);
   Serial.println("Testing GSM SIM800L");
   gsm.begin(9600);

}

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

   if(gsm.available())
   {
      Grsp = gsm.readString();
      Serial.println(Grsp);
   }

   if(Serial.available())
   {
      Arsp = Serial.readString();
      gsm.println(Arsp);
   }
}

Here is wiring

Codes for arduino
Schematics
SIM800L

Are you have connected ground between arduino and SIM800L?

thank you for your reply, yes I used one of GND on arduino and connect to the common ground (sim800l, dc-dc, arduino, voltage divider)

Could you please post your wiring and code what you used? Maybe you have wrong wiring.

i edited it, so you can check if its something wrong :)

You're not connected reset pin to arduino. You can try to connect it.
Pin 2 Arduino > Transistor > Reset pin SIM800

and it needs to be? because i read that reset pin dont need to connect

so how can i modify code? to use reset pin?

Ok sorry for missunderstanding. I think you must check that your cable is work perfectly.I doubt if rx pin arduino is not connected properly to tx gsm module. And are you have connected VCC gsm module into GND using resistor?

no those resistors are from lm350 dc-dc buck, im using 10V/3A and converting it to 4V for VCC sim800l

and cables are good, i tested them

Then i'm sorry i have no more clue. I have tested your circuit and mine is working. My only suggestion you rewiring it. Good luck buddy.

Let us continue this discussion in chat.


text:
ESP8266HTTPClient conflict with other libraries?
I can successfully send a GET request with the ESP8266HTTPClient library in the first sketch. However the exactly same code won't work when used in the second sketch, which is more complex and uses other libraries too. I'm not sure why, maybe a conflict between libraries?
Sketch 1 (working)
#define DEBUG

#ifdef DEBUG
  #define SB(...) Serial.begin(__VA_ARGS__)
  #define SP(...) Serial.print(__VA_ARGS__)
  #define SPL(...) Serial.println(__VA_ARGS__)
#else
  #define SB(...)
  #define SP(...)
  #define SPL(...)
#endif

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
const char* ssid = "TALKTALK-17409C";
const char* password = "HPHRKJYX";

void setup() {

   SB(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    SPL("Waiting to connect…");
  }

  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin("http://francescosoave.com/blind/getTime.php?pw=ciao");
    int httpCode = http.GET();
    SP("HTTP: ");
    SPL(httpCode);
    if(httpCode > 0){
      String payload = http.getString();
      SP("PAYLOAD: ");
      SPL(payload);
    }

    http.end();
  }
}

void loop() {}

Sketch 1 response in the serial monitor (Tools -> Debug port -> Serial // Tools -> Debug Level -> HTTP_CLIENT)
SDK:2.2.1(cfd48f3)/Core:2.4.1/lwIP:2.0.3(STABLE-2_0_3_RELEASE/glue:arduino-2.4.1)
scandone
scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 3
cnt
Waiting to connect…

connected with TALKTALK-17409C, channel 10
dhcp client start...
Waiting to connect…
ip:192.168.1.4,mask:255.255.255.0,gw:192.168.1.1
Waiting to connect…
[HTTP-Client][begin] url: http://francescosoave.com/blind/getTime.php?pw=ciao
[HTTP-Client][begin] host: francescosoave.com port: 80 url: /blind/getTime.php?pw=ciao
[HTTP-Client] connected to francescosoave.com:80
[HTTP-Client] sending request header
-----
GET /blind/getTime.php?pw=ciao HTTP/1.1
Host: francescosoave.com
User-Agent: ESP8266HTTPClient
Connection: close
Accept-Encoding: identity;q=1,chunked;q=0.1,*;q=0

-----
[HTTP-Client][handleHeaderResponse] RX: 'HTTP/1.1 200 OK'
[HTTP-Client][handleHeaderResponse] RX: 'Server: nginx'
[HTTP-Client][handleHeaderResponse] RX: 'Date: Wed, 08 Aug 2018 21:24:46 GMT'
[HTTP-Client][handleHeaderResponse] RX: 'Content-Type: text/html; charset=UTF-8'
[HTTP-Client][handleHeaderResponse] RX: 'Transfer-Encoding: chunked'
[HTTP-Client][handleHeaderResponse] RX: 'Connection: close'
[HTTP-Client][handleHeaderResponse] RX: 'Vary: Accept-Encoding'
[HTTP-Client][handleHeaderResponse] RX: 'X-Powered-By: PHP/5.6.32'
[HTTP-Client][handleHeaderResponse] RX: 'Vary: Accept-Encoding'
[HTTP-Client][handleHeaderResponse] RX: 'Access-Control-Allow-Origin: *'
[HTTP-Client][handleHeaderResponse] RX: ''
[HTTP-Client][handleHeaderResponse] code: 200
[HTTP-Client][handleHeaderResponse] Transfer-Encoding: chunked
HTTP: 200
[HTTP-Client] read chunk len: 11
[HTTP-Client][writeToStreamDataBlock] connection closed or file end (written: 11).
[HTTP-Client] read chunk len: 0
[HTTP-Client][end] still data in buffer (2), clean up.
[HTTP-Client][end] tcp stop
PAYLOAD: TIME: 22:24
[HTTP-Client][end] tcp is closed
pm open,type:2 0

Sketch 2 (not working)
#define DEBUG

#ifdef DEBUG
  #define SB(...) Serial.begin(__VA_ARGS__)
  #define SP(...) Serial.print(__VA_ARGS__)
  #define SPL(...) Serial.println(__VA_ARGS__)
#else
  #define SB(...)
  #define SP(...)
  #define SPL(...)
#endif

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "TALKTALK-17409C";
const char* password = "HPHRKJYX";

ESP8266WebServer server(80);   //instantiate server at port 80 (http port)
IPAddress ip(192, 168, 1, 7);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

String pageFinal = "";
byte curPos;
boolean timerState = true; //true = on, false = off
//int[] curTime = {0, 0}; // {hour, minutes

// HTML PAGES
String page1="<!DOCTYPE html>"
""
""
"<meta charset='utf-8'/>"
"<meta name='viewport' content='width=device-width, initial-scale=1'>"
"<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />"
"<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css' integrity='sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B' crossorigin='anonymous'>"
"<link rel='stylesheet' type='text/css' href='http://www.francescosoave.com/blind/style.css'>"
""
""
""
""
"
"
"
"
"
"
"
"
"
Fran's Blind
"
"
"
"
"
"
"
"<form action='/' method='get' id='manualForm'>"
"<input id='1' type='submit' class='btn btn-primary' name='manualBtn' value='1' />"
"
"
"
"
"<input id='2' type='submit' class='btn btn-primary' name='manualBtn' value='2' />"
"
"
"
"
"<input id='3' type='submit' class='btn btn-primary' name='manualBtn' value='3' />"
"
"
"
"
"<input id='4' type='submit' class='btn btn-primary' name='manualBtn' value='4' />"
"
"
"
"
"<input id='5' type='submit' class='btn btn-primary' name='manualBtn' value='5' />"
"
"
"
"
"<input id='6' type='submit' class='btn btn-primary' name='manualBtn' value='6' />"
"
"
"
"
"<input id='7' type='submit' class='btn btn-primary' name='manualBtn' value='7' />"
"</form>"
"
"
"
<form action='/' method='get'>"
"<input id='timer' name='timerBtn' value='' class='' type='submit'></form>
Timer is
"
"
"
"
"
"
"
"
"
"
"
""
"";

void setup(void){

  WiFi.config(ip, gateway, subnet);
  delay(1000);
  SB(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    SPL("Waiting to connect…");
  }

  SP("IP address: ");
  SPL(WiFi.localIP());

  //here's the same GET request as in Sketch 1 but here it doesn't work
if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin("http://francescosoave.com/blind/getTime.php?pw=ciao");
    int httpCode = http.GET();
   SP("HTTP: ");
   SPL(httpCode);
    if(httpCode > 0){
      String payload = http.getString();
      SP("PAYLOAD: ");
      SPL(payload);
    }

    http.end();
  }

  server.on("/", control);
  server.begin();
  SPL("Server listening");
}

int  i = 0;

void loop(void){
  server.handleClient();
}

void control(){

  if(server.args() > 0){ //there is something to change
    if(server.argName(0) == "timerBtn"){
      timerState = !timerState; //change timer
    }else if(server.argName(0) == "manualBtn"){
      curPos = server.arg(0).toInt(); //change current (manual)
    }
  }

  //build the page
  if(timerState)
    pageFinal = page1 + page2;
  else
    pageFinal = page1 + page2_5;

  pageFinal += page3 + curPos + page3_5 + page4;
  server.send(200, "text/html", pageFinal);
}

Sketch 2 response in the serial monitor (Tools -> Debug port -> Serial // Tools -> Debug Level -> HTTP_CLIENT)
SDK:2.2.1(cfd48f3)/Core:2.4.1/lwIP:2.0.3(STABLE-2_0_3_RELEASE/glue:arduino-2.4.1)
scandone
Waiting to connectâ€¦
IP address: 192.168.1.7
[HTTP-Client][begin] url: http://francescosoave.com/blind/getTime.php?pw=ciao
[HTTP-Client][begin] host: francescosoave.com port: 80 url: /blind/getTime.php?pw=ciao
[HTTP-Client] failed connect to francescosoave.com:80
[HTTP-Client][returnError] error(-1): connection refused
HTTP: -1
[HTTP-Client][end] tcp is closed
Server listening
pm open,type:2 0

edit: the issue was in the Wifi.config() line. It should be WiFi.config(ip, gateway, subnet, gateway);

Chances are it's that insane string you're constructing that is causing your problems.

that part works well..you can try it since it's the full code..

Humour me and replace that string with something tiny. See what the effect is. I am not at my desk to try it myself.

If you want to configure a static IP address, make sure it is unique in you LAN and outside the range managed by the DHCP server.
EDIT:
the WiFi.config() function doesn't assign the gateway address as DNS address. add 4th parameter with DNS server address.
WiFi.config(ip, gateway, subnet, gateway);

Hi, it is indeed unique in my LAN since it's working. Not sure how to check "outside the range managed by the DHCP server"?

ok so the static IP seems to be the issue. If I remove that the HTTP request will work. However I need a static IP. Any idea?

it is not working, if you can't connect. is the AP in your control? do you know the DHCP range of IPs? do you know what other devices with static IP are in your network? for start try to use the IP that was assigned by the DHCP 192.168.1.4

sorry maybe I wasn't clear. So: right now with DHCP (removing the WiFi.config() line) everything works fine: the HTTP request is sent and the html page is displayed at 192.168.1.8. If I set the static IP instead, the html page won't work and the HTTP request will return the error. BUT, for my application I need a static IP. So I need to find a solution so that both works with a static IP.

but the static address of your choice 192.168.1.7 is in conflict. then use 192.168.1.8 as a static IP if it works as lease, it will work as static. you can reserve it on the router

tried but still the same issue. It seems the conflict is something between the WiFi things and the HTTPclient. If I remove the HTTP request code completely, it will work fine both with 192.168.1.7 and 192.168.1.8

is the router a DNS server at 192.168.1.1? try to print the DNS server address assigned by the DHCP.

sorry, not sure how to do that. the default gateway in my LAN is 192.168.1.1 if that's what you're asking

WiFi.dnsIP();

with DHCP is 192.168.1.1. If I leave the WiFi.config() instead, WiFi.dnsIP() prints 0.0.0.0

WiFi.config(ip, gateway, subnet, gateway);

working!! had no idea about this. could you please explain? thanks!!!

the 4th parameter is the DNS server. your url has hostname that needs to be resolved by DNS

Comment out the WiFi.config() line in the second example. You’re probably not configuring your ESP correctly. Let it get it’s configuration from its DHCP server.

Hi, unfortunately I need a static IP address. However that part is working fine. It looks like there's a conflict somewhere.

Hi, unfortunately I need a static IP address. And that seems to be the issue. If I remove the line, the HTTP request is working. But I need the static IP. any solution? Thanks!


text:
Pro Micro recognised as Micro (win10, IDE 1.8.1)
I just got this pro-micro clone 5V and it's my first pro micro ever. After reading lots of discussions about how easy it is to brick and how it's just a smaller Leonardo, I've also found tutorials where they guide you to install custom things (sprkfun) to recognise the board, and others where it shows up as a Leonardo board.
However in my case I just plugged it in my Win10 laptop, the drivers got installed and it is automatically recognised as an Arduino Micro.
Since I haven't found people having this, and since I'd like not to brick it immediately I was wondering what's the procedure between:

follow sparkfun's guide for pro micro and install their custom
drivers
treat it as a Leonardo (in the IDE)
treat it as a standard Micro (in the IDE) since it's recognised as such

Thanks!
edit: solution: it's a Leonardo.

Treat it as what it is.
What windows sees it as is just what USB reports it as. It's just a name. It has no bearing on what it is or how you program it. Select the actual board that you have in the IDE, not what Windows says it thinks it is.
As a general rule: Ignore everything Windows ever says, it's full of sh!t.

yeah, but it is sh!t in carefully crafted layers of never ending annoyance ... lol