text:
How to send data from an Arduino to PC, without using the Serial Monitor?
I have an analog sensor which I want to send data from my Arduino Certified Intel Edison to PC, without using a Serial Monitor and preferably putting the data into a text file.

What do you mean by "serial monitor"? The serial monitor is an application used to.. well, monitor the serial port. Once you can see that the data is correct, you should develop your own application to get the serial data and do what you need. Anyway you used wrong tags for your question (arduino-uno and arduino-mega) and.. The edison is an Intel board, not an Arduino..

I believe you are looking for something like the Telemetry library.
Full disclaismer : I am the author
It allows you to send string, numbers, arrays, sparse arrays through the serial port for instance. Each sent data has a label, called topic, that is used to identify it.
The Pytelemety command line interface then allows you to connect to the serial port, plot received data in real time, write parameters to reconfigure the arduino from the computer, etc.
Example of arduino code thats send an incrementing counter
#include <Telemetry.h>

Telemetry TM;
int8_t counter;

void setup() {
  TM.begin(115200);
  counter = 0;
}

void loop() {
  TM.pub_i8("count",counter);
  counter++;
  delay(10);
}

Overview of the CLI (Command-Line Interface)

Overview of a graph (not produced by the arduino program above)

Output to file is not implemented yet, although all received data is logged to a file (but this log also contains system information). However, this is an interesting feature, quite straightforward to implement, that I might add in coming days if you are interested.
Central documentation is available here.

This looks interesting, thanks for posting.

As the author of the arduino eclipse plugin I want to state that the arduino eclipse plugin has a 6 channel plotter/scope. Also Arduino IDE has a 1 channel plotter/scope. I know there are plenty other similar and advanced tools around. Because there are so many better alternatives to your proposal I'm downvoting this answer as to biased.

@jantje So many better alternatives to my proposal... ? So you haven't even tested what I propose, how can you know what is better exactly ? You have a similar project, that is cool I respect that. However, there are features in my repo that will be extremely hard or even impossible to find anywhere else. Like supporting array data for instance. Or being able to monitor in real time amount of received characters, corrupted frames, to detect issues on the arduino with undersized buffer, too high data throughput. And finally, this project is not tied to Arduino. Runs on Mbed too.

@jantje so please next time you decide to talk about an open-source project, please get informed first, test it and forge your own opinion. And if you find a better alternative, post it, simple as that. Let the people decide. But you should know that I'm not particularly fond of reiventing the wheel. If I developped this project, it is simply because I haven't found an existing solution that would satisfy me.

There are a couple of ways you can communicate between a "Arduino' and a "PC"*.
1)Serial communication.
A serial port on your system is created and a program that reads and writes to the serial port is used as communication.
A program that does this is the "serial monitor" which comes in many flavours.
In linux dumping serial monitor incoming data to a file is as easy as:
cat /dev/ttyS0> myFile

2)Bluetooth (LE)
Bluetooth is a low energy consuming protocol that is commonly used for communication between a PC and a "device". The LE uses even less energy.
I'm not aware of any "official Arduino" boards that contain the hardware for Bluetooth on board.
3) Network
Today network equals to WIFI of tcpip. These methods allow for huge distances between the pc and the device.
Of these methods the serial communication over USB is the best know because -in Arduino world- this method is most commonly used to upload the "sketch" to the  "Arduino". As such all hardware is commonly available.
*I put quotes around Arduino and PC because in perspective of this answer both arduino and PC are to be interpreted as a device containing a cpu.

You seem to be missing the point of the question, mixing up protocol with physical layer, while OP is clearly asking for a software alternative to the serial monitor.

@Overdrivr. I disagree on me missing the point of the question. OP states he does not want to use the serial monitor. OP does not state the serial port is a must. You make the assumption he wants to use the serial port, I do not. Personally I think OP is not aware the serial monitor is using the serial port. Nor is OP aware that there are other ways to communicate. But the way the question is asked the serial port is not a must. Therefore I included other protocols in my answer just as other serial port programs.

@Overdriver I guess you downvoted this answer as: "not related to the question". As stated in the comment above: I disagree.

Well, in this case we'll have to agree to disagree :) The question is not exactly clear either, so I don't see how we could do more.

Regarding our other conversation, I am very open to a friendly and constructive discussion on the chat or by email regarding your opinion on the Telemetry library, and what strongpoints/weaknesses you feel it has, if you're interested. Let me know.

I know, I'm late, but I recommend, using python, as I most always do. The serial module is part of the basic python installation

import serial

S = serial.Serial('/dev/tty/USB0', 115200, timeout=1)

S.write("Hello")
print S.readline()

Should echo Hello, if the arduino sketch replies all incoming data.
Very handy in combination with ipython, where one can interactively poke around with the serial connection object.


text:
Safe to control multiple power sources through a switch through the ground?
I've attached the breadboard layout and schematic of a circuit I'm constructing, which is a simple Arduino radio control car, with a 9V powering the Arduino Uno, and the 6 volt battery pack feeding power to the motors via the L293D. My question is regarding the switch where I've connected the ground from both battery power supplies to one side, and connected the ground of the circuit to the other side. Is this OK and safe to do? Is there anything I should be concerned about with this setup? Is there a safer or better way to do this? What components added or removed (if any) would improve this circuit in terms of power safety and battery longevity?
In case you are wondering why I have two switches, the reason is because I wanted to debug the radio receiver using the serial monitor when I wired this to USB, but I also wanted to prevent it from powering up the motors so my project doesn't try and roll away while it's still connected to the USB cable. The switch I'm asking about in my question is sort of a mains power switch, so when it's off USB I can just flip on both switches and set the robot car free...

Be very careful with those switches. If you remove the power from the motor driver chip, you must be sure all the arduino pins connected to it, are all LOW. Otherwise you will exceed the maximum input-voltage allowed for the L293D, and thing could get damaged.

Gerben your comment is interesting, would you mind elaborating? We definitely don't want to burn out any parts, but I'm not seeing the issue you see. Your comment about if I "remove the power from the motor driver chip" could refer to one of three sources of voltage feeding the chip. Based on this L293D datasheet, plus the fact that the Arduino pins output only 5V, I believe all the connections are within recommended operating conditions. Regardless, what would you add/remove to improve the circuit?

Input High voltage (Vih) shouldn't exceed Vcc1, which it does in an arduino pin is high, and you disconnect Vcc1. Secondly Vcc2 should be at least Vcc1. So if you disconnect Vcc2, while Vcc1 is connected, you fail this requirement.

You have the grounds of the batteries permanently connected together, so opening the switch won't remove them from the circuit altogether: it will leave a potential difference of 3v between the Arduino's power input at the L293's power input.
That would be exactly equivalent to having a 3v battery with its +ve terminal connected to the Arduino power input, and its -ve connected to the L293's power input, with their grounds connected together - so they're sort of wired in series, with one of them backwards, with a far-too-small supply voltage.
I suspect it won't kill anything but I would imagine it would drain the batteries and probably isn't what you want to do.

Thank you for your reply. What would be a better way to wire this up? What components added or removed (if any) would improve this circuit in terms of power safety and battery longevity? I think I provided enough information about the reason for the two switches, but if you have questions that would help clarify things, please let me know. Thanks!

You're welcome. You could put a DP (double pole) switch on the batteries -  switch both of them together. Or, you could drive the whole lot from the 9v battery and just be careful to limit the level you drive the motors at to 2/3 of their maximum -- check my calcs first though!

source: Stack Exchange

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

sort: votes


text:
How to power an Arduino using automated mains/rechargeable battery switching?
I'd like to power my Arduino circuit like a smartphone. That is:

When the device is unplugged, power by rechargeable battery
When the device is plugged in, power by mains and charge battery at the same time

I'd like to not go the expensive shield route and instead purchase some inexpensive breakout boards from Aliexpress or eBay if possible. I'm willing to put in the time to learn if someone will point the way.
Can someone please provide some guidance?

Yes, charging a battery and supplying an Arduino at the same time is possible as long as we manage the caveats (see below) of in-circuit charging.

This is what I use:

a 3.3V Arduino (a Pro Mini in my case),
a regular Li-Ion battery,
a charging controller that supports constant voltage (CV) and constant current (CC) charging,
optionally, a 6V solar panel.

This is how it works:

charger is fed via solar panel and/or USB supply,
battery is continuously supervised and charged on demand
Arduino is connected to the output side of the charger

This works because the load that the Arduino presents is relatively small compared to what the charger can feed (and what the battery can take).
During recharging the charge current will predominantly flow through the battery.
And since the current through the battery drops once it gets full, the charger can still recognise this drop and finish the charge cycle – even though the Arduino is connected all the time.

Example setup:
I took some quick snapshots, please excuse the image quality. Charger is in the center, Arduino to the upper left, battery in a holder to the lower left, solar panel to the upper right.
The Arduino has a voltage regulator, but I don't use it in this setup. An explanation why and when to use the regulator is beyond the scope of this question and a matter for another answer.

In the first photo the charger input is only connected to the solar panel, but the panel voltage is low. So the charger is actually off and the Arduino is running off the battery.

In the second photo the charger is now connected to a USB power supply. The charger is on and in CC/CV charge mode (as indicated by the red LED of this charger model).

In the third photo the charge cycle is completed, the battery is full (as indicated by the blue LED of this charger model). Note that the charger could determine the charge completion even though the Arduino is connected and running (no power saving tricks involved here).

Background info:
The charger switches between CC and CV mode, depending on the level of discharge the battery is in. Particularly, my charger uses CC mode in case the voltage on the battery side is below 4V and CV mode in case the voltage on the battery side is above 4V. The current limit can be configured and the voltage limit is hard coded to around 4.2V, which makes the circuit save for a device like Arduino.

Image source: Nanjing Top Power
Other chargers may have other thresholds, but that doesn't matter as long as it fits your battery type and uses constant current/voltage only.
I have no particular recommendation for a charger, but so far have a good impression of the one I used in this answer.

Caveats:
There are a couple of cases to consider, though:
Deep discharge
Should the battery voltage ever go below around 2.9V (e.g. deeply discharged battery), the charger will switch into trickle charge mode where only very small amounts of current are passed to the battery – too little current (i.e. too low a voltage) for the Arduino to run. Arduino will go into brown-out and try to restart until the battery has recovered. So this can become a state in which your Arduino won't respond for an unknown amount of time.
High load
If the load connected to the battery draws a current that isn't small anymore – compared to the battery charge current – then the charger cannot recognise a full battery anymore, since the current as seen by the charger will never fall off at the end of any charge cycle. So watch out how many gadgets you connect to this kind of in-circuit charger.
Wrong charger type
There are a multitude of ways to charge a battery. Things like trickle charge, pulse charge, timer based charging, and so on.
None of these would likely work, as the voltage those charger types generate could upset the Arduino and the load the Arduino presents could upset the charger.
Please also note that some chargers don't supervise the battery. With Li-Ion or Li-Poly (and other) batteries this would be a very bad idea. Always choose a charger appropriate for your battery.

Alternatives
The charger I use employs a linear regulator. That's not very efficient, other topologies are possible. But they might require supply filtering for the Arduino.

Shameless plug
I wrote a library for the purpose of supervising an Arduino's supply voltage (and chip temperature). This technique allows to check the battery level without any additional components. That library is called CoreSensors.

Further links:

New TP4056 Lithium Cell Charger Module with Battery Protection
Solar Pannel and LiOn or Lipo
How to autoregulate a TP4056 for maximum solar power extraction

There are many ways you can do this, as you mention there are ready made shields that do this.
You need to take a few thing into consideration:

Power - how much power will your cirquit be drawing, as many of these boards will only be able to deliver 3-600mah is this enough, at the same time you will find out how long your cirquit will be able to stay on battery power.
Complexity - a ready made controller/charger is already made to work togheter, if you go for a separate charger and booster module you might end up with unwanted power loss, or you need ekstra buttons/sliders to control power.

You could in theory use 1 lipo cell directly to power your MCU, as the voltage spans from 3,6 to 4,7 Volts pr.cell and charge the lipo when NOT in use (you cannot charge a lipo directly while in use, thats why you need a controller). This would be the cheapest way.

That got me puzzled: "you cannot charge a lipo directly while in use". While it's true that the charging circuit would be irritated by an additional load in parallel to the battery, are you saving you can't have battery charging without turning off the device? Because that's not the case (e.g. see your phone/computer). I think a good answer should address exactly this issue, as everything else follows from there.

Charging lipo is done in stages:

Sure, but there are controllers that handle load switching. Since you suggest a controller, why not suggest one that does? I would if I could. ;)

sparkfuns LiPower shield would get the job done, but OP is looking for cheap china solution. and I gave a few considerations to think about. My comment reg. Lipo's was aimed at directly connecting the battery to the 5v line, a full lipo will supply (aprox) 4.7V and deliver down until brown out. I should also mention that draining a lipo too much might destroy it.

I've been looking at the SparkFun DEV-13158. Ignoring the fuel gauge and the fact that it produces multiple output voltages, we have: charger -> battery -> voltage regulator -> Arduino. So, no magic compared to a breakout board. Of course I agree that the battery voltage has to be monitored in order to prevent a deep discharge.

Can someone please provide some guidance?

power your arduino from a power bank and then power the power bank via ac adapter.
simplest and likely most inexpensive solution.

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


text:
vrdude stk 500 not responding error inspeed control of dc motor using arduino uno board .how to solve this issue
vrdude stk 500 not responding error inspeed control of dc motor using arduino uno board  .how to solve this issue

...COM1...? Are you sure about that?

Yes i do only one usb port in the system

Have you tried turning it off and on again?


text:
ISR executes twice if data coming through SoftwareSerial
I am using Arduino Pro Mini to get GPS info from a u-blox NEO-M8N chip and display it on a Adafruit OLED display. NEO-M8N has a PPS(pulse per second) output which is aligned to GPS's second. Because UART and deserialization is slow, I use PPS signal to make time displays more accurately. The PPS(time pulse) signal and UART message are coming like this:

On my Arduino, SoftwareSerial RX/TX is on pin 7/8 (but only use pin 7 because Arduino has no message to send to NEO-M8N), and the interrupt(PPS) is on pin 2. If I just connect pin 7, display update once per second as intended; if I just connect pin 2, time increased by one second per second as intended. BUT if connect them both, ((time will increased more than one second per second) and ( processGPS() will lost sync with upcoming UBX(u-blox message format) message)) occasionally.
And here is the entire code:
#include <SoftwareSerial.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 9
Adafruit_SSD1306 display(OLED_RESET);

#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

// Connect the GPS RX/TX to arduino pins 7 and 8
SoftwareSerial S_Serial = SoftwareSerial(7,8);
int intpin = 2;
volatile int state = LOW;

const unsigned char UBX_HEADER[] = { 0xB5, 0x62 };

struct NAV_PVT {
  unsigned char cls;
  unsigned char id;
  unsigned short len;
  unsigned long iTOW;
  unsigned short year;
  byte month;
  byte day;
  byte hour;
  byte miniute;
  byte sec;
  unsigned char valid;
  unsigned long tAcc;
  long nano;
  byte fixType;
  unsigned char flag;
  unsigned char flag2;
  byte numSV;
  long lon;
  long lat;
  long height;
  long hMSL;
  unsigned long hAcc;
  unsigned long vAcc;
  long velN;
  long velE;
  long velD;
  long gSpeed;
  long headMot;
  unsigned long sAcc;
  unsigned long headAcc;
  unsigned short pDop;
  byte reserved1[6];
  long headVeh;
  byte reserved2[4];
};

NAV_PVT pvt;

void calcChecksum(unsigned char* CK) {
  memset(CK, 0, 2);
  for (int i = 0; i < (int)sizeof(NAV_PVT); i++) {
    CK[0] += ((unsigned char*)(&pvt))[i];
    CK[1] += CK[0];
  }
}

bool processGPS() {
  static int fpos = 0;
  static unsigned char checksum[2];
  const int payloadSize = sizeof(NAV_PVT);

  while ( S_Serial.available() ) {
    byte c = S_Serial.read();
    if ( fpos < 2 ) { //SYNC
      if ( c == UBX_HEADER[fpos] )
        fpos++;
      else
        fpos = 0;
    }
    else {
      if ( (fpos-2) < payloadSize )
        ((unsigned char*)(&pvt))[fpos-2] = c;

      fpos++;

      if ( fpos == (payloadSize+2) ) {
        calcChecksum(checksum);
      }
      else if ( fpos == (payloadSize+3) ) {
        if ( c != checksum[0] )
          fpos = 0;
      }
      else if ( fpos == (payloadSize+4) ) {
        fpos = 0;
        if ( c == checksum[1] ) {
          return true;
        }
      }
      else if ( fpos > (payloadSize+4) ) {
        fpos = 0;
      }
    }
  }
  return false;
}

void pps()
{
  state=!state;
}

void PrintScreen()
{
  display.clearDisplay();

  //Size 2
  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  float sik = (pvt.gSpeed / 100) / 3.6f;
  if (sik<100)
    display.print(" ");
  if (sik<10)
    display.print(" ");
  display.print(sik,1);//SpeedInKph
  display.setCursor(84,0);
  if (pvt.numSV<10)
    display.print(" ");
  display.print(pvt.numSV);//SV

  //Size 1
  display.setTextSize(1);
  display.setCursor(60,8);
  display.print("km/h");
  display.setCursor(63,0);
  display.print("CHL");
  display.setCursor(108,8);
  display.print("SVs");
  display.setCursor(108,0);
  switch (pvt.fixType){
    case 0:
      display.print("N.F");
      break;
    case 2:
      display.print("2D");
      break;
    case 3:
      display.print("3D");
      if ((byte)pvt.flag & 2)
        display.print("+");
      break;
    default:
      display.print("INV");
      break;
  }

  long  temp;
  //Line 1
  display.setCursor(0,16);
  if (pvt.lat >= 0)
    temp = pvt.lat;
  else
    temp = -pvt.lat;
  if (temp >= 1000000000)
    display.print("lat:");
  else
    if (temp >= 100000000)
      display.print("lat: ");
    else
      display.print("lat:  ");
  display.print(temp / 10000000);display.print(".");
  long temp2 = 1000000;
  temp = temp % 10000000;
  while ((temp / temp2 == 0)&&(temp2>1))
  {
    display.print("0");
    temp2 /= 10;
  }
  display.print(temp);
  if (pvt.lat >= 0)
    display.print("N");
  else
    display.print("S");
  temp = 10000;
  while (((pvt.pDop / temp) == 0)&&(temp>1))
  {
    display.print(" ");
    temp /= 10;
  }
  display.println(pvt.pDop);

  //Line2
  if (pvt.lon >= 0)
    temp = pvt.lon;
  else
    temp = -pvt.lon;
  if (temp >= 1000000000)
    display.print("lon:");
  else
    if (temp >= 100000000)
      display.print("lon: ");
    else
      display.print("lon:  ");
  display.print(temp / 10000000);display.print(".");
  temp2 = 1000000;
  temp = temp % 10000000;
  while ((temp / temp2 == 0)&&(temp2>1))
  {
    display.print("0");
    temp2 /= 10;
  }
  display.print(temp);
  if (pvt.lon >= 0)
    display.print("E");
  else
    display.print("W");
  display.println(" HEAD");

  //Line3
  display.print("hMSL:");
  if (pvt.hMSL < 0)
    pvt.hMSL = -pvt.hMSL;
  temp = 10000000;
  while (((pvt.hMSL / temp) == 0)&&(temp>1000))
  {
    display.print(" ");
    temp /= 10;
  }
  display.print((pvt.hMSL % 100000000) / 1000);display.print(".");
  if ((pvt.hMSL % 1000) < 100)
    display.print("0");
  if ((pvt.hMSL % 1000) < 10)
    display.print("0");
  display.print(pvt.hMSL % 1000);
  display.print("|");
  temp = pvt.headMot / 100000;
  if (temp < 100)
    display.print(" ");
  if (temp < 10)
    display.print(" ");
  display.print(temp);display.print(".");
  temp2 = (pvt.headMot%100000)/1000;
  if (temp2<0)
    temp2 = -temp2;
  if (temp2<10)
    display.print("0");
  display.println(temp2);

  //Line4
  display.print("h,vAcc:");
  if (pvt.hAcc >= 100000)
    display.print("  >100");
  else
  {
    display.print(pvt.hAcc / 1000);display.print(".");
    if (pvt.hAcc % 1000 < 100)
      display.print("0");
    if (pvt.hAcc % 1000 < 10)
      display.print("0");
    display.print(pvt.hAcc % 1000);
  }
  display.print(",");
  if (pvt.vAcc >= 100000)
    display.print(" >100");
  else
  {
    display.print(pvt.vAcc / 1000);display.print(".");
    if (pvt.vAcc%1000 < 100)
      display.print("0");
    if (pvt.vAcc%1000 < 10)
      display.print("0");
    display.print(pvt.vAcc%1000);
  }
  display.println("m");

  //Line5
  display.print("V:");
  if (pvt.gSpeed < 1000000)
    display.print(" ");
  if (pvt.gSpeed < 100000)
    display.print(" ");
  if (pvt.gSpeed < 10000)
    display.print(" ");
  display.print((pvt.gSpeed % 10000000)/1000);display.print(".");
  if (pvt.gSpeed % 1000 < 100)
    display.print("0");
  if (pvt.gSpeed % 1000 < 10)
    display.print("0");
  display.print(pvt.gSpeed % 1000);
  display.print("m/s");
  if (pvt.sAcc < 1000000)
  {
    if (pvt.sAcc < 100000)
      display.print(" ");
    if (pvt.sAcc < 10000)
      display.print(" ");
    display.print("~");
    display.print(pvt.sAcc / 1000);display.print(".");
    if (pvt.sAcc % 1000 < 100)
      display.print("0");
    if (pvt.sAcc % 1000 < 10)
      display.print("0");
    display.println(pvt.sAcc % 1000);
  }
  else
  display.println(" ~>100");

  //Line6
  if ((pvt.year<10000)&&(pvt.year>=1000))
    display.print(pvt.year);
  else
    display.print("????");
  display.print("/");
  if ((pvt.month<=12)&&(pvt.month>=1))
  {
    if (pvt.month < 10)
      display.print("0");
    display.print(pvt.month);
  }
  else
    display.print("??");
  display.print("/");
  if ((pvt.day<=31)&&(pvt.day>=1))
  {
    if (pvt.day < 10)
      display.print("0");
    display.print(pvt.day);
  }
  else
    display.print("??");
  if (pvt.valid & 0x04)
    display.print("UTC");
  else
    display.print("INV");
  if ((pvt.hour<=23)&&(pvt.hour>=0))
  {
    if (pvt.hour < 10)
      display.print("0");
    display.print(pvt.hour);
  }
  else
    display.print("??");
  display.print(":");
  if ((pvt.miniute<=59)&&(pvt.miniute>=0))
  {
    if (pvt.miniute < 10)
      display.print("0");
    display.print(pvt.miniute);
  }
  else
    display.print("??");
  display.print(":");
  if ((pvt.sec<=60)&&(pvt.sec>=0))
  {
    if (pvt.sec < 10)
      display.print("0");
    display.print(pvt.sec);
  }
  else
    display.print("??");

  display.display();
}

void PrintSec()
{
  pvt.sec = (pvt.sec + 1)%60;
  display.fillRect(114,56,12,8,BLACK);
  display.setCursor(114,56);
  if (pvt.sec<10)
    display.print("0");
  display.println(pvt.sec);
  display.display();
  state = LOW;
}

void setup()
{
  S_Serial.begin(9600);
  pinMode(intpin, INPUT);
  attachInterrupt(digitalPinToInterrupt(intpin), pps, RISING);
  // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  // init done
}

void loop() {
  if (state == HIGH)
    PrintSec();
  if ( processGPS() )
    PrintScreen();
}

I found a similar issue here (Interrupt Service Routine Executes Twice ATmega88), but since ISR only executes once if I connect pin 2 alone, I think the cause might be something else.
Is it a software issue or a hardware issue? How to fix it?

How can you tell that time is increased more than one second per second? You you show some of the Serial output you get on your PC?

I show the time on an oled display, looks like this and the seconds was increased twice in one second sometimes, and other information on the display just froze. Normally, the lon(titude), lat(titude) and other positioning info are jittering all the time, so it is obvious when something goes wrong.

The ISR just won't be called twice from one interrupt. However your code is complex enough that what you observe is possible. For example, if state is HIGH, then you print the seconds, followed by reading the GPS (which also prints the seconds). This may well cause the seconds to update twice.

1) First, deferring PrintSec to loop through the volatile state, which is set by the ISR, actually takes more time to update the display.  You might as well just test the pin in loop:
void setup()
{
  S_Serial.begin(9600);
  pinMode(intpin, INPUT);

  // by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
}

void loop() {

         bool state    = digitalRead(intPin);
  static bool oldState = false;

  // Watch for change
  if (oldState != state) {
    oldState = state;

    // RISING edge?
    if (state)
      PrintSec();
  }

  if ( processGPS() )
    PrintScreen();
}

2) "But I might miss a PPS!" you exclaim.  The bad news is that if you can't finish PrintScreen in time to get back to testing the pin, then you're Trying To Do Too Much.
You might want to consider incremental updates of the display.  If you have the previous pieces (i.e., an extra NAV_PVT struct), you could compare each piece to see if it has changed.  If it has, it's ok to spend time writing it.  Just add an extra test to each piece:
NAV_PVT pvt, prevPVT;
static bool firstTime = true;
  .
  .
  .
void PrintScreen()
{
  if (firstTime)
    display.clearDisplay();

  //Size 2
  display.setTextSize(2);
  display.setTextColor(WHITE);

  //  Update the Speed?
  if (firstTime || (pvt.gSpeed != prevPVT.gSpeed)) {
    display.setCursor(0,0);
    float sik = (pvt.gSpeed / 100) / 3.6f;
    if (sik<100)
      display.print(" ");
    if (sik<10)
      display.print(" ");
    display.print(sik,1);//SpeedInKph
  }

At the end of PrintScreen, do this:
  display.display();

  prevPVT   = pvt;
  firstTime = false;
}

For most updates, only the seconds field would get written.
Clearing the screen and drawing the labels could probably happen just once in setup.

3) I would suggest a more efficient and reliable software serial library.  SoftwareSerial disables all interrupts for the entire 10-bit character time, once the start bit is received.  This makes it both vulnerable and intrusive to other interrupts, like PinChange and SPI.  Ick.  If you can use pins 8 & 9, AltSoftSerial is the best choice.
If you can't use those pins, and you're not using the USB port to connect to a host, could you use Serial input (pin 0) for the GPS?  The GPS would have to be disconnected to do USB programming, but it could stay connected if you're using an ISP.

4) You need a more robust way to restart UBX packet framing, even if chars are lost.  I would suggest something like this:
void loop() {
  if (state == HIGH) {
    PrintSec();
    fpos = 0; // new packet coming soon, ditch old partial packet
  }
  if ( processGPS() )
    PrintScreen();
}

At least that will keep you in sync.  Without it, packet completion might not happen until after a 2nd PPS occurs (and 2nd packet begins arriving).  Maybe this explains the symptoms you're seeing?

I tried 3) first, and the hardware serial input works much better and never lose chars. But meanwhile, second was increased twice per second constantly. You are right, PrintSec was deferred to the loop, so the use of interrupt is meaningless. I tried 1) then, but the second still got increase twice sometimes.  I found this article, it says "Pin Change Interrupt Request 2 (pins D0 to D7)" shared the same interrupt vector, so I use pin 12 to receive PPS instead. The second will only get increase twice once every 3min now.

If i understand you correctly you have 2 ways that increase your seconds,

when software serial receives data
When PPM pin goes high

And when each of theese are run separately things work, but when you use them together seconds increase by 2 each time ?
wouldnt this suggest that your program only should use one of theese to increase your seconds.

No, I just have one way to increase my seconds, when PPS pin goes high. I GET the seconds from serial data. That is, when the PPS goes high, seconds++; when serial data comes, seconds = seconds_from_gps.

Maybe showing your complete code will clarify for us what is going on.

Ok, I just edited it.

You sure about this line: pvt.sec = (pvt.sec + 1)%60;

It increase the second by one. Use pvt.sec instead of a local variable to save some space.


text:
Interfacing 9-Axes Motion Shield with RPi and WiFi Shield
I recently purchased the Arduino 9-Axes Motion Shield. I have two questions:
Q1. The official Arduino page says that the shield doesn't have any external power source and can only be powered up by stacking on top of an Arduino board. How can I use this shield with a Raspberry Pi?
Q2. A page here shows that it has support for the Ethernet Shield but doesn't mention WiFi shield anywhere. Does this mean that I cannot use my WiFi shield with it? I plan to stack the 9-axes shield on top of the WiFi shield which in turn is stacked over Arduino Uno.

Q1. The official Arduino page says that the shield doesn't have any external power source and can only be powered up by stacking on top of an Arduino board. How can I use this shield with a Raspberry Pi?

By providing the right power to the right pins.

Q2. A page here shows that it has support for the Ethernet Shield but doesn't mention WiFi shield anywhere. Does this mean that I cannot use my WiFi shield with it? I plan to stack the 9-axes shield on top of the WiFi shield which in turn is stacked over Arduino Uno.

No, it says it is compatible with the Arduino Ethernet which is not a shield, it is an Arduino.
What other shields you can use it with depends on what pins those other shields use.  Look at the schematics. Read the manuals. Do some leg-work.


text:
Stepper Motor not Stepping Properly
I have an Arduino Uno connected to the Adafruit Motorshield v2. I have it hooked up to a stepper motor(27BYJ-48). I am trying to make the motor do one complete revolution. However, the number of steps I specify to the stepper motor(200 in the code) doesn't affect the motor steps. For example, the 2200 step in this code, is roughly one rotation and is completely unaffected by change the steps/revolution specified when instantiating the motor. How do I get the motor to do one exact revolution?
Here is the code on the arduino:
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Stepper test!");

  AFMS.begin();  // create with the default frequency 1.6KHz

  myMotor->setSpeed(2000);  // 10 rpm
}

void loop() {
  Serial.println("Single coil steps");
  myMotor->step(2200, FORWARD, DOUBLE);
  myMotor->step(2200, BACKWARD, DOUBLE);
}

Edit:
Wiring:

What happens if you disconnect the red wire?

Also change the 200 at AFMS.getStepper(200, 2); to 64.
The spec sheet says 5.625 degrees per step -> so the motor does 64 steps for 1 revolution.

Nothing changes, motor turns same as before. Changing the the code also did not change anything.

That's the RPM, so with 10 it does 10 a minute, however, it is painfully slow and goes much slower than that. So yes, setting the RPM there does not actually convert to the real RPM.

This motor is a unipolar type, right? Wiring is thus a bit different than a bipolar. The AFMS expects bipolar by default if I remember correctly. In any case, double check their doc for more info on how to connect unipolar/bipolar steppers.

https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/using-stepper-motors says the common terminal of 5-wire unipolar motors should be connected to the GND terminal, which is how it appears from the pics.

What happens, if you raise the baudrate to 115200?

Ok so I'm not familiar with the sheild or API (or motor lol) but going off the spec sheets etc
Leave the red wire disconnected [see 1] and try this code and report back what happens:
  #include <Wire.h>
  #include <Adafruit_MotorShield.h>
  #include "utility/Adafruit_MS_PWMServoDriver.h"

  Adafruit_MotorShield AFMS = Adafruit_MotorShield();
  Adafruit_StepperMotor *myMotor = AFMS.getStepper(64, 2); // 64 steps pr revolution
                                                           // Using M3 and M4 of shield

  void setup()
  {
    AFMS.begin();  // create with the default frequency 1.6KHz
    myMotor->setSpeed(30);  // 30 rpm, so 1 full turn every 2sec
  }

  void loop()
  {
    // 64 steps per motor shaft revolution,
    // 64 revolutions of motor per output shaft revolution
    myMotor->step(4096, FORWARD, DOUBLE);    // Should be 1 rev in one direction
    myMotor->step(4096, BACKWARD, DOUBLE);   // and 1 rev in other direction
  }

[1] : your motor is unipolar (wikipedia on unipolar and bipolar motors), according to its documentation. The red wire is the central tap, and useless in this context.

It goes forward and back incredibly minutely, i had to up the values from 2 just to acknowledge it was working.

Try 128 steps (2 rev's)...how long in seconds for each rev?

It goes ~20 degree back and forth, each 30 degree takes about 2 seconds

Maybe there is some gearing on the motor. It might be called the speed variation ratio in the spec sheet (1/64). Let's assume thats it and so we could say 64 steps multiplied by 64 (allow for the gearing ratio for 1 turn). Can you edit the code to be... step(4096, Forward, Double);? Try that.

edited code above

It does ~2 revolutions but nothing exact.

I also tested 27BYJ-48 stepper motor with instructables source code. It works but I had the same "complete revolution" problem.
They compute on their website that a revolution contains 4096 steps.
As @James said, indeed, there is gearing inside the stepper motor.
The problem is the gearing could be different for the exact same reference !
Everything is described here : 28BYJ-48


text:
avrdude: stk500_recv(): programmer is not responding
Arduino IDE is throwing this error when uploading sketches - avrdude: stk500_recv(): programmer is not responding
The problem arose just after I uploaded a blink sketch to my Arduino Mini, which worked absolutely fine. After the successful upload I tried to upload a different sketch and got the error.
I thought I had destroyed the boot loader somehow and was about to get out the Bus Pirate for ICSP but I decided to try another Arduino Mini I had lying around (albeit from another manufacturer) and got the same error.
So I'm convinced it's a driver issue as I successfully uploaded a sketch (it still runs as we speak!) then just magically without changing ANYTHING I can no longer upload.
In a futile attempt to get back to work I've done the following:
Switched the RX-TX lines (clearly not the issue as the first upload worked)
Used a different FTDI cable
used a  different programmer
(FTDI 5V/3.3V USB to TTL Basic FT232 FIO Programmer)
(USB to TTL Serial UART RS232 Adaptor (PL2303HX)
I'm fairly certain these use different drivers - FTDI and Prolific
Please help me I'm about to murder something :'(
Screencaps of error and device manager - Imgur

The error appears when you overwrite the bootloader. Only the bootloader makes the standard Upload button work.

i am having same problem in uno, I checked all of possible situation(board/COM), what to do? and aslo please tell me which programmer I need to choose?

Answer is below. You need to press the button on the arduino board as you are uploading the sketch.    https://www.arduino.cc/en/Guide/ArduinoMini

Did you check the pin alignment of your FTDI connector with the 6-pin connector on your Arduino board? Although the FTDI adapters look the same, the 6-pin connector may actually have been swapped. BTW, my FTDI adapter resolves the need to reset the Arduino before uploading by bringing out the DTR signal on pin 6. However, it was made backwards from other ones.

Please post this as "Comment" because it ISNT an answer!

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Is it this?
"To upload a new sketch to the Arduino Mini, you need to press the reset button >on the board immediately before pressing the upload button in the Arduino >environment."
https://www.arduino.cc/en/Guide/ArduinoMini

You sir, are a hero.
I don't even know how I accidentally did this sequence to upload the first sketch... Perhaps I plugged the USB to Serial UART in to the USB port and quickly pressed upload? Having got the first sketch on there really mixed me up :/
Solution:

Click upload sketch - It will show 'Compiling Sketch'
Immediately after clicking upload, hold the reset button down on the Arduino mini
Release the reset button when 'Compiling Sketch' turns in to 'Uploading'

Is it this?
"To upload a new sketch to the Arduino Mini, you need to press the reset button on the board immediately before pressing the upload button in the Arduino environment."
https://www.arduino.cc/en/Guide/ArduinoMini

avrdude: stk500_recv(): programmer is not responding
I have the same problem (Arduino uno)
I reset the Arduino several times, but finally i fixed the problem.
so you must change the pic of the arduino and make sure it was instilled correctly on the arduino board.
hope it work...

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


text:
What is pulseIn in programming Arduino?
I have seen some tutorials on ultrasonic range detector sensor.
In that, what is the meaning of the word pulseIn?

pulseIn() is used to Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds or 0 if no complete pulse was received within the timeout.
The timing of this function has been determined empirically and will probably show errors in shorter pulses. Works on pulses from 10 microseconds to 3 minutes in length. Please also note that if the pin is already high when the function is called, it will wait for the pin to go LOW and then HIGH before it starts counting. This routine can be used only if interrupts are activated. Furthermore the highest resolution is obtained with short intervals.
Syntax
pulseIn(pin, value)
pulseIn(pin, value, timeout)

Parameters
pin: the number of the pin on which you want to read the pulse. (int)
value: type of pulse to read: either HIGH or LOW. (int)
timeout (optional): the number of microseconds to wait for the pulse to be completed: the function returns 0 if no complete pulse was received within the timeout. Default is one second (unsigned long).
Returns
The length of the pulse (in microseconds) or 0 if no pulse is completed before the timeout (unsigned long).
For additional information and example code, visit: https://www.arduino.cc/en/Reference/PulseIn, hope this help you to understand the meaning of pulseIn().

Why are you copying directly from the reference page? What is the added value?

@MikaelPatel you are right, there isn't any added value. Anyway, I believe that the information contained in my answer can better help people inside the community to have knowledge of the function explained.

But you have simply copied the text directly from the reference page. And skipped the important example code!

@MikaelPatel you can edit the answer if you want to improve it with additional information. Or if you prefer you can also write a new answer.


text:
How to check if all pins are connected on my board to make sure Arduino sends the correct pattern number on my tool
What to add on this code to check my pins state during run? And how can i trigger error using Visual basic when 1 of my pin is disconnected?
String input = "";

void setup(){

Serial.begin(9600); // Sets up communication with the serial port

pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT); // for start of program operation
pinMode(12,OUTPUT); // for stop of program operation

digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);

digitalWrite(11,LOW);
digitalWrite(12,LOW);

}

void loop(){

int recipe;
//Serial.print("Enter recipe number: ");

while(Serial.available()==0){    // Waits for data from serial port
}

while(Serial.available() > 0){
int data = Serial.read();
  // convert the incoming byte to a char
  // and add it to the string
input += (char)data;

recipe = input.toInt()+'0';    //recipe=0 if not a digit
if(recipe == '0')
  recipe = data;

if(data == '\n'){
  //Serial.print("Recipe: ");
  //Serial.println(recipe);
  //Serial.print("String: ");
  //Serial.println(input);
  input = "";
}
}

if(recipe == 's'){
digitalWrite(11,HIGH);
delay(1000);
digitalWrite(11,LOW);

digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
}

else if(recipe == 't'){
digitalWrite(12,HIGH);
delay(1000);
digitalWrite(12,LOW);

digitalWrite(6,LOW);
digitalWrite(7,LOW);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
}

else if(recipe>'0' && recipe<'32'){

recipe = recipe-'0';
char binary[7] = {0};   // This is where the binary representation will be stored
recipe += 32; // Adding 32 so that there will always be 6 digits in the string
itoa(recipe,binary,2);  // Convert recipe to a string of base 2 and save it in array 'binary'
char* signals = binary + 1; // Get rid of the most significant digit to get the 5 bits

//Serial.print(signals);    // Print out the signals in binary

int i;
for(i=0; i<5; i++){
  if(signals[i] == '0')
    signals[i] = '1';
  else
    signals[i] = '0';
  digitalWrite(i+6, signals[i]-'0');    // write to pin; converts the bit of the string to HIGH or LOW
  //Serial.print(signals[i]);
}

}
else
loop();

}

Welcome to Stackexchange. Please ask a question. And please post your code in a readable format (see editor help).

It's probably not possible to know how an interrupted signal can be recognised in code as long as we don't know how you connect them. Without external logic only input pins could do this in code and even then Arduino has a lot of them.

I have attached the connections of my pins to the tool controller. The purpose of this setup is Arduino will send the data from my traveller to my tool then automatically start my tool once data was received. Since the data from my traveller is critical and Arduino must send the correct value to the tool prior start. The only thing i need to know is that how can i detect if my pins are connected properly

If a pin gets disconnected, Arduino won't recognise it as is. This would require some form of feedback from the tool controler, e.g. by bringing another set of wires from the connection terminals back to some of Arduino's input pins. Also, your code still contains errors (e.g. you call loop() from within loop()). And then there's Visual Basic all of a sudden. :) May I suggest you compile this into different questions?

As mentioned in a comment, your code has some fundamental flaws. Do not call loop() from within loop()! Aside from the code errors, your question has a legitimate element.
Testing the tri-state behaviour of an input pin will let you know if it is genuinely high, genuinely low, or floating (disconnected). The technique was given in this answer to similar problem I was encountering.
In short:
Connect a large (1MOhm) resistor to each input between the pin and ground, then for each pin:

Turn off internal pullup;
Read value of input pin;
Turn on internal pullup;
Read value again.

If the value changes from the first to the second digitalRead(), the input was not connected to anything. If the value remains the same then it is a genuine value from a connected device.

+1, Great answer to the original issue of detecting an open pin. It's also in line with my suspicion that external hardware is required: feedback to input pins... ;)

That being said, what about shorts to ground or supply, what if the impedance in the machine is too low for this approach... I have a suspicion that this arduino shall double as a failsafe device in order to protect the machine and people – and that involves much more.

If it is for a truly safety-critical application then there should be many more steps taken, the first being a second processor (complete Arduino board) for a Master/Slave setup. Then there's 'toggle-checking' of all the inputs as the next step. However, if the OP posted this question in the first place then they should not be responsible for designing something so technical.


text:
Is it possible to replace this delay with millis()? (And issue with other millis loop)
I am working on updating a project and I have a thread over in the Arduino forum which helped me out, but I'm a bit stuck, and there isn't much activity going on there.
This code is for use with a one wire temperature sensor, however, each time it retrieves data for the sensor, it has a 750ms delay as seen here:
ds.reset();
ds.select(addr);
ds.write(0x44, 1);        // start conversion, with parasite power on at the end

delay(750);     // maybe 750ms is enough, maybe not
// we might do a ds.depower() here, but the reset will take care of it.

present = ds.reset();
ds.select(addr);
ds.write(0xBE);         // Read Scratchpad

Now, I'm going to be using a momentary button as a toggle, but for this I need to debounce it, using a delay. With the 750ms delay present for the temperature sensor, that just isn't feasible, it makes it too unpredictable and difficult to use.
I need to replace this delay with a millis counter, but I'm not sure if I can without hanging up the rest of the script. I gave it a try like so, but it completely screwed up the reading.
if (owcurrentMillis - owpreviousMillis >= owinterval) {
owpreviousMillis = owcurrentMillis;
present = ds.reset();
ds.select(addr);
ds.write(0xBE);         // Read Scratchpad
}

I then tried it like so, and the readout does still work, however, I have an LED which lights up when the temperature has "Stabilized", which it's supposed to check every one second, but that has stopped working, and it's basically instant making it useless. I don't know why that millis loop does not work though, it was only working due to the 750ms delay.
if (owcurrentMillis - owpreviousMillis >= owinterval) {
owpreviousMillis = owcurrentMillis;
ds.reset();
ds.select(addr);
ds.write(0x44, 1);        // start conversion, with parasite power on at the end
}

Here is the bit of code controlling the LED illumination.
if (currentMillis - previousMillis >= interval) {  //If it has been 20 seconds, check to turn LED on
previousMillis = currentMillis;
if ((delta < 00.03) && (delta > -00.03)) {      //If temperature hasn't changed by +/- .05 turn led on.
  digitalWrite(A0, HIGH);
}
}
if (delta >= 00.06) {                             //If temperature has changed by more than .1 turn LED off
digitalWrite(A0, LOW);
}
if (delta <= -00.06) {
digitalWrite(A0, LOW);                         // If temperature has changed by more than -.1 turn LED off
}

I think if I can get that one to work properly, instead of messing up like it is now I should be good, then I just need the 50ms delay to debounce the button which will trigger what I need, I just can't figure out why it will not work.
You can see the version which works best here (with the 750ms delay in place):
#include <OneWire.h>
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>
const int chipSelect = 10;

OneWire  ds(9);                               //Onewire + lcd setup
LiquidCrystal lcd(6, 7, 5, 4, 3, 2);
float lasttemp;                              //Variable for last temperature
float delta;                                 //Variable for temperaturechange
long previousMillis = 0;
const long interval = 1000;                       //Check once every 20 seconds

const long sdinterval = 5000;
long sdpreviousMillis = 0;

File myFile;

void setup(void) {
  pinMode(A0, OUTPUT);
  pinMode(A3, OUTPUT);

  Serial.begin(115200);                       //Start serial + LCD/Light test
  lcd.begin(8, 2);
  lcd.setCursor(0,0);
  lcd.print("STARTING");
  lcd.setCursor(0, 1);
  lcd.print("VER. 1.2");
  digitalWrite(A0, HIGH);
  digitalWrite(A3, LOW);
  delay(1000);
  digitalWrite(A0, LOW);
  digitalWrite(A3, HIGH);
  lcd.clear();                                //End of LCD/Light test

  if (!SD.begin(10)) {                       // Check for SD card
    digitalWrite(A3, LOW);
    lcd.setCursor(0,0);
    lcd.print("SD CHECK");
    lcd.setCursor(0,1);
    lcd.print("  FAIL  ");
    delay(1000);
    lcd.clear();
    digitalWrite(A3, HIGH);
  } else {
    delay(1000);
    digitalWrite(A3, LOW);
    lcd.setCursor(0,0);
    lcd.print("SD CHECK");
    lcd.setCursor(0,1);
    lcd.print("  PASS  ");
    delay(1000);
    lcd.clear();
    digitalWrite(A3, HIGH);
  }
}

void loop(void) {

  unsigned long sdcurrentMillis = millis();
  unsigned long currentMillis = millis();
{
  }

  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
    Serial.println("CRC is not valid!");
    return;
  }
  Serial.println();

  // the first ROM byte indicates which chip
  switch (addr[0]) {
  case 0x10:
    Serial.println("  Chip = DS18S20");  // or old DS1820
    type_s = 1;
    break;
  case 0x28:
    Serial.println("  Chip = DS18B20");
    type_s = 0;
    break;
  case 0x22:
    Serial.println("  Chip = DS1822");
    type_s = 0;
    break;
  default:
    Serial.println("Device is not a DS18x20 family device.");
    return;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

  delay(1000);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  }
  else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }

  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");

  delta = celsius - lasttemp;                       //Create value to check how much temperature has changed

  if (currentMillis - previousMillis >= interval) {  //If it has been 20 seconds, check to turn LED on
    previousMillis = currentMillis;
    if ((delta < 00.03) && (delta > -00.03)) {      //If temperature hasn't changed by +/- .05 turn led on.
      digitalWrite(A0, HIGH);
    }
  }
  if (delta >= 00.06) {                             //If temperature has changed by more than .1 turn LED off
    digitalWrite(A0, LOW);
  }
  if (delta <= -00.06) {
    digitalWrite(A0, LOW);                         // If temperature has changed by more than -.1 turn LED off
  }

    if (sdcurrentMillis - sdpreviousMillis >= sdinterval) {  //Write to SD card every 5 seconds.
    sdpreviousMillis = sdcurrentMillis;
    digitalWrite(A3, LOW);
    myFile = SD.open("Log.txt", FILE_WRITE);
    myFile.print(celsius);
    myFile.println(" C ");
    myFile.close();
    digitalWrite(A3, HIGH);
  }

  lcd.setCursor(0, 0);
  lcd.print(celsius);
  lcd.print(" C ");
  lcd.setCursor(0, 1);
  lcd.print(fahrenheit);
  lcd.print(" F ");
  lasttemp = celsius;
  }

and this is the one I'm working on as I write this, with the illumination delay messing up:
#include <OneWire.h>
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>

unsigned long owpreviousMillis = 0;
const long owinterval = 750;
//---------------------------------------------------------------------------------- One wire temperature sensor stuff
OneWire  ds(9);                 //Setting one wire bus pin
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
float celsius, fahrenheit;      //Variables for celsius and farenheit conversions
long previousMillis = 0;
float lasttemp;                 //Variable for last temperature
float delta;                    //Variable for temperaturechange
const long interval = 1000;     //Check once every 1 second

//---------------------------------------------------------------------------------- End of one wire temperature sensor stuff.

LiquidCrystal lcd(6, 7, 5, 4, 3, 2); //Defining pins for the LCD

//---------------------------------------------------------------------------------- SD card stuff
const int chipSelect = 10;              //Setting SD chip select pin (obviously)
File myFile;
long sdpreviousMillis = 0;
const long sdinterval = 5000;           //SD card write interval

//-----------------------------------------------------------------------------------End of pre-setup

void setup(void) {
  pinMode(A2, INPUT);
  pinMode(A0, OUTPUT);    //Green LED for temperature stability indication
  pinMode(A3, OUTPUT);    //Red LED for sd card activity indication
  Serial.begin(115200);
//------------------------- Testing LCD and LED's, displaying version number and checking for SD card.
  lcd.begin(8, 2);
  lcd.setCursor(0,0);
  lcd.print("STARTING");
  lcd.setCursor(0, 1);
  lcd.print("VER. 1.5");
  digitalWrite(A0, HIGH);
  digitalWrite(A3, LOW);
  delay(1000);
  digitalWrite(A0, LOW);
  digitalWrite(A3, HIGH);
  lcd.clear();

  if (!SD.begin(10)) {                    // Check for SD card
    digitalWrite(A3, LOW);
    lcd.setCursor(0,0);
    lcd.print("SD CHECK");
    lcd.setCursor(0,1);
    lcd.print("  FAIL  ");
    delay(1000);
    lcd.clear();
    digitalWrite(A3, HIGH);
  } else {
    delay(1000);
    digitalWrite(A3, LOW);
    lcd.setCursor(0,0);
    lcd.print("SD CHECK");
    lcd.setCursor(0,1);
    lcd.print("  PASS  ");
    delay(1000);
    lcd.clear();
    digitalWrite(A3, HIGH);
  }
//----------------------------------- Setting up one wire temperature sensor.
  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }
  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }
  if (OneWire::crc8(addr, 7) != addr[7]) {
    Serial.println("CRC is not valid!");
    return;
  }
  Serial.println();

  // the first ROM byte indicates which chip
  switch (addr[0]) {
  case 0x10:
    Serial.println("  Chip = DS18S20");  // or old DS1820
    type_s = 1;
    break;
  case 0x28:
    Serial.println("  Chip = DS18B20");
    type_s = 0;
    break;
  case 0x22:
    Serial.println("  Chip = DS1822");
    type_s = 0;
    break;
  default:
    Serial.println("Device is not a DS18x20 family device.");
    return;
  }

}
//----------------------------------------------------------------------------- End of setup.

void loop(void) {

  unsigned long sdcurrentMillis = millis();
  unsigned long currentMillis = millis();
  unsigned long owcurrentMillis = millis();

  if (owcurrentMillis - owpreviousMillis >= owinterval) {
    owpreviousMillis = owcurrentMillis;
    ds.reset();
    ds.select(addr);
    ds.write(0x44, 1);        // start conversion, with parasite power on at the end
    }

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  }
  else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }

  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");

  delta = celsius - lasttemp;                       //Create value to check how much temperature has changed

  if (currentMillis - previousMillis >= interval) {  //If it has been 20 seconds, check to turn LED on
    previousMillis = currentMillis;
    if ((delta < 00.03) && (delta > -00.03)) {      //If temperature hasn't changed by +/- .05 turn led on.
      digitalWrite(A0, HIGH);
    }
  }
  if (delta >= 00.06) {                             //If temperature has changed by more than .1 turn LED off
    digitalWrite(A0, LOW);
  }
  if (delta <= -00.06) {
    digitalWrite(A0, LOW);                         // If temperature has changed by more than -.1 turn LED off
  }

    if (sdcurrentMillis - sdpreviousMillis >= sdinterval) {  //Write to SD card every 5 seconds.
    sdpreviousMillis = sdcurrentMillis;
    digitalWrite(A3, LOW);
    myFile = SD.open("Log.txt", FILE_WRITE);
    myFile.print(celsius);
    myFile.println(" C ");
    myFile.close();
    digitalWrite(A3, HIGH);
  }

  lcd.setCursor(0, 0);
  lcd.print(celsius);
  lcd.print(" C ");
  lcd.setCursor(0, 1);
  lcd.print(fahrenheit);
  lcd.print(" F ");
  lasttemp = celsius;
  }

This is the post on the Arduino forum which sort of explains what I'm doing a bit better, if it does not make sense: Best way to set up a button to toggle a second function? (millis issue now).
Edit/update
Alright, so I think it has to do with how I structured that bit of the code, it seems like the arguments to turn the LED off weren't in the if statement which used the delay, so changed it to this, and unfortunately now it is on constantly, but I think I am on the right track.
if (currentMillis - previousMillis >= interval) {  //If it has been 20 seconds, check to turn LED on
previousMillis = currentMillis;
if ((delta < 00.03) && (delta > -00.03)) {       //If temperature hasn't changed by +/- .05 turn led on.
  digitalWrite(A0, HIGH);
} else {
  if ((delta >= 00.06) && (delta <= -00.06)) {
    digitalWrite(A0, LOW);
  }
}
}

It seems like this should work but perhaps there's an issue with having two if statements set up on top of each other like that. I also gave it a try like this, to no avail.
(currentMillis - previousMillis >= interval) {  //If it has been 20 seconds, check to turn LED on
previousMillis = currentMillis;
if ((delta < 00.03) && (delta > -00.03)) {       //If temperature hasn't changed by +/- .05 turn led on.
  digitalWrite(A0, HIGH);
} else {
  if (delta >= 00.06){
    digitalWrite(A0, LOW);
  } else {
  if (delta <= -00.06){
   digitalWrite(A0, LOW);
  }
 }
}
}

Edit/update
Quick clarification, I managed to get rid of the delay and use millis instead but it introduced an issue with the LED which indicates stable temperature not working (being lit most of the time, and then flashing off/on fairly quickly as the temperature changes, instead of remaining off until it stabilizes again). It seems to be ignoring the delay I have it waiting for.
Now, after going through it a lot, it seems like this is how I need it set up. It checks if the interval has been reached, if so, it checks if the temperature has changed less than x amount, if so it lights the LED.
However, if the temperature has changed more than that, it checks if it exceeds y amount, and if so turns the light off.
I have tried reversing these and it has had no effect, it just seems like the boolean arguments aren't working and I don't know why, but at least the delay issue is solved.
if (currentMillis - previousMillis >= interval) {  //If it has been 20 seconds, check to turn LED on
previousMillis = currentMillis;
if ((delta < 00.03) && (delta > -00.03)) {       //If temperature hasn't changed by +/- .05 turn led on.
  digitalWrite(A0, HIGH);
} else if ((delta >= 00.06) || (delta <= -00.06)) {
    digitalWrite(A0, LOW);
  }
}

Here? Best way to set up a button to toggle a second function? - you posted this issue there 30 minutes ago. there isn't much activity going on there - maybe everyone's eating dinner? Try to let a little longer elapse before running off cross-posting that "nothing is happening" on another site. Like, 12 hours.

There hasn't been activity on that thread much longer than that, and I wanted to get feelers out in multiple places, different sites are likely to be used by different people, who are in different places in the world, so why not try and maximize the chances of getting a response? Especially at this time of day when the majority of people who use this forums north america) will be asleep?
Besides, this also puts out the issue as it's own thing relating to the millis function, which means that people searching for something similar will be able to find this more easily, what's wrong with that?

Besides, chances are most of the people who read that thread and did not reply were not interested in it or could not offer advice, so they will likely not visit it again, and I don't want to spam their forum.
So, I'll just wait for an actual helpful reply on either of these, unfortunately this forum has turned out unhelpful in that regard thus far.

Looks like you got a good answer here from Edgar Bonet. Especially at this time of day when the majority of people who use this forums north america) will be asleep? However on the Arduino forum I note that you also got answers 49 mins, 83 mins, and 102 mins after the post I referred to. so they will likely not visit it again - apparently not.

I was referring to people who have previously looked at a thread, when it was in it's infancy, and were not interesting in the original problem.
If that was the case, they would likely not revisit and see that there was a new problem. Apparently you are incapable of contributing though, and instead decide to just spit out useless and pointless comments.

Currently, your algorithm for reading the temperature in loop() looks
like:
request_temperature_conversion();
delay(1000);
float temp = read_temperature();
report_temperature_to_user(temp);

If you take care to send the first request in setup(), then you can
roll these pieces around so that your loop() code looks like:
delay(1000);
float temp = read_temperature();
report_temperature_to_user(temp);
request_temperature_conversion();

And that's the trick: you send the new request in the same loop
iteration. Once you do that, it becomes quite simple to remove the delay
and use millis() instead. Your compete loop code could then look like:
void loop() {
  uint32_t now = millis();

  if (now - last_temp_read >= temp_read_interval) {
    float temp = read_temperature();
    report_temperature_to_user(temp);
    request_temperature_conversion();  // make request now, will read next time
    last_temp_read = now;
  }

  if (now - last_led_update >= led_update_interval) {
    update_led_display();
    last_led_update = now;
  }

  if (now - last_SD_card_write >= SD_card_write_interval) {
    write_data_to_log_file();
    last_SD_card_write = now;
  }
}

Make sure to account for for the fact that the first temperature read is bogus. Other than that, an excellent technique.

@Gerben: Could you explain why the first read is bogus?

Sorry, not really the most accurate word here. The first time you start the code it will read the temperature before you started the first conversion. So the value you get back could be anything.

Sorry again. It seems you already explained/fixed that: If you take care to send the first request in setup() ....


text:
VirtualWire send function
I am a little confused on how exactly VirtualWire's "send" function works. After looking at the code, the process I gathered is the following.

In the Arduino IDE, call vw_send() with the right parameters.
Inside this method, it will start to encode the message and create the packet.
Then before the function returns, it calls vw_tx_start().
Inside that function, it enables the transmitter hardware and sets the variable "vw_tx_enabled" equal to true. Then this function returns, followed by the immediate return of vw_send(). So there is no where in this flow where the message is actually being sent.

However, the actual transmission of the message happens inside vw_Int_Handler(). But this function is never called in vw_send() or vw_tx_start(). So the only way this could be happening is if there was some sort of multi-threading correct? Because by setting vw_tx_enabled to true, the transmission process would begin inside vw_Int_Handler.
Can someone explain/clarify this?
Moreover, this library uses digitalWrite to transmit the bits. Wouldn't it just be faster to toggle the bits at the registry level?
Lastly, in VirtualWire, they send a 36 bit preamble, I assume this is for synchorinzation purposes. So if I want to send 128 byte packet length, how much of a preamble should I use? I believe the reason for VirtualWire only transmitting 27 byte packet length is because the 36 bit preamble will only keep the data synchronized for that long. So is there a certain formula used to determine the preamble size?

However, the actual transmission of the message happens inside vw_Int_Handler(). But this function is never called in vw_send() or vw_tx_start(). So the only way this could be happening is if there was some sort of multi-threading correct? Because by setting vw_tx_enabled to true, the transmission process would begin inside vw_Int_Handler.

The vw_Int_Handler function is called from the interrupt handler of one of the timer modules in the chip. Yes, you could say it was some form of multi-threading in that it happens interleaved with the main processing of your sketch.

Moreover, this library uses digitalWrite to transmit the bits. Wouldn't it just be faster to toggle the bits at the registry level?

Yes it would, but it would be less portable.  VirtualWire has been written to work on a wide range of chips, and doing low-level port access would make the code about 1000x more complex, having to include special code for each and every chip it runs on.  Easier (though less efficient) to just use digitalWrite().

Lastly, in VirtualWire, they send a 36 bit preamble, I assume this is for synchorinzation purposes. So if I want to send 128 byte packet length, how much of a preamble should I use? I believe the reason for VirtualWire only transmitting 27 byte packet length is because the 36 bit preamble will only keep the data synchronized for that long. So is there a certain formula used to determine the preamble size?

VirtualWire uses a coding system called 4b/6b (actually a sub-set of 5b/6b coding). In that system it takes 6 symbols to transmit 4 bits. It is a way of encoding the clock into the signal in a reasonably efficient manner.
The encoding system means that there can never be 36 alternating 1/0 bits in a message. That unique stream is used as the synchronisation because it can't be confused with anything else.  From then on it's just data encoded as 4b/6b. The limit on how much data can be transmitted in one packet is a purely arbitrary value. Since this is a low-speed protocol to low-power devices it is expected that they will have limited RAM, and so limited space to receive data. So small packets are the default.
The numbers in use, incidentally, have been chosen because they fit into the 4b/6b coding scheme quite nicely.  For instance 36 symbols of preamble is equivalent to 24 bits of data. The packet size is 30 bytes, three bytes of which are used for control information (checksum, byte count, etc), leaving 27 bytes of actual payload.  30 bytes is 240 bits, which is, in 4b/6b, 360 symbols. 360 symbols could be packed cleanly into 45 bytes for simple transmission (pre-encoding from binary to 4b/6b before transmission).
Other values won't fit quite so neatly.


text:
How to define a SoftwareSerial object inside a class?
I have a header file called Rhino.h with class Rhino. I want to pass RX and TX pin numbers to this object class, and with this, define a SoftwareSerial object to be used inside the Rhino class. The code in my header file looks like this (there are more number of functions like gotoPos() which I have omitted for brevity purpose):
#include "Arduino.h"

class Rhino
{
public:
    Rhino(int rx,int tx):serial(rx,tx){}

    void gotoPos(int pos)
    {
        serial.write(pos);
    }
private:
    SoftwareSerial serial;
}

And my Arduino code looks like this:
#include <Rhino.h>
Rhino motor1(9,10);
void setup()
{
    motor1.gotoPos(10);
}
void loop() {}

I get this as error:
Arduino: 1.0.6 (Windows NT (unknown)), Board: "Arduino Uno"
S:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 -IS:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino -IS:\Program Files (x86)\Arduino\hardware\arduino\variants\standard -IS:\Program Files (x86)\Arduino\libraries\Rhino C:\Users\Samvrit\AppData\Local\Temp\build2516495983752907071.tmp\Test2.cpp -o C:\Users\Samvrit\AppData\Local\Temp\build2516495983752907071.tmp\Test2.cpp.o

In file included from Test2.ino:6:
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:740: error: 'SoftwareSerial' does not name a type
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In constructor 'Rhino::Rhino(int, int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:16: error: class 'Rhino' does not have any field named 'serial'
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::init()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:21: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::reset()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:30: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::autoCalibrate()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:37: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::sendCmd(String)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:46: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::sendCmd(char*)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:58: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::rotate(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:76: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::stopMotor()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:88: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoPos(float)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:103: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoAngleDeg(float)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:123: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoAngleRad(float)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:143: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoAngleDegC(float)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:164: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoAngleRadC(float)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:185: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoRel(long int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:218: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoRelDeg(float)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:253: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::gotoRelRad(float)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:289: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::setSFGain(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:306: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::setP(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:322: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::setI(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:338: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::setD(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:355: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::setSpeed(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:372: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::setI2CAddr(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:389: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'void Rhino::setPos(int)':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:406: warning: unused variable 'curr_pos'
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:415: warning: unused variable 'curr_pos'
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:426: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getPos()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:474: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'float Rhino::getAngleDeg()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:501: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'float Rhino::getAngleRad()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:528: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getSpeed()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:555: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getRotSpeed()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:582: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getI2CAddr()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:609: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getSFGain()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:636: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getP()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:663: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getI()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:690: error: 'serial' was not declared in this scope
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h: In member function 'int Rhino::getD()':
S:\Program Files (x86)\Arduino\libraries\Rhino/Rhino.h:717: error: 'serial' was not declared in this scope

Put a semicolon (;) after right brace (}) that ends the class def.  As noted in a C++ Syntax: class page (at end of Track.h section),  “The end of the compound statement ... is followed by a semi-colon [unless defining] a class and an object of that class in a single statement”

In your header file, I dont see where you included SoftwareSerial.h; this may be a part of why you got those errors. Also you need to end the class definition with a semi-colon, like you were advised in a comment.
That said, you could just pass a pointer to a SoftwareSerial object to your Rhino constructor. In your library header:
#include "Arduino.h"
#include <SoftwareSerial.h>

class Rhino {
  private:
    SoftwareSerial * serial;

  public:
    Rhino(SoftwareSerial * ss);
    // other prototypes
};

In your .cpp source:
#include "Rhino.h"  // assuming thats what you named the header

Rhino::Rhino(SoftwareSerial * ss){
  serial = ss;
 }

void Rhino::begin(uint32_t baud){
  serial->begin(baud);
}

void Rhino::gotoPos(int pos)
{
  serial->write(pos);  // must use the structure pointer operator
}

In your Arduino sketch:
#include "Rhino.h"
#include <SoftwareSerial.h>

SoftwareSerial ss(2,3);
Rhino rhino(&ss);  // pass a pointer to ss

void setup(){
  rhino.begin(9600);
  rhino.gotoPos(50);
}

Thank you. It worked when I included the SoftwareSerial library in my Arduino sketch. Also, I figured that it is better to include the SoftwareSerial.h in the Rhino.h as well, because then the order of including the header files in the Arduino sketch doesn't matter. Otherwise the SoftwareSerial.h should be included BEFORE the Rhino.h library.

Personally I wouldn't go down this route. Instead I would pass a Stream object (as a pointer or a reference) to the constructor and use that. Then it is up to your sketch to define what that Stream object is and initialize it.
That way if you want to use the same class on a hardware UART instead of a SoftwareSerial you just change the sketch, not the library.
So you would initialize as something like this:
SoftwareSerial mySerial(6, 7);
Rhino myRhino(mySerial);

void setup() {
    mySerial.begin(9600);
    myRhino.gotoPos(34);
}

Your Rhino class would look something like this:
class Rhino {
    private:
        Stream *_dev;

    public:
        Rhino(Stream *dev) : _dev(dev) {}
        Rhino(Stream &dev) : _dev(&dev) {}
        void gotoPos(int pos);
};

void Rhino::gotoPos(int pos) {
    _dev->write(pos);
}

The double constructors, one with a pointer and one with a reference, allow the simplicity of passing an object as in the example, or as a pointer, which could be done with the new operator all in one step. I like the way shown in the example though since it is nice and clean.
Of course, because you now have a pointer to your stream object, you need to use the pointer dereference operator instead of the normal .:
_dev->write(pos);

Changing to a hardware UART is then as simple as, for example:
Rhino myRhino(Serial);

Heck, you could even send it through the internet since an Ethernet or WiFi Client is also a Stream object.

that's a very interesting approach. Such infinite knowledge you have sir.

Thank you. Your method is of course more compatible. However, I have functions in my library which use the begin(), listen() & available() functions, which are not available in Stream class. Also, the Rhino motor that I am trying to operate using this library uses only UART. I solved the issue by including SoftwareSerial.h in both the Arduino sketch and the Rhino.h header file.

Also, I don't want the user to initialize an additional SoftwareSerial object in the Arduino code and then send it to the Rhino library. It's better that the user just sends the pin numbers and everything is taken care in the Rhino library.

You need to import the SoftwareSerial library into your Rhino.h file, since you are using that class in your header file. Perhaps you are also in need of a forward declaration. Inside your Rhino.h file, include SoftwareSerial library, and then above class Rhino, type class SoftwareSerial;. This effectively lets the compiler know that Software Serial is being used. More information on forward declarations can be found here.
Modified Code:
#include "Arduino.h"
#include "SoftwareSerial.h"

class SoftwareSerial; //this might be unnecessary, but doesn't hurt to have it.
class Rhino
{
public:
Rhino(int rx,int tx):serial(rx,tx){}

void gotoPos(int pos)
{
    serial.write(pos);
}
private:
    SoftwareSerial serial;
}

Thank you. It did work when I included the SoftwareSerial.h in the Rhino.h.


text:
Using millis() and micros() inside an interrupt routine
The documentation for attachInterrupt() says:

... millis() relies on interrupts to count, so it will never increment inside an ISR. Since delay() requires interrupts to work, it will not work if called inside an ISR. micros() works initially, but will start behaving erratically after 1-2 ms. ...

How does micros() differ from millis() (except of course for their precision)? Does the above warning mean that using micros() inside an interrupt routine is always a bad idea?
Context - I want to measure low pulse occupancy, so I need to trigger my routine when my input signal changes and record the current time.

The other answers are very good, but I want to elaborate on how micros() works. It always reads the current hardware timer (possibly TCNT0) which is constantly being updated by the hardware (in fact, every 4 µs because of the prescaler of 64). It then adds in the Timer 0 overflow count, which is updated by a timer overflow interrupt (multiplied by 256).
Thus, even inside an ISR, you can rely on micros() updating. However if you wait too long then you miss the overflow update, and then the result returned will go down (i.e you will get 253, 254, 255, 0, 1, 2, 3 etc.)
This is micros() - slightly simplified to remove defines for other processors:
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;
    cli();
    m = timer0_overflow_count;
    t = TCNT0;
    if ((TIFR0 & _BV(TOV0)) && (t < 255))
        m++;
    SREG = oldSREG;
    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

The code above allows for the overflow (it checks the TOV0 bit) so it can cope with the overflow while interrupts are off but only once - there is no provision for handling two overflows.

TLDR;

Don't do delays inside an ISR
If you must do them, you can time then with micros() but not millis(). Also delayMicroseconds() is a possibility.
Don't delay more than 500 µs or so, or you'll miss a timer overflow.
Even short delays may cause you to you miss incoming serial data (at 115200 baud you will get a new character every 87 µs).

Not able to understand the statement given below that is used in micros(). Could you please elaborate? Since ISR is written, TOV0 flag will be cleared as soon as ISR is entered and hence below condition may not become true!. if ((TIFR0 & _BV(TOV0)) && (t < 255)) m++;

micros() isn't an ISR. It is a normal function. The TOV0 flag lets you test the hardware to see if the timer overflow has happened (but not been processed yet).

Since the test is done with interrupts off you know the flag will not change during the test.

So you mean to say after cli() inside micros() function, if any overflow occurs, that needs to be checked? That make sense. Otherwise even though micros is not a function, TIMER0_OVF_vect ISR will clear TOV0 in TIFR0 is what my doubt was.

Also why TCNT0 is compared against 255 to see if it is less than 255? After cli() if TCNT0 reach 255 what will happen?

Even with interrupts off the hardware timers will continue to count. I think the test for < 255 is because of a possible situation where the overflow flag has been set but the timer is still at 255 (so it hasn't quite overflowed yet). The next one up from 255 would be 0.

TIMER0_OVF_vect ISR will clear TOV0 in TIFR0 is what my doubt was - the timer might have overflowed and the ISR has been scheduled but not yet run.

In particular after the line t = TCNT0; the timer might overflow just now so we need to test the overflow flag, and it t is less than 255, and the overflow flag is set, then it probably overflowed between those two instructions.

It is not wrong to use millis() or micros() within an interrupt routine.
It is wrong to use them incorrectly.
The main thing here is that while you are in an interrupt routine "the clock isn't ticking".  millis() and micros() won't change (well, micros() will initially, but once it goes past that magic millisecond point where a millisecond tick is required it all falls apart.)
So you can certainly call on millis() or micros() to find out the current time within your ISR, but don't expect that time to change.
It is that lack of change in the time that is being warned about in the quote you provide.  delay() relies on millis() changing to know how much time has passed. Since it doesn't change delay() can never finish.
So essentially millis() and micros() will tell you the time when your ISR was called no matter when in your ISR you use them.

No, micros() updates. It always reads the hardware timer register.

The quoted phrase is not a warning, it is merely a statement about how things work.
There's nothing intrinsically wrong with using millis() or micros() within a properly-written interrupt routine.
On the other hand, doing anything at all within an improperly-written interrupt routine is by definition wrong.
An interrupt routine that takes more than a few microseconds to do its job is, in all likelihood, improperly written.
In short:  A properly-written interrupt routine will not cause or encounter issues with millis() or micros().
Edit:  Regarding “why micros() "starts behaving erratically"”, as explained in an “examination of the Arduino micros function ” webpage,  micros() code on an ordinary Uno is functionally equivalent to
unsigned long micros() {
  return((timer0_overflow_count << 8) + TCNT0)*(64/16);
}

This returns a four-byte unsigned long comprised of the three lowest bytes from timer0_overflow_count and one byte from the timer-0 count register.
The timer0_overflow_count is incremented about once per millisecond by the TIMER0_OVF_vect interrupt handler, as explained in an examination of the arduino millis function  webpage.
Before an interrupt handler begins, AVR hardware disables interrupts.  If (for example) an interrupt handler were to run for five milliseconds with interrupts still disabled, at least four timer 0 overflows would be missed.  [Interrupts written in C code in the Arduino system are not reentrant (capable of correctly handling multiple overlapping executions within the same handler) but one could write a reentrant assembly language handler that reenables interrupts before it begins a time-consuming process.]
In other words, timer overflows don't “stack up”; whenever an overflow occurs before the interrupt from the previous overflow has been handled, the millis() counter loses a millisecond, and the discrepancy in timer0_overflow_count in turn makes micros() wrong by a millisecond too.
Regarding “shorter than 500 μs” as an upper time limit for interrupt processing,  “to prevent blocking the timer interrupt for too long”, you could go up to just under 1024 μs (eg 1020 μs) and millis() still would work, most of the time.  However, I regard an interrupt handler that takes more than 5 μs as a sluggard, more than 10 μs as slothful, more than 20 μs as snail-like.

Could you please elaborate on "how things work", in particular why micros() "start behaving erratically"? And what do you mean by "properly-written interrupt routine"? I assume it means "shorter than 500us" (to prevent blocking the timer interrupt for too long), "using volatile variables for communication" and "not calling library code" as much as possible, is there anything else?

@PetrPudlák, see edit

You should never do anything inside an ISR except set a flag saying you got the interrupt, and return.

While it is true that one should keep ISR code as short as possible, this statement is excessive. There are many situations where doing something else is relevant. In fact, just setting a flag is useless: the hardware, at least on AVR, does that for you, without having to enable the interrupt.

@EdgarBonet, I am not sure, but I think high rep users can vote to delete an answer with negative score

@Juraj: Indeed, you are right.

It is different than the advice you've gotten maybe, but it simplifies code and encourages good program structure.  Open your mind and see how the suggestion would make the problems in the sample code go away.  The only thing "excessive" is my 30 years of coding firmware for IBM :)