text:
How to access Software Serial contents/value and extract some details?
I'm using SoftwareSerial with a SIM808 GSM modulde to detect incoming SMS messages.
The problem I'm currently having is that I need to access the phone number from the received SMS so I can send a reply back to that number.
I'm trying to access the contents of the SoftwareSerial and print it to the serial monitor, just so I can see its contents but for some reason, nothing at all is being output. The "Message received" string is being output to the monitor, along with everything else that's needed. It's just the mySerial.read() that won't show.
How can I access the incoming SMS message and get the phone number from it?
Excuse the messy code. It's a work in progress.
 #include <SoftwareSerial.h>
 #include <ADSWeather.h>

SoftwareSerial mySerial(9, 10);

#define ANEMOMETER_PIN 2
#define VANE_PIN 0
#define RAIN_PIN 3

#define CALC_INTERVAL 1000

unsigned long nextCalc;
unsigned long timer;

int windDir;
int windSpeed;
int rainAmmount;
const int switchpin =  7;

ADSWeather ws1(RAIN_PIN, VANE_PIN, ANEMOMETER_PIN); //This should configure all pins correctly

void setup()
{
  pinMode(switchpin, OUTPUT);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(ANEMOMETER_PIN), ws1.countAnemometer, FALLING); //ws1.countAnemometer is the ISR for the anemometer.
  nextCalc = millis() + CALC_INTERVAL;

  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  delay(100);

  digitalWrite(switchpin, HIGH);
  delay(3000);
  digitalWrite(switchpin, LOW);
        RecieveMessage();
      Serial.write("SMS set to recieve messages");
}

void loop()
{

  timer = millis();

  int rainAmmount;
  long windSpeed;
  long windDirection;
  int windGust;
  int sent;

  ws1.update(); //Call this every cycle in your main loop to update all the sensor values

  if(timer > nextCalc)
  {

    nextCalc = timer + CALC_INTERVAL;
    rainAmmount = ws1.getRain();
    windSpeed = ws1.getWindSpeed();
    windDirection = ws1.getWindDirection();
    windGust = ws1.getWindGust();

//     windSpeed / 10 will give the interger component of the wind speed
//     windSpeed % 10 will give the fractional component of the wind speed
    Serial.print("Wind speed: ");
    Serial.print(windSpeed);
    //Serial.print('.');
    //Serial.print(windSpeed % 10);
    //Serial.print(" ");

    Serial.print(" Gusting at: ");
    Serial.print(windGust);
    //Serial.print('.');
    //Serial.print(windGust % 10);
    Serial.println("");

  }

  //if (Serial.available()>0)
  //{
      //RecieveMessage();
     // Serial.write("SMS set to recieve messages");
  //}

//  mySerial.flush();
 // serialFlush();

  //If an message comes in
 if (mySerial.available()>0){

  Serial.write("Message received");
  Serial.write(mySerial.read());

  String stringSMSMessage;
  stringSMSMessage = String("Wind speed near St. John's lock: ");
  stringSMSMessage += windSpeed;
  stringSMSMessage += "MPH";
  //stringSMSMessage += '.';
 // stringSMSMessage += windSpeed & 10;
  stringSMSMessage += " Gusting at: ";
  stringSMSMessage += windGust;
    stringSMSMessage += "MPH";
 // stringSMSMessage += '.';
  //stringSMSMessage += windGust % 10;
  stringSMSMessage += ' ';

  //Send the wind speed response.
    mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"07769218312\"\r"); // Replace x with mobile number
  delay(1000);
  mySerial.println(stringSMSMessage);// The SMS text you want to send
  delay(100);
   mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(10000);
  mySerial.flush();
  serialFlush();

}
}

 void SendMessage()
{
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"Phone Number Goes Here\"\r"); // Replace x with mobile number
  delay(1000);
  mySerial.println("I am SMS from GSM Module");// The SMS text you want to send
  delay(100);
   mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(10000);
  mySerial.flush();
  serialFlush();

}

 void RecieveMessage()
{
  mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
  delay(1000);
 }

 void serialFlush(){
  while(mySerial.available()>0)  {
     mySerial.read();
    }
}

What are you expecting to show up? Serial.write(mySerial.read()); will just send exactly 1 byte/character from the mySerial buffer over Serial. Nothing more. Only 1 byte. You need to read the full message from mySerial. Then you can send that over Serial.

Why not digging more on AT commands....you can send At command and can get data.
https://www.electronicsforu.com/resources/cool-stuff-misc/gsm-at-commands Just send the commands and read the response then print to serial monitor.

Excuse the messy code. It's a work in progress. ... the look of the code is not important ... mostly, it is properly indented, which should keep you from adding code in wrong places .... there is a problem though, there is too much code for the problem you are trying to solve .... there is no reason to have any sendMessage code ... all you need, at this time, is SMS receive code and print received text code ... when that code works, add extract phone number code

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


text:
How to clear SoftwareSerial values?
I'm using software serial on my weather station. The way it's supposed to work is that you send an SMS to the device and it replies with the wind speed, etc.
At the moment, The wind speed is detected, waiting for an incoming SMS. The SMS arrives and it sends a response but the response SMS is sent over and over infinitely.
I'm guessing the problem is due to the:
 if (mySerial.available()>0){

As this is what I'm using to test whether the SMS has arrived and presumably, it's then always set to available.
Does anyone know how to basically reset the software serial after the message has been sent?
 #include <SoftwareSerial.h>
 #include <ADSWeather.h>

SoftwareSerial mySerial(9, 10);

#define ANEMOMETER_PIN 2
#define VANE_PIN 0
#define RAIN_PIN 3

#define CALC_INTERVAL 1000

unsigned long nextCalc;
unsigned long timer;

int windDir;
int windSpeed;
int rainAmmount;

ADSWeather ws1(RAIN_PIN, VANE_PIN, ANEMOMETER_PIN); //This should configure all pins correctly

void setup()
{
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(RAIN_PIN), ws1.countRain, FALLING); //ws1.countRain is the ISR for the rain gauge.
  attachInterrupt(digitalPinToInterrupt(ANEMOMETER_PIN), ws1.countAnemometer, FALLING); //ws1.countAnemometer is the ISR for the anemometer.
  nextCalc = millis() + CALC_INTERVAL;

  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  delay(100);
}

void loop()
{
  timer = millis();

  int rainAmmount;
  long windSpeed;
  long windDirection;
  int windGust;
  int sent;

  ws1.update(); //Call this every cycle in your main loop to update all the sensor values

  if(timer > nextCalc)
  {

    nextCalc = timer + CALC_INTERVAL;
    rainAmmount = ws1.getRain();
    windSpeed = ws1.getWindSpeed();
    windDirection = ws1.getWindDirection();
    windGust = ws1.getWindGust();

//     windSpeed / 10 will give the interger component of the wind speed
//     windSpeed % 10 will give the fractional component of the wind speed
    Serial.print("Wind speed: ");
    Serial.print(windSpeed / 10);
    Serial.print('.');
    Serial.print(windSpeed % 10);
    Serial.print(" ");

    Serial.print("Gusting at: ");
    Serial.print(windGust / 10);
    Serial.print('.');
    Serial.print(windGust % 10);
    Serial.println("");

  }

  if (Serial.available()>0)
  {
      RecieveMessage();
  }

  //If an message comes in
 if (mySerial.available()>0){
  // Serial.write(mySerial.read());
  Serial.write("Message received");

  //Send the wind speed response.
  SendMessage();

  //At this point the SendMessage() repeats and the message is sent over and over.
}
}

 void SendMessage()
{
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"NUMRemoved\"\r"); // Replace x with mobile number
  delay(1000);
  mySerial.println("I am SMS from GSM Module");// The SMS text you want to send
  delay(100);
   mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
}

 void RecieveMessage()
{
  mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
  delay(1000);
 }

 void serialFlush(){
  while(mySerial.available() > 0) {
    char t = mySerial.read();
  }
}

You need to read the stuff from SoftwareSerial.  Use mySerial.read() until available is false.  If you don’t care what was sent then simply use read and ignore the value that was read.

you have a serialFlush() function in the sketch. use it.

@Juraj It doesn't work. The SMS messages keep coming.

change the sketch in question so we can see how do you use serialFlush();

For the hardware serial port, the buffer is 64 and I was reading at least 100 times. Every read will clear one byte of data from the serial buffer at a time.
For the software serial port, you do a dummy read and then check whether the buffer is empty or not using
    while(mySerial.available()>0)  {
       dummy = mySerial.read();
    }

So, in summary, you have to read the buffer until it is empty.
Useful notes:

You should be knowing when to expect actual data and when not to
have a way to identify the valid messages (some fixed header bytes)
have a way to validate the contents (checksum)

Leave a comment if you have any questions

I've tried using this loop to flush the serial port, it's even in the code I posted above but it does not work. The SMS messages keep coming. Am I calling it in the wrong place?

You never call it.

if (mySerial.available() > 0) {
  // Serial.write(mySerial.read());
  Serial.write("Message received");

  //Send the wind speed response.
  SendMessage();

  mySerial.begin(9600);   // Reset myserial buffer

  //At this point the SendMessage() repeats and the message is sent over and over.
}

 if (mySerial.available()>0){

You are checking if any serial data has arrived. Then you never read it. So naturally it is always available. You have a serialFlush function which does read it, however that function is never called.
You need, however, to read more than one byte. Otherwise you will send an SMS for every byte in the input message.

source: Stack Exchange

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

sort: votes


text:
Distance sensor - Not working on fabric surface
I am using ultrasonic HC-SO04, not giving reading on fabric. I lost many hours on testing my obstacle avoidance robot car in front of my sofa, every time it hits hard but works fine on other hard surfaces. Is there any other distance sensor which can detect soft objects like fabric from long or short distance?
Also looking any other accurate long distance cheap sensor which can work easily with Arduino. Please let me know.  Thanks

Ultrasonic uses sound, and fabric absorbs sound. IR distance sensors may be an alternative. Unless the sofa is also black :-) (not necessarily true, as black might still reflect IR)

There are three types of commercially viable sensors for small scale projects:

Ultrasonic sensors(HC-SO04 and similar): These sensors use ultrasound much like a submarine uses its sonar to locate things by sending out a sound wave(trigger pin) and then measuring the time it takes for the sound wave to bounce back by reading the echo.There are two problems with this sensor. It needs a pretty solid object to bounce sound of thus walls are good but cloth absorbs the sound wave and the echo never bounces back. The second is you can encounter ghost echos when the sound wave strikes a corner and creates a echo for an object that is not really there. These sensors typically have a range of around 250cm to 600cm however some sensors can sense up to 7 meters away. Thus while it has good range it can not reliably detect all things and you might have false positives on it as well.
IR(Infrared) Sensors: These work like the ultrasonic ones but with light instead of sound. The sensor sends out a pulse/beam of IR light and measures the time it takes to reflect the light pulse/beam. This sensor is much faster than the ultrasonic ones but they have a much smaller range than ultrasonic sensors with a normal range of about 1.5 meters. While they work on most obstacles some might be missed due to the ability of some materials to absorb the IR light pulse thus there is no echo to measure.
LIDAR(Laser Range Sensors): There are various models of these but the principle is the same as the IR sensor. These can have massive range but they also come in at a massive prices. You can find cheaper ones around I saw a model for $80 that has a 40 meter range.

Thanks @Namphibian for a detailed description, can you also mention when and where you found that LIDAR for $80? any link?

Sparkfun has the LIDAR-Lite v2 for ~$120, which sounds similar to this.  The previous version was about $80 but has been upgraded and is now more expensive. https://www.sparkfun.com/products/13680

I'd just like to add that not all IR sensors work that way.  Some have an IR led that shines a dot straight ahead and then it looks at that spot and based on the angle, determine the distance.  I'm pretty sure this is how the sharp ir sensors work, but I could be wrong.

@mwwalk my point number 2 covers this though I was not clear. I made some alterations.

@Namphibian I don't think you understood what I was saying but I don't think I said it very clearly.  Note that it doesn't really matter for this question and is a bit pedantic.  I was just saying that some IR sensors use the angle of the echo light rather than the time it takes to determine distance.  This is what the Sharp IR sensors do.

@mwalk noted. I was not aware of this difference. Will go read up about it as it seems a different way to approach the problem. Thanks a million!

If you are using HC-SR04 then I would suggest you to first check it out on simulation. I use Proteus software for simulation purposes and you should download the Ultrasonic Sensor Library for Proteus, using this library you can easily simulate your Ultrasonic sensor in Proteus and can design your code. It will save you from hardware testing.

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


text:
What does 16u and 128u mean?
The below is a snippet of a code for operating SI4455 Rf module with Arduino. I have some doubts which I'd like to seek some help in clearing.
byte numOfBytes = *pSetPropCmd++;

    if (numOfBytes > 16u) // What does this 16u mean?
    {
        /* Initial configuration of Si4x55 */
        if (SI4455_CMD_ID_WRITE_TX_FIFO == *pSetPropCmd)
        {
            if (numOfBytes > 128u) // What does this 128u mean?
            {
                /* Number of command bytes exceeds maximal allowable length */
                return SI4455_COMMAND_ERROR;
            }

            /* Load array to the device */
            pSetPropCmd++;
            WriteEZConfigArray(numOfBytes - 1, pSetPropCmd);

            /* Point to the next command */
            pSetPropCmd += numOfBytes - 1;

            /* Continue command interpreter */
            continue;
        }

In the above snippet, what does 16u and 128u mean?. I think its meaning u for unsigned, but still not clear as what does 16u and 128u mean.
Rgds
VD

It means that it is a unsigned value. Because the compiler checks for signed and unsigned in the same operation this is used (amongst others) to avoid warnings.
This is explained on stackoverflow here https://stackoverflow.com/questions/14844119/define-foo-1u-2u-4u-what-does-1u-and-2u-mean

ok does it mean an unsigned int with a decimal value 16 for 16u and unsigned int with a decimal value of 128?. And is it valid to perform "numofBytes > 128u" check in the snippet, since numofBytes is a byte?

Please ckick the answer is usefull :-)

The u just types the value as unsigned. You also have f which is float. which makes 1.0 and 1f the same thing.

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


text:
How can I run multiple programs on an Arduino?
I'm trying to get students to experiment with Arduino. However, due to a lack of boards, two teams of students will collaborate on each board. They will push their own code (independent from each other) and use half the pins.
The "hardware" part isn't really a concern: students will push their sketches on a server that uploads them on the board, or something like that.
What I'm worried about is the software part. How can I allow two sketches to run on the same board, and allow the user to upload sketches without resetting the board?

As of my understanding, using the flash memory isn't an option, because the board must be reset before it can be written.
My first idea was to compile the students' C code into custom-made "assembly", and then push the assembly code to the board, which stores it into RAM and interprets it. However, my biggest problem would be implementing functions, I don't really have a clue of how I could do that. While common C functions could just be encoded in a fashion like FUNC printf STRING %s VAR a for printf("%s", a), I don't know how to encode user-defined functions. Besides, I don't even think the RAM is sufficient for running the client, storing two small programs, and running them.
Then, I thought about running the C code on the computer, but replacing digitalWrite with appropriate signals to the board. However, I'm worried about the performance of this, mostly when dealing with "high" speeds - say, using a custom-made library to print text on a LCD driver.

Can you source the bare AVRs and USB-UART bridge modules instead?

Very very hard. Where can I send the money to help you purchase enough Arduinos so each kid can have one? Getting more Arduinos is an easier solution than "simulating" multi-tasking.

Why don't you just have them wright normal programs and swap the board back and forth? one person codes, the other testes, repeat. Or if you want to get this complicated with a server and everything, what about just using an avr emulator for half the class's code? some work pretty well.

@BrettM: Because swapping the board back and forth would dramatically slow down the work, and make the workflows of the two teams dependent on each other. What I am seeking is something that makes the workflows independent, so that they can push updates and test the behaviour whenever they want, without waiting the other team.

Your time would be better spent engineering a simulation environment to make progress less dependent on the hardware, than on trying to get some sort of pre-emptive multitasking running on the board and lock out constructs such as interrupt handlers which would have global effect.  Realistically, I'd say only a small minority of my firmware development time consists of testing on hardware (though that does sometimes involve extended periods), but be reasonable about the fact that the hardware (or at least its alternatives) costs about what students will spend on two lunches.

Not what you asked per se, but I buy these,they work well and are liable to be well below what you pay now. Other models available from same source. I have no relationship with them other than as a happy customer.

I've just rereread most of the answers and comments. It's hard to see that my suggested $2.85 per team solution is going to be easy to beat. You have to reset the system when you load your own new code but this takes only seconds and each team is then absolutely independent. [And yes - these really do work and are of reasonable quality, somewhat to my amazement].

For a truly nonstop experience spend $5.70 for two, add some gates and/or multiplexers and change from old to new instantly. [That seems worth trying. The following gives 2 microcontrollers A & B with 15 pins from either switchable selectively to 15 interface pins. If drive levels can be tolerated then a CD4043 multiplexer can provide 3 pins x 2  channels of switchable analog or digital biirectionally. About 10 cents per channel (30c/IC) in 100's. ....

...  So eg 15 switched pins between 2 microcontrollers and 16 outputs costs about $1.50 - plus board space etc. "Glue" is one pullup resistor for the enable lines and a switch or logic level. So 2 x uCs and mux ICs costs about $7.50.

Giulio - For interest - where are you and what is your organisation. If you do not want to comment online you could email me via email address in my profile, if you wished.

You could perhaps merge the teams so that each team would have its own board. For the teams for perform proper debugging of their setups, they need complete isolation from other teams' setups. Otherwise, no one will really be able to isolate individual variables and check what's specific behavior. Also, changes made by one team to the shared setup will have an impact on the other team's setup, rendering the learning process impossible to carry out. The teams sharing a board will effectively become a single team anyway.

In addition to the other answers, I have a few ideas:
1.) Instead of doing variable prefixes, have them wrap all of their code inside a namespace! Please note that you can't wrap "setup" or "loop" in that namespace. Example
setup() {
  if(conditionIsTrue) {
    aGroup::setup();
  } else {
    bGroup::setup();
  }
}

loop() {
  if(conditionIsTrue) {
    aGroup::loop();
  } else {
    bGroup::loop();
  }
}

namespace aGroup {
setup() {
  // Code
}

loop() {
  // Code
}
}

namespace bGroup {
setup() {
  // Code
}

loop() {
  // Code
}
}

2.)
Please note you'll have issues with a student tries to access an analog pin and doesn't prefix it with A. For example, if I wanted analog pin 5, I should do analogRead(A5);, not analogRead(5);. That could cause some major issues.

A little late, but I used a potentiometer as a switch to determine which "sketch" to run; in this case swapping LEDs on/off. I assume it can be applied to this instance, the students just have to share/divide pins and declare variables together at the top with comments. (I'm new at this, but I think a shift register (75HC595) could be used if you run out of pins). Thoughts?
EDIT: Potentiometers give a value of 0-1023. I split that up into 2, 3, and 4 separate sketches with no problems. You just have to change the IF/ELSEIFs to reflect how many sketches you want to run (512 for 2, 341 for 3, ~256 for 4, etc).
int sensorPin = 0;
int sensorValue = 0;
int ledPin1 = 4;
int ledPin2 = 8;

void setup() {

  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
}

void loop() {

  sensorValue = analogRead(sensorPin);

  if (sensorValue < 512)
{
    digitalWrite(ledPin1,HIGH);
    digitalWrite(ledPin2,LOW);
}

  else
{
    digitalWrite(ledPin2,HIGH);
    digitalWrite(ledPin1,LOW);
}
}

There is no native multitasking on an Arduino. A few solutions have been suggested above, all of which depend on cooperative multitasking - each half has to play fair.
An alternative may be this:
Buy some AtTiny chips - e.g. AtTiny 24a; they are about $2-3 each. Buy some VeroBoard. Solder the AtTiny on to the board, so each verboard strip has 2 pins on it (not the other way, where each veroboard strip has half of the pins on it). Solder on some pins, cut the track between the pairs of pins, and cut the board to size. You should be able to get a working board, with 12 usable pins per board, and you'll be paying less than $5 per board in your local currency. Buy a USBISP, and hook up the pins, whenever you need to program them - I suggest using the FreeTronics programmer, like this one here: http://www.jaycar.com.au/productView.asp?ID=XC4237 - you can solder 2 pins for the "slow clock" option - you'll need this. Optionally, you could make an adapter board which plugs into all of the relevant pins in one go, to program it. You should only need one of these. To figure out which wires to connect where, compare the top diagram on http://www.dz863.com/datasheet-8310956563-ATTINY24A-SSU_8-bit-Microcontroller-With-2k-4k-Bytes-In-system-Programmable-Flash/ with https://www.olimex.com/Products/AVR/Programmers/AVR-ICSP/resources/AVR-ICSP.gif
You can power them with AA batteries or an external power supply - you could easily make one power supply that runs many boards. Check out the spec sheet for the voltage required - it varies, depending on the clock speed (default clock speed as described is 1 MHz, google "avr fuses" for how to set them to e.g. 8 MHz at no extra cost).

How can I allow two sketches to run on the same board, and allow the user to upload sketches without resetting the board?

This is "easily" dealt with as long as you can enforce certain minimum disciplines.
Students must only use assigned pins.
Identifiers (functions, variables ...) defined by a group must always be unique to that group. This can be as simple as eg always starting with a group specific symbol or eg one group NEVER using a z in names and the other ALWAYS using Z etc. Annoying but easy.
Loop() contains calls to two non-terminating functions eg Group1() and Group2()
All code for Group1 is in Group1() and ....
One digital pin is assigned for Giulio's use.
When GiuliosPin is low the system executes Group1() - and never exits it until restarted.
When GiuliosPin is high the system executes Group2() - and never exits it until restarted.
I uses a system very close to the Group1() / Group2() selection for my own purposes to allow multiple sketches to be compiled at once - but I use a constant which is set  as I compile to choose which to run. My concern is the ability to test multiple code fragments.

Added:
After reading Mac's similar answer I see I missed mentioning Setup().
Code from both users can be merged into the same Setup() as the identifiers are unique.
Or the Setup() function for each Group can be carried out inside their unique Groupx() function with a "run once" function at the start of their code. This is a matter of programming discipline and not in any way hard per se.

Although this isn't exactly what I was looking for (I was aiming at a board where students can upload their code and see it "live", not upload a series of sketches and run one of their choice), this looks like a step in the right direction.

@GiulioMuscarello multithreading isn't an efficient solution, if that's what you're looking for. I would recommend checking a small switch at the start of the sketch so you can tell if it should run A or B.

There is a solution. It requires some programming discipline from your students, but it is feasible.
1) Make sure each group uses different variable and function naming conventions (one starts all variable and functions with a_ and the other group with b_). These functions will be written in separate include files.
2) In the setup() and in the loop() functions, you will call either a_setup() or b_setup(), and either a_loop() or b_loop(). Each of the group setup and loop functions will call their functions and use their variables as the groups want to, but they are not allowed to call variables/functions from the other group. Other resources can also be allocated by you in advance for each team.
3) During the setup() function, start by reading a specific input that you will either connect to GND or to 5V. Use the result of this reading to execute either one version of the software, or the other.
This is not elegant, but it gets two program into each Arduino.

However, this would make the development flow of each team dependent on the other's, because the board must be reset upon each upload. What I was seeking is something that allows for independent development flows.

The arduino cannot run from it's limited RAM and is not going to be particularly efficient at executing a virtual machine doing so... at that point, you might as well run your custom virtual machine on something more powerful, such as the computer the students are sitting at.

On relooking I see that my answer is essentially the same as MAC's but explained slightly differently. As each answer contributes somewhat differently I'll leave mine in place BUT MAC said it first.  And yes, it works well. Some student discipline is required - but minimal.


text:
GPS stream question
I have an adafruit Ultimate GPS unit, its working fine. I am reading the GPS stream, via the command line, and one of the details, is "Angle: 167.97"
I looked at a page about GPS sentences, but I'm still confused. Angle, is the direction of wind, or rudder, or angle at altitude. In this case i would guess its either rudder (because I don't know what rudder it may be referring to) or wind angle. Its changing frequently, but the device is stationary in my shed.
My questions are: What is angle referring to? as in, is it wind or rudder?
And where is it referring to? obviously, its not getting that data from its present location, so is that data coming from a whether station or something?
pardon me if this is the wrong exchange to post in, Im not sure where to ask.

Can we see the entire sentence?

It will be referring to the angle of travel. But since it's not travelling that angle is meaningless.

Sure, ill post the entire sentence soon.

It will be referring to the angle of travel. That is, if you're moving (say driving in a car) what direction that movement is in.
But since you aren't moving the angle is meaningless. Instead it's trying to work out a direction from the random noise of the slight changes in the calculated location.
Unless your shed is in a tornado and flying through the air then the angle is not something you need to care about. Ignore it.

+1 for a sense of humor  :)


text:
how to set up an ESP8266 as a webserver
I would like to set up an esp8266, connected arduino as a webserver, specifically, one that has its own IP, and is stand alone, not connected to other networks, and offers its sensor info as the contents of its internal webpage. what is this called?
I see numerous examples for connecting the esp8266 to another network, but that is not what I want to do. I want the esp8266 to read its sensors, and write a webpage, but have other devices connect to it.

https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino

The keyword to search for is "SOFTAP".

the ESP8266 has to act as a wifi access point .... https://duckduckgo.com/?q=esp8266+wifi+access+point&ia=web


text:
RTC interrupts and coin batteries
Summary
I'm having problems with my RTC draining its coin cells quickly - fresh batteries are drained in a few months. The RTC is set to signal an interrupt every 5 minutes, and I wonder - if there is no other power attached to the circuit, is that enough to drain the coin cell?
Details and my troubleshooting:
Problems with my RTC - if I leave the circuit unpowered for a few days (so that the only power to the RTC is from the coin cell backup), the time resets to 00:00 January 1, 2000. This doesn't happen immediately when I unplug it. If I disconnect it from the computer, plug it back in the next day, the time is ok. If I leave it unplugged for a few days, then plug it in, the date is reset.
This suggests the battery is bad. So I tested it with my meter (and an 100 ohm load, as described here: https://www.youtube.com/watch?v=HcikzMG7mMU). And sure enough, the batter has dropped quite a bit from its 3V start value.
That's all good, except that this battery is only a few months old, and it should last for years in an RTC. I've got two batteries purchased in the last year and used in RTC modules, and both are now drained.
My current hypothesis is that, after I unplug my circuit from the computer, the RTC continues to run on the coin cell, firing interrupts every 5 minutes, and it is these interrupts that are causing the drain. Does this make sense? If not, what else could I check?
Setup
Breadboard arduino, DS3231 RTC on a breakout, connected

RTC SDA -> Arduino A4
RTC SCL -> Arduino A5
RTC GND -> Common GND
RTC VCC -> Common 5V (from ftdi/USB cable, when plugged in)
RTC SQW -> Arduino D2

The RTC is 'active-low', and the SQW pin is held at 5V between interrupts. With my multimeter, the brief drop to 'LOW' is undetectable. I also can't detect any current flow from the SQW pin with my multimeter.
Sketch
Including only the code related to the RTC (SD card and temperature bits removed).
/*-(Import required libraries)-*/
#include <Time.h>
#include <DS3232RTC.h> //source: https://github.com/JChristensen/DS3232RTC

/*-( Declare Constants )-*/
const int wakeUpPin = 2;
#define resolution 5 // frequency in minutes to wake from sleep

/*-(Declare Variables)-*/
time_t t;
int nextLoop;

/****** SETUP: RUNS ONCE ******/
void setup()
{
  Serial.begin(9600);

  Serial.println();
  pinMode(wakeUpPin, INPUT);

  t = RTC.get();

  nextLoop = ((minute(RTC.get()) / resolution) + 1) * resolution;
  if (nextLoop >= 60) {
    nextLoop -= 60;
  }
  Serial.print(RTC.temperature());
  Serial.print(",");
  Serial.print(RTC.oscStopped());
  Serial.print(",");
  Serial.println(nextLoop); // the minutes when the next reading will be taken

}

/****** LOOP: RUNS CONSTANTLY ******/
void loop()
{
  t = RTC.get();

  Serial.print(year(t), DEC);
  Serial.print("/");
  Serial.print(month(t), DEC);
  Serial.print("/");
  Serial.print(day(t), DEC);
  Serial.print(",");
  Serial.print(hour(t), DEC);
  Serial.print(",");
  Serial.print(minute(t), DEC);
  Serial.print(",");
  Serial.print(second(t), DEC);
  Serial.print(",");

  goToSleep();
}

void goToSleep(void) {
    Serial.print("Sleeping until: ");
    Serial.println(nextLoop);
    Serial.flush();
    RTC.setAlarm(ALM2_MATCH_MINUTES, nextLoop, 1, 1);
    RTC.alarmInterrupt(ALARM_2, true);
    attachInterrupt(0, wakeUp, LOW);

    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
    detachInterrupt(0);
    RTC.alarm(ALARM_2);
    nextLoop += resolution;
    if (nextLoop >= 60) {
         nextLoop -= 60;
    }
}

void wakeUp(){
  // Handler for the pin interrupt.
}

Sorry, that probably isnt why your battery is getting drained. Is there anything else connected to the battery other than the RTC?

Nothing else is connected to the coin cell - it's part of an RTC breakout board.

Do you have another RTC to compare against this one in case its damaged in some non-obvious way? What was the voltage when you measured it after a few days and it couldnt power the RTC any longer? The coin cell is a CR2032, right?

If I remember correctly, interrupts are disabled while the DS3231 is not getting power (except through the battery). Are you saying the battery is drained after a few months of no-power, or after a few months of power (and sometimes no power). What breakout are you using? Some breakouts use rechargeable batteries. Putting a regular battery in those will damage the battery and would explain the short lifetime.

Does the breakout board have a pullup resistor for SQW? If not you could try INPUT_PULLUP pin mode or an external pullup.

If the DS3231 is connected to the circuit(power) and the Arduino itself is not powered down, then it shouldn't use the battery at all, alarms or no.  Either some wire is connected wrong or the RTC should be swapped out to see whether the problem persists.  btw, DS3231s have internal pullups.  They work so well that if you have one on your I2C you do not want to add others because they are then in parallel, which reduces their effective resistance.  Also, I2C is connected to analog pins (A4 & A5) so INPUT_PULLUP would not apply.

Just caught where you say the problem happens when you unpower the circuit entirely.  I have done that for weeks by preprogramming a few DS3231's that I leave disconnected, on my workbench for quick installation.  They have always kept the time and date, though with some drift.  So if your RTC is good then it must be some external drain caused by the circuit.

Check your battery, it is behaving like a rechargeable one without a charger.  Mine have the letter "R" at the end of the part number.  There are a lot of RTC modules that charge the battery. Conversely they are some that do not charge the battery. Are you powering it with something other then the coin cell.

1) Could be a short in your PCB. As suggested, try another module if possible.
2) Shouldn't you somehow program SQW pin to be an interrupt? By default I remember it outputs a squarewave.
3) Try calling clearAlarm(); for your RTC to see how it goes.
4) Having the RTC sitting there, by connecting GND and a digital input from an Arduino, can you digitalRead(); the pin? That way you'll see if it keeps firing interrupts.


text:
error C1083: Cannot open include file: 'Ethernet.h':
i'm trying to compile native code in VC++ using galileo sdk for windows iot.
I've copied Ethernet.h file to the include directory of
D:\galileo-sdk-develop\galileo-sdk-develop\source> but still getting error on cannot open include file "Ethernet.h"


text:
Motion sensored speaker with display screen?
I want to create a motion sensored system, if the motion sensor detects motion it will make a speaker play a sound and a screen will record the time. This needs to be a loop that turns on for x number of hours and off for z number of hours.
Also, I need the speaker to loop through different sounds...
I'm new to this sort of programming so any help anyone can give me on how to write this code would be greatly appreciated, thanks.

The scope of this question is far too broad.  Breakdown you questions into the specific tasks.  When you have done that, try submitting questions showing what you have tried and what you need.

Good project idea...This breaks down very nicely into parts that you can build and test individually.
First, I would start with the blink example, this will be helpful when debugging the other parts and it will guarantee that you have everything setup and can program the Arduino with the IDE.
Then there's the actual pieces to get the project working.
*Play a Sound
*Display Information
*Record Time of Day
*Enable and Disable based on Elapsed Time or Time of Day
*Motion Sensing
To play a sound you have a couple of options.  The simplest would be to get a buzzer since you can control these right from an Arduino pin.  If you want to play a specific MP3 or wav file, you will need a slightly more involved setup.  Here is an example for playing a tone with a buzzer.  http://www.arduino.cc/en/tutorial/tone
For the motion sensing you probably want a PIR sensor.  You can find them everywhere (Ebay, Sparkfun, Adafruit, Amazon, etc).  You can also google Arduino PIR Example.  Here is one result. http://playground.arduino.cc/Code/PIRsense
Once you've got those two bits working you can play a tone, when motion is detected.  Next is the display.  Outputting to an LCD is pretty easy.  There's a few ways to do this.  You may want to find a tutorial for the specific LCD screen that you decide to buy.  (While you are looking, check out the OLED screens from Adafruit, they are pretty neat).  Anyway, get the screen working in code by itself, then you can connect it to the rest of your system to print something when you trigger the motion sensor and play the tone.
So, the timing...This is a little more involved.  The Arduino does not have a real time clock (RTC) so it can't tell the time.  You would have to get a separate RTC module and set the time on it.  I haven't worked with those before but...there are a few ways to interact with time.  If motion is triggered, you can check the time and if it is between the times that are valid (which you would define) then trigger the speaker, otherwise don't.
Once you can get the time from the RTC, you can display that information to the screen.
That should get you started.


text:
Merging two codes, one for speaker one for LCD clock (Arduino Uno)
I have two different codes. The first one makes a LCD screen count the time and print it, then when one of the buttons on the LCD shield itself is pressed, it prints the time on the top line that it was pressed. That's the one below, I apologize that it has a lot of notes though it so unless it's in the Arduino program it looks confusing.
/*--------------------------------------------------------------------------    ------------
 Includes
 --------------------------------------------------------------------------------------*/
#include <Wire.h>
#include <LiquidCrystal.h>   // include LCD library
/*--------------------------------------------------------------------------------------
 Defines
 --------------------------------------------------------------------------------------*/
// Pins in use
#define MILLIS_OVERFLOW 34359738
#define BUTTON_ADC_PIN           A0  // A0 is the button ADC input
#define LCD_BACKLIGHT_PIN         3  // D3 controls LCD backlight
// ADC readings expected for the 5 buttons on the ADC input
#define RIGHT_10BIT_ADC           0  // right
#define UP_10BIT_ADC            145  // up
#define DOWN_10BIT_ADC          329  // down
#define LEFT_10BIT_ADC          505  // left
#define SELECT_10BIT_ADC        741  // right
#define BUTTONHYSTERESIS         10  // hysteresis for valid button sensing           window
//return values for ReadButtons()
#define BUTTON_NONE               0  //
#define BUTTON_RIGHT              1  //
#define BUTTON_UP                 2  //
#define BUTTON_DOWN               3  //
#define BUTTON_LEFT               4  //
#define BUTTON_SELECT             5  //
//some example macros with friendly labels for LCD backlight/pin control, tested and can be swapped into the example code as you like
#define LCD_BACKLIGHT_OFF()     digitalWrite( LCD_BACKLIGHT_PIN, LOW )
#define LCD_BACKLIGHT_ON()      digitalWrite( LCD_BACKLIGHT_PIN, HIGH )
#define LCD_BACKLIGHT(state)    { if( state ){digitalWrite(     LCD_BACKLIGHT_PIN, HIGH );}else{digitalWrite( LCD_BACKLIGHT_PIN, LOW );} }
/*--------------------------------------------------------------------------------------
 Variables
 --------------------------------------------------------------------------------------*/
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds = 0, minutes = 34, hours = 8;

byte buttonJustPressed  = false;         //this will be true after a          ReadButtons() call if triggered
byte buttonJustReleased = false;         //this will be true after a         ReadButtons() call if triggered
    byte buttonWas          = BUTTON_NONE;   //used by ReadButtons() for     detection of button events
        /*--------------------------------------------------------------------------------------
     Init the LCD library with the LCD pins to be used
 --------------------------------------------------------------------------------------*/
       LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2 LCD     shield. LCD: ( RS, E, LCD-D4, LCD-D5, LCD-D6, LCD-D7 )
/*--------------------------------------------------------------------------------------
     setup()
     Called by the Arduino framework once, before the main loop begins
 --------------------------------------------------------------------------------------*/
    void setup()
    {
  //button adc input
      pinMode( BUTTON_ADC_PIN, INPUT );         //ensure A0 is an input
      digitalWrite( BUTTON_ADC_PIN, LOW );      //ensure pullup is off on A0
  //lcd backlight control
  digitalWrite( LCD_BACKLIGHT_PIN, HIGH );  //backlight control pin D3 is         high (on)
  pinMode( LCD_BACKLIGHT_PIN, OUTPUT );     //D3 is an output
  //set up the LCD number of columns and rows:
  lcd.begin( 16, 2 );

  //Print some initial text to the LCD.
  Serial.begin(9600);
  lcd.begin( 16, 2 );

}
/*--------------------------------------------------------------------------------------
 loop()
 Arduino main loop
 --------------------------------------------------------------------------------------*/
void loop()
{
  setClock();
  byte button;

  button = ReadButtons();

  /**
   * After set clock now you have 3 int variables with the current time
   */
  //seconds
  //minutes
  //hours
  lcd.setCursor ( 0, 1);
  lcd.print(hours);
  lcd.print(":");
  lcd.print(minutes);
  lcd.print(":");
  lcd.print(seconds);
  lcd.print(":");
  lcd.print(elapsedMillis);

      //get the latest button pressed, also the buttonJustPressed,     buttonJustReleased flags

  //blank the demo text line if a new button is pressed or released, ready for a new label to be written

  //show text label for the button pressed
   if(buttonJustPressed || buttonJustReleased)
  switch( button )
  {

  case BUTTON_LEFT:
    {
      lcd.setCursor( 0, 0 );
               lcd.print(hours);
               lcd.print(":");
               lcd.print(minutes);
               lcd.print(":");
               lcd.print(seconds);
               lcd.print(":");
               lcd.print(elapsedMillis);

      break;

    }
  default:
    {
      break;
    }
  }

  if( buttonJustPressed )
    buttonJustPressed = false;
  if( buttonJustReleased )
    buttonJustReleased = false;
}
     /*--------------------------------------------------------------------------------------
     ReadButtons()
     Detect the button pressed and return the value
     Uses global values buttonWas, buttonJustPressed, buttonJustReleased.
 --------------------------------------------------------------------------------------*/
        byte ReadButtons()
    {
  unsigned int buttonVoltage;
  byte button = BUTTON_NONE;   // return no button pressed if the below         checks don't write to btn

  //read the button ADC pin voltage
  buttonVoltage = analogRead( BUTTON_ADC_PIN );
  //sense if the voltage falls within valid voltage windows
  if( buttonVoltage < ( RIGHT_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_RIGHT;
  }
  else if(   buttonVoltage >= ( UP_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( UP_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_UP;
  }
  else if(   buttonVoltage >= ( DOWN_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( DOWN_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_DOWN;
  }
  else if(   buttonVoltage >= ( LEFT_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( LEFT_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_LEFT;
  }
  else if(   buttonVoltage >= ( SELECT_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( SELECT_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_SELECT;
  }
  //handle button flags for just pressed and just released events
  if( ( buttonWas == BUTTON_NONE ) && ( button != BUTTON_NONE ) )
  {
    //the button was just pressed, set buttonJustPressed, this can optionally be used to trigger a once-off action for a button press event
//it's the duty of the receiver to clear these flags if it wants to detect a new button change event
    buttonJustPressed  = true;
    buttonJustReleased = false;
  }
  if( ( buttonWas != BUTTON_NONE ) && ( button == BUTTON_NONE ) )
  {
    buttonJustPressed  = false;
    buttonJustReleased = true;
  }

  //save the latest button value, for change event detection next time round
  buttonWas = button;

  return( button );
}
void setClock()
{
  currentMillis = millis();
      /**
   * The only moment when currentMillis will be smaller than previousMillis
   * will be when millis() oveflows
   */
  if (currentMillis < previousMillis){
    elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
  }
  else {
    elapsedMillis += currentMillis - previousMillis;
  }

  /**
   * If we use equals 1000 its possible that because of the mentioned loop     limitation
   * you check the difference when its value is (999) and on the next loop its value is (1001)
   */
  if (elapsedMillis > 999){
    seconds++;
    elapsedMillis = elapsedMillis - 1000;
  }

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

  previousMillis = currentMillis;
    }

The next code is to control the speaker and makes it play happy birthday when the a proximity sensor is set off. I need to somehow merge the two codes so that when the proximity sensor is set off the speaker plays the sound, but so that the clock continues to still count. Does anyone know how I can do this?
#include <Wire.h>
#include <LiquidCrystal.h>

int timer = 1000;
int C = 262;
int D = 294;
int E = 330;
int F = 349;
int G = 392;
int A = 440;
int B = 494;
int Bflat = 466;
int Chigh = 523;

LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );
const int analogPin = A1;    // pin that the sensor is attached to
const int threshold = 400;

void setup()
{
     // initialize serial communications at 9600 bps:
     Serial.begin(9600);
     pinMode(10, OUTPUT); // Red LED
     pinMode(12, OUTPUT); // Yellow LED
     pinMode(11, OUTPUT); // Green LED
     pinMode(13, OUTPUT); // Speaker
         lcd.begin(16, 2);
 }
void loop()
{
 int analogValue = analogRead(analogPin);

  if (analogValue > threshold) {

tone(13,C,timer/2);// Happy Bday to You
delay(200);
tone(13,C,timer/2);
delay(200);
tone(13,D,timer/2);
delay(400);
tone(13,C,timer/2);
delay(400);
tone(13,F,timer/2);
delay(400);
tone(13,E,timer);
delay(750);

 }
else {
}
}

Step one is to do away with all those horrible delay() calls

Just change if (elapsedMillis > 999){ to while (elapsedMillis > 999){ and add the loop code of the music to the loop code of the lcd. The only downside is that the display will not update while the melody is playing. But it will update after the 5 tones are played. But it won't miss any seconds.


text:
Change code so motion sensor prints time instead of a button
I have the code below. At the moment there is a proximity sensor that makes a speaker play happy birthday when it is set off. I also have an LCD shield attached and when one of the buttons on LCD screens interface is pressed, the time that it was when the button was pressed prints on the screen. I need to get it so that when the proximity sensor is set off it plays the sound on the speaker and then prints the time which is was set off on the screen.
/*--------------------------------------------------------------------------------------
 Includes
 --------------------------------------------------------------------------------------*/
#include <Wire.h>
#include <LiquidCrystal.h>   // include LCD library

int timer = 1000;
int C = 262;
int D = 294;
int E = 330;
int F = 349;
int G = 392;
int A = 440;
int B = 494;
int Bflat = 466;
int Chigh = 523;

const int analogPin = A1;    // pin that the sensor is attached to
const int threshold = 400;

/*--------------------------------------------------------------------------------------
 Defines
 --------------------------------------------------------------------------------------*/
// Pins in use
#define MILLIS_OVERFLOW 34359738
#define BUTTON_ADC_PIN           A0  // A0 is the button ADC input
#define LCD_BACKLIGHT_PIN         3  // D3 controls LCD backlight
// ADC readings expected for the 5 buttons on the ADC input
#define RIGHT_10BIT_ADC           0  // right
#define UP_10BIT_ADC            145  // up
#define DOWN_10BIT_ADC          329  // down
#define LEFT_10BIT_ADC          505  // left
#define SELECT_10BIT_ADC        741  // right
#define BUTTONHYSTERESIS         10  // hysteresis for valid button sensing     window
//return values for ReadButtons()
#define BUTTON_NONE               0  //
#define BUTTON_RIGHT              1  //
#define BUTTON_UP                 2  //
#define BUTTON_DOWN               3  //
#define BUTTON_LEFT               4  //
#define BUTTON_SELECT             5  //
//some example macros with friendly labels for LCD backlight/pin control,     tested and can be swapped into the example code as you like
#define LCD_BACKLIGHT_OFF()     digitalWrite( LCD_BACKLIGHT_PIN, LOW )
#define LCD_BACKLIGHT_ON()      digitalWrite( LCD_BACKLIGHT_PIN, HIGH )
#define LCD_BACKLIGHT(state)    { if( state ){digitalWrite(     LCD_BACKLIGHT_PIN, HIGH );}else{digitalWrite( LCD_BACKLIGHT_PIN, LOW );} }
/*--------------------------------------------------------------------------------------
 Variables
 --------------------------------------------------------------------------------------*/
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds = 0, minutes = 34, hours = 8;

byte buttonJustPressed  = false;         //this will be true after a        ReadButtons() call if triggered
byte buttonJustReleased = false;         //this will be true after a     ReadButtons() call if triggered
byte buttonWas          = BUTTON_NONE;   //used by ReadButtons() for detection of button events
/*--------------------------------------------------------------------------------------
 Init the LCD library with the LCD pins to be used
 --------------------------------------------------------------------------------------*/
LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2     LCD shield. LCD: ( RS, E, LCD-D4, LCD-D5, LCD-D6, LCD-D7 )
/*--------------------------------------------------------------------------------------
 setup()
 Called by the Arduino framework once, before the main loop begins
 --------------------------------------------------------------------------------------*/
void setup()
{
  //button adc input
  pinMode( BUTTON_ADC_PIN, INPUT );         //ensure A0 is an input
  digitalWrite( BUTTON_ADC_PIN, LOW );      //ensure pullup is off on A0
  //lcd backlight control
  digitalWrite( LCD_BACKLIGHT_PIN, HIGH );  //backlight control pin D3 is     high (on)
  pinMode( LCD_BACKLIGHT_PIN, OUTPUT );     //D3 is an output
  //set up the LCD number of columns and rows:
   pinMode(13, OUTPUT);
  lcd.begin( 16, 2 );

  //Print some initial text to the LCD.
  Serial.begin(9600);
  lcd.begin( 16, 2 );

}
/*--------------------------------------------------------------------------------------
 loop()
 Arduino main loop
 --------------------------------------------------------------------------------------*/
void loop()
{

  setClock();
  byte button;

  button = ReadButtons();

  /**
   * After set clock now you have 3 int variables with the current time
   */
  //seconds
  //minutes
  //hours
  lcd.setCursor ( 0, 1);
  lcd.print(hours);
  lcd.print(":");
  lcd.print(minutes);
  lcd.print(":");
  lcd.print(seconds);
  lcd.print(":");
  lcd.print(elapsedMillis);

  //get the latest button pressed, also the buttonJustPressed,     buttonJustReleased flags

  //blank the demo text line if a new button is pressed or released, ready for a new label to be written

  //show text label for the button pressed
   if(buttonJustPressed || buttonJustReleased)
  switch( button )
  {

  case BUTTON_LEFT:
    {
      lcd.setCursor( 0, 0 );
               lcd.print(hours);
               lcd.print(":");
               lcd.print(minutes);
               lcd.print(":");
               lcd.print(seconds);
               lcd.print(":");
               lcd.print(elapsedMillis);

      break;

    }
  default:
    {
      break;
    }
  }

  if( buttonJustPressed )
    buttonJustPressed = false;
  if( buttonJustReleased )
    buttonJustReleased = false;
}
/*--------------------------------------------------------------------------------------
 ReadButtons()
 Detect the button pressed and return the value
 Uses global values buttonWas, buttonJustPressed, buttonJustReleased.
 --------------------------------------------------------------------------------------*/
byte ReadButtons()
{
  unsigned int buttonVoltage;
  byte button = BUTTON_NONE;   // return no button pressed if the below checks don't write to btn

  //read the button ADC pin voltage
  buttonVoltage = analogRead( BUTTON_ADC_PIN );
  //sense if the voltage falls within valid voltage windows
  if( buttonVoltage < ( RIGHT_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_RIGHT;
  }
  else if(   buttonVoltage >= ( UP_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( UP_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_UP;
  }
  else if(   buttonVoltage >= ( DOWN_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( DOWN_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_DOWN;
  }
  else if(   buttonVoltage >= ( LEFT_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( LEFT_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_LEFT;
  }
  else if(   buttonVoltage >= ( SELECT_10BIT_ADC - BUTTONHYSTERESIS )
    && buttonVoltage <= ( SELECT_10BIT_ADC + BUTTONHYSTERESIS ) )
  {
    button = BUTTON_SELECT;
  }
  //handle button flags for just pressed and just released events
  if( ( buttonWas == BUTTON_NONE ) && ( button != BUTTON_NONE ) )
  {
    //the button was just pressed, set buttonJustPressed, this can optionally be used to trigger a once-off action for a button press event
    //it's the duty of the receiver to clear these flags if it wants to detect a new button change event
    buttonJustPressed  = true;
    buttonJustReleased = false;
  }
  if( ( buttonWas != BUTTON_NONE ) && ( button == BUTTON_NONE ) )
  {
    buttonJustPressed  = false;
    buttonJustReleased = true;
  }

  //save the latest button value, for change event detection next time round
  buttonWas = button;

  return( button );
}
void setClock()
{
  currentMillis = millis();
  /**
   * The only moment when currentMillis will be smaller than previousMillis
   * will be when millis() oveflows
   */
  if (currentMillis < previousMillis){
    elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
  }
  else {
    elapsedMillis += currentMillis - previousMillis;
  }

  /**
   * If we use equals 1000 its possible that because of the mentioned loop limitation
   * you check the difference when its value is (999) and on the next loop     its value is (1001)
   */
  while (elapsedMillis > 999){
    seconds++;
    elapsedMillis = elapsedMillis - 1000;
  }

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

  previousMillis = currentMillis;

 int analogValue = analogRead(analogPin);
  if (analogValue > threshold) {

tone(13,C,timer/2);// Happy Bday to You
delay(200);
tone(13,C,timer/2);
delay(200);
tone(13,D,timer/2);
delay(400);
tone(13,C,timer/2);
delay(400);
tone(13,F,timer/2);
delay(400);
tone(13,E,timer);
delay(750);
 }
else {

}
}

Why are you still posting code with the MILLIS_OVERFLOW stuff now that you know it's both useless and bogus? Do you at least follow the answers to your previously posted questions?

Dude, I'm completely new to this and not good at knowing which parts to take out. I do follow the previous answers I get which is why I've gotten to where I am, I'm just trying to get it all working before I simplify it cause every time I try to I end up deleting stuff I shouldn't on accident and it all stops working, but I'll try again now

The code seems a little hotchpotch; is the code for reading the sensor supposed to be within the setClock() function? It would be better to put the following within loop():
if(analogRead(analogPin) > threshold)
{
    playMelody();
    printTriggerTime();
}

And create two new functions that handle the playing of 'Happy Birthday' and the printing of the time:
void playMelody()
{
    tone(13, C, timer / 2);// Happy Bday to you
    ...
    delay(750);
}

...which is just a cut-paste of what you've got in the setClock() function, and:
void printTriggerTime()
{
    lcd.setCursor(0, 0);
    ...
    lcd.print(elapsedMillis);
}

...which is a copy-paste of the code from within case BUTTON_LEFT:.
This will now play 'Happy Birthday' and print the time whenever the proximity sensor is triggered, AND it will print the time when the left-button is pressed (unless you remove that part of the code).
On a separate point, it's bad coding practice to use #define for a function, as you have done with #define LCD_BACKLIGHT(state) { if ( state )... - it makes it quite difficult to read the code, and can't conceive any reason why this isn't its own function. However, a nice trick in C is the following 'shortcut' statement:
( CONDITION ? DO_IF_TRUE : DO_IF_FALSE )

Thus you should change that line to:
#define LCD_BACKLIGHT(state) ( state ? digitalWrite(LCD_BACKLIGHT_PIN,HIGH) : digitalWrite(LCD_BACKLIGHT_PIN,LOW))

That being said, "LCD_BACKLIGHT(state)" isn't actually used anywhere in the program!

(state ? digitalWrite(LCD_BACKLIGHT_PIN,HIGH) : digitalWrite(LCD_BACKLIGHT_PIN,LOW)) can be simplified to digitalWrite(LCD_BACKLIGHT_PIN, state ? HIGH : LOW), and then further to digitalWrite(LCD_BACKLIGHT_PIN, state), as digitalWrite() interprets its second argument as a boolean.


text:
Class TKPotentiometer has no member named 'read'
I am testing a set-up using the TinkerKit shield for Arduino Uno, and a few TinkerKit inputs and outputs. I have an issue with the code provided on the TinkerKit website for the potentiometer component:
#include <TinkerKit.h>

// creating the object 'pot' that belongs to the 'TKPotentiometer' class
TKPotentiometer pot(I0);

// creating the object 'led' that belongs to the 'TKLed' class
TKLed led(O0);

int brightnessVal = 0;  // value read from the pot

void setup() {
  // initialize serial communications at 9600 bps
  Serial.begin(9600);
}

void loop() {
  // read the potentiometer's value:
  brightnessVal = pot.read();

  // set the led brightness
  led.brightness(brightnessVal);

  // print the results to the serial monitor:
  Serial.print("brightness = " );
  Serial.println(brightnessVal);

  // wait 10 milliseconds before the next loop
  delay(10);
}

I get an error message when compiling:
Class TKPotentiometer has no member named 'read'

According to this webpage, though, read should be a member of the class. Why am I receiving this message?

As soon as I finished writing the question, it came to my mind that perhaps I misspelled something, so I looked for a file in the Menu's sketchbook that I could load.
With my surprise, I found the same exact code as I posted, with a little difference:
pot.read() was substituted with pot.get()


text:
Webserver with Arduino Yun without SD
I'm trying to set up a simple web-server with Arduino Yun without an SD card, i.e via REST, if I understood it right (I'm new to some of these stuff). I want to be able to "get" data (sent by Arduino) through a jQuery script and show the user a formatted HTML page.
Here I provide you a simplified version of my Arduino sketch:
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

const byte internalLED = 13;

YunServer server;

void setup() {
  pinMode(internalLED, OUTPUT);
  digitalWrite(internalLED, HIGH);     // Turn the led on to advise about bridge begin in progress
  Bridge.begin();          // Let's activate the Yun Bridge...
  ledBlink(150);           // ...bridge activation done (user sees a blink)
  // server.listenOnLocalhost();       // Listen for incoming connection only from localhost (no one from the external network could connect)
  server.begin();          // Let's acrivate the Yun server...
  ledBlink(150);           // ...server activation done (user sees a blink)
}

void loop() {
  YunClient client = server.accept();  // Get clients coming from server
  if (client)                          // Is there a new client?
  {
    client.print(77);                  // Send a "77" to client (e.g. browser)
    client.stop();                     // Close connection and free resources.
    ledBlink(500);
  }
  delay(50);
}

void ledBlink(int delayTime) {
  digitalWrite(internalLED, HIGH); // Turn (or keep) the LED on
  delay(delayTime);
  digitalWrite(internalLED, LOW);  // Turn (or keep) the LED off
  delay(delayTime);
}

My Arduino Yun is connected via WiFi with static IP (192.168.1.98) to the same network of my laptop, and they can ping each other. Right now, if I insert into my browser the address
http://192.168.1.98/arduino/whatever

I correctly receive a simple «77» (no quotes or \r\n)
But I cannot "get" it when opening the page get_test.html (which is on my harddisk, not in the SD):
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $.get("http://192.168.1.98/arduino/whatever", {}, function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
</script>
</head>
<body></body>
</html>

This is strange to me because this html code works if I change the address inside the "get" request with https://dl.dropboxusercontent.com/u/12389503/demo_test.txt which consists only of a «21» (no \r\n). The problem is I don't even receive the alert when the address is the IP of Arduino, but the board is receiving the request since I can see the led blinking once, as expected.
I'm running out of tests, any suggestion is welcome.

Whenever making ajax calls from/to different hosts (as your pc and the yun) you should use JSONP.

Thank you, I finally got it working today. I created a JSONP message as you told me. I changed in the sketch from client.print(77); to client.println("temperature({\"value\": 77});");. My jQuery request is now $.ajax({url: 'http://192.168.1.98/arduino/api/temperature', dataType: 'jsonp', jsonpCallback: 'temperature', success: function(result){alert("Value received through JSONP is "+result.value)}});


text:
Why bootloader sizes differs from 0.5 to 8 kilo bytes for different boards?
According to official web info bootloader sizes are 0.5, 2 and 8 kilo bytes for UNO, Pro mini and ATMega2560. I believe all three boot loaders do similar job of receiving serial link data and write to Flash memory.
UNO and Pro mini use same/similar ATMega168/328 chips but boot loader size are 0.5 and 2 KB.
ATMega2560 apparent has a more advanced MCU which presumably should use similar or even less memory to do the same task, but the size is significantly large at 8 KB.
Why sizes differ? Small difference may be explained by different development teams, but, should be that much different, from 0.5 to 8KB.

Different bootloaders have different capabilities.

Bootloader of the Mini and Uno are pretty much the same. (I can't find the source-code but the hex files are only slightly different).
The 2k is because they haven't updated mini328.upload.maximum_size in boards.txt. Probably because that would break the board for users that haven't updated the bootloader yet.
The 2560 is using a stk500v2 compatible boot loader instead of Optiboot (uno and mini), because optiboot only supports upto 64kb addresses. Not sure why it is that much bigger though.

How to find out if UNO, Pro Mini/ATMega2560 boards are loaded with latest version boot loader (hoping that it is smaller in size to allow max user program)?  Where can I get latest boot loaders for these 3 boards?  If needed, how to re-program boot loader of UNO/Pro Mini/ATMega2560?

Uploading the latest is probably easier than testing which version is on it. Bootloaders can be found at: https://github.com/arduino/Arduino/tree/master/hardware/arduino/bootloaders . Just google how to upgrade. If you can work it out ask a new question here on SE.

Generally speaking the chips offer four possible bootloader size configurations. For example, on the Atmega328 you can have 512, 1024, 2048 or 4096 bytes (notice that the sizes increase by a power of 2).
The chips with less program memory offer smaller bootloaders because they won't want to use a lot of that memory for something that is only used to upload code. The chips with more memory (like the Atmega2560) offer larger bootloaders, ie. 1k, 2k, 4k, 8k (again it increases by a power of 2).
The Uno manages to use a 512 byte bootloader (Optiboot). The Mega, which has more complex instructions (to handle a larger address space) would need larger bootloaders. Also in some cases the bootloader writers add in extra stuff like a debugging console.


text:
Arduino serial communication broken. Possible due to short circuit
So I have a project I'm working on where I have about 6 arduino boards communicating with one another through cables. I've been testing them using a regulated DC PSU and at some point I caused a short and since then I can't upload any sketches onto the arduino. On some of them, the TX pin will light up while trying but RX won't and the IDE tends to freeze after around 90% of the upload process is complete.
Does anyone know how badly I screwed up? How do I avoid this next time? Is there an easy fix?
Thank you!

Can you give more details about the short circuit? Where did the current go?

Can you say us which Arduino board you have? Maybe you can switch the micro itself or maybe not

Try disconnecting the arduinos from each other, use a different power supply,plug pack or power via usb from pc and try programming and running them one by one. Try the simplest program possible and go from there(led flash of onboard led then change pins and use a led with resistor to check if you have blown any io pins).Which boards as if its older ones you may have just damaged the usb to serial chip. Or if a dip not smd board you maybe able to just replace the atmel chip. More details, circuit diagram and maybe a link to a picture would help us help you.


text:
Is the Arduino library so slow?
I have a plan to operate 5MP camera module with the arduino Due. But I wonder if I can use the arduino libraries that include digitalRead, digitalWrite and so on. But some people said that it is a bad idea. Especially I found that people wrote values on registers instead of using the library, when they control ov7670 with Uno.
Contrary to this, ArduCam uses the libraries, even for OV5642!. Here is the link
https://github.com/ArduCAM/Arduino/blob/master/ArduCAM/examples/mini/ArduCAM_Mini_OV5642_Video_Streaming/ArduCAM_Mini_OV5642_Video_Streaming.ino
So could anyone please let me know, if it is okay to use such library and never to use register directly? With 'register' I mean arduino's register, not camera's.
I guess the system clock and existence of FIFO would affect the answer. But still I don't know how to evaluate their effect analytically.

I don't see any digitalWrite call in that that library.

Unless you have a really large number of read/write operations and very tight time constraints, I doubt you are going to have any significant advantage in terms of speed.
Accessing the bits in a port together, rather than individually is certainly more efficient, both in terms of time and space, but it might cost in readability, depending on how comfortable you are with leaving the Arduino libraries behind.
You can have also a look at this thread.
Notice that the maximum gain happens only when all the pins you have to read or write belong to the same register.

You can use ANY and ALL libraries (if their LICENCies allows it) you want, or none library at all.
More important is, if the result does what you need.
For some kinds of problems even very slow library is fast enought. For some kinds only highly optimized library can do. Some problems are so complex, that any Arduino cannot do it even with the best effort and total optimization of code and HW resources. (Well, for some problems even todays best supercomputers are not good enough)
Lot depends on what exactly you plan to do with such camera - if you need some simple controls (like START, STOT, change sesitivity ...) maybe anything is good. If you want to make some autonomous system navigated by vison system which would learn from experience and will recognize all your face expression, than there is no Arduino with needed computing power at all.
Just try find any project vaguelly similar to yours, look, what they are using and what they say about it (excelent, barely usable, we found it impossible) and try library/approach based on that. If it works somehow, make it better and be celebrity too :) If it does not work at all and does not yeld any usable results, maybe try something different.
A lot can be done, if you enhance Arduinos capabilities with external modules (commercial or home made) be it in form of shield or in form of totally different platform.


text:
arduino --verify / --upload not working (command line)
I installed Arduino IDE version 2.1 on Ubuntu via apt-get. Then I typed the following command in terminal to see if the Arduino IDE compiles my sketch.
 arduino --verify xx.ino

However, this command launches the GUI IDE. Is the CLI not supported anymore, or is the cause in apt-get the package?

There's no such thing as Arduino IDE version 2.1, the most recent version is a mere 1.8.5.

It's quite possible that this "version 2.1" doesn't support command line processes. I've never heard of an Arduino IDE version 2.1. My understanding is the version you get from apt-get install arduino is something like 2:1.0.5+dfsg2 so maybe you interpreted that as 2.1. That version is based on Arduino IDE 1.0.5, though apparently it has some non-standard modifications. Command line operation was first added in Arduino IDE 1.5.2, though some additional functionalities were added in newer versions.
You should always install the official Arduino IDE downloaded from:
https://www.arduino.cc/en/Main/Software

Thank you very much  for the clear answer! I indeed interpreted 2:1.0.5+dfsg2 as 2.1.


text:
toggling Rx, Tx pins after Serial.begin
What should one expect when the following program runs on Arduino Uno?
void setup()
{
    Serial.begin(9600);
    DDRD |= 0b11;
}

void loop()
{
    PORTD |= 0b11;
    delay(100);
    Serial.print("ABCD");
    PORTD &= ~0b11;
    delay(100);
    Serial.print("DEFG\n");
}

When Serial.begin() is used, the pins PD0, PD1 might be configured as UART pins. After that if DDR is used, are the pins configured as GPIO, or are they still UART Rx, Tx pins?

what happens when you run the sketch?

As always, the answer is in the datasheet:

TXD/PCINT17 – Port D, Bit 1

TXD, Transmit Data (Data output pin for the USART). When the USART Transmitter is enabled, this pin is configured as an output regardless of the value of DDD1.
  PCINT17: Pin Change Interrupt source 17. The PD1 pin can serve as an external interrupt source.

RXD/PCINT16 – Port D, Bit 0

RXD, Receive Data (Data input pin for the USART). When the USART Receiver is enabled this pin is configured as an input regardless of the value of DDD0. When the USART forces this pin to be an input, the pull-up can still be controlled by the PORTD0 bit.

As to what trying to set the output level on the TX pin would have, only experimentation can show.  It's not defined in the datasheet (because who would do it?)


text:
connection between two ARDUINO with xbee
I have a setup where two XBEES modules are talking to each other, both using XBEE shields, one attached to an UNO ARDUINO and the other a MEGA ARDUINO. One XBEE sends the data and the other receives it and switch on or off a LED.
The problem is the receiver one don't work.
This is the sender code
int led = 13;
const int bouton = 2; String inputString;
void setup() {
pinMode(led, OUTPUT);
Serial1.begin(9600);
Serial.begin(9600);
digitalWrite(led, LOW);
}
void loop() {
while (Serial.available() ) {
// get the new byte:
delay(3);
char inChar = Serial.read();
// add it to the inputString:
inputString += inChar;
}
if (inputString.length() >0) {
Serial.println(inputString);
Serial1.println(inputString);
inputString="";
}
}

This the receiver one
int led = 13;
String inputString;
void setup() {
// put your setup code here, to run once:
pinMode(led, OUTPUT);
Serial.begin(9600);
}
void loop() {
while (Serial.available() ) {
// get the new byte:
delay(3);
char inChar = Serial.read();
// add it to the inputString:
inputString += inChar;
}

if (inputString.length() >0) {
Serial.println(inputString);
if (inputString == "on"){
digitalWrite(led,HIGH);
Serial.println("LED ON");
}

if (inputString == "off"){
digitalWrite(led,LOW);
   Serial.println("LED OFF");
}
inputString="";
}
}

I get on the serial monitor of ARDUINO UNO what i wrote in the serial monitor of ARDUINO MEGA but the LED don't switch on or off :/

This question is purely on Arduino, and should be (/have been) posted on Arduino.stackexchange.com.
It has nothing to do with "electronics design". And the only relevancy is due to it being a microcontroller, but Arduino actually has it's own StackExchange page.

Probably you are getting a new character/carrier return (\n or \n\r) in your receivers' string, that is why it won't match exactly "on" or "off", it will be "on\n", "on\r\n" or similar.


text:
How do I even out Infared distance sensor readings?
I am using a standard infared distance sensor on a small robot and i am trying to even out the readings on it so it is more accurate. The readings are very sporadic and often take huge jumps in the distance. Is there a method of programming or circuit design that might make this easier to use? I'm trying to keep my robot from running into things.

Can you please include which sensor(s) you are including and your current circuit/code? Thanks!

Thanks for the quick reply. The sensor is the Infrared Proximity Sensor - Sharp GP2Y0A21YK I believe.

Wikipedia has a page on moving averages: http://en.wikipedia.org/wiki/Moving_average
I'd suggest at first try an exponential moving average:

average = a * sample + (1 - a) * average

Experiment with different values of a (with 0 < a <= 1).
The smaller a is, the smoother the curve, but also the longer (more iterations) it takes for an actual change in the input to be reflected in average.

Averaging is a very good technique for improving noisy data, provided
you have a “nice” noise. “Nice” meaning that you never get “atypical”
data points, i.e. the error of any given data point is of the order of
the “typical” error amplitude. If you have for instance
additive white Gaussian
noise, then
it can be shown that averaging is in some way the “best” way to clean
your data.
However, if you have big sporadic errors, then averaging is not a good
solution. This is because you will have to average a lot of samples
in order to smoothen out a single big error... and the more samples you
average, the more chances you have to get another huge error that will
ruin your average. Of course, averaging will somewhat improve things,
and it is better than no smoothing at all, but there are better options.
The solutions to this problem lye in the realm of robust
statistics. It may look
like hairy math, but there is actually a very simple smoothing filter
that is far more robust than the average: it's called the
median. The idea is quite simple:
you sort your list of samples from smallest to largest, then you pick
the one sample that ends right in the middle of the sorted list. Unlike
the average, this filter is completely insensitive to samples carrying
huge errors, as long as the majority of samples are reasonable.
Here is an implementation of a simple moving-median filter based on the
standard libc’s qsort(). It assumes samples have int type, but you
can change it to whatever numeric type you want. You can also change the
filter length: longer lengths provide more robustness against series of
consecutive bad samples, at the cost of more filter delay, more memory,
and more processing time.
/*
 * Comparison function for qsort(): return an integer "less than, equal
 * to, or greater than zero if the first argument is considered to be
 * respectively less than, equal to, or greater than the second."
 */
int compare(const void *pa, const void *pb) {
    int a = *(int *)pa;
    int b = *(int *)pb;
    return a<b ? -1 : a>b ? +1 : 0;
}

#define FILTER_LENGTH 11  // length of the median filter, should be odd

/*
 * Input: raw sample.
 * Ouput: filtered sample.
 */
int median_filter(int data) {
    static int input_buffer[FILTER_LENGTH];
    static int input_index;
    int sorted_buffer[FILTER_LENGTH];

    // Store the current data point.
    input_buffer[input_index] = data;
    if (++input_index >= FILTER_LENGTH) input_index = 0;

    // Sort a copy of the input buffer.
    for (int i = 0; i < FILTER_LENGTH; i++)
        sorted_buffer[i] = input_buffer[i];
    qsort(sorted_buffer, FILTER_LENGTH, sizeof *sorted_buffer, compare);

    // Return median.
    return sorted_buffer[FILTER_LENGTH/2];
}

As I did not explicitly initialize the filter memory, this will output
zeros the few first times it is called. I encourage you to try this
filter and compare against an exponential moving average, and only then
decide which works best for you.

The Sharp GP... infra red proximity sensors can produce noisy output sometimes.  This is partly caused by the fact that they work by repeating a brief, powerful IR pulse.
So - the very first tweak I would suggest when using any of these sensors is to try a cheap 10 micro Farad electrolytic capacitor on the 5V power connections, reasonably close to the sensor itself.  This is mentioned on some of their datasheets, but gets forgotten...

IR sensors are very erratic in my experience. The best way is to take an average of multiple sensor readings. The number of readings required can be found by experimentation.
Example Sketch (Source)
The example below should be similar, and a good start for your model of IR sensor.
/*
 Sharp GP2Y0A21YK0F infrared proximity sensor (#28995)
 Collects an average of five readings from the sensor and displays the
 resulting value about every half second.

 See the SharpGP2Y0A21_Simple demonstration for additional usage notes,
 including connection diagram.

 This example code is for the Arduino Uno and direct compatible boards, using the
 Arduino 1.0 or later IDE software. It has not been tested, nor designed for, other
 Arduino boards, including the Arduino Due.

*/

const int irSense = A0;          // Connect sensor to analog pin A0
int distance = 0;

void setup() {
  Serial.begin(9600);            // Use Serial Monitor window
}

void loop() {
  Serial.println(irRead(), DEC); // Call irRead function to read sensor
                                 // Print value in Serial Monitor
  delay(250);                    // Wait another 1/4 second for the next read
                                 // (Note: Because of delays built into the
                                 //   irRead function the display of values will
                                 //   be slower than in the SharpGP2Y0A21_Simple
                                 //   sketch
}

// Take multiple readings, and average them out to reduce false readings
int irRead() {
  int averaging = 0;             //  Holds value to average readings

  // Get a sampling of 5 readings from sensor
  for (int i=0; i<5; i++) {
    distance = analogRead(irSense);
    averaging = averaging + distance;
    delay(55);      // Wait 55 ms between each read
                    // According to datasheet time between each read
                    //  is -38ms +/- 10ms. Waiting 55 ms assures each
                    //  read is from a different sample
  }
  distance = averaging / 5;      // Average out readings
  return(distance);              // Return value
}

My solution keeps reading for cycles (10 times) and calculate average it.
Be careful voltage output of many surface NOT same.


text:
How to update multiple outputs simultaneously
I need to update simultaneously all the outputs of a specific port.
I am familiar with using micro-processors assembly language. After initializing a port (Data Direction Register), I can write to that port and all outputs will update simultaneously.
In the Arduino commands  : I am aware of how to configure pins, such as pinMode(pin, mode), to make a pin an output or input.
I know of the digitalWrite(pin, value) , but this only updates one pin per command.
For timing reasons, I need to update several (same port) outputs without any time delay.
Normally (using assembly language) , I would keep a register with the data I desire on the output port, and write that register's data to the port.
Is there a command I can use in Arduino to accomplish the same thing?
If not a single command, what other choices do I have?
I use Arduino  micro,  UNO,  but I think the question might be valid for most Arduino

Yes, the ports of an Uno are addressed in C/C++ as PORTB, PORTC, and PORTD respectively, each 8 bits wide. You can read them or assign to them. Other processors' ports have similar names. Of course the pins' port assignments and functions differ from one to the other, which is one reason for providing the single-pin pinMode() and digitalRead(), digitalWrite() functions. But where you need to deal directly with the hardware (and probably don't care about chip-to-chip portability), the registers are exposed with the above symbols.
Also note that most other CPU registers are exposed the same way - the ports' data-direction registers as DDRA, DDRB, DDRC. You may not care about setting them up simultaneously, but if you wanted to make all of your hardware accesses similarly (and save the flash space for the portable pin functions), you could.
Update:

Is there a specific command I can use ? Such as Write PortD ?

Yes, you can use the PORTx names like any other C/C++ variable:
PORTD = 0xFF;
PORTD ^= 0x02;
if( (PORTD & 0x40) != 0 ){, for just a couple of examples - just like real C! :-)
PS: Pighixxx makes absolutely top-notch pinout diagrams for boards & processors. Here is his diagram for the 28-pin DIP-packaged AtMega328p for instance. They're extremely useful when you're working with a chip at the port or board level.

Is there a specific command I can use ?   Such as Write PortD  ?

If you need to do more than 8 (especially LOTS more), and timing is very critical, you can use a Serial In, Parallel Out (SIPO) chip, such as the 74HC595 - it also saves a lot of pins on the Arduino.
To use it, you need 3 pins connected to the Arduino. You send one bit to the chip from the Arduino for each output, then when you have them all set, you toggle the Latch pin - all output pins change at the same time. The chip has 8 outputs.
Another advantage of a chip like this is that you can daisy-chain them - with the same 3 pins, you can control as many pins as you like (subject to power availability, of course!).
Read https://www.arduino.cc/en/Tutorial/ShiftOut for more information on how to use them. They are dirt cheap (about US$1.26 each if you buy 10 from AliExpress, shipped to NZ, which is where I am).

Even though I selected another answer as more directly answering my question, your answer is also very helpful.


text:
Sparkfun Red board and CC3000 shield not allowing multiple HTTP_GET requests.
I have a SparkFun Red board (Arduino Uno R3) with a SparkFun CC3000 shield attached. I am trying to post data to the "data.sparkfun.com" service in order to test a basic Wifi data logger. I am using the AdaFruit CC3000 library for the sketch.
The problem is am having is that immediately after a power off and reset, the HTTP Get is successful. However, when the loop runs again, the post fails. Usually on the 2nd attempt. I have had a few times where it has looped 2-3 time before failing. But it always fails. If I reset the board with the push button or by disconnecting the serial monitor and reconnecting, it still fails to send the HTTP request.
I have checked my ram usage, and it doesn't appear to have any sort of leak in that regards. I have spent days looking online for similar issues, and can't seem to find anything related.
To make this all the more confusing, the board just seems to freeze, it doesn't give any sort of error on anything. And the freeze seems to happen at different places, nothing seems consistent.
Would someone mind checking my sketch code, seeing if there is anything glaring; maybe I have a bad board?
    #include <Adafruit_CC3000.h>
    #include <SPI.h>
    #include <avr/wdt.h>

    ////////////////////////////////////
    // CC3000 Shield Pins & Variables //
    ////////////////////////////////////
    // Don't change these unless you're using a breakout board.
    #define ADAFRUIT_CC3000_IRQ   2
    #define ADAFRUIT_CC3000_VBAT  7
    #define ADAFRUIT_CC3000_CS    10
    #define IP_ADDR_LEN     4   // Length of IP address in bytes

    #define SensorPin A0

    ////////////////////
    // WiFi Constants //
    ////////////////////
    #define WLAN_SSID "Hayes"
    #define WLAN_PASS "123456"
    #define WLAN_SECURITY WLAN_SEC_WPA2
    #define timeout 30000
    #define website "data.sparkfun.com"
    #define publicKey "MGg93JbM8LFJAQxG3jK0"
    #define privateKey "nz9M8WZVaXU7WXz4VnlX"
    #define NUM_FIELDS 1

    // Initialize the CC3000 objects (shield and client):
    Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,
                             ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIV2);

    /////////////////
    // Phant Stuff //
    /////////////////
    const String fieldNames[1] = { "value" };
    String fieldData[1];
    uint32_t ip = 0;

    //////////////////////
    // Input Pins, Misc //
    //////////////////////

    void setup()
    {
      wdt_disable();
      Serial.flush();
      Serial.begin(115200);
      Serial.println(F("\nInitializing..."));
      if (!cc3000.begin())
      {
        Serial.println(F("Couldn't being()! Check your wiring?"));
        while (1);
      }

      //Connect to WiFi network
      Serial.print(F("Connecting to WiFi network... "));
      Serial.println(String(WLAN_SSID));
      cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY, 3);
      Serial.println(F("done!"));
      while (!cc3000.checkDHCP())
      {
        delay(1000);
      }
      Serial.print(F("data.sparkfun.com -> "));
      while (ip == 0)
      {
        if (!cc3000.getHostByName("data.sparkfun.com", &ip)) {
          Serial.println(F("Couldn't Resolve!"));
          while (1) {}
        }
        delay(1000);
      }
    }

    void loop()
    {
      cc3000.printIPdotsRev(ip);
      Serial.println(F(""));
      float moisture = analogRead(SensorPin);
      fieldData[0] = String(moisture);
      Serial.println("Sensor Reading: " + String(moisture));
      int t = millis();
      //wdt_enable(WDTO_8S);
      Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);
      if (client.connected()&&
        ((millis() - t) < timeout))
      {
        Serial.println(F("Connection to Sparkfun data server."));
        Serial.print(F("Sending Request..."));
        client.print("GET /input/");
        client.print(publicKey);
        client.print("?private_key=");
        client.print(privateKey);
          client.print("&");
          client.print(fieldNames[0]);
          client.print("=");
          client.print(fieldData[0]);
        client.println(" HTTP/1.1");
        client.print("Host: ");
        client.println(website);
        client.println("Connection: close");
        client.println();
        Serial.println(F("HTTP command posted, getting response."));
      }
      else {
          Serial.println(F("Connection to website failed."));
        }

    //  while (client.connected())
    //  {
    //    while (client.available())
    //    {
    //      char c = client.read();
    //      Serial.print(c);
    //    }
    //  }
      client.close();
      Serial.println(F("Posting Data Complete"));
      //wdt_reset();
      //cc3000.disconnect();

      //reset watchdog and disable
      //wdt_reset();
      wdt_disable();

      delay(15000);
    }

Why do you have //cc3000.disconnect(); disabled? Without experience with your wifi board, it seems like this line could be important causing it to not reset, thus causing it to not totally disconnect from the client.

the cc3000.disconnect(); is used to disconnect from the AP. At this point, since it is plugged into constant power source, I assumed that I wouldn't want to disconnect from the AP, thus allowing my subsequent posts to the site to occur faster... by not having to reconnect to the Wifi AP again and again.


text:
SoftwareSerial.h alternative with AVR (Two Serial/UART ports in atmega328p)
Arduino pins can be used as UART using the SoftwareSerial.h library. Is there any alternative for AVR?
I need more than one serial port on a ATmega328P, but i don't use Arduino.
SoftwareSerial.h is tied to Arduino.h and Arduino pins. I do not use Arduino, i use avr-gcc with atmega328p and atmega8.

Sorry my english

Software serial should only be used as an absolute last resort. If you are having to look at using it then you aren't using the right microcontroller.  Don't just use a certain microcontroller "because you always have", or "because the arduino uses it" - use the right one for that job, and if you need multiple serial connections then choose one that has multiple serial ports in it.  There's plenty to choose from, even within the same family of chips, that provide more than one serial port, so would require minimal changes to your project to use them.

AVR274 describes a single-wire, half-duplex software UART.
AVR304 describes a half-duplex, interrupt-driven software UART, and AVR305 describes a polled alternative.
AVR307 describes implementing a half-duplex UART using a USI.
All code associated with each app note can be downloaded from Atmel's website.

where can I download them?

Do a search on the app note handle.


text:
why there is 4 ground in l293d?
I am using L293d motor driver to drive 2 motors simutaniusly in several direction.
But I am not shure why there is 2 Vcc and 4 GND in this IC.
Can anyone tell explain it?
Thank You...

It's explain in the datasheet.

A VCC1 terminal, separate from VCC2, is provided for the logic inputs to minimize device power dissipation. (pg. 2)

VCC1 is for the logic and VCC2 is for the motor supply.
The four grounds are all tied together internally and act as a heatsink for the chip. (pg. 11)

Apart from heatsinking the four pins in parallel reduce the impedance (resistance) to ground. The actual bond wires that run from the chip to the leadframe are pretty thin and as an effect the resistance is relatively high. By wiring these pins in parallel the impedance is reduced which is a good and important property when you are trying to drive high current loads.
Also the ground potential on the chip will be slightly lifted proportonal to the current in the ground connections. In practice this may cause strange effects like logic levels shifting up and down with load current.
Best to attach GND all to the ground plane, the impedance on the PCB will be low and and the large copper surface helps to keep temperature down.
Vcc1 is for logic and will often interface with your 5V microcontroller.
Vcc2 is the supply rail that will actually power the load.

They are connected together and used for heatsinking,
VS - is voltage supply
VSS - is logic level definition, if your uC logic level is 5V then power this with 5V. This will define voltage levels for the signal to be considered 0 or 1

Welcome to Arduino SE! Can you please explain a little more about the two pins? Not all new users know what logic level definition is...


text:
what is the coversion details of temperature usnig lm35?
I found similar type of code in many sites for coverting analog signal lm35 to centigrade.
But i can't understand that fully. So I need some help what this equation means
tempC = (5.0 * tempC * 100.0)/1024.0;

Thank you,

That equation doesn't quite make sense. Are you sure you copied it accurately?

I took a quick look at the data sheet for LM35 and it says that each centigrade means a 10 millivolt change.
If you have an ADC with 10-bit resolution, it means you have 1024 steps from 0 V to 5 V.
The temperature is then:
tempC = 5 * (ADCdata / 1024) * 100
This is equal to your equation. So it seems to be correct.
EDIT:
A more thorough explanation of the formula:
Lets call the value you read from your LM35 "ADCdata". The range of this value is determined by the resolution of the Analog-to-Digital Converter (ADC). The ADC converts a voltage to a digital value in the Arduino. This value is again what I refer to here as "ADCdata".
If the ADC resolution is 10-bits, it means the 5 volt input can be divided into 1024 equal levels. One level is about 5 millivolts (five thousands of a volt).
To find what value "ADCdata" is in volts we need to divide it with the resolution (1024) and multiply with 5 volts.
Lets say we have a 2.5 volt input signal. The ADCdata will then be 512. If we now divide 512 by 1024 we get 0.5. Lets multiply that with 5 volts and we get 2.5 volts!
We know from the data sheet that 10 millivolts equals 1 centigrade. Since we have our value in volts (2.5 V, which is the same as 2500 millivolts) we need to multiply it with 100 to get centigrades.