text:
how to measure level shock using vibration sensor and arduino

My project title is about crash detection, by using this kind of vibration sensor. When the sensor reads the shock (which is when I knock the sensor) more than 50, it assumes it's a crash and will send via SMS the location of the crash to me. The problem is, that I tried to connect the sensor with Arduino, but when I knocked the sensor, the value of the shock did not change. How can I fix this?
VCC I connected to 5V,
GND to Arduino GND,
A0 to analog input Arduino,
D0 is not used
This is my code

#include <SoftwareSerial.h>

#include <TinyGPS.h>

TinyGPS gps;
SoftwareSerial ss(2, 3);
SoftwareSerial GSMx(5, 11);

static void smartdelay(unsigned long ms);
static void print_float(float val, float invalid, int len, int prec);
static void print_int(unsigned long val, unsigned long invalid, int len);
static void print_date(TinyGPS &gps);
static void print_str(const char *str, int len);

//-------------------VARIABLE-------------------------------
float LastLon;
String dataString = "";
String DateString = "";
String TimeString = "";
int Sens1Pin = 0;
float Sens1;
int update=0;
float LastLat;
int dummy=0;
int RQScount;
int countERROR;
int countPHONE;
int countOK;
int commaPosition;
int index = 0;
int SMSx=0;
int ALARM=0;
int LOCK=0;
float latx;
float lonx;
int OUTRANGE=0;
String result[10];
String USER1 = "\"019*******\"";
String Data1 = "";
String Data2 = "";
String Data3 = "";
String Data4 = "";
String head = "";
String phone = "";
String pword = "";
String MESSAGE1="";
String MESSAGE2="";
String inputString = "";         // a string to hold incoming data
boolean stringComplete = true;  // whether the string is complete
boolean command = true;
boolean Enabled = false;
boolean Enabled1 = false;
boolean Enabled2 = false;
boolean Enabled3 = false;
boolean GPS_NoData = false;
float SHOCK;
int count;
float flat, flon;
  unsigned long age, date, time, chars = 0;
  float ExistingSpeed;
float SpeedGPS;

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

void setup()
{

  Serial.begin(9600);
  GSMx.begin(9600);
  inputString.reserve(150);
 delay(8000);

  //Serial.println("AT");
  GSMx.println("AT");
  delay(2000);
 // Serial.println("AT+CMGF=1");
  GSMx.println("AT+CMGF=1");
  delay(2000);
 // Serial.println("AT+CMGD=1");
  GSMx.println("AT+CMGD=1");
  delay(2000);
  //Serial.println("AT&W");
  GSMx.println("AT&W");
  delay(2000);

  //Serial.print("AT+CMGS=");
  delay(300);
  //Serial.println(USER1);
  GSMx.print("AT+CMGS=");
  delay(300);
  GSMx.println(USER1);
  delay(1000);
  //Serial.print("GPS-GSM TRACKER---ACTIVATED ");
  GSMx.print("Controller is now ready...");
  delay(200);
  //Serial.println(char(26));
  GSMx.println(char(26));
  delay(4000);

  //Serial.println("Sats HDOP Latitude  Longitude  Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum");
  //Serial.println("          (deg)     (deg)      Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail");
  //Serial.println("-------------------------------------------------------------------------------------------------------------------------------------");

  ss.begin(9600);
  //--------------------------------------

  stringComplete = true;
}

void loop()
{

  Sens1 = analogRead(Sens1Pin);           //read the value from the sensor
  Sens1 = (5.0 * Sens1 * 100.0)/1024.0;  //convert the analog data to digital

  SHOCK = ((390 - Sens1)/390)*100;

  unsigned short sentences = 0, failed = 0;
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

 if (SHOCK > 40){
    ALARM=1;
  }

  if (ALARM==1){
    delay(100);

    if (SMSx==0){
     //  Serial.print("AT+CMGS=");
                GSMx.print("AT+CMGS=");
               // Serial.println(USER1);
                GSMx.println(USER1);
                delay(1000);
               // Serial.print("ALARM ALERT!! at location, lat:");
                GSMx.print("EMERGENCY ALERT!!");
               // Serial.print(flat,5);
                GSMx.print(TimeString);
                GSMx.print(" ");
                GSMx.print(DateString);
                GSMx.print(" (LAT/LON/SPEED) ");
                GSMx.print(dataString);

                GSMx.print("www.google.co.in/maps/place/");
                GSMx.print(flat,5);
                GSMx.print(",");
                GSMx.println(flon,5);

                delay(200);
               // Serial.println(char(26));
                GSMx.println(char(26));
                delay(4000);

      SMSx=1;
      ALARM=0;
    }
  }

  print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
  print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
  gps.f_get_position(&flat, &flon, &age);
  print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 10, 6);
  print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 11, 6);
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  print_date(gps);
  print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
  print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
  print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
  print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
  print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
  print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);

  gps.stats(&chars, &sentences, &failed);
  print_int(chars, 0xFFFFFFFF, 6);
  print_int(sentences, 0xFFFFFFFF, 10);
  print_int(failed, 0xFFFFFFFF, 9);
  //Serial.println();

   if (flat < 0.1){
    GPS_NoData = true;
  }
  if (flat > 0.1){
    GPS_NoData = false;
  }

  if (flat != LastLat){
               if (GPS_NoData == false){
                 LastLat = flat;
               }
             }
             if (flon != LastLon){
               if (GPS_NoData == false){
                 LastLon = flon;
               }
             }

  //---------------------------------GSM FUNCTION-----------------------------------------

              Serial.print(TimeString);
              Serial.print(" ");
              Serial.print(DateString);
              Serial.print(" ");
              Serial.print(flon,5);
              Serial.print(", ALARM:");
              Serial.print(ALARM);
              Serial.print(", DATA:");
              Serial.print(dataString);
              Serial.print(", SHOCK LEVEL: ");
              Serial.println(SHOCK);

if (stringComplete == true){

  //Serial.println("AT+CMGR=1");
   GSMx.println("AT+CMGR=1");

  count = 0;
  countERROR = 0;
  countPHONE = 0;
  countOK = 0;
  stringComplete = false;
  Enabled = false;
  Enabled1 = false;
  Enabled2 = false;
  Enabled3 = false;
}

  while (stringComplete == false){
 // count = count + 1;
       while (Serial.available() > 0){

        char inChar = Serial.read();
        inputString += inChar;

        if (Enabled2){
          Data2 += inChar;
          countPHONE = countPHONE + 1;
            if (countPHONE == 10){
            Enabled2 = false;
            }
        }

        if (inChar == 'E'){
          Enabled1 = true;
         }
         if (Enabled1){
          Data1 += inChar;
          countERROR = countERROR + 1;
                if (countERROR == 5){
                 Enabled1 = false;
                      if (Data1 == "ERROR"){
                        stringComplete = true;
                      }
                      if (Data1 != "ERROR"){
                        countERROR = 0;
                        Data1 += "";
                        Enabled1 = false;
                      }
                }

        }

        if (inChar == 'O'){
          Enabled3 = true;
         }
         if (Enabled3){
          Data4 += inChar;
          countOK = countOK + 1;
               if (countOK == 2){
                if (Data4 == "OK"){
                  stringComplete = true;
                }
                if (Data4 != "OK"){
                  countOK = 0;
                  Data4 = "";
                  Enabled3 = false;
                }
               }
         }
        if (inChar == '+'){
          if (count > 5){
            Enabled2 = true;
          }
        }
        if (count > 80){
            stringComplete = true;

         }

       }
}

       if (stringComplete){
         /*

                */
            // Serial.println(inputString);
            index = 0;
    do
  {
      commaPosition = inputString.indexOf('*');
      if(commaPosition != -1)
      {
          result[index++] = (inputString.substring(0,commaPosition));
          inputString = inputString.substring(commaPosition+1, inputString.length());
      }
    //  else
    //  {  // here after the last comma is found
    //     if(inputString.length() > 0)
    //       Serial.println(inputString);  // SMS message after final splitting
                             // print it
     // }
   }
   while(commaPosition >=0);
     MESSAGE1 = result[2];
     MESSAGE2 = result[3];

         if (result[1] == "LOCATION") {
    //            Serial.print("AT+CMGS=");
                GSMx.print("AT+CMGS=");
    //            Serial.println(USER1);
                GSMx.println(USER1);
                delay(1000);
    //            Serial.print("DEVICE TRACKING, lat:");
                GSMx.print("DEVICE TRACKING, lat:");
    //            Serial.print(flat,5);
                GSMx.print(flat,5);
    //            Serial.print(", lon:");
                GSMx.print(", lon:");
    //            Serial.println(flon,5);
                GSMx.println(flon,5);
    //            Serial.print("www.google.co.in/maps/place/");
    //            Serial.print(flat,5);
    //            Serial.print(",");
    //            Serial.println(flon,5);
                GSMx.println(" SPEED:");
                GSMx.println(SpeedGPS);
                GSMx.print("www.google.co.in/maps/place/");
                GSMx.print(flat,5);
                GSMx.print(",");
                GSMx.println(flon,5);

                delay(200);
    //            Serial.println(char(26));
                GSMx.println(char(26));
                delay(4000);
    //            Serial.println("AT+CMGD=1");
                GSMx.println("AT+CMGD=1");

                delay(4000);

            }

                              if (result[1] == "RST") {
    //            Serial.print("AT+CMGS=");
                GSMx.print("AT+CMGS=");
    //            Serial.println(USER1);
                GSMx.println(USER1);
                delay(1000);
    //            Serial.print("Alarm reset...");
                GSMx.print("Alarm reset..");
                delay(200);
    //            Serial.println(char(26));
                GSMx.println(char(26));
                delay(4000);
    //            Serial.println("AT+CMGD=1");
                GSMx.println("AT+CMGD=1");
                ALARM=0;  SMSx=0;

                delay(4000);

            }

       inputString = "";
       result[1] = "";
       result[2] = "";
       result[3] = "";
       result[4] = "";
       result[5] = "";
       result[6] = "";
       Data1 = "";
       Data2 = "";
       Data3 = "";
       Data4 = "";
      // Serial.flush();

      // stringComplete = true;
  delay(100);
  Sens1 = analogRead(Sens1Pin);           //read the value from the sensor
  Sens1 = (5.0 * Sens1 * 100.0)/1024.0;  //convert the analog data to digital
  SHOCK = ((390 - Sens1)/390)*100;
  if (SHOCK > 50){
    ALARM=1;
  }
  Serial.print("SHOCK LEVEL: ");
  Serial.println(SHOCK);
  delay(100);
  Sens1 = analogRead(Sens1Pin);           //read the value from the sensor
  Sens1 = (5.0 * Sens1 * 100.0)/1024.0;  //convert the analog data to digital
  SHOCK = ((390 - Sens1)/390)*100;
  if (SHOCK > 40){
    ALARM=1;
  }
  Serial.print("SHOCK LEVEL: ");
  Serial.println(SHOCK);
  delay(100);
  Sens1 = analogRead(Sens1Pin);           //read the value from the sensor
  Sens1 = (5.0 * Sens1 * 100.0)/1024.0;  //convert the analog data to digital
  SHOCK = ((390 - Sens1)/390)*100;
  if (SHOCK > 40){
    ALARM=1;
  }
  Serial.print("SHOCK LEVEL: ");
  Serial.println(SHOCK);
  delay(100);
  Sens1 = analogRead(Sens1Pin);           //read the value from the sensor
  Sens1 = (5.0 * Sens1 * 100.0)/1024.0;  //convert the analog data to digital
  SHOCK = ((390 - Sens1)/390)*100;
  if (SHOCK > 40){
    ALARM=1;
  }
  Serial.print("SHOCK LEVEL: ");
  Serial.println(SHOCK);
       }

  delay(100);
 // smartdelay(300);
}
//--------------------------------------START OF SUBROUTINES-------------------------------------
static void smartdelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

static void print_float(float val, float invalid, int len, int prec)
{
  if (val == invalid)
  {
    while (len-- > 1)
    //  Serial.print('*');
    //Serial.print(' ');
    dummy=0;
  }
  else
  {
   // Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1); // . and -
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i)
     // Serial.print(' ');
     dummy=0;
  }
  smartdelay(0);
}

static void print_int(unsigned long val, unsigned long invalid, int len)
{
  char sz[32];
  if (val == invalid)
    strcpy(sz, "*******");
  else
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
 // Serial.print(sz);
  smartdelay(0);
}

static void print_date(TinyGPS &gps)
{
  int year;
  byte month, day, hour, minute, second, hundredths;
  float Speed;
  unsigned long age;
  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  if (age == TinyGPS::GPS_INVALID_AGE)
   // Serial.print("********** ******** ");
   dummy = 1;

  else
  {

    char sz[32];
    sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ",
        month, day, year, hour, minute, second);
   // Serial.print(sz);

  //  hour = hour+8;
  //  sprintf(lcd_buffer,"%02d/%02d/%02d %02d:%02d",day,month,year,hour,minute );

    hour = hour + 8;
    if (hour > 23){
      hour = hour - 24;
    }
    dataString="";
    TimeString="";
    DateString="";
    ExistingSpeed = gps.f_speed_kmph();
    Speed = gps.f_speed_kmph();
    SpeedGPS = Speed;

   TimeString = String(hour) + ":" + String(minute) + ":" + String(second);
   DateString = String(day) + "/" + String(month) + "/" + String(year);
   dataString = String(flat,5) + "  " + String(flon,5) + "  " + String(Speed,2);

  }
  print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
  smartdelay(0);

    }

static void print_str(const char *str, int len)
{
  int slen = strlen(str);
  for (int i=0; i<len; ++i)
  //  Serial.print(i<slen ? str[i] : ' ');
  smartdelay(0);
}

Have you tried a minimal sketch that just reads the vibration sensor and prints what it reads?

no, i didn't try it yet, i want the sensor that i used compatible with the coding as this is my fourth sensor that i had try on.

So step one is to confirm that the sensor is working and that it gives you the kind of values you expect - with a minimal program that reads the sensor and prints out the values.

From the huge amount of code it's hard to tell what exactly is wrong, but I noticed that you used 0 for the analog pin which is not the same as A0.
Your pin number should be defined as:
int Sens1Pin = A0;

On the UNO the two are interchangeable, since the analog pins are completely separate from the digital pins. It sees the numbers 0 to 5 or 14 to 19 (the latter are what A0-A6 alias to) with an analogRead() and maps then to the 6 available analog channels.

oh, i'm little bit confuse,  what do you means by maps then to the 6 available analog channels? could you give me an example according to my coding.

@Majenko I see. I just checked the pin definition and not the implementation of analogRead.

yes, my sensor implemented for analogRead, that why i use int Sens1Pin=0; but the problem is, my sensor cannot read the shock level, so the device cannot detect the shock level when it crash. because i use if else selection which is if shock level > 40, is assume as crash and sending me a SMS. There is no error at my coding i give above. just i not sure why i can't read the level of sensor when i knock it. i had try to change int SenslPin= A0; but the result are same. can u help me.

@MissBlur Did you try just reading the sensor and sending it to serial, to see if it works? Maybe try to use the digital pin on the module, since you just need a trigger at a threshold value. And adjust the sensitivity with the pot.

@gre_gor i had tried to testing the sensor and sending it to the serial, and i found out that my sensor do not detect the vibration because the result are not change. so the problem is my sensor right ? but when i run the code, the light(LED) of my sensor are just fine. do i need to replace the sensor? or i just need to try another code??


text:
GSM librarys Software Serial conflicts with I2C pins 2 and 3 for Arduino Micro
The GSM library apparently uses the Software Serial library to perform the communication. The Arduino Micro specified pins for the serial connection to the GSM is pin 2 and 3 (doc says, but see def of RXPIN below?). I would like to shift this to pin 7 and 8 , with 8 as Rx (has interrupt). However: Changing the definition of TXPIN in GSM3IO.h does not appear to give a working sketch. Also: The pin "number" here, does it refer to PDxx number or other (a bit confused by all the pin names )
.
.
#elif defined(__AVR_ATmega32U4__)
#define __TXPIN__ 7
#define __RXPIN__ 8  /* Previous 3,8,3 ,... but */
#define __RXINT__ 8
#endif

If the pins aren't changing when you change them is it possible that (AVR_ATmega32U4) isn't defined?

How do I check for defines way down in the .h  tree? I tried just printing RXPIN in the sketch source (assuming it would be part of the GSM.h includes), but it appears to be undefined. Strange. The GSM library docs suggest this to be the way of changing the pin number.. I do not understand the specification of the interrupt pin not being the same as the receive pin though...  (other places I note that somebody suggest this define to be set to a non-valid value....and with apparent success)..Meanwhile i tried using pin 7 and 8 using the SoftwareSerial library with AT commands. It worked.

source: Stack Exchange

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

sort: votes


text:
I2C collision detection
I have put together a system that uses multiple Arduinos and a couple of 20x4 LCD displays to monitor my PV sun tracker and a weather station.  I am using I2C to link them all together.  One of the LCDs has been modified to have a different address (0x3b) so as to not conflict with the first one (0x3f).  So far, so good.   The sun tracker shows its display on the yellow one and the weather station shows its data on the blue one.
In order to connect this together I am using the Mayhew I2C&Power devices, so one power source energizes the entire system.  I send 12 Volts on the wire, then at each node I use a 12v to 5v converter to provide power for the I2C&Power board and the Nanos.  (The anemometer on the WX needs 12V to operate so that's a plus)
Each Arduino has a unique I2C address - there is no master in the system.
I have learned to set the screen updates to be quick (take readings and do any calculations before writing to the LCD in one swell foop), and to stagger the display update timings (the WX info updates every 65050 ms (full display update) and the PV info updates every 67050 ms (4 characters) and 605550 ms (full display refresh).  I chose these (arbitrarily random) values to make it less likely that they would try to update at the same time, because when both systems try to update their respective displays at the same time it causes some very interesting results - basically wiping out one or both displays.  It works most of the time but eventually one or the other screen will get wiped out.
Question:  Is there any way to implement collision detection on the I2C bus to prevent transmitting while other devices are communicating?  Something like CSMA/CD (Carrier Sense Multiple Access with Collision Detection) on Ethernet..

What are the physical distances involved with your interconnections?

Less than 50 feet for the longest one.  If the I2C&Power over Ethernet cable doesn't do the trick (They claim 300 feet - but the time delays could become an issue) then I will need to put a Pi out there to put up a value somewhere, like the way people Tweet parameters.

I did find this little gadget that provides interrupts so I could have dual I2C buses feeding into a single device without having them actually collide:  http://www.ebay.com/itm/401208338113

Collision detection on I2C is fully supported (See I2C Multi-Master). It works basically by attempting to transmit something and reading what is being transmitted at the same time. If what is read matches what is transmitted then the transmission worked. If it didn't match then there was a collision.
It is usually performed on a per-bit basis:

If a 0 then pull the data line LOW. If a 1 then let the resistor pull the data line HIGH.
Read the data line. If you want a 1 and get a 0 then some other device is pulling the data line low for a 0.
If the value was wrong then stop your transmission and back off by a random amount. Retry again. (note: both ends may retry, so you need good random numbers).

There is no support in the Wire library for collision detection, though, so you will have to implement it yourself. Section 22.4 of the datasheet gives you more information about how to implement it.

Thank you, @Majenko.  I'll follow up on this one for sure.  I am not using any pull-ups at all right now, (though I suspect some of my devices on the line, like the RTC, might have their own).  But this is very intriguing.

The Wire library turns on the internal pullups on the I2C pins for you. It really shouldn't, since they are too big (by about 10x). You should use external ones at about 3.3kΩ.

Upon more experimentation I have discovered that my I2C bus (extended by Mayhew I2C&Power modules) only works so well because of the presence of the RTC module.  It can be anywhere on the bus - at the display or out at the sensors with the Nano.  If I remove it, the bus quits working.  So I presume it is doing the job for me.

I will be multi-master, per se.  But will designate a primary system that can have one byte to say which system is currently allowed to transmit.  After determining that the bus is not busy I will read that one byte  and if zero then will put my node number in and then read it back to confirm.  Then open the connection then set it back to zero when I am done.  If nonzero I will know either a part failed in the middle of a write operation or the bus-busy failed.  So will wait and try again.  If the problem persists then I will write a FF to signal the primary to do a poll for missing nodes.

That link to the datasheet is quite interesting.  It is clear that there needs to be a software solution.  I like the idea of opening and writing a byte then checking to see if it went through.  The other nodes will have to honor that and wait their turn.  I'll be sending short messages from all of them, so a too-long delay in releasing the channel will mean a node failed to clear the byte.

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


text:
Arduino Leonardo - Using ICSP pins for serial
I'd like to know if it's possible to use the ICSP header pins on the Leonardo as GPIO pins, for example for software serial, and how to address them. I've a project which needs all available I/O pins, and I could use having serial comms on those "extra" pins.

From packages/arduino/hardware/avr/1.6.*/variants/leonardo/pins_arduino.h:

// Map SPI port to 'new' pins D14..D17
#define PIN_SPI_SS    (17)
#define PIN_SPI_MOSI  (16)
#define PIN_SPI_MISO  (14)
#define PIN_SPI_SCK   (15)

static const uint8_t SS   = PIN_SPI_SS;
static const uint8_t MOSI = PIN_SPI_MOSI;
static const uint8_t MISO = PIN_SPI_MISO;
static const uint8_t SCK  = PIN_SPI_SCK;

Those are the pin names and numbers you can use. Note that SS/17 is connected to the RX LED.

Thanks! I'll test it as soon as I have some time to spare! ;)

It works, though SoftwareSerial don't seem to be able to manage baud rates of 115200 bps, which I need.. :$


text:
Arduino Nano periodic reset under program control?
Is there a way to cause a periodic reset of an Arduino Nano under program control, short of some kind of external relay that signals the RST pin?
I'd like to do a full reset triggered by a digital write.
When the power is applied to the Nano it automatically pulls all the digital output pins to LOW so it appears that simply connecting a wire from a digital output to the RST pin would cause the system to continually reset and never run the program.  This would apply equally to using the DS3231 RTC chip's alarm function.  It would require the program to run in order to use it.
I suppose a relay would do the trick.  Or maybe even just an inverter chip like the 7404 between a digital output and the RST pin.  I am trying to fit this all in a small box so more hardware gets to be a problem.
So the question:  Is there any way to do this without external hardware?

Use the watchdog.

You didn't elaborate enough for me to know what you mean, @Majenko.  Besides, I want to trigger it programatically, not just periodically, if possible.  But maybe you are on to something - yet you didn't explain how to do it.  If you have an answer, please post it as one.

You simply turn the watchdog on with a short period and don't bother kicking it. It'll reset. Be sure that the period is longer than the bootloader timeout so you can disable the watchdog at startup - otherwise only a poweroff will disable it.

http://playground.arduino.cc/Main/ArduinoReset

@Majenko, thank you for this info.  I upvoted all your comments.  (If you had made this an answer I would have accepted and upvoted it that way.)  If you read my comment on the other answer you will see why I needed this and why I thought program control was best.  But upon further reflection I see that the watchdog is by far the simplest answer.  This is why I like this forum.  Thanks again.

Why do you want to reset you board?  The reason affects the answer.
Do you want to reset the board because your program crashes after n hours?  If so its probably better to fix the memory leak that you have in the code.
Is it because some global variables need to resetting every now and again?  If so could you place them in a class and store a pointer to them as your only global.  When you want to 'reset' the board delete the instance of the class and recreate it.
What happens if the software crashes?  Have you got it configured to restart on a crash?  If so could you just crash the code deliberately?
Because you have size constraints then it may be worth a bit of lateral thinking to see what the code can do for you.

The reason is that the communications over the wire to the LCD sometimes suffers bit errors which scrambles the screen.  The only fix I have found is to power it off by unplugging the cable, then plugging it back in.  I still haven't looked into the watchdog timer, but I do know that I can detect bit errors by reading back what I just wrote, periodically.  If they don't match then I want to force a reset.

Upvote because your answer made me have to think harder.....  I believe I will go with the watchdog instead of adding a bunch of new code.  Thanks!

@Archway - Do you need to reset the whole system, would power cycling just the LCD fix it?


text:
Making two Arduinos/MKR1000s communicate
I am trying to create a project in my free time just for a bit of fun. It consists of two MKR1000s (one acting as a web server connected to one laptop, and the other acting as a web client connected to a different laptop - so I can view the Serial Monitor).
One MKR1000 has a potentiometer attached to it (therefore I can change the value of it), and sends the potentiometer value to the serial monitor every 4 seconds.
THE AIM: Once the web server sets up the w
WifFi network, and the web client connects to that WiFi network, I want to send the potentiometer value across to the web client every time it gets updated. However, I am clueless on how to achieve this.
This is my web server void loop code (the rest is similar to the https://www.arduino.cc/en/Tutorial/Wifi101WiFiWebServer):
void loop() {
  WiFiClient client = server.available();
  // listen for incoming clients
  if (client) {
    // if you get a client,
    Serial.println("new client");
    // print a message out the serial port
    String currentLine = "";
    // make a String to hold incoming data from the client
    while (client.connected()) {
      // loop while the client's connected
      if (client.available()) {
        // if there's bytes to read from the client,
        char c = client.read();
        // read a byte, then
        Serial.write(c);
        // print it out the serial monitor
        if (c == '\n') {
          if (currentLine.length() == 0) {
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();
            // the content of the HTTP response follows the header:
            client.print("Click here showValue of the potentiometer
");
            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          } else {
            // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        } else if (c != '\r') {
          currentLine += c;
          // add it to the end of the currentLine
        }
        if (currentLine.endsWith("GET /showValue")) {
          Serial.println(sensorValue);
          delay(2000);
        }
      }
    }
    client.stop();
  }
}

And this is my web client code I use this https://www.arduino.cc/en/Tutorial/Wifi101WiFiWebClient  - I am not sure how I should modify this in order to receive the potentiometer value across from the web server MKR1000. Any tips or hints would be hugely appreciated!
I am sorry if this is a simple question, however I am just starting with the Arduino idea, and I'm new to coding!

At the bottom of the page for the client code link you provided, there's a link to a Chat Server example. If you study the code I think you'll see how to send and receive the potentiometer reading. Hint: Look in the code where it echoes what it receives.
mkr1000 WiFi Chat Server

You don't have to use a webserver/webclient for this; a raw socket would also work. If you do want to use "web technology":
You can either have the webclient poll the webserver periodically for a new value (ask for a new value every few seconds, and interpret the response), or have the webserver initiate the communication every time a new value is available.
For the latter, you could use Server-Sent Events (SSE) or a Websocket, both of which are very google-able.
I have made examples for both, but these examples are fairly large and have extra functionality. Still, they may give you some pointers and/or code to reuse.
These examples are here:
https://github.com/ocrdu/arduino-webinterface-sse
and here:
https://github.com/ocrdu/arduino-webinterface-websocket-ap
Note that the client side in the examples is a webpage in a webbrowser, but the principle is the same.

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


text:
Record Ping time using ultrasonic sensors and calculate speed
I'm trying to find the speed of remote control toy car passing by two ultrasonic sensors. I need help on my code and suggestion on max speed car should go to record time. Opposite direction not accounted for and ideally the car would pass by both sensors without stopping. I know laser reading is better for this simulation but I need it for a presentation in two weeks.
Here are the steps I was recommended to use:

Get the duration of pulse for sensor 1 and convert to distance
if the distance the object is within the desired threshold (you detected something)
2a. record the system time at which object was detected
2b. start a loop to for sensor 2
Within the sensor 2 loop keep getting the duration/distance until an object is detected or too much time has passed
If an object is detected record the system time
Subtract the two system times (from sensor 1 and 2) and use that to determine object speed
#define sensor_distance .111 //distance between two sensors in meters
const int trigPin1 = 3;
const int echoPin1 = 4;
const int trigPin2 = 5;
const int echoPin2 = 6;

double first_time = 0;
double second_time = 0;
double final_time = 0;

double vehicle_speed = 0;

void setup() {

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  Serial.begin(9600);
}

void loop() {

double ping_time(int trig1, int echo1, double first_time);
double ping_time(int trig2, int echo2, double second_time);

final_time = second_time - first_time;
vehicle_speed = sensor_distance/final_time;
}

double ping_time(int trig, int echo, double record_time) //function used to record time.
{
  long duration, distance;

   digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);

  duration = pulseIn(echo, HIGH);
  distance = duration * 0.034 / 2;

  if (distance < 35) {
    Serial.print(distance);
    Serial.println("  cm");
    record_time = millis();
    record_time = record_time/100; //Divided by 100 to get time in seconds

    return record_time;

  }
  if (distance > 35) {
    Serial.println("OUT OF RANGE");
  }
  delay(20);
}

You can try this, but I don't know if this gonna works or not since it is "imaginary-based"
const int trigPin1 = 3;
const int echoPin1 = 4;
const int trigPin2 = 5;
const int echoPin2 = 6;

void setup() {

  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  Serial.begin(9600);
}

void loop()
{
    if (ultraSonicdetect())
    {
        while (ultraSonicdetect(trigPin1,echoPin1)); // wait the car pass ultrasonic 1
        first_time = millis();
        while (!ultraSonicdetect(trigPin2,echoPin2)); //wait the car approach ultrasonic 2
        second_time = millis();

        //here you can calculate the speed, time needed to travel from ultrasonic 1 to ultrasonic 2
        //can be calculated from
        //(speed = second_time - first_time) / sensor range
    }
}

bool ultraSonicdetect(int trig, int echo) {
   long duration;
   float distance;
   digitalWrite(trigPin, LOW);
   delayMicroseconds(60);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(60);
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = (duration * 0.034) / 2;
   if (distance<35) return true; else return false;
}

In THEORY, this code should work. If there are any mistakes, please notify me and not hate on me. I did not have the equipment at hands to test the code in real life.
Chears!
const int trigPins[2] = {3, 5}; //trig1 and trig2
const int echoPins[2] = {4, 6}; //echo1 and echo2

const int sensorDistance = 7;   //7 is the cm distance at which the sensors distant from eachother in CM

void setup() {
  pinMode(trigPins[0], OUTPUT); //set trig pin 1 as output
  pinMode(echoPins[0], INPUT);  //set echo pin 1 as input
  pinMode(trigPins[1], OUTPUT); //set trig pin 2 as output
  pinMode(echoPins[1], INPUT);  //set echo pin 2 as input

  Serial.begin(9600);
}

void loop() {

  if (getDistance(0) == true)                   //if the car passed the first sensor
  {
    unsigned long currentMillis = millis();               //time when the passed the first sensor

    while (getDistance(1) == false);            //wating car to pass the second sensor

    unsigned long endMillis = millis();                   //time at which the car passed the second sensor

    unsigned long timeMillis = endMillis - currentMillis; //get duration in ms
    float timeSeconds = timeMillis / 1000.0;        //because 1000ms = 1s

    float s = sensorDistance / timeSeconds;       //speed = distance / time

    Serial.print(s);
    Serial.print(" cm/s");
    Serial.println();
  }
}

bool getDistance(int sensor)
{
  //max range is 200cm, if further, it will go a little wild

  digitalWrite(trigPins[sensor], LOW); //set the trigger pin to low
  delayMicroseconds(2); //wait for 2 microseconds
  digitalWrite(trigPins[sensor], HIGH); //set the trigger pin to high
  delayMicroseconds(10); //wait for 10 microseconds
  digitalWrite(trigPins[sensor], LOW); //set the trigger pin to low

  long duration = pulseIn(echoPins[sensor], HIGH); //read the echo pin and calculate the duration in microseconds

  long distance = duration * 0.034 / 2;

  if (distance < 50) //50 is a reasonable distance other wise it might be innacurate
  {
    return true;
  }

  else
  {
    return false;
  }

}

So my output has just been 0 cm/s so far. I'm still trying to figure that out. Also, why is your sensor distance zero? Also, how can getDistance() determine which sensor you are using?

I included an input for the sensor. I dont call getDistance(), I have to say getDistance(sensor 0 or 1). 0 is the first sensor and 1 is the second. The reason I do this is to use an array for the pins thus saying which sensor I want.

How far are your sensors from each other??

Replace timeMillis / 1000 with either timeMillis / 1000.0 or timeMillis / 1e3.

the sensors are 7 cm apart from each other. I input 7 for sensorDistance. Now highest reading is 7 cm/s.

New edit to the answer following @EdgarBonet comments, what are the results now?

my results look like:
73.68 cm/s
7000.00 cm/s
777.78 cm/s
7000.00 cm/s
7000.00 cm/s
7000.00 cm/s
7000.00 cm/s
7000.00 cm/s
inf cm/s
I assume the first number is the real speed

What color are the pins of your sensor? are they gold is yellow or more silvery aluminium colored?

silvery aluminum colored

The reason for all the numbers is that when a stationery object is in front of the sensors, it prints out random numbers. I need to fix code to take time of transition recorded.


text:
DHT11 sensor works on Arduino Uno, not on LoLin NodeMcu
When run this code on an Arduino Uno (clone), everything works.
When I run it on my LoLin NodeMcu, I get the following verbose upload output:
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM4
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

The only difference I really see is that on the Arduino Uno, the voltage pin is connected to 5V, while on the LoLin, it's connected to one of the 3V pins. Does the DHT11 require 5V?
Edit
So I stumbled upon this list of port mappings. When I change my pin number to 5 (meaning D1), it actually works. Kinda. The numbers outputted are strange. Even when I put the board outside, in about -6 Celcius, it still displays
Temp 247.208 °C
RH 216.208 %

Well, I guess this oddity should be posted as another question. I'll answer my own question here with reference to the weird pin-to-number mapping on the LoLin board.

The problem is that the code doesn't upload? Try removing all peripherals and uploading a basic, verified to be working sketch

The problem was that the port mappings on the LoLin board didn't make much sense.
Port D0 is for instance mapped to number 16, not 0.
Go to this Github comment to get a complete list:
/*
 * Weird pin mappings on LoLin:
 *
 * static const uint8_t D0   = 16;
 * static const uint8_t D1   = 5;
 * static const uint8_t D2   = 4;
 * static const uint8_t D3   = 0;
 * static const uint8_t D4   = 2;
 * static const uint8_t D5   = 14;
 * static const uint8_t D6   = 12;
 * static const uint8_t D7   = 13;
 * static const uint8_t D8   = 15;
 * static const uint8_t D9   = 3;
 * static const uint8_t D10  = 1;
*/

Missing decimal digits and not able to measure sub zero values
If this comment on github is correct, the DHT11 sensor does not offer decimals and does not measure values below zero.

I was scratching my head since last two days over similar issue. I am using ESP8266 NodeMCU which is V2 of LoLin NodeMCU and wanted to read DHT11 sensor data over WiFi into blynk app. However my serial output was 'Failed to read from DHT sensor!'. The program and interfacing was working perfectly with Arduin Uno and Raspberry Pi but not with NodeMCU.
Being a hardware guy, I tried all sorts of hardware modification possible. I had DHT11 sensor module which is already having 5k pull up resistors on board. Since NodeMCU board doesn't have 5V supply, I desoldered the sensor and did direct interfacing with 10k resistor as recommended by adafruit DHTxx guide. Doing internet search , someone recommended IDE version issue, tried that too. Nothing worked.
Finally referring per @nitech answer, I checked the pin details of NodeMCU board and got the idea of D2 pin actual mapped on GPIO4. Just changed the pin 2 with 4 in example code and it worked. Voila! I think recent race in achieving most of the boards as Arduino shield and IDE standard compatible, we need to be used for such issues for any deviation.

Glad my experience could help you.

The datasheet says 3V-5V. 3V is the minimum so I DOUBT that isn't the problem, BUT try to pump more juice into it to see what happens. Never believe the datasheet if these cheap components at 100%.
It does say this though:

VDD=5V, T = 25℃ (unless otherwise stated)

So maybe....
Link to datasheet.

Check out my edit - does it shed light?

Well check the pin out of your circuit a second time.... I dont know...

Sorry, didn't quite understand what you meant there. The signal pin of the sensor is connected to D1 on the LoLin board, and in the code, I write int DHpin = 5;

Please post a circuit schematic

Btw: More juice into it? I don't understand. I'm quite newbie in electronics. Are you talking about the sensor or the board? the board gets power from the USB-connection and as far as I can see, the board doesn't have any other than 3V outputs.

Hm, okay. It seems that the VU pin might output 5V.


text:
WaveHC Library Trouble
I posted this on the main Arduino forum, but no one has responded in 24 hours.
I'm trying to use the WaveHC library from Adafruit with a custom PCB. I am having trouble getting the SPI com to work for some reason, I modified the ArduinoPins.h, SS_PIN, from pin 10 to 8.
Using the Arduino SD library, I can see all the files no problem.
In the WaveHC library, all of the examples freeze after card.init(), I traced it to the spiSend(uint8_t b) in SdReader.cpp. It seems to get stuck in while(!(SPSR & (1 << SPIF)). This looks like the SPDR register (the SPI data register) is never loaded properly.
Does anyone know what is going on?
Adafruit library : https://github.com/adafruit/WaveHC
Edit :
This is the output from the SDReadTest example (Arduino SD Library)
Initializing SD card...Wiring is correct and a card is present.

Card type: SD2

Volume type is FAT32

Volume size (bytes): 1973350400
Volume size (Kbytes): 1927100
Volume size (Mbytes): 1881

Files found on the card (name, date and size in bytes):
SYSTEM~1/     2016-11-07 14:11:06
  INDEXE~1      2016-11-07 14:11:06 76
0.WAV         2016-11-07 11:44:14 22124
1.WAV         2016-11-07 11:44:14 18604
2.WAV         2016-11-07 11:44:14 19244
3.WAV         2016-11-07 11:44:14 19884
4.WAV         2016-11-07 11:44:14 21164
5.WAV         2016-11-07 11:44:14 23084
6.WAV         2016-11-07 11:44:14 21484
7.WAV         2016-11-07 11:44:14 29484
8.WAV         2016-11-07 11:44:14 20844
9.WAV         2016-11-07 11:44:14 25004
P.WAV         2016-11-07 11:44:14 21804

Notes :

I am using an Atmega328P @ 8MHz with the pro mini bootloader (this may be the issue)
SPI_DEFAULT_HALF_SPEED is set to true
SPI_INIT_SLOW is set to 1

Please post both code and circuit schematic.

I have tried all the examples in their repository https://github.com/adafruit/WaveHC. A schematic is unnecessary, I have verified my connections by testing my board with the arduino SD library.

Please edit your question to include a link to your Arduino forum post. Try setting the pinMode of SS pin of your microcontroller(10 on ATmega328P, 53 on ATmega2560) to OUTPUT in your setup() function. Even though you can use any pin to control the SS pin of the SD card, you need to sure the microcontroller's SS pin doesn't go low while using SPI, otherwise it goes into slave mode. Other useful information would be which microcontroller you're using and whether you've tried using the WaveHC library with SS on pin 10.

The arduino post is copy and paste...and still no one has responded. The pinMode for the SS pin is in the init method in SdReader.cpp, also I already tried adding in another pinMode in the setup. I'm using the Atmega328P 8Mhz. I can't try to use pin 10 because it is a smd custom PCB.

Have you tried the suggestions in the WaveHC readme?

Yes, I have tried all the suggestions in the readme

Just noticed that if the SS_PIN is left as 10 (as default, but not connected to anything in my case), I immediately get an error code, when I set it to 9 (not connected to anything either), it gets stuck in the while(!(SPSR & (1 << SPIF)) just like when it is set to 8 (which is the correct SS_PIN)

It seems that something is happening in the library that only allow SS to be 10, but I can't find where that is.. EDIT: Just thought that maybe there is a timing thing that depends on a 16Mhz clock

Just ran my board at 16MHz (@3.3V, don't yell at me, I know it's unstable) and it does the same thing, so I'm kind of ruling out the clock frequency being the issue.

Alrighty, found an SD breakout with a buffer and tested it with an Arduino Uno, and it works with pin 10 but not with pin 8 (whereas the official SD library works with both pins). So it looks like there is something in the library preventing the SS from being changed....

So the problem was that I did not read this comment carefully
/** SPI slave select pin. Warning: SS may be redefined as another pin
but the hardware SS_PIN must be set to output mode before any calls to
WaveHC functions. The SS_PIN can then be used as a general output pin */

"SS_PIN must be set to output mode before any calls to
WaveHC functions"
I read this and thought that meant whatever pin was being used as the SS pin needed to be an output, but it meant literally that pin 10 (the hardware SS pin) had to be set as an output regardless of whether it was being used or not.
So the solution is to add
pinMode(10, OUTPUT);

to anywhere in the code
Edit : also thanks @per1234 for pointing out the correct answer, I just didn't read your comment properly.

Glad to hear you found the solution! Please update your post on the Arduino forum with a link to this page so that people there will know you no longer need assistance. This will also help anyone with the same problem who finds your post there to be led to the answer.


text:
Sim900 error on AT command AT+HTTPINIT
I want to send data to my php server using sim900 module but I am unable to initialize http service on sim900.
code:
#include <SoftwareSerial.h>
SoftwareSerial gprsSerial(8, 9);

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

  Serial.println("Con");
  delay(2000);
  Serial.println("Done!...");
  gprsSerial.flush();
  Serial.flush();

  // See if the SIM900 is ready
  gprsSerial.println("AT");
  delay(1000);
  toSerial();

  // SIM card inserted and unlocked?
  gprsSerial.println("AT+CPIN?");
  delay(1000);
  toSerial();

  // Is the SIM card registered?
  gprsSerial.println("AT+CREG?");
  delay(1000);
  toSerial();

  // Is GPRS attached?
  gprsSerial.println("AT+CGATT?");
  delay(1000);
  toSerial();

  // Check signal strength
  gprsSerial.println("AT+CSQ ");
  delay(1000);
  toSerial();

  // Set connection type to GPRS
  gprsSerial.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
  delay(2000);
  toSerial();

  // Set the APN
  gprsSerial.println("AT+SAPBR=3,1,\"APN\",\"web\"");
  delay(2000);
  toSerial();

  // Enable GPRS
  gprsSerial.println("AT+SAPBR=1,1");
  delay(10000);
  toSerial();

  // Check to see if connection is correct and get your IP address
  gprsSerial.println("AT+SAPBR=2,1");
  delay(2000);
  toSerial();

}

void loop()
{
   // initialize http service
   gprsSerial.println("AT+HTTPINIT");
   delay(2000);
   toSerial();

   // set http param value
   // ToDO : send dynamic value
   gprsSerial.println("AT+HTTPPARA=\"URL\",\"http://www.fohoraayo.000webhostapp.com/?lat=1111&lon=1111\"");
   delay(4000);
   toSerial();

   // set http action type 0 = GET, 1 = POST, 2 = HEAD
   gprsSerial.println("AT+HTTPACTION=0");
   delay(6000);
   toSerial();

   // read server response
   gprsSerial.println("AT+HTTPREAD");
   delay(1000);
   toSerial();

   //gprsSerial.println("");
   gprsSerial.println("AT+HTTPTERM");
   toSerial();
   delay(300);

   gprsSerial.println("");
   delay(10000);
}

void toSerial()
{
  while(gprsSerial.available()!=0)
  {
    Serial.write(gprsSerial.read());
  }
}

output:
Config SIM900...
Done!...
AT

OK
AT+CPIN?

+CPIN: READY

OK
AT+CREG?

+CREG: 0,1

OK
AT+CGATT?

+CGATT: 1

OK
AT+CSQ

+CSQ: 31,0

OK
AT+SAPBR=3,1,"Contype","GPRS"

OK
AT+SAPBR=3,1,"APN","web"

OK
AT+SAPBR=1,1

ERROR
AT+SAPBR=2,1

+SAPBR: 1,1,"xx.xxx.x.x"

OK
AT+HTTPINIT

ERROR
AT+HTTPPARA="URL","http://www.fohoraayo.000webhostapp.com/?lat=AT+HTTPACTION=0

ERROR
AT+HTTPREAD

ERROR
AT+HTTPTERM

ERROR

Use this command "AT+CMEE=2\r // Enable +CME ERROR: <err> result code and use verbose <err> values so your module won't response with a simple "ERROR" string but will tell what is the exact problem. Save this parameter with AT&W\r command.

List of possible errors:http://www.micromedia-int.com/en/gsm-2/73-gsm/669-cme-error-gsm-equipment-related-errors with AT+CMEE=2\rthe module should return the error description string.

AT+SAPBR=1,1  this command responds with
+CME ERROR: operation not allowed and after restarting the gsm module i get ERROR after AT+HTTPINIT

When you reset the AT+CMEE=2 setting lost, you have to enable it after every reset or power on or save the setting with AT&W command

What does AT+HTTPINIT returns if you set AT+CMEE=2 before?

It returns ERROR.

http://www.seeedstudio.com/forum/viewtopic.php?p=20195 try this before AT+SAPBR=1,1.

Finally I got it! My sim900 module doesnot supports HTTP.

You can try to use the TCP/IP commands to make a connection and just send a HTTP string along.

For me, your code is working like charm. but change the
gprsSerial.begin(9600)

to
gprsSerial.begin(4800)


text:
Atmega boot loading UART or SPI
I have an Atmega 328 chip and want to load the Arduino boot loader to the chip. I have planned to use a SPI protocol to do this, but I have read other posts saying that they have done similar using an UART with using an FTDI chip. I have planned to use the FTDI to support USB.
I did rad some information that said that loading the boot loader through UART is very slow.
Which is best? I would like to save space, if I do not need a SPI header then I would like to remove this. Is what I have read correct?
Thanks

I have read other posts saying that they have done similar using an UART with using an FTDI chip.

You have probably misread something. A brand-new, blank ATmega328 can only be programmed over SPI, or via parallel programming (more pins). There is no "native" UART bootloader.
It's possible to use certain FTDI chips to bit-bang the SPI programming interface. This is probably what the posts you're reading are referring to. As the post suggests, though, this is slower than using a programmer which directly supports the SPI interface, and is only really suitable if you don't have a better programmer available.
If space is a concern, one option to consider may be to provide the ISP port as a set of test points and use pogo pins to access it during manufacturing. You can lay out the test points however you want, possibly at a finer pitch than the 100 mil header you're probably used to.
Depending on your manufacturing process, another approach may be to program the chip before mounting it to the board.

Loading via UART is not so bad if you configure the bootloader to use a reasonable baud rate (say, 115200 instead of the default 9600). However, you do have to get the bootloader onto the chip in the first place, and that has to be done with SPI.

But if you do have SPI then you don't need the bootloader, not even for Arduino code.

True, but the bootloader could theoretically be loaded before soldering the chip or via pogo pins on test points, alleviating the need for a bulky ISP header while enabling simple firmware updates via UART.


text:
Controlling 20 servo motors independently with a single Arduino
I am wondering if I can control 20 different servo motors with only a single Arduino Uno board. My motors must be able to rotate in both directions and I also should be able to define the speed for each of them independently. Also I am able to use integrated circuits or a device that connects to my Arduino board.
Is this a possible scenario?

Surely you can implement it using shift registers to effectively increase your pin count?

@Makoto Will I be able to control any of my pins independently  using shift registers ? Lets say I want 2,7 and 16th pin to be high and others low. Will I be able to do this ? It always confuses me to be able to do these kind of things with only controlling couple pins.

Yes, shift registers usually have a memory stage and an output stage. You can shift the levels you want in to the memory and then latch all of them to the output at the same time. You can also do this fast enough to pwm each pin independently

You may modify Servo.h with #define SERVOS_PER_TIMER 20 and attach a servo to every single pin of your Uno – which may give slightly jerky movements due to the high CPU load. Or you may use another chip just to drive the servos. Or you could use another Arduino/ATmega/ATtiny and volunteer to test my Tiny Servo Controller program.

You could use GPIO expanders like the MCP23008. Very easy to use over an I2C bus and you can have 4 of them per bus, or you could use the 16 bit version.


text:
Multiple If Conditions Arduino
I have a project which requires me to read if the input is "HIGH".
I have 15 inputs (switches), and each input has its own output (LED). I am using a Shift Register to control its inputs and outputs.
My current code looks like this (4 inputs and 4 outputs, it works though...):
#include "SPI.h"
#include "MFRC522.h"
#include "rgb_lcd.h"
#include <Wire.h>

#define SS_PIN 17
#define RST_PIN 7

int counter = 0;
int lock = 100;

MFRC522 rfid(SS_PIN, RST_PIN);
rgb_lcd lcd;
MFRC522::MIFARE_Key key;

// Define Pins
int SHIFTIN_LATCH = 22;
int SHIFTIN_DATA = 23;
int SHIFTIN_CLOCK = 21;
int numberToDisplay = 0;

#define SHIFTOUT_DATA  18
#define SHIFTOUT_LATCH  19
#define SHIFTOUT_CLOCK  20

//Define variables to hold the data
//for each shift register.
//starting with non-zero numbers can help
//troubleshoot
byte keySlotID[15] = {
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
byte keyInsert[15] = {
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
byte keyReg[10] = {
  0,0,0,0,0,0,0,0,0,0}; // amt of reg.

void setup() {
  //start serial
  Serial.begin(9600);

  //define pin modes
  pinMode(SHIFTIN_LATCH, OUTPUT);
  pinMode(SHIFTIN_CLOCK, OUTPUT);
  pinMode(SHIFTIN_DATA, INPUT);

  pinMode(SHIFTOUT_DATA, OUTPUT);
  pinMode(SHIFTOUT_LATCH, OUTPUT);
  pinMode(SHIFTOUT_CLOCK, OUTPUT);
  Serial.begin(9600);
  SPI.begin();
  rfid.PCD_Init();
  lcd.begin(16, 2);
}

void KeyID(){
  // Key slot indicator.
  keySlotID[0] = (keyReg[0] & 0x1E) >> 1;
  keySlotID[1] = (((keyReg[1] & 0x03) << 3) | ((keyReg[0] & 0xE0) >> 5)) >> 1;
  keySlotID[2] = (keyReg[1] & 0x78) >> 3;
  keySlotID[3] = (keyReg[2] & 0x0F);
  // Key inserted indicator.
  keyInsert[0] = (keyReg[0] & 0x01);
  keyInsert[1] = (keyReg[0] & 0x20) >> 5;
  keyInsert[2] = (keyReg[1] & 0x04) >> 2; // X
  keyInsert[3] = (keyReg[1] & 0x80) >> 7; // X
}

void registerWrite(byte data1, byte data2) {
  digitalWrite(SHIFTOUT_LATCH, LOW);
  delay(10);
  shiftOut(SHIFTOUT_DATA, SHIFTOUT_CLOCK, MSBFIRST, data2);
  shiftOut(SHIFTOUT_DATA, SHIFTOUT_CLOCK, MSBFIRST, data1);
  digitalWrite(SHIFTOUT_LATCH, HIGH);
  delay(10);
}

void LedIFs() {

  if (keyInsert[0] == 0 && keyInsert[1] == 0 && keyInsert[2] == 0 && keyInsert[3] == 0) {
    registerWrite(0xFF,0);
  }
  else if (keyInsert[0] == 0 && keyInsert[1] == 0 && keyInsert[2] == 0 && keyInsert[3] == 1) {
    registerWrite(0x40,0);
  }
  else if (keyInsert[0] == 0 && keyInsert[1] == 0 && keyInsert[2] == 1 && keyInsert[3] == 0) {
    registerWrite(0x10,0);
  }
  else if (keyInsert[0] == 0 && keyInsert[1] == 0 && keyInsert[2] == 1 && keyInsert[3] == 1) {
    registerWrite(0x50,0);
  }
  else if (keyInsert[0] == 0 && keyInsert[1] == 1 && keyInsert[2] == 0 && keyInsert[3] == 0) {
    registerWrite(0x04,0);
  }
  else if (keyInsert[0] == 0 && keyInsert[1] == 1 && keyInsert[2] == 0 && keyInsert[3] == 1) {
    registerWrite(0x44,0);
  }
  else if (keyInsert[0] == 0 && keyInsert[1] == 1 && keyInsert[2] == 1 && keyInsert[3] == 0) {
    registerWrite(0x14,0);
  }
  else if (keyInsert[0] == 0 && keyInsert[1] == 1 && keyInsert[2] == 1 && keyInsert[3] == 1) {
    registerWrite(0x54,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 0 && keyInsert[2] == 0 && keyInsert[3] == 0) {
    registerWrite(0x01,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 0 && keyInsert[2] == 0 && keyInsert[3] == 1) {
    registerWrite(0x41,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 0 && keyInsert[2] == 1 && keyInsert[3] == 0) {
    registerWrite(0x11,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 0 && keyInsert[2] == 1 && keyInsert[3] == 1) {
    registerWrite(0x51,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 1 && keyInsert[2] == 0 && keyInsert[3] == 0) {
    registerWrite(0x05,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 1 && keyInsert[2] == 0 && keyInsert[3] == 1) {
    registerWrite(0x45,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 1 && keyInsert[2] == 1 && keyInsert[3] == 0) {
    registerWrite(0x15,0);
  }
  else if (keyInsert[0] == 1 && keyInsert[1] == 1 && keyInsert[2] == 1 && keyInsert[3] == 1) {
    registerWrite(0x55,0);
  }
}

void loop() {

  //Pulse the latch pin:
  //set it to 1 to collect parallel data
  digitalWrite(SHIFTIN_LATCH,1);
  //set it to 1 to collect parallel data, wait
  delay(1);
  //set it to 0 to transmit data serially
  digitalWrite(SHIFTIN_LATCH,0);

  //while the shift register is in serial mode
  //collect each shift register into a byte
  //the register attached to the chip comes in first
  keyReg[0] = ~shiftIn(SHIFTIN_DATA, SHIFTIN_CLOCK);
  keyReg[1] = ~shiftIn(SHIFTIN_DATA, SHIFTIN_CLOCK);
  keyReg[2] = ~shiftIn(SHIFTIN_DATA, SHIFTIN_CLOCK);

  LedIFs();
  KeyID();
}

The problem I'm facing is that it would be too long for me to write down 15 KeyInserts. That would mean I have to write about or close to 200,000 lines of code...

some code wasn't added as it is of no relations to this part of the code.

What are you trying to do EXACTLY?

Just Read the Inputs and if the input is high, output is high. It would've been easier if i don't need to use a shift register but i have to , to save pins. Im currently doing a project, a 15 lock project.

Can you please add your circuit diagram.

Could you please describe KeyInsert, KeyReg and KeySlotID.

Key insert is the switch. KeyReg is thE SHIFTIN register. Key Slot ID is smtg unrelated, you can just ignore that.

May I respectfully suggest you read up on how to write loops? This should be achievable in a dozen lines of code.

If each input represents a single bit in the output then it's about 3 lines: uint16 output=0; for (int i=0;i<16;i++) output |= keyInsert[i]<<i;

Let's assume value that will be stored into "keyInsert" are either "1" or "0". Therefore, its a waste to declare them as an array byte
byte keyInsert[15] = {
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

It means that you will have 15 * 8 bytes variable, and its overkill.
it will be much simpler if you declare it as
uint16_t keyInsert;

Which have 16 bits data (2 bytes).
in your code, you can implement it by doing
void LedIFs() {
if (keyInsert == 0x0001) registerWrite(0xFF,0); else
if (keyInsert == 0x0002) registerWrite(......)......
......
}

I will be using digitalReads and digitalWrites but just follow this logic:
int state[num_of_switch_that_you_have];

for(int i=0; i<num_of_switch_that_you_have; i++)
{
  //buttonPins is the pin to which all your buttons are connected to in an array
  state[i] = digitalRead(buttonPins[i]);

  //leds is the pin to which all your leds are connected to in an array
  digitalWrite(leds[i], state[i]);
}

Try to follow this logic while using your shift registers. Sorry if I don't have a full code with shift registers for you, I'm not really good with them!
If you need any more details, please comment, I'll be happy to help!

I can't quite get the logic of your keyInsert[] array. Why don't you
use a binary number (e.g. uint16_t, which is 16 bits) instead of an
array of zeros and ones? Also, half of the lines of the output shift
register seem essentially unused.
If I understand correctly, you want to simplify LedIFs() in order to
handle many bits with few lines of code. Examining your current
implementation, it appears that you are writing to the output register
the very same bits you have in keyInsert[], only in different
positions. Instead of testing every possible combination, it would be
much simpler to just move the bits into their appropriate positions:

keyInsert[0] becomes bit 0 (i.e. least significant) of the first
argument of registerWrite()
keyInsert[1] becomes bit 2 (it's weight is 22 = 0x04)
keyInsert[2] is bit 4 (weight: 24 = 0x10)
keyInsert[3] is bit 6 (weight: 26 = 0x40)

This is done using bit shifts, and joining the bits with the |
bitwise-or operator:
void LedIFs() {
    byte val = keyInsert[0] << 0
             | keyInsert[1] << 2
             | keyInsert[2] << 4
             | keyInsert[3] << 6;
    if (val == 0) val = 0xff;
    registerWrite(val, 0);
}

Notice that << 0 has no effect: it is here only because it looks nicer
(more symmetric, easier to read) this way. The compiler will optimize
out this operation anyway. Also, the case when all the bits are zero is
special, since you are writing 0xff instead of zero.
If I were you, what I would do is store the information in keyInsert[]
as a single number with the bits already at their correct position. Then
I would write
uint16_t keyInsert;

//...

static inline void LedIFs() {
    registerWrite(keyInsert ? keyInsert : 0xff, 0);
}


text:
Firmware update for remote situations
We are currently deploying units with the ATMEGA328 chip. Currently, all ICs have been flashed using the Arduino IDE. Upon release, we would like to offer updating of firmware in some cases, but obviously we would not want to send them the source code and let them download the arduino IDE.
We would like to send a firmware file, and an .exe file like a firmware upgrader, as most companies do. How would I start to go about this?

Send them avrdude (including the config file) and the hex file. Look at the commands the IDE runs to see the right command format. You can then put that into a batch file if you like.


text:
How to connect GPS Neo-6M module to GSM Shield SIM900 V2?
I'm doing my final year project, My project is based on "Arduino Real Time Gprs/Gsm & GPS Tracker". So Now I have purchased the hardware components such as:

Arduino UNO R3
GSM Shield SIM900 V2.0
Ublox GPS Neo - 6M Module

I'm a begginer to this project, I have a doubt connecting these components together. I have stack the GSM Shield with the Arduino Uno but I don't know how to connect the GPS module to the GSM Shield (How to wire the components). because as you see my pic you might see on the top of the GSM shield there are no female headers except one which comes for the display.

So do I need to implement a female header on the GSM Shield and solder it to conncet the GPS module?

Can't I connect the GPS module to the GSM Shield's UART Pins?
Please Help me Guys :)

For your program, I'll highly suggest to use softwareSerial. It pretty much emulates the serial communication on other pins (NOT PIN 0 & 1). Then connect it like if you would normaly connect an UART device to your Arduino on the 2 other pins that you chose (NOT PIN 0 & 1). This should make it easy to prorgam your Arduino while having the GPS and GSM module connected to your Arduino.
The shield can cause problems if it uses Tx and Rx on pins 0 & 1, WHICH ARE THE PINS NOT TO USE IF YOU USE SOFTWARE SERIAL, so you might as well connect it with jumper wires. Take the TXs from both of your module and connected to whatever GPIO you want and do the same to the RXs, NOT ON PIN 0 & 1.
Once again, softwareSerial is NOT ON PIN 0 & 1.


text:
Is my Arduino possibly broken?
We work in groups on a project at school. We had to build an electric scheme with an Arduino to make a small car moving.
We got the parts from our school, except the Arduino (we had to buy it ourselves). We had to use a battery of 11.5 V. We also had electrical resistors to protect the Arduino and the stepper drivers.
The car worked for a while, but then we wanted to change the program and tried to upload new software to the Arduino. Now the Arduino is not recognized by any computer.
We tried several things, like multiple times unplugging the USB cable, hitting the reset button on a specific timed moment (some method found on the internet).
But it still doesn't work. When the Arduino is connected via USB, the 'on' LED on the Arduino is on. After that all we came also to the conclusion that some people made mistakes on building the electric scheme...

Is it possible that the Arduino is broken, since the battery has 11.5 V?
If the Arduino isn't broken, can the problem that it's not recognized by the computer be solved?

(Arduino Uno)

You can read 10 Ways to Destroy An Arduino, it might help you to find out what did you do. BTW, there is even possibility to destroy USB port, are you sure it's still working?

Without knowing what you did with your sheme or your "electrical resistors" it's impossible to tell. Some pictures and schematics would be useful.

you can get a working Arduino uno online for 5$ on ebay. think of that it's about 7 for the price of one!

This question appears to have been abandoned after being asked. You may get help from Have I bricked my Arduino Uno? Problems with uploading to board. If there is no response I'll close this question. There is no point asking questions and then not responding to queries. We had to use a battery of 11.5 V. We also had electrical resistors to protect the Arduino and the stepper drivers. - that is very unclear.

Considering that you used resistors to lower the 11.5V to an cough - cough "very normal and regulated 5V", that most certainly is the problem.
The "right and cheap" way to lower such high voltage and connect them directly to your 5V (just assuming, since you said that you used resistors to protect the Arduino) is actually to use a voltage regulator. Any cheap 7805 should do the job. The Arduino actually has its own voltage regulator on it, if you connect it though the Vin pin.
The "true and efficient" way to step down some voltage is actually to use a step-down converter. The way this is better then any normal regulator is that a regulator will lower your voltage by creating heat when the step-down converter will do it in a more efficient process.
The USB of your PC might also be the problem. There is a fuse on the Arduino and one in almost all USB ports of decent PCs. If the voltage spike is high enough, it might have burned the port. That is quite a rare event, but still possible.
Need anymore help, just comment. I'll be happy to help you!

If you connect 11.5V directly to the Arduino then you might have killed you Arduino, BUT you say the LED comes up when you hook up the USB lead.  So take things one step at a time.

Get an Arduino that you know is working and try it in the PC with the same cable.  Does it work?  (No -> Cable or PC is broken - Get a new cable/PC)
Remove all wires, shields, etc. from your Arduino.
Connect the USB cable to the PC, does the Arduino power up? (No -> Arduino is almost certainly dead)
Does the PC recognise the board? (Window -> Beeps, tries to download drivers, etc.) (No-> Manually uninstall the drivers and then repeat this step if it doesn't succeed then the Arduino is very unwell)
Start the Arduino IDE and open Examples->Basic->Blink.  Upload the program to your board.  Does it work? (No -> You need more advanced fault finding)
Change Blink so it prints a message every time the loop, Serial.println("Hello"); will do.
Upload you modified program and open the serial monitor.  Does it show the message?  (No -> You need more advanced fault finding)

I know this doesn't fix the problem, but hopefully this will help you narrow down the fault.
My gut feeling is that your Arduino has executed its last lines of code, but you never know...


text:
Arduino SSCANF stop on comma delimiter
I have the following problem, the arduino is receiving a command like
LCD,Display line text one, Display line text two
I use an strcmp to match the beginning of the string that works but now I would like to ignore the beginning of the string (LCD) and scan in the next 2 variables until the comma to 2 new variables.
                sscanf(Command, "%[^,]%[^,]%[^,]", &dummy, &lcd_display_l1, &lcd_display_l2);

I don't know if it's possible to ignore the first variable (which would be the LCD) but I setup a dummy variable for it anyway what I not going to use.
All I get with this is the LCD in the dummy the other 2 does not fill up.
I have tried this syntax:
https://support.microsoft.com/en-us/kb/38335
Doesn't work either. Any ideas?

Try "%*[^,],%[^,],%[^,]". The asterisk is for ignoring the field.

I would suggest using strtok() to chop the string up:
char *prefix = strtok(mystring, ",");
char *firstString = strtok(NULL, ",");
char *secondString = strtok(NULL, ",");

That has the effect of slicing the existing string up in memory replacing the commas with \0 and placing three pointers at the start of the three substrings. It has the advantage that it doesn't need to copy the contents of the string anywhere, so doesn't use any extra memory (other than the few bytes for the pointers).


text:
Entering integers as bytes in serial monitor
I am doing some byte manipulation in Arduino, but when I enter an integer into the serial monitor, such as 1, and my program stores it as byte incomingByte, the value stored in incomingByte is 49 and not 1. How do I enter the ASCII equivalent of an integer?

The serial monitor is meant to let you enter text, not arbitrary binary data. You can parse the text into numbers in the Arduino.

You can convert it in your program. For a single digit you can easily convert using value = incomingByte - '0'; For multiple digits you need to separate the ascii out into digits, subtract 48 ('0' is a simple way to do that without having to remember the ascii value of 0)  and then add them together with the appropriate *10^n scale factors.

Using the Arduino IDE Serial Monitor, there's not much you can do. But you can use a different serial-port terminal such as RealTerm (for Windows, if that's your thing) which allows for a wide array of serial port nitty-gritty details.

Check out the ASCII table.
When you enter 1 into the Serial Monitor you are telling it to send the (ASCII) character 1 - which is represented by the decimal value 49, so the byte that is sent is 49.
I don't believe it is possible to enter the decimal value 1 into the Serial Monitor (you'd have to find some way of entering SOH via the keyboard), so the only option is to recognize and accommodate that on the Arduino end.
The usual way to do this is to subtract 48 from the received value. However this is typically written as - '0' which is actually subtract the ASCII value of 0 (this helps indicate that you converting from ASCII)
So...
int intVal = incomingByte -'0';
... should work fine for you if you are receiving single digit integers.
However, if you also want to accommodate multi digit integers (e.g. 123) then it becomes more complex requiring converting each byte to it's integer equivalent and then multiplying it by 10 to the power of it's position/column...
123 = (1 * 10^2) + (2 * 10^1) + (3 * 10^0)
This is a fun little coding task in itself, but if you're not into that kind of thing then parseInt('123'); will get you going faster...

You can do this little trick:
void loop()
{
while (Serial.available() == 0); //waiting for input
int val = Serial.parseInt(); //read as integer
}


text:
Error: Expected primary-expression before void
We have been working on this "disaster bot" code for days and hours. AFter all of our hard work, Arduino gives us this error code: expected primary-expression before void. Please please please assist we are so desperate to get this to work. Here is our code below. Please.
// HEARTBEAT SENSOR (displays heart rate on LCD screen)
int sensorPin = A0; // This is the analog sensor pin the backwards S pin is connected to
                           // you can use any of the analog pins, but would need to change this to match
double alpha = 0.75; // This code uses a rather cool way of averaging the values, using 75% of the
                               // average of the previous values and 25% of the current value.
int period = 20; // This is how long the code delays in milliseconds between readings (20 mSec)
int in = 8;
int Reset=6;
int start=7;
int count=0,i=0,k=0,rate=0;

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

// BIG SOUND SENSOR
int soundDetectedPin = 10;
int soundDetectedVal = HIGH;
boolean bAlarm = false;

unsigned long lastSoundDetectTime;

int soundAlarmTime = 500;

// PUSH BUTTON AND BUZZER
int buzzer = 3;
int ledPin = 13;
int inPin = 7;
int val = 0;

#define sing

#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
#define NOTE_D1  37
#define NOTE_DS1 39
#define NOTE_E1  41
#define NOTE_F1  44
#define NOTE_FS1 46
#define NOTE_G1  49
#define NOTE_GS1 52
#define NOTE_A1  55
#define NOTE_AS1 58
#define NOTE_B1  62
#define NOTE_C2  65
#define NOTE_CS2 69
#define NOTE_D2  73
#define NOTE_DS2 78
#define NOTE_E2  82
#define NOTE_F2  87
#define NOTE_FS2 93
#define NOTE_G2  98
#define NOTE_GS2 104
#define NOTE_A2  110
#define NOTE_AS2 117
#define NOTE_B2  123
#define NOTE_C3  131
#define NOTE_CS3 139
#define NOTE_D3  147
#define NOTE_DS3 156
#define NOTE_E3  165
#define NOTE_F3  175
#define NOTE_FS3 185
#define NOTE_G3  196
#define NOTE_GS3 208
#define NOTE_A3  220
#define NOTE_AS3 233
#define NOTE_B3  247
#define NOTE_C4  262
#define NOTE_CS4 277
#define NOTE_D4  294
#define NOTE_DS4 311
#define NOTE_E4  330
#define NOTE_F4  349
#define NOTE_FS4 370
#define NOTE_G4  392
#define NOTE_GS4 415
#define NOTE_A4  440
#define NOTE_AS4 466
#define NOTE_B4  494
#define NOTE_C5  523
#define NOTE_CS5 554
#define NOTE_D5  587
#define NOTE_DS5 622
#define NOTE_E5  659
#define NOTE_F5  698
#define NOTE_FS5 740
#define NOTE_G5  784
#define NOTE_GS5 831
#define NOTE_A5  880
#define NOTE_AS5 932
#define NOTE_B5  988
#define NOTE_C6  1047
#define NOTE_CS6 1109
#define NOTE_D6  1175
#define NOTE_DS6 1245
#define NOTE_E6  1319
#define NOTE_F6  1397
#define NOTE_FS6 1480
#define NOTE_G6  1568
#define NOTE_GS6 1661
#define NOTE_A6  1760
#define NOTE_AS6 1865
#define NOTE_B6  1976
#define NOTE_C7  2093
#define NOTE_CS7 2217
#define NOTE_D7  2349
#define NOTE_DS7 2489
#define NOTE_E7  2637
#define NOTE_F7  2794
#define NOTE_FS7 2960
#define NOTE_G7  3136
#define NOTE_GS7 3322
#define NOTE_A7  3520
#define NOTE_AS7 3729
#define NOTE_B7  3951
#define NOTE_C8  4186
#define NOTE_CS8 4435
#define NOTE_D8  4699
#define NOTE_DS8 4978

#define melodyPin 3
//Hotline Bling Melody
int hotlineb_melody[] = {
  0, NOTE_D5, NOTE_D5, NOTE_D5,
  NOTE_F5, NOTE_E5, NOTE_D5, NOTE_C5,
  NOTE_E5, NOTE_C5, 0,  NOTE_F5,
  NOTE_E5, NOTE_D5, NOTE_C5, NOTE_E5,

  NOTE_C5, NOTE_A4, NOTE_F5, NOTE_E5,
  NOTE_D5, NOTE_C5, NOTE_E5, NOTE_C5,
  0, NOTE_F5, NOTE_E5, NOTE_D5,
  NOTE_C5, NOTE_E5, NOTE_C5, NOTE_A4,

  NOTE_F5, NOTE_C6, NOTE_C6,
  NOTE_C6, NOTE_A5, NOTE_C6, NOTE_C6,
  NOTE_D6, 0, NOTE_F5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,

  NOTE_A5, 0, NOTE_C6, NOTE_C6,
  NOTE_C6, NOTE_A5, NOTE_C6, NOTE_C6,
  NOTE_D6, 0, NOTE_F5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,

  NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,
  NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,
  NOTE_A5, NOTE_D6, NOTE_A5, NOTE_A5,
  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,

  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
  NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5,
  NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5,
  NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5,

  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
  NOTE_F5, NOTE_C6, NOTE_A5, NOTE_C6,
  NOTE_A5, NOTE_C6, NOTE_A5, NOTE_C6,

  NOTE_A5, NOTE_D6, NOTE_A5, NOTE_A5,
  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_G5,
  NOTE_A5, NOTE_A5, NOTE_A5, NOTE_A5,

  NOTE_AS5, NOTE_A5, NOTE_G5, NOTE_F5,
  NOTE_G5, NOTE_G5, NOTE_A5, NOTE_A5,
  NOTE_A5, NOTE_A5, NOTE_AS5, NOTE_A5,
  NOTE_G5, NOTE_F5, NOTE_G5, NOTE_A5, NOTE_G5
};

//HotlineBLING tempo
  int hotlineb_tempo[] = {
  12, 12, 12, 12,
  12, 12, 12, 12,
  6, 2, 3, 12,
  12, 12, 12, 3,

  3, 3, 12, 12,
  12, 12, 6, 2,
  3, 12, 12, 12,
  12, 3, 3, 4,

  12, 12, 12,
  12, 12, 12, 12,
  2, 3, 12, 12,
  12, 12, 12, 12,

  2, 3, 12, 12,
  12, 12, 12, 12,
  3, 3, 12, 12,
  12, 12, 12, 12,

  2, 12, 12, 12,
  12, 12, 12, 12,
  12, 1.5, 12, 12,
  12, 12, 12, 12,

  12, 12, 6, 2,
  12, 12, 12, 12,
  12, 12, 12, 12,
  6, 2, 12, 12,

  12, 12, 12, 12,
  12, 12, 6, 2.4,
  12, 12, 12, 12,
  12, 12, 12, 12,

  12, 1.5, 12, 12,
  12, 12, 12, 12,
  12, 12, 6, 2,
  12, 12, 12, 12,

  12, 12, 12, 12,
  6, 2, 12, 12,
  12, 12, 12, 12,
  12, 12, 8, 24, 2
};

void setup() {

{
  //lcd.createChar(1, heart);
  lcd.begin(16,2);

  lcd.print("Heart Beat");
  lcd.write(1);
  lcd.setCursor(0,1);
  lcd.print("Monitering");
  pinMode(in, INPUT);
  pinMode(Reset, INPUT);
  pinMode(start, INPUT);
  digitalWrite(Reset, HIGH);
  digitalWrite(start, HIGH);
  delay(1000);

  lcd.begin(16,2);
  lcd.print("need to talk?");
  delay(1000);

  lcd.begin(16,2);
  lcd.print("not yet satisfied with care?");
  delay(1000);
}
// This code runs on startup, it sets ledPin to output so it can blink the LED that is built into the
// Arduino (but then never does), and sets the serial port up for fast 115,200 baud communication
// of the values (make sure you change your serial monitor to match).

  Serial.begin (115200); // the baud rate of the serial data
  {
    Serial.begin(115200);
    pinMode (soundDetectedPin, INPUT);
  }
  //PUSH BUTTON AND BUZZER
  {
    pinMode(buzzer, OUTPUT);
    pinMode(13, OUTPUT);
    pinMode(inPin, INPUT);
    }
}

void loop() {
  // HEARTBEAT SENSOR
    static double oldValue = 0; // used for averaging.
    static double oldChange = 0; // not currently used
    int rawValue = analogRead (sensorPin); // This reads in the value from the analog pin.
                                                              // this is a 10 bit number, and will be between 0 and 1023
                                                              // If this value doesn't change, you've connected up
                                                              // something wrong

  unsigned long time2,time1;
  unsigned long time;

    double value = alpha * oldValue + (1 - alpha) * rawValue; // Calculate an average using 75% of the
                                                                                // previous value and 25% of the new

    Serial.print (rawValue); // Send out serially the value read in
    Serial.print (",");          // Send a comma
    Serial.println (value);   // Send out the average value and a new line
    oldValue = value;        // Save the average for next iteration
    delay (period);            // Wait 20 mSec

  if((digitalRead(start)))
  {
    k=0;
    lcd.clear();
    lcd.print("Please wait.......");
    while(k<5)
    {
     if(digitalRead(in))
     {
      if(k==0)
      time1=millis();
      k++;
      while(digitalRead(in));
     }
    }
      time2=millis();
      rate=time2-time1;
      rate=rate/5;
      rate=60000/rate;
      lcd.clear();
      lcd.print("Heart Beat Rate:");
      lcd.setCursor(0,1);
      lcd.print(rate);
      lcd.print(" ");
      lcd.write(1);
      k=0;
      rate=0;
    }

  if(!digitalRead(Reset))
  {

      rate=0;
      lcd.clear();
      lcd.print("Heart Beat Rate:");
      lcd.setCursor(0,1);
      lcd.write(1);
      lcd.print(rate);
      k=0;
  }
  // LCD SCREEN (helpful hotlines message)
  {
    lcd.setCursor(0,1);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("1-800-273-8255");
    delay(1000);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("1-877-726-4727");
    delay(1000);
  }
  // BIG SOUND SENSOR
  {
    soundDetectedVal = digitalRead(soundDetectedPin);

    if (soundDetectedVal == LOW)
    {
      lastSoundDetectTime = millis();
      if (!bAlarm){
        Serial.println("you're doing great :)");
        bAlarm = true;
      }
    }
    else
    {
      if( (millis()-lastSoundDetectTime) > soundAlarmTime && bAlarm) {
        Serial.println("keep breathing");
        bAlarm = false;
      }
    }
  }
  // LCD SCREEN (are feeling better/listen to these sick tunes buddy message)
  {
    lcd.setCursor(0,1);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("if still need comfort");
    delay(500);
    lcd.clear();
    lcd.begin(16,2);
    lcd.print("hold button");
    delay(1000);
    }
    //PUSH BUTTON AND BUZZER
    {
      val = digitalRead(inPin);
      if (val == HIGH) {
        digitalWrite(buzzer, LOW);
      } else {
        digitalWrite(buzzer, HIGH);
      }
      }
// BUZZER
{{
  sing(1);
  sing(1);
  sing(2);
  }
  int song = 0;
   void sing(int s) {
    song = s;
    if (song == 1) {
      Serial.println("recognize this?");
      int size = sizeof(hotlineb_melody) / sizeof(int);
      for (int thisNote = 0; thisNote < size; thisNote++) {
        int noteDuration = 1000 / hotlineb_tempo[thisNote];

        buzz(melodyPin, hotlineb_melody[thisNote], noteDuration);

        int pauseBetweenNotes = noteDuration * 1.30;
        delay(pauseBetweenNotes);

        buzz(melodyPin, 0, noteDuration);
      }
    }
  }
  {
    void buzz(int targetPin, long frequency, long length) {
      digitalWrite(13, HIGH);
      long delayValue = 1000000 / frequency / 2;
      long numCycles = frequency * length / 1000;
      for (long i - 0; i < numCycles; i++) {
        digitalWrite(targetPin, HIGH);
        delayMicroseconds(delayValue);
        digitalWrite(targetPin, LOW);
        delayMicroseconds(delayValue);
      }
      digitalWrite(13, LOW);
          }
        }
      }
    }
  }
}

You could probably use a rest ... My first year university programming I spent the whole day from 6 am to midnight trying to solve this one little impossible task, at the end I just gave up and went to bed. The next morning I woke up at 9:00 and solved it by 9:05

Try properly indenting your code. The error will then become perfectly obvious.

`void setup() {
{?? There are 2 more }than{`.

One of the most effective techniques for dealing with compilation errors is to read the error message, then read the code near the line referred to.  If the message is obscure, google it.

Auto-format is your friend. Use it.

HEARTBEAT SENSOR (displays heart rate on LCD screen), you mean play Hot Line Bling with a piezo buzzer?? :)

@DatHa Yes! We actually spent a whole day coding the hotline bling! These codes work by themselves, just when we compile them into a master code, this error shows up.

@Majenko We auto-formated; how do we proceed after?

@EdgarBonet do you mean auto-format? We still don't understand, more help please? Thank you!

@ИвоНедев Lol! That's really funny, however, we are actually very incompetent so we still have no idea what to do for this :(

Just read the formatted code. The error should be absolutely obvious now.

@EdgarBonet I'm sorry, we have no idea what's going on right now. If you think the error is actually obvious right now, we would appreciate if you would tell us what is going on. Thank you very much.

Here are the problems I found while trying to make your code compile:
Opening and closing braces should match
Trying to autoformat your code gave me the error:

Auto Format Canceled: Too many right curly braces.

I had to remove the last two braces for Auto Format to succeed.
Functions cannot be nested
You should move the declarations of sing() and buzz() out of
loop(). You can call them from loop() though.
Other random errors

#define sing is defining sing as an empty string, and you cannot
give a function an empty name
the variable song should be either global or local to sing(), not
local to loop()
to declare and initialize a variable to zero you should write
int i = 0, not int i - 0
soundAlarmTime should be unsigned
oldChange and time should be removed (they are not used)

Thank you so much for your assistance! This project was made so much easier, and we appreciate your efforts and time! Thanks again :)


text:
Slow response from ENC28J60
I am making a circuit which turns a LED on and off through internet. I am connecting an Arduino to a LED and to an Ethernet controller(ENC28J60), but when I make a GET request to the device, it takes too long to respond - around 2 minutes - but my internet connection is fast.Before i get ip "ether.begin(sizeof Ethernet::buffer, mymac,8)" command fails it returns zero still i am able to control it.
Code:
#include <EtherCard.h>

#define STATIC 0

// mac address
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
// ethernet interface ip address
static byte myip[] = { 172,26,40,250 };
// gateway ip address
static byte gwip[] = { 172,26,40,1 };

// LED to control output
int ledPin10 = 10;

byte Ethernet::buffer[700];

const char page[] PROGMEM =
"HTTP/1.0 503 Service Unavailable\r\n"
"Content-Type: text/html\r\n"
"Retry-After: 600\r\n"
"\r\n"
""
"<title>"
"Service Temporarily Unavailable"
"</title>"
""
"
This service is currently unavailable
"
"
"
  "The main server is currently off-line.
"
  "Please try again later."
"
"
""
""
;

void setup () {
    pinMode(ledPin10, OUTPUT);

  Serial.begin(9600);
  Serial.println("Trying to get an IP...");

  Serial.print("MAC: ");
  for (byte i = 0; i < 6; ++i) {
    Serial.print(mymac[i], HEX);
    if (i < 5)
      Serial.print(':');
  }

  if (ether.begin(sizeof Ethernet::buffer, mymac,8) == 0)
    Serial.println( "Failed to access Ethernet controller");
  else
    Serial.println("\nEthernet Controller Initialized");

#if STATIC
  Serial.println( "Getting static IP.");
  if (!ether.staticSetup(myip, gwip)){
    Serial.println( "could not get a static IP");

  }
#else

  Serial.println("Setting up DHCP");
  if (!ether.dhcpSetup()){
    Serial.println( "DHCP failed");
  }
#endif

  ether.printIp("My IP: ", ether.myip);
  ether.printIp("GW IP: ", ether.gwip);
  ether.printIp("DNS IP: ", ether.dnsip);
}

void loop () {

  word len = ether.packetReceive();
  word pos = ether.packetLoop(len);

  // IF LED10=ON turn it ON
  if(strstr((char *)Ethernet::buffer + pos, "GET /?LED10=ON") != 0) {
  Serial.println("Received ON command");
  digitalWrite(ledPin10, HIGH);
}

// IF LED10=OFF turn it OFF
if(strstr((char *)Ethernet::buffer + pos, "GET /?LED10=OFF") != 0) {
  Serial.println("Received OFF command");
  digitalWrite(ledPin10, LOW);
}

// show some data to the user
memcpy_P(ether.tcpOffset(), page, sizeof page);
ether.httpServerReply(sizeof page - 1);
}


text:
How to turn a LED if ultranonic HC-SR04 reading is on defined range for some interval
My objective is if ultrasonic readings ranging between 1 to 10 cm and no distance change for 10 seconds or more, a LED will turn on. Here is my current code.
#define trigPin 7
#define echoPin 8
#define led 13
#define led2 12

long duration, distance, interval = 4000;
int detection = 0;

void setup() {
   Serial.begin (9600);
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);
   pinMode(led, OUTPUT);
   pinMode(led2, OUTPUT);
   detection = millis();
}

void loop() {

   ultraSonic();

   if (distance > 0 && distance < 10 && (millis() - detection >= interval)) {
   digitalWrite(led, HIGH);
   digitalWrite(led2, LOW);
   } else {
   digitalWrite(led, LOW);
   digitalWrite(led2, HIGH);
   }

   Serial.print(millis());
   Serial.print(" - ");
   Serial.println(distance);

   delay(250);
}

void ultraSonic() {
   digitalWrite(trigPin, LOW);
   delayMicroseconds(60);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(60);
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = (duration / 2) / 29.1;
}

Sorry for my bad english.
Cheers.

In your primary if statement:
if (distance > 0 && distance < 10 && millis() - detection >= interval)
Consider grouping clauses with parentheses to make order-of-operations explicit. If nothing else, it will improve readability of the code.

Based on previous answer and your comment, maybe you can try this one
I assume if the range is ranging 1-10 cm for 10 secs or more the led will turn on:
void setup() {
   Serial.begin (9600);
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);
   pinMode(led, OUTPUT);
   pinMode(led2, OUTPUT);
}
int togle = 0;

void loop() {

   ultraSonic();

   if ((distance >= 1) && (distance =< 10)) //dont use (distance>0)
   //there are possibility you get 0.xx distance
   {
     Serial.print("Distance on range - ");
     if (toggle == 0)
       {
        toggle=1;
        detection=millis();
        Serial.println("last detection outside range");
       } else
     if (toggle == 1)
     {
        Serial.print("last detection in range - ");
        if ((millis()-detection) >= interval)
            {
             Serial.println("objective complete");
            }
        else Serial.println("not enough interval");
     }
   } else
   {
     //turn off the led
     Serial.println("Distance out of range");
     toggle = 0;
   }

}

void ultraSonic() {
   digitalWrite(trigPin, LOW);
   delayMicroseconds(60);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(60);
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = (duration / 2) / 29.1;
}

Feel free to tell if something is not right

Sir, thanks for your help. Can you explain about starttime that you made it in the code?

ah sorry I did not notice that. I fixed the answers

the result of that code is the led turned on after distance is more than 10 cm. any suggestion sir?

Can you provide more information? About the test condition, results, expected results, etc

the result I expect is if the distance is between 1 and 10 cm, and no change in distance in a minimum of 10 seconds, the led turn on. as long as the distance still no changed after 10 seconds, the led still on. but if any change in distance after that, the led will turn off.

its debugging time then. I update my answer, tell me what you got

Let us continue this discussion in chat.

great. everything is working as my expected result. thanks for everyone.

void loop() {

   ultraSonic();

   if ((distance > 0) && (distance =< 10)) {
   digitalWrite(led, HIGH);
   digitalWrite(led2, LOW); // turning LED on
   } else {
   digitalWrite(led, LOW);
   digitalWrite(led2, HIGH); // turning LED off
   }

   Serial.print(millis());
   Serial.print(" - ");
   Serial.println(distance);

   delay(250);
}

sir, how about the timing? what i want is if no change in distance for more than 10 seconds then led will turn on. Cheers.

Take an integer and increase it every time that the object is on the required distance. If it's not, you set it back to 0. You can then check if the integer is as high as required (amount of checks done). Find a neat way to put a little delay between the checks, and you're set.

Paul is correct, but using integer as counter will less precise. Even if delay is arranged neatly, a small change in program can decrease the accuracy of "10 secs". But its simple and great if the "10 secs" accuracy is not too important


text:
Keyboard key press listener
Is there a way to make a listener for a key press to begin a loop?
Example:  I press the Tab key on my keyboard and the programmed loop begins running.
Essentially creating a keyboard hotkey.

Please edit your question so that it meets the quality standards set out in the help center.

The answer is yes and no.
Only the Arduino and its IDE, no.
The way I found is to use Processing to wait until it detects a hotkey, then send a serial message to your Arduino. If you tune in the right COM port, this should work.


text:
What's the problem with baudrate?
I was trying to evaluate the speed of communication between pc and Arduino, using this code in Arduino:
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("Ciao Arduino");
}

and this in Python:
import time, serial

arduino = serial.Serial('/dev/cu.usbmodem1421', 250000)

time.sleep(3)
count = 0
start = time.time()
while True:
   a = arduino.readline()
   print a
   count = count+1
   time1 = time.time()
   if time1-start >1 :
      print "--" + str(count)
      print a
      count = 0
      start=time1

Wich print out how many readline() he managed to do to evaluate the speed in further project.
And I realized two things:

The program is working even with different baudrate
and with correct baudrate(For ex. 300-300 or 250000-25000) the baudrate is irrelevant(and wrong), I mean the 300 baudrate makes 20000 readline() and the 250000 make 5000 of them.

What's the problem? thank you

On the Micro I can understand that being the case. You tagged Uno as well. Are you sure you have experienced that on the Uno?

On a direct USB CDC/ACM connection (as you get on the Micro) there is no such thing as baud rate.
Any baud rate setting performed by the host (the PC) is merely an instruction to the device (the Arduino) to say "I would like you to operate at this speed", not "I would like you to communicate with me at this speed".
It is used in situations where the PC may want to set the baud rate of a real UART interface within the device, such as when the ATMega16U2 is used as a USB interface on the Uno - in that case the PC tells the 16U2 that it wants to communicate at, say, 115200 baud, and the 16U2 sets its UART (the one that communicates with the ATMega328P) to 115200 baud. The actual PC to ATMega16U2 (or ATMega32U4 in the case of the Micro) is at the native USB 2 bulk packet rate.

It is also used as a "reset" instruction to the ATMega32U4 - if the CDC/ACM port is opened by the PC at 1200 baud and then immediately closed again the 32U4 resets and enters the bootloader. This makes programming (usually) easy, as long as the program on the chip hasn't crashed and left the USB interface in an unusable condition (as sometimes happens).

Another question: It is right to think that the native usb used with micro is way faster than the ATMega16U2? Now I am using the Arduino Uno, and it makes(at 400'000 baudrate) 2855 readline(), while the Micro achieved 20'000.

No, the USB is the same on both. The bottleneck is the connection between the two chips on the Uno which runs at the baud rate you specify, and is limited to less than the rate of USB.

Is there any difference between Android setting baud-rate when connecting to Arduino via USB/serial and putty setting baud-rate when connecting to (virtual) COM-port (Arduino again)...?