text:
Trying to pass a single char to a serial device
Good day,
I have a serial device that when connected via hyper terminal gives me a status report when I press the letter 'd' no enter key or anything required just the letter d. Also Ctrl-t will give me some routing information.
I would like to press a button connected to the arduino and send the b to the serial device and view the status information back from it.
At this point I have the Serial device connected to the arduino and am able to see messages from it, however when I press the switch connected to pin 2 the serial device does not send me the status output as expected and as seen via direct serial connection to my computer with hyperterminal.
Does anyone have an experience or input regarding this?
#include <SoftwareSerial.h>
// software serial #1: TX = digital pin 10, RX = digital pin 11
 SoftwareSerial portOne(10, 11);
 const int buttonPin = 2;     // the number of the pushbutton pin
 const int button1Pin = 4;
 const int ledPin =  13;      // the number of the LED pin
//define char to send to serial

char stat = 'd';
char route = '\x14';
// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status
int button1State = 0;

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
                pinMode(ledPin, OUTPUT);
                pinMode(buttonPin, INPUT);
                pinMode(button1Pin, INPUT);
                Serial.begin(4800);
                while (!Serial) {; // wait for serial port to connect. Needed for native USB port only
                }
                // Start each software serial port
                portOne.begin(4800);
                while (!portOne) {; // wait for serial port to connect. Needed for native USB port only
                }
              }

// the loop function runs over and over again forever
void loop() {
            static int Once = 0;
            static int Once1 = 0;
            buttonState = digitalRead(buttonPin);
            button1State = digitalRead(button1Pin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
            if (buttonState == HIGH ) {
                                      if (Once == 0) {
                                                        Once = 1;
                                                        // turn LED on so I can tell the button is working
                                                        digitalWrite(ledPin, HIGH);
                                                        // send d to Radio
                                                        portOne.write(stat);
                                                        // send d to serial monitor so I can see the charector
                                                        Serial.print(stat);
                                      }
                                      }

if (buttonState == LOW) {
                          // turn LED off:
                          Once = 0;
                          digitalWrite(ledPin, LOW);

                          }

  // check if the other pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (button1State == HIGH) {
    if (Once1 == 0) {
          Once1 = 1;
    // turn LED on:
   // digitalWrite(ledPin, HIGH);
    // send ctrl-t to radio
    portOne.write(route);
    }
  }
  if (button1State == LOW) {
    // turn LED off:
    //digitalWrite(ledPin, LOW);
    Once1 = 0;
  }
    portOne.listen();
      // read data from the Software Serial portOne
   // and send to the hardware serial port:
   while (portOne.available() > 0) {
     char inByte = portOne.read();
     Serial.print(inByte);
   }
}

Maybe add a while(Serial.available())portOne.print(Serial.read()); to allow you to inject characters from the serial monitor to you device.  Then you could bypass potential issues with bouncing/debouncing.

I see what your saying however I think its more of a problem getting the char passed to the serial device. You see if I change char stat from 'd' to 'c' this should "enable monitor all" however this doesn't happen, so i'm guessing either the char isn't getting to the device or its garbled some how...

We should be seeing a Ground wire going to the device. As a convention, you should connect 5V to the red line on the breadboard, and Gnd to blue. It is confusing to reverse that. Please add some debugging displays, eg. Serial.println ("Sending 'd' to device"); - then you'll know if it is a switch-detection issue, or a comms issue.

In your intro you wrote "gives me a status report when I press the letter 'b'". In the code you wrote // send d to Radio (and the code appears to actually do that). Is this correct, and could that be the source of your error?

Understood, sorry my breadboard has the blue to the left and red to the right, so I did the schematic to match my breadboard and didn't change it to the match the picture in Fritzing. I have had that Serial.println in my code and seen the indication everytime I press the button. I Also have at times had a ground connected from the device to the arduino. I will make those changes and get back to you.

jrobert Thank you for noticing that, for some reason while typing this I put a 'b' however 'd' is correct.
Nick I added a ground with no change and updated the image to reflect that along with the power/ground to the breadboard changes. Also in my code above you should see // send d to Radio                                                           portOne.write(stat);                                                           // send d to serial monitor so I can see the charector                                                           Serial.print(stat);

It was not entirely clear from your question, but have you verified that the signalling voltage and polarity of the serial device is compatible with the Arduino?  Traditional serial interfaces (ie RS232, etc) are not, and require an inverting level translator to interface with an Arduino.

@ChrisStratton When I metered the serial connection from the device I found the TX lines to be -9.2v. Based on your suggestion I did some research and based on this https://www.sparkfun.com/tutorials/215 it looks like I do indeed need to run a MAX3323 chip (or similar).  Its amazing I was able to get data from the device to display on the arduino at all, and definitely added to my confusion.

Glad you figured it out.  Beware that exposure to such voltages may have permanently damaged your Arduino.  As for how it could have worked, I suppose it is possible that the software serial implementation is (intentionally or accidentally) more polarity agnostic than a hardware UART would be.  People sometimes drive RS232 receivers with a logic level signal that has merely been inverted to the needed polarity and not amplified, and you could imagine trying to receive them with a resistor/diode network.


text:
Detect when RFID card is absent
I am trying to build a mobile device that turns itself on when removed from its usual location. I am attempting to do this with an Adafruit PN532 RFID reader and a MiFare card. Using the sample code I can detect when the card is present
success= nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
Serial.println("Scanning");
if (success){
  Serial.println("FOUND");
}

However, when I try to detect the absence of the card using the following code it will tell me "Present" over and over (since its in the Loop) while the RFID card is present but when it is removed it stops printing "Present" but never prints "Card Gone"
success= nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
    Serial.println("Present");
    if (!success){
      Serial.println("Card Gone");
    }

Is this a function of how Im using ! or is there something else at play here? I have found very few suggestions regarding detecting the absence of an RFID card and none of them seem to provide any useful answer. Most suggest some other hardware methodology as the solution. That is not the type of answer Im interested in for the moment. I would simply like to figure out why my code is incorrect.

Post the whole function, at least, not this snippet. There is no context.

First, your code isn't structured properly. It should be:
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

if (success)
  Serial.println("Present");
else
  Serial.println("Card Gone");

From what I could find in the library, the reason you aren't getting either the 'Card Gone' or 'Present' message when there is no card is because nfc.readPassiveTargetID() is a blocking function. It will wait forever until a tag is detected, at which point it returns to the caller. When you bring a card within the reader's range, the function returns quickly and loop() runs smoothly, giving you the 'Present' message over and over again. When you remove the card however, on the next call of nfc.readPassiveTargetID(), the function tries to locate a card but finds none and then it keeps trying and does not return. So loop() never gets past that point, until you bring a card within range again.
To detect the presence or absence of something, an observer must observe for some pre-determined period of time before making a decision. So, I suggest you get the latest version of this library which gives you the option of adding a milliseconds timeout argument to nfc.readPassiveTargetID(). That way, you can specify how long you want the function to try detecting a card before concluding there is no card and returning.
Alternatively, you could use your existing function as is but in setup() you need to set the maximum number of re-tries before the nfc.readPassiveTargetID() returns. This is done with setPassiveActivationRetries(). Any argument from 0x00 to 0xFE indicates a finite number of tries, while 0xFF is to wait forever:
nfc.setPassiveActivationRetries(0x9A); // for example
nfc.SAMConfig();  // this comes next

Good luck.

thank you for the great explanation and thoughts on approaches to address the issue. One question before I try this. From your explanation, it seems the "if (success)" line is redundant?

@techkilljoy In your code, it is redundant because the function only ever returns if it finds a card. However, if you make these changes, it will become possible for the function to return 0 after trying a few times and finding no card. A card detected would result in a return value of 1 though

You can edit the .cpp file and add a timeout. I did this to remove the blocking scan. Search for TIMEOUT in the Adafruit_PN532 source code.

source: Stack Exchange

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

sort: votes


text:
How to implement a priority queue
I was wondering if I would be able to use specific parts of the c++ library for my arduino sketch. For example the arduino library has a queue array but I wanted to use a priority queue for my sketch and I am unsure how to modify the queue header file to do that. Also if I can use the priority queue from the c++ library can you please tell me how I would go about doing that.
Thank-you

There is no priority queue on the Arduino - and for a good reason: these kind of things really aren't suitable for small microcontrollers with limited resources. While it may be possible to roll your own it most likely isn't the right thing to do - instead you should think about what you are actually trying to achieve and consider if this is really the right way to go about it.

Hi Majenko thanks for answering. Do you know if there is an arraylist implementation. I am trying to implement djikistra's algorithm. I was able to do a bfs just with the use of an array, but djikistra's gets a little complicated when using just arrays. I think I can work with an arraylist if arduino has it. @Majenko

It may be time to teach yourself linked lists...

Does the arduino library include linked lists @Majenko

No, they are a basic concept of C, not a library function.

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


text:
Simple Arduino Serial Arithmetic
I'm developing a program to calculate static margin of an aircraft through the calculations of mass,moment and arm. Essentially dealing with large numbers.
I'm having difficulty in setting up my code in the way so that the arithmetic is applied correctly to larger numbers. What I have so far works but only when the input is 0-9. The arithmetic fails to calculate digits beyond.
I understand that I'm breaking the digits into separate variables as to convert them from ASCII format to their intended value. The problem is in putting those digits back together.
I know this is probably very simple but I'm picking up arduino again after a long break and I'm very rusty.
Here's my code thus far:
long batterymoment,num1,num2,answer;
int batterymass = 720;
int batteryposition;
boolean mySwitch = false;

void setup() {
  Serial.begin(9600);
  num1=0;
  num2=0;
  Serial.println("Enter battery position");
}

void loop() {
  while (Serial.available()){
   batteryposition = Serial.read();

   if(batteryposition>47 && batteryposition<58){
     if(!mySwitch){
       num1=(num1*10)+(batteryposition-48);
     }else{
       num2=(num2*10)+(batteryposition-48);
     }
   }

   answer=num1+num2;
   batterymoment=answer*batterymass;
   Serial.print("Battery moment is: ");
   Serial.println(batterymoment);
   num1=0;
   num1=0;
   mySwitch=false;
  }
}

Thanks.

Read and understand this before you go any further: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

will do @Majenko

Do you mean to repeat num1=0; in loop()?
It is only reading one character per loop() because loop() happens much faster than Serial.available() and Serial.read().
Do the reporting and clearing when you receive some sort of separator/non-digit character.

so you mean have a statement that requires a non-digit character to be satisfied before 'answer=num1+num2'?

Yes.  You should be able to add an else { ... } around the last chunk of code to make this work.  It would probably be cleaner to copy the characters into a buffer and then do atol(), atoi(), atof()... etc.  on the buffer after you know you have the whole message.


text:
How do I upload the sensor data from arduino into a database?
I have just connected a Libelium shield to connect many sensors to Arduino UNO, that measure water ph level, temperature,...etc. I really couldn't figure out how do I upload the sensor data into a database(MySQL). I have the code for database connectivity, but still couldn't figure out how(Querying) to upload the sensor data into the database.
The main problem here is how do I make the arduino recognize the sensor data to upload it into database or send to to another Arduino or Raspberry pi through XBee.
Code for database connectivity:
void sendData(){

          Serial.println("Connecting...");
          if (my_conn.mysql_connect(server_addr, 3306, user, password)){
            delay(500);
            Serial.println("Starting SQL!");
            Serial.println(INSERT_SQL);
            my_conn.cmd_query(INSERT_SQL);
            Serial.println("Query Success!");
            my_conn.disconnect();
            Serial.println("\n");
          }
          else {
            Serial.println("Connection failed!");
          }
}

You might be mixing concerns and you may benefit from decomposing your mental model of the situation a bit.  You should have sensor reading components, a component that consumes the sensor data (does something with it, e.g. drop into DB), and your network layer.
Ideal architecture
(1) Arduino connected to sensor.  Read in measurements of environment and transmit data via ZigBee
(2) Arduino or, ideally, Raspberry Pi listens for messages on ZigBee mesh network.  On message, sanitize data and insert into DB.  Even better there is a queue process between "sanitize data" and "insert into DB"

First you have to create the table in your MySQL database, like:
CREATE TABLE IF NOT EXISTS `table_log` (
  `log_id` int(11) NOT NULL AUTO_INCREMENT,
  `log_date` date NOT NULL,
  `log_time` time NOT NULL,
  `log_t1` float NOT NULL,
  `log_t2` float NOT NULL,
  `log_t3` float NOT NULL,
  `log_t4` float NOT NULL,
  `log_vbatt` float NOT NULL,
  PRIMARY KEY (`log_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1;

You can execute it in your phpmyadmin page (or create the table manually there). Above we have columns for auto-increment id ('log_id' - necessary), date & time, 4 temperature values and voltage value (modify these according your requirements).
Than the query to create a new record would be like this:
INSERT INTO `table_log` (`log_id`, `log_date`, `log_time`, `log_t1`, `log_t2`, `log_t3`, `log_t4`, `log_vbatt`) VALUES
    (0, '2016-03-04', '01:53:30', 1.0, 2.0, 3.0, 4.0, 3.0);

You need to create this string dynamically (with real values) and use instead of INSERT_SQL.


text:
nrf24l01+ with antenna problem
I just got 4 nrf24l01+ modules with the external antennas, but I'm not able to make them work.
I'm using arduino nanos and MySensors to create a gateway and a sensor.
The funny thing is that when I put a antenna nrf as the gateway and a pcb nrf as sensor, they work just fine, but the other way doesn't.
I also tried two nrfs as gateway and sensor, but the behavior does not look good.
What could it be? Wifi router interference? Channel? Baud rate? Data rate?

Try moving them further apart.

Oh, now that I read it again I noticed that you most certainly have clone modules. There are plenty of links online talking about fake NRF24L01+s.

It's likely an issue related to the modules'  electric supply. The effects can be packet loss (even down to zero bps) or loss of communication with the module.
Two things have to be covered with the nRF modules for them to work:

current draw (i.e. power),
decoupling/filtering (i.e. bypass capacitors).

Since you don't mention specific devices, I'm assuming you refer to an 'antenna' module with SMA (or RP-SMA) connector.
The Nordic Semiconductor nRF24l01+ that is typically used in these modules has a maximum power consumption well below 100mW.
A module with power amplifier (PA) draws significantly more power than the nRF chip alone, the total power consumption will be larger than 100mW.
An Arduino can only supply power according to it's onboard regulator capabilities.
The Minis (and Micros) feature a smaller regulator that cannot drive both the Atmel AVR microcontroller and the PA.
Solution:

provide a separate 3.3V regulator for the nRF module(s),
place a capacitor directly at the modules' connector's supply pins.

Link:

https://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo#PP

It's always worth giving a shot lowering the power level.


text:
Why can't most servos rotate more than around 180°
I was looking how a servomotor works. I realized that a standard servo can only turn up to 180°, but I didn't understand why. Is it because of the potentiometer?

You could actually modifiy (most) servo's to do a continious rotation. BUT it would be somewhat against the reasoning behind servo's. Usually, you won't be able to set the position anymore, but only be able to set the speed.

Fundamentally, because the systems they were designed for convert rotary motion to linear, typically with a range substantially less than 180 degrees (probably more like 120 degrees).
Next, because the control scheme of PWM position pulses is not able to convey requests over an arbitrary range - the mapping of pulse width to position must be limited, and it is sensibly set up to map to something related to the useful range.
Because these limitations in task, a fairly ordinary rotary potentiometer of less than 360 degree range can be employed for position sensing.
Given that the useful range is limited, and the potentiometer relatively easy to damage by over rotation, the gearbox is typically constructed with a mechanical rotation stop somewhere outside the normal range of self rotation.


text:
Machine installed with arduino suddenly turns on when usb is unplugged
Why is my machine suddenly turns ON when I unplugged the USB on my computer? Does it have connection on the auto reset feature of my arduino board?

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

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

  digitalWrite(11,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>'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();

}

Post your schematic or wiring, and point to the datasheet on your machine.  Maybe when the arduino is depowered and the pins tristate, your machine is no longer inhibited from being ON.  But that is only a guess based on the information in your question.

hi Dave X, where can I send/post my schematic diagram? do you have an email or something so i can show both the wiring and arduino code. thanks in advance

Please add it to your question.  The editor has a little mountain-landscape icon that lets you upload graphics.

Hi Dave x, here you go. I have added the sketch as well for you to correlate. this is to automatic select recipe once press "send recipe" and automatic start the tool once press "start" button

Is your Arduino powered only through the USB or is there alternate power?

Opening a serial connection will reset the board.

DaveX yes the arduino is connected on the tool's controller as well which also supply power to the board

I have already tried to put a 10uf capacitor to disable the auto reset but tool still start when i pull off the usb cable from the PC

Do not call loop from loop. You will quickly run out of RAM and the sketch will crash:
void loop(){

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

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

  while(Serial.available() > 0){
...

  }
  else
    loop();

}

For the pins that are supposed to be high, I suggest pull-up resistors:
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);   // for start of program operation

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

When the Arduino powers up it enters the bootloader for a second or so. Those pins won't be set high yet. A pull-up resistor would make sure they are high until such time as you want to drive them low.

If you are saying that the machine powers up when you disconnect the power to the Arduino, that is still a good reason for using pull-up resistors, to make sure that it does not operated until commanded to do so.

where will i connect the pull up resistors and how?

Typically pull-up resistors will be around 10k, and are connected from the pin to +5V. Of course, if the Arduino is not powered, then you need another source of the +5V.

please to clarify the "do not call from loop to loop"

Remove these two lines:
else
    loop();

When loop exits, is it immediately re-called. You don't need to do it that way, in fact it is a Bad Idea.

Hi Nick, where will i connect the pull up resistors and how? and also please to clarify the "do not call from loop to loop". What line should i need  to remove? thanks!

See amended answer.

It looks like the this line in your setup:
  digitalWrite(11,LOW);

... would trigger contact input 211, and do "Start of Program Operation when D11 switches from off to on" every time the sketch starts.
If the arduino resets, it will pull this line low.  Autoreset would initiate this.
By changing the line to the following, the code will wait until it gets an 's' before pulling the line low.
  digitalWrite(11,HIGH);

I don't have an Arduino, but perhaps http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection may help in managing the Auto-Reset issue.

Hi Dave X, thanks, so what i need to do is to remove the digitalWrite (11,LOW) line on the code?

It defaults to LOW, so removing it won't do much. Set it to HIGH if that is what is required here.

Yes, what Nick said.

Sorry fo the confusion. Pin 11 is set to HIGH initially that is why when I unplugged the controller , the machine will suddenly turns ON. If i set it to low, machine will turn ON when i unplug then plugged my ports to PC.

Your code seems to set Pin 11 to LOW initially.

Yes that is actually HIGH (typo error).


text:
Opto Isolator question
I'm building a CANBUS network based on an arduino to go into an offroad racing truck. The vehicle has two separate battery systems, and I would like to monitor the voltage while still electrically isolating them from the arduino itself. For the voltage monitoring itself, I assume I can use a simple voltage divider into an Analog pin. To electrically isolate the arduino, would an Opto Isolator work? I found this one: https://www.sparkfun.com/products/9118 But it appears that it's designed for low voltage to control high voltage, as opposed to the other way around.

An optoisolator is good for digital signals, but won't transfer an analog signal accurately.
Instead, you could put ADCs on the different circuits and optoisolate their communication with a master Arduino.

Instead of an ADC, I'd use another microcontroller with an integrated ADC (even a snall Attiny85, just 8 pins and three analog pins) powered by the battery it has to sense. Every x seconds (or milliseconds, but going really fast is useless I think) it wakes up, makes a conversion, sends it on the serial interface and sleeps again. This way you will just need one optoisolator (on the serial wire going from the attiny to the receiving circuit). using an external ADC will require three optoisolators for SPI or a strange configuration for I2C (because its wires are bidirectional)

The voltage sensing side was going to have it's own microcontroller anyway, so I'll probably do that!

If you are using separate microcontrollers on separate battery systems, maybe a wireless solution would be good.

1) using current sensors based on Hall effect: https://www.sparkfun.com/products/8882. Their sensing circuit/leads and analog parts are electrically isolated.
The drawbacks are: to calculate the voltage, need to wire some load resistor with known value to batteries, but you can switch on the load circuit by relay during measurement; susceptible to magnetic field, some shielding might be needed.
2) to use isolation amplifiers: please see http://www.analog.com/en/products/amplifiers/isolation-amplifiers.html


text:
Bluetooth Arduino control (was Speech recognition arduino control)
How to I control arduino with voice. I got an Android app but it works only with Internet connectivity. So I was an Android app with works offline when I connect to my Bluetooth HC-05. Please suggest me some ideas

You again?! We aren't an Android App search engine I am afraid. Maybe you should ask somewhere more appropriate?

But with that only we control arduino ya

99.999999999% of all android speech recognition apps use the Google Speech API. That is, by its very nature, an on-line facility. Good luck finding one that can run stand-alone on phone and is actually capable of recognising voice reliably.

The fact that, somewhere down the line, after going through a number of other bits of hardware, you may be controlling an Arduino is neither here nor there. We don't know (and we don't care) what android apps are available for voice recognition. Ask on an Android App forum, or maybe search the play store

By asking here you're effectively asking car mechanics about the technical aspects of the petrochemical industry.

I thought I will get the answer here.. As Android control over adruino is very command. My apology to you then

Android control may be common - speech recognition isn't and off-line speech recognition is even further from common. That is a very specific topic and as such has nothing at all to do with Arduino.

As far as the Arduino side of things, this question is effectively "Bluetooth Serial ardunino control".  Or maybe this question is intended to be "What sort of voice control apps can send strings to bluetooth".  The second question is better asked elsewhere, and also answered before any progress can be made on the first.

You might find your answer with someone else who has done the same thing on Instructables:
Arduino Voice recognition Via Bluetooth HC-05 - http://www.instructables.com/id/Arduino-Voice-recognition-Via-Bluetooth-HC-05/
Hope this helps!

You might add the bluetooth/serial parsing code from that link, and a note that it gets the serial input from the Android app AMR_Voice.

ARM app works with Internet connectivity


text:
Problem running WiFiWebClient example
I'm running the WiFiWebClient example which comes preloaded with Arduino IDE 1.6.7. I'm using Arduino Uno board with WiFi Shield Model R3.
/*
  Web client

 This sketch connects to a website (http://www.google.com)
 using a WiFi shield.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 This example is written for a network using WPA encryption. For
 WEP or WPA, change the Wifi.begin() call accordingly.

 Circuit:
 * WiFi shield attached

 created 13 July 2010
 by dlf (Metodo2 srl)
 modified 31 May 2012
 by Tom Igoe
 */

#include <SPI.h>
#include <WiFi.h>
#include <WiFiClient.h>

char ssid[] = "Vanilla Sky"; //  your network SSID (name)
char pass[] = "mypass";    // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0;            // your network key Index number (needed only for WEP)

int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "www.google.com";    // name address for Google (using DNS)

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv != "1.1.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();

  Serial.println("\nStarting connection to server...");
  // if you get a connection, report back via serial:
  if (client.connect(server, 80) == 0) {
    Serial.println("connected to server");
    // Make a HTTP request:
    client.println("GET /search?q=arduino HTTP/1.1");
    client.println("Host: www.google.com");
    client.println("Connection: keep-alive");
    client.println();
  }
}

void loop() {
  // if there are incoming bytes available
  // from the server, read them and print them:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting from server.");
    client.stop();

    // do nothing forevermore:
    while (true);
  }
}

void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

It gets my WiFi shield connected to Vanilla Sky but doesn't fetch the HTTP request (see image below). What is getting wrong here?

Let's break it down :)

Please upgrade the firmware

Visit here to upgrade the firmware of your board. Your original post doesn't show the fw version, but could have outdated library references and has been noted many times that outdated fw will not work.
https://www.arduino.cc/en/Hacking/WiFiShieldFirmwareUpgrading
Also add this to your project to help us determine your firmware:
  Serial.print("Firmware version: ");
  Serial.println(WiFi.firmwareVersion());

My guess is that it is less than 1.1.0. If the Arduino IDE is out of date, and the board is newer,  the NOT EQUAL TO(!=) may suggest that the firmware is newer than the library which could also be an issue.
Just b/c it connects to your router, doesn't mean that it can still communicate correctly.
One last side note, some versions of Arduino IDE have proven to be problematic with uploading a sketch to a wifi shield. A quick search with your Arduino version followed by the Wifi Shield not connecting could point you in the right direction. eg- Arduino x.xx wifi shield not connecting
Hope this helps!

My firmware version is 1.0.0 and it's not a concern unless you're using it for a sophisticated application. 1.0.0 should be able to do at least simple GET requests. I'm using Arduino Uno with the WiFi shield Model R3. My IDE version is 1.6.7


text:
Why does the Arduino UNO have a separate power port if USB also powers it?
Can you power the Arduino off a USB cable alone, without using the regular power connection? If so, what's the point of the additional power connection: to provide extra power?
Also Why not just have two usb ports one for power one for connecting to the computer, or a micro usb.

As Hyperbola pointed out, the USB port function is primarily to allow for programming the board. Now, since the USB port has the power cables too, it is convenient to power the device from the USB port.
The main drawback of USB port powering, however, is that it can supply a limited current: usually the USB2 ports can deliver up to 500mA before shutting down. In order for the arduino board to be compliant with this, consequently, a 500mA fuse was put on the board just after the 5V usb input.
Now, what if your final circuit requires more than 500mA? Will you have to change board? Of course not! you can just use the external power input to power the arduino board and all the other circuitry without worrying about the 500mA limitation. Of course the onboard regulator has limits too, but you have more flexibility.
Moreover portable applications run on batteries. No battery can supply exactly 5V (usually alkaline ones deliver 1.5V per battery, while lithium have usually 3.7V/cell, but this varies over time). Consequently they put an onboard regulator for providing 5V from any 6.5V+ source.
Summarizing: the USB power is convenient, since you will usually power it from the PC when programming. An external connector, however, is very important because it gives you more flexibility when choosing the power supply. You don't have to use both: you can just choose the most suitable for your needs.

thanks this answers my question in addition to the comments and pictures by Robert Cole.

So, what's the MAX voltage I can provide to Arduino ?

@HenriquedeSousa this highly depends on your arduino board and project. For instance, on the UNO there is an NCP1117 after a silicon diode. Let's say your application draws 75mA total (so including also the arduino board). Let's suppose the board will stay at max 30°C; this means that the junction can rise by 120°C.
The calculations are: Rth = 160°C/W -> MaxPower = 120°C/160°C/W = 0.75W -> MaxDeltaV = 0.75W/75mA = 10V; Max input voltage = 5V + 10V + 0.7V = 15.7V. The input voltage of the regulator is max 20V, so the power one is the max one.

@HenriquedeSousa please consider that the calculations provided are just one example. For instance, if the current is 250mA instead of 75 the max voltage gets down to 8,7V. If, on the other hand, you change the board this will also change: for instance if you use a pro mini 5v instead of uno, at 75mA you will be able to use max 10,7V (since the regulator is different)

Can you power the Arduino off a USB cable alone, without using the
  regular power connection?

You can use the USB cable alone to power the board.

If so, what's the point of the additional power connection: to provide
  extra power?

You can use either to power the board. By using just the power plug you can make your Arduino portable by using a battery box or power it via a wall plug.

Also Why not just have two usb ports one for power one for connecting
  to the computer, or a micro usb.

Only ONE USB is needed to power and program.

Arduino, in its very esence, is an embedded system and can be used as a standalone device. The USB port is provided for:

To power up the device.
To program it through a computer i.e. dump the sketch on it which one can program in the Arduino IDE.

Once you have dumped the program on it, it will stay on it forever unless you change/erase it and hence you can use the Arduino anywhere without actually bringing a computer (USB port) along.


text:
Combining 2 State Machines?
I want to gain from recent advice from this forum by re-doing my project using 'state machine' logic if possible, in an effort to reduce wasted processor time and variables usage.
I'm starting from Nick Gammons 'state machine to process input from the serial port' example http://www.gammon.com.au/statemachine, which shows all the different possible combinations for all the special control character 'events' against all the possible machine states - essentially a 2-dimensional grid.
I've refined my goal to the processing of serial input in a format of "command  [parameters]  [options]", similar to a DOS command-line format, eg:  DIR  "c:\program files"  /w /s. This would free me from needing large Buffer[] and Header[] string, and avoides any parsing,
Therefore my event control characters are space, comma, single-quote, double-quote, forward-slash, Carraige Return, and my 'states' are NULL, COMMAND, PARAMETER, OPTIONS
The OPTIONS state adds characters to a temporary option[] string until a comma or space delimiter or Carraige Return causes that option to be processed as appropriate, perhaps saving its value to a recognised variable.
The COMMAND and PARAMETER 'states' add characters to their corresponding command[] and parameters[] strings, including the special control characters if they are contained within either single or double quotes (thereby allowing quotes as part of a string if used within a pair of the other type).
So there appears to be a second state machine needed for NoQuotes, SingleQuotes and DoubleQuotes to modify the operation of the COMMAND, PARAMETER and OPTIONS states.
This is where I run out of neurons, because all I see is an impossibly complex 2-machine-state 3-dimensional grid with too many possible permutations.
But I suspect there must be a very practical way to implement this, because it lies at the heart of almost all command-line utilities dating back to a time when processor power and memory availability were scarcer than hens teeth, and those old DOS command-line utilities needed to be as mimimal as was possible, including their command-line parsing.
So can anybody suggest a feasible model (machine-state or otherwise) for getting command-line type format from input?
UPDATE
Oh dear... I've just seen another complication I hadn't spotted before, which is that '/' options are not necessarily always at the end, which means that except if the options state changes by carraige-return, options state change by delimiter have to return to the state prior to the options state change (phew, I hope that makes some sense).  Anyway, I think it's back to drawing board because this approach seems likely to be too complicated, as the 2 answers already suggest.

The common way of handing interacting states is to expand the interactions into their own state.  i.e. PARAMETER vs SingleQuotes_PARAMETER DoubleQuotes_PARAMETER, where their processing could share much the same code.    See https://github.com/Traumflug/Teacup_Firmware/blob/master/gcode_parse.c for an big example.   Also, this is too broad (you don't have a syntax for us to use) and is really off topic for an Arduino-focused forum.

Another way to think of it as a state  machine is that your state space is a many-dimensional vector of state variables, with a {COMMAND, PARAMETER[],OPTIONS[],etc...)

The question is very much Arduino because I wish to read incoming serial and 'sort' it into command plus optional parameter plus optional control-options, therefore mention of DOS command-line was merely giving a syntax example of the required serial format.

Some sort of general DOS syntax, or the much more limited syntax for a particular command?  With a particular command, there are only a limited number of parameters and options, and your /parser/ state machine can sort them out into their /process/ state variables somewhat like Teacup does.

It's for whatever local 'commands' and 'parameters the arduino is programmed tolook for in  incoming serial, eg: 'LED1 ON', or 'IRSEND "NEC 0xFFEE9123 32".
The options are for optional arduino-to-arduino sending of control info, such as /c(hecksum)=nnn,  /l(ength)=nnn, /s(ource)=nnn etc.     The idea is to read incoming serial a byte at a time and send to command or params or options on the fly, rather than needing to parse an additional large buffer string after.

I would think you can't dispatch the command until the last character of the last option is parsed--so the COMMAND, PARAMETERS, and OPTIONS must all be merely a vector of parameters for the next stage of processing.  You need to collect them all before moving on.  Is the 'LED1' in 'LED1 ON' a command?  ///  For your updated Q, the '\n' changes the state of the system from parsing bytes into the cleaning up the parameter state and executing a command state/oneshot, for example https://github.com/Traumflug/Teacup_Firmware/blob/master/gcode_parse.c#L362 to #390.

Personally I don't think Nick advised to do command line pattern parsing with a state machine. His example is about changing a state machine based on command line input.
I have written some command line parsers and I never used a state machine to do so. I would not advice to use a state machine to do so.
Simple string parsing is far easier.
Edit To answer the remark below:
I would not advice to go byte by byte. I'd advice to go the line by line way.
I have written a library to do read line by line and an article on how that one works. http://blog.baeyens.it/#post16
Here a link to the lib https://github.com/jantje/libraries/tree/master/SerialCommunicator.
Here is a parcing code example. It is not so interesting for you as I have it done in a stage by stage way in a very high level way of coding.
https://github.com/jantje/libraries/blob/master/SerialBridgeCommunicator/SerialBridgeCommunicator.cpp#L21
Basically the algorithm is=
1 Take the first word;
2 identify the word.
3 If the command is complete ->do it
 else Send the rest of the string to a specialized piece of code. (which has the same algorithm)

I thought my needs were the same as Nicks example - to read incoming serial a byte at a time and send to command or params or options on the fly then action them as appropriate after reading a carraige-return, rather than then needing to parse an additional large buffer string after.  But no point me shooting for the moon - you mentioned doing command line parser previously... would you happen to have a suitable flowchart or algorithm?

I would not advice to go byte by byte. I'd advice to go the line by line way.

Suggestion: - don't try to "moosh" (that's a technical-term!) the state-machine heirarchy down into one large, flat state-machine. That way lies madness. Keep your { NULL, COMMAND, PARAMETER, OPTIONS } state machine, for instance, and, wherever you need something more than simple string collection in one of those states, call a parser SM appropriate to the kind(s) of input you expect at that point - a number, a quoted string, an option specifier, etc.

I think I understand (probably too late to avoid madness though cos I think the state machine may have already 'mooshed' my head).  As you say, use NULL, COMMAND, PARAMETER as the states to change through. And even though NoQuotes, SingleQuotes, Double-Quotes and possibly Options might justify a state machine themselves, best just to treat them as separate processes within the main state machine.

You might also consider as a mid-point, a universal parser that can handle various input types, but separate from the main SM. You'll know best, once you quick sketch up a couple of SM hierarchies (that's 'sketch' as in 'circles and arrows', not as in 'coding').


text:
How to save data to SD card using Memory Shield Module SPI
I am trying to save some data to the SD card using the memory shield module that I read from HC-SR04 Ultrasonic Module. The data that gets printed indicates error. This is how my SD card module is connected.

SD card attached to SPI bus as
  VCC -Arduino 5v
  GND- Arduino GND
  MOSI - pin 11
  MISO - pin 12
  CLK - pin 13
  CS - pin 4

Still, Arduino complains that there was an error opening the file in SD card. My sketch is this:
#include <SPI.h>
#include <SD.h>
#define echoPin 6 // Echo Pin
#define trigPin 7 // Trigger Pin

int maximumRange = 250; // Maximum range needed
int minimumRange = 1; // Minimum range needed
long duration, distance; // Duration used to calculate distance
const int chipSelect = 4;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  Serial.print("Initializing SD card...");
  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");
}

void loop() {
  readDistance();
  if(distance>minimumRange && distance < maximumRange){
    String string = "distance is" + distance;
    // open the file. note that only one file can be open at a time,
    // so you have to close this one before opening another.
    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    // if the file is available, write to it:
    if( dataFile ){
      dataFile.println(string);
      dataFile.close();
      Serial.println( string );
    }else{
      // if the file isn't open, pop up an error:
      Serial.println("error opening datalog.txt");
      dataFile.close();
    }
  }else{
    Serial.println("Out of range...");
  }
  delay(50);
}

int readDistance(){
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration/58.2;
}

Output:
rror opening datalog.txt
rror opening datalog.txt
error opening datalog.txt
rror opening datalog.txt
error opening datalog.txt
error opening datalog.txt
error opening datalog.txt
error opening datalog.txt
error opening datalog.txt

How do I solve this to save the readings to SD card?

Re-opening the file each time through the loop seems like a bad idea.  Unfortunately file system abstractions don't map very well to what you want to do.  You may want to write a number of readings, then re-open a file, perhaps with a different name in an incrementing pattern.  Or you could skip the filesystem and write to raw blocks.  Most practically, have a look at the code typically used with Arduino-based uSD data loggers and see what you can learn from how they handle it.

I think you have fried your SD card. Those cards operate at 3.3V and may not be 5V tolerant.

Is there any print out based on this;
Serial.print("Initializing SD card...");
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
  Serial.println("Card failed, or not present");
  // don't do anything more:
  return;
}
Serial.println("card initialized.");

Solution;
Try change
const int chipSelect = 4; // change value to 10

If not, try change the above code to;
Serial.print("Initializing SD card...");
if (!SD.begin(10)) {
  Serial.println("Initialization failed!");
  while (1);
}
Serial.println("Initialization done.");

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


text:
How to properly process large arithmetic
just a question that requires a simple answer. How do I process a large number of arithmetic steps in arduino efficiently and precisely?
For example I have this code function setup:
void calc() {
  batterymoment = input*batterymass;
  totalmoment = 149650+batterymoment;
  buoyancymoment = buoyancymass*centrebuoyancy;
  wheelmoment = totalmoment - buoyancymoment;
  wheelweight = totalmass - buoyancymass;
  cgwheels = wheelmoment/wheelweight;
  maindistance = mainarm - wheelweight;
  nosedistance = wheelweight - nosearm;
  mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  mainmoment = mainmass*mainarm;
  nosemoment = nosemass*nosearm;
  netmoment = buoyancymoment+mainmoment+nosemoment;
  netcg = netmoment/totalmass;
  staticmargin = adc - netcg;
  answer = staticmargin/meanadc;

}

Now I've properly setup up data types for all of these variables and they are a combination of float, int and long. I don't think it's a problem with the data type. What I'm getting when I print final answer in the serial is the same number regardless the input the user enters.
I'm guessing I need to format the code in such a way that it performs each line step by step and verifies the answer before proceeding to the next arithmetic line. If so would I need a function for each arithmetic step? Or is there a simpler way to process this that I'm missing.
Any guidance is appreciated. Thanks.
Here is the code in its entirety:
unsigned long batterymoment,num1,num2,input,totalmoment;
double buoyancymoment,wheelmoment,cgwheels,mainmass,nosemass,maindistance,nosedistance;
double mainmoment,nosemoment,netmoment,netcg,staticmargin,answer;
double centrebuoyancy = 14.164;
double mainarm = 14.3;
double adc = 11.4;
double meanadc = 22.65;
double nosearm = 1.8;
int totalmass = 12404;
int batterymass = 720;
int buoyancymass = 4401;
int batteryposition,wheelweight;
boolean mySwitch = false;

void calc() {
  batterymoment = input*batterymass;
  totalmoment = 149650+batterymoment;
  buoyancymoment = buoyancymass*centrebuoyancy;
  wheelmoment = totalmoment - buoyancymoment;
  wheelweight = totalmass - buoyancymass;
  cgwheels = wheelmoment/wheelweight;
  maindistance = mainarm - wheelweight;
  nosedistance = wheelweight - nosearm;
  mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  mainmoment = mainmass*mainarm;
  nosemoment = nosemass*nosearm;
  netmoment = buoyancymoment+mainmoment+nosemoment;
  netcg = netmoment/totalmass;
  staticmargin = adc - netcg;
  answer = staticmargin/meanadc;
 }

void setup() {
  Serial.begin(9600);
  num1=0;
  num2=0;
  Serial.println("Enter battery position");
 }

void loop() {
  while (Serial.available()){
    batteryposition = Serial.read();
    if(batteryposition>47 && batteryposition<58){
      if(!mySwitch){
         num1=(num1*10)+(batteryposition-48);
      }else{
         num2=(num2*10)+(batteryposition-48);
        }
       }

if(batteryposition==61){
  input=num1+num2;
  calc();
  Serial.print("Static margin is: ");
  Serial.println(answer);
  num1=0;
  num1=0;
  mySwitch=false;
  }
 }
}

So depending on the user input, the calculations will change the final output answer. For example if a 5 should be entered the output should be -4.22 based on my calculations in excel.

Please do show the declarations, the actual result, and the expected result. And put some extra Serial.print("answer:");Serial.println(answer); debugging code in to help you isolate the problem.

And what does it print?  I'd put a "input=5;" in the code before calc(), and then try difft debug printing in calc() until you get something unexpected.

it prints -113.70 regardless of the input @DaveX

What I have found useful, is testing complex algorithms in a spreadsheet or small console application (even not so complex ones). Once I get them working, I convert to Arduino code, which is pretty straightforward. This is not a warranty of bug-free code but it's pretty close.

Again, do you want to clear num1 twice or did you intend to clear num2 after the processing.

You're getting the same value every time because that is the value that is being calculated.
I think you have something wrong with how you have implemented your formula.  If you start from "answer = " and repeatedly substitute the variables with the formulae or values that make up those variables you end up with this:

answer = (11.4 - (((4401 * 14.164) + ((((12404 - 4401)*(1-((14.3 - (12404 - 4401))/((14.3 - (12404 - 4401))+(12404 - 4401 - 1.8)))))/2) * 14.3) + ((((12404 - 4401)*(1-((12404 - 4401 - 1.8)/((12404 - 4401 - 1.8)+(14.3 - (12404 - 4401))))))/2) * 1.8)) / 12404)) / 22.65

There's nothing variable about that at all.
Your input value is being used to calculate batterymoment. batterymoment us being used to calculate totalmoment. totalmoment is being used to calculate wheelmoment. wheelmoment is being used to calculate cgwheels. cgwheels is never used for anything.

Per your comments, the calc() function is not acting as expected.
Change calc() to be:
void calc() {
  Serial.print("input:");Serial.println(input);
  batterymoment = input*batterymass;
  totalmoment = 149650+batterymoment;
  buoyancymoment = buoyancymass*centrebuoyancy;
  wheelmoment = totalmoment - buoyancymoment;
  wheelweight = totalmass - buoyancymass;
  cgwheels = wheelmoment/wheelweight;
  maindistance = mainarm - wheelweight;
  nosedistance = wheelweight - nosearm;
  mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  mainmoment = mainmass*mainarm;
  nosemoment = nosemass*nosearm;
  netmoment = buoyancymoment+mainmoment+nosemoment;
  netcg = netmoment/totalmass;
  staticmargin = adc - netcg;
  answer = staticmargin/meanadc;
  Serial.print("answer:");Serial.println(answer);
 }

and see if it gets the expected inputs and works as expected.  Then add debugging statements in-process until you discover the mismatch.
I'd turn in into more of a function, or a series of better defined functions, and then test them individually.
As your code is there is interaction between global variables, serial parsing, and calculations.  If you break it into distinct pieces, you can isolate where the problem is.


text:
Why does the Pro Mini 5 v and 3.3 v version have different clock frequencies?
It looks like the 5 volt version used the 16MHz external crystal while the 3.3V one uses the 8MHz crystal. I need to use 3.3v as my operating voltage.
Can I just remove the linear regulator and bring in 3.3V. I still have to select the 5V 16MHz version in the Arduino IDE, right?
https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf

Don't make it work at 5V @16MHz, since it is out of the safe operating area

The ATMega328p is not rated to operate at 16 MHz on a 3.3v supply.
In practice it may sometimes work, but cannot be considered reliable.
The data sheet will show the actual clock rate vs. voltage tradeoffs, so there might be an intermediate value that is workable for you.
The Arduino toolchain needs to know the CPU clock frequency for the serial baud rates, timing delay code, and any time-based use of the timer peripherals to come out right.
There is a special case where if the configured clock rate and the actual clock rate differ by a factor of two, you may be able to cover that by selecting a similarly wrong baud rate - however, the baud rate in the bootloader was set in comparison to the expected clock frequency when it was compiled before flashing, and the baud rate expected of the bootloader is set in the boards file, so less readily changed than it is in something like the serial monitor.

And if I wanted to use the same arduino board, can I simply replace the crystal with an 8MHz one and bypass the linear regulator with my own 3.3V supply? I know it seems like a lot of work... lol but i have spare parts around.

Some components on the board may be expecting 5v (LEDs immediately springs to mind); you may also need to change the fuse settings - http://www.engbedded.com/fusecalc/ - in fact, if clock accuracy isn't terribly important, then you can change the fuse to use the internal 8mhz clock, save yourself some soldering.

PS - setting fuses is advanced black magic - it's easy to brick your Arduino that way (as I did) if you get it wrong.

Changing the fuses isn't necessary when changing the crystal. What you do need to change is the bootloader to the 8MHz version.

If the brown out detector is already either disabled or set at 2.7v or below that may be the case (seems to be in the boards.txt).  If it is set at 4.3v there would be a problem.  Also if the "3.3v" is really two AA cells that will drain to a lower voltage in operation, the chip might be fine but the 2.7v BOD will shorten the usable life.


text:
Why does my PIR sensor stay high with ESP8266 breakout board?
I have a PIR sensor attached to a Amica nodeMCU board routing 5v from VIN and attached via USB port for testing. When motion is deteted it connects to the internet and sends data to IFTTT which i receive a notification on my phone.
When I power up, the PIR pauses for calibration and then immediately goes HIGH and fires the motion detected call which i receive on my phone. However From then on it never goes LOW but every 5-8 minutes sends another HIGH call through even if there is no motion.
Testing

Tried using separate 5v supply to PIR same thing happens
I have tried both retrigger modes (H & L) and experienced the same result
The same happens with the Adafruit featherwing huzzah board.
I have tested the PIR without a micro-controller and can confirm that it functions correctly -lighting an led
I have tested with an Arduino Nano with the same code and it functions correctly - lighting an led

My Code modified version of Arduino Playground PIR Project
//Sends IFTTT every 5 minutes it detects motion

#include <ESP8266WiFi.h>
//WiFi Settings

// Set up macros for wifi and connection.
#define SSID "my-network"    // SSID
#define PASS "mypassphrase"      // Network Password
#define HOST "maker.ifttt.com"  // Webhost
//-------------------------------
const char* streamId   = "test";
const char* privateKey = "mysecretkey";

//PIR Settings
//the time we give the sensor to calibrate (10-60 secs according to the datasheet)
int calibrationTime = 10;

//the time when the sensor outputs a low impulse
long unsigned int lowIn;

//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;

int  interval = 1000; // Wait between dumps
boolean lockLow = true;
boolean takeLowTime;
int ledPin = 1;
int pirPin = 2;    //the digital pin connected to the PIR sensor's output
int nPIR_detect;
int motion = 2;

int minSecsBetweenUpdates = 300; // 5 minutes
long lastSend = -minSecsBetweenUpdates * 1000l;
//-------------------------------

// Begin Setup
void setup(){
  Serial.begin(115200);
  pinMode(pirPin, INPUT);
  digitalWrite(pirPin, LOW);

  //give the sensor some time to calibrate
  Serial.print("calibrating sensor ");
  for(int i = 0; i < calibrationTime; i++){
    Serial.print(".");
    delay(1000);
    }
  Serial.println(" done");
  Serial.println("SENSOR ACTIVE");
  delay(50);
   nPIR_detect = 0;

  // Test ESP8266 module.
  Serial.println("AT");
  delay(5000);
  if(Serial.find("OK")){
    connectWiFi();
  }
}

void loop(){
 if(digitalRead(pirPin) == HIGH){
       digitalWrite(BUILTIN_LED, HIGH);   //the led visualizes the sensors output pin state
       if(lockLow){
         //makes sure we wait for a transition to LOW before any further output is made:
         lockLow = false;
         Serial.println("---");
         Serial.print("motion detected at ");
         Serial.print(millis()/1000);
         Serial.println(" sec");
         sendData(String(motion));
         delay(50);
         }
         takeLowTime = true;
       }

     if(digitalRead(pirPin) == LOW){
       digitalWrite(BUILTIN_LED, LOW);  //the led visualizes the sensors output pin state

       if(takeLowTime){
        lowIn = millis();          //save the time of the transition from high to LOW
        takeLowTime = false;       //make sure this is only done at the start of a LOW phase
        }
       //if the sensor is low for more than the given pause,
       //we assume that no more motion is going to happen
       if(!lockLow && millis() - lowIn > pause){
           //makes sure this block of code is only executed again after
           //a new motion sequence has been detected
           lockLow = true;
           Serial.print("motion ended at ");      //output
           Serial.print((millis() - pause)/1000);
           Serial.println(" sec");
           delay(50);
           }
       }
}

void sendData(String motion){

  //Send the motion to IFTTT value1
  Serial.print("connecting to ");
  Serial.println(HOST);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(HOST, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  // We now create a URI for the request
  String url = "/trigger/";
  url += streamId;
  url += "/with/key/";
  url += privateKey;
  url += "?value1=";
  url += "motion";

  Serial.print("Requesting URL: ");
  Serial.println(url);

  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + HOST + "\r\n" +
               "Connection: close\r\n\r\n");
  delay(10);

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection");

}

boolean connectWiFi(){
  Serial.println("AT+CWMODE=1");
  delay(2000);
  String cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  Serial.println(cmd);
  delay(5000);
  if(Serial.find("OK")){
    Serial.println("Connection");
    return true;
  }
  else{
    Serial.println("No Connection");
    return false;
  }
}

OQ: Why does my PIR sensor stay high with ESP8266 breakout board?
In essence, I never see the serial message "motion ended at.."

What do the measured voltage levels look like?  Is your breakout board to 5v tolerant?

How are you converting the 5v signal to 3.3v?

@Gerben which 5v signal? (from where?)

@Gerben the pir converts 5v to 3v

I'm sure you have probably done both these, but just in case you haven't...
I see from your code you are using Pin 2 for the PIR sensor.  I'm sure your not as dumb as I am every time I program a ESP8266, but check you have connected the PIR to pin 2, that's not the connection labelled D2 its GPIO2, which may or may not be labelled.
Assuming that's right then the next possible problem may be that GPIO2 is shared with TXD1, its possible that this is being used.  So try moving to GPIO4.

Changing from GPIO2 to GPIO4 worked for me.

I have the same issue with Huzzah and a PIR. The PIR is noisy and I get a false high every 10-20s while the code runs without any problem on an UNO.
I think it is a problem of HF coupling from wifi interfering with the PIR's amplification circuit. I will try shielding and caps/ferrites to get rid of the HF on the PIR or use another power supply and couple the signal line via optocoupler.

The solution I found to this problem is use a 10k resistor between the PIR sensor output and the input pin of the ESP8266.
Not sure if 10K is the best value, someone else may find a better value, but for now, for me its working great.
John


text:
434 RF Transmitter and Receiver for distance measurement problem
As a student I'm working on a project where we use 434 MHz RF Transmitter and receiver pairs for distance measurement. I know that this technology is not a good choice for this, but we have to deal with this problem due to external constraints.
Here is the receiver: RF Link Receiver - 4800bps (434MHz).
I did a little bit of research how these receivers works, but I found it a bit overwhelming to understand them bit by bit.
We want to use the signal strength for distance measurement. So we tried sending pulses of signals from one transmitter to a receiver. If the amplitude of the signal received is higher than a certain value (let's say 3V), it sends back a signal (let's call it trigger signal) in the gap between the two pulses.
The problem is that that these signals seems to affect each other even though they are not in the same time (so it's not superposition that we are talking about). When there is a signal sent back, the next pulse will be lower, which results in false distance measurement.
The whole difficulty is (to me it seems) that we are not using these signals to send data, we are using it for distance measurement. My idea is that we are using too long pulses and the AC coupling in the receiver doesn't tolerate it, but again, I don't have enough electrical knowledge to safely say that.
I know this is not descriptive, but I don't know how to make it more descriptive, so I'm happy to answer more questions on demand.

Did you read about the RX module? Does it have AGC (Automatic Gain Control)? If is does it will increase gain until noise level. When a signal is detected it has to "tune back".

Where can I read more about that? Or what is that for?

This does sound like transmitting the reply could be desensetizing the receiver's AGC.  Perhaps you can run some tests by sending pairs of pulses in one direction a varied time period apart, and a looking at how the amplitude of the second received pulse varies based on the time delay.  Perhaps you can simply reduce the experiment frequency to give the AGC more time to recover, or transmit the reply by some other means (2.4 GHz?  IR?).  Even better implementations of your RSSI distance idea (BTLE chips for example) are less than impressive.

What do you mean by reducing the experiment frequency? Isn't increasing what would be reasonable here? So it doesn't set its noise level to a new value?

That depends on which AGC gain you want.  I was thinking by waiting longer after each reply pulse (or opportunity) before a new transmit pulse, you could let the AGC reset.  Though I suppose an alternative would be to wait less time, and try to keep the AGC active.  To do that you would need to always transmit a reply.  Perhaps you could encode the result in a variable delay between the outgoing pulse and the reply, but always make the time from the reply to the next outgoing pulse the same. If you miss a reply entirely, you'll probably have to ignore the next one given the unkown AGC state.

This is the simple RSSI implementation for RF433 Virtual Wire that I came up with for Cosa; https://github.com/mikaelpatel/Cosa/blob/master/libraries/VWI/VWI_Receiver.cpp#L156. After receiving a message the receiver measures the time to "recover", i.e. the AGC to tune back to noise level. The weaker the TX was the faster the tune back.

It is very likely you have an AGC problem. Try to slow down the measurement. The sender shall send data not often than once per second.
This idea is not fully perfect for doing a distance measurement. It measures incoming power strength - affected by walls, reflection, AGC of the receiver, and a lot more. If you have a scope, measure the waveform on the pin 3 of the module (linear out). It is not a constant voltage, I am afraid, so you need some sort of averaging too.
A tricky way to get along even if you have an AGC is to measure how long the AGC needs to settle. The AGC works as follows: it detects the signal, and within some time (say, 2ms) it will change the amplification so that the signal will look having the full amplitude.

compare on a two channel scope the signal pulse driving the transmitter
and the signal on the pin 3 of the receiver module

If you are lucky, you'll see that actually pin3 or pin2 output is delayed a bit compared to the transmitter driving pulse. The delay depends on the power of the incoming signal to the receiver, which depends on the distance.
I was able to make an acceptable distance sensor from a standard AGC enabled IR receiver using the principles above.

We got around the problem today by sending 2ms pulses and 100ms gaps. This seems to solve the problem on the scope level. The thing is that our Arduino delays seem to be not precise enough to read the 2ms pulse in the right time, but that's another problem.

I found that delays are surprisingly precise. However, you have to have some mechanism to get the rising edge of your pulse first. For that, you either need a simple loop which checks for the pin state with digitalRead, and once a rising edge is found, you can start timing. But, aren't you planned to read the analog value on pin 3 of the module?

I don't know why I haven't accepted this answer before. It was a very old project and I do remember that making a sensor using an RF receiver is not a good idea. The automatic gain controller (AGC) was a significant problem. You would want to use probably something else but that wasn't available for me back then in an university setting.


text:
Digit LED has single input, multiple outputs for each segment. Concerns about "sinking" 5v supply into digital pins
The model name is 5161BS

Pins 3/8 are input and the rest are output for each individual segment.
I have connected pin 3 to the 5v pin on the Arduino, and the rest to individual digital pins.
With a simple sketch with the pins set to mode output, all segments are lit.
My concern is that the way I am turning off each segment is by setting the output pin to high.
Meaning
5v pin --> LED <-- Digital pin

Is this dangerous to have two voltage sources going in the same direction? Is there another way to do this?

Do you have current-limiting resistors? This is the first question. Otherwise you are probably damaging something.

Fortunately I put a 330 ohm resistor from the 5v pin. But no other resistors.

Well that is better than nothing. However when multiple segments are displayed they will have different brightnesses because that one resistor will have different currents through it. You really need 330 ohm on all the pins except the 5V one.

@NickGammon I'm not sure about that. I'd expect any segments that are lit to have the same brightness, though the brightness of each LED will increase as fewer LEDs are lit, since theres more current to go around.

@TisteAndii, they would have the same brightness if they are identical.  But only a slight difference in the voltage drop leads to a large bias for current flow when hooked up this way.

If there was a difference it wasn't noticable. https://photos.google.com/share/AF1QipP6Iu9o1PD-RNipc_BTrsXK7nRzVLYJW2y1YnLTNN_77PJ8C-p51hIno2YDOdtKVw/photo/AF1QipPV3GTbBiy80Gbe3I1roi4pKFCxMRerhH68xS6b?key=eFVKdER2RTFNQTNtM0lqSjZYbHRJZUU3VmZDckpB Although it does seem that the final digit "-" was significantly brighter from the video than when the multiple segments were lit.

This is called a common-anode LED. The anodes (+ side) are shared. They probably dedicate two pins (3 and 8) to share the current to the anodes.
Connecting the common anode to +5V is fine. However you should have current-limiting resistors between each of the other pins (the cathodes) and the Arduino digital pin. Otherwise you are getting the Arduino to try to "sink" its own 5V supply through a digital pin, which far exceeds its rating. You will probably damage the output driver MOSFETs and they will stop working. Plus the excessive current will damage the LEDs as well.
See the LED resistor calculator. Something like a 330 ohm resistor, in series with each of the cathodes, should be adequate.
Now, setting the digital pins to output will "sink" 10 mA or thereabouts from +5V, through the LED (which lights up) and through the digital pin to ground.
You control what "number" you see on the LED by turning off the appropriate pins, to make the segments light up.
Also see The care and feeding of LEDs.

The device you have is a common anode display. This means that the anodes (+ve terminals) of all the LEDs are connected to one common pin (well, 2 pins actually, pin 3 and 8 are connected internally) . Their cathodes (-ve terminals) are what make up the remaining pins. Now, to light up any LED, you need 5 V at its anode and GND at its cathode. You have connected 5 V to pin 3, which stands for the common anode of every LED, so all that is left for any LED to turn on, is for you to connect GND to its corresponding cathode. So when you made all the remaining pins (the cathodes) OUTPUT, by default the Nano sets those pins to a logic LOW (or GND) value, so ALL the LEDs got lit up. Each LED now has 5 - 0 = 5 V across its terminals and is forward-biased.
However, when you write HIGH to any cathode, the potential difference across the associated LED/segment is now zero, because that LED has 5 V at its anode (pin 3/8) and 5 V at its cathode (as a result of writing HIGH), and 5 - 5 = 0 V so it is reverse-biased (at least 2 V or thereabouts is needed for a red LED to become forward-biased) and so the segment turns off. And this is how you control which segment is on at any time: You write a LOW to a cathode to turn on the associated segment, and write HIGH to turn it off. It sounds counter-intuitive but it follows if you think about it. Regarding your question, there's no damage being done to anything; the minimum voltage across the LED is 0 V (well below its maximum peak inverse voltage), while the maximum voltage across the LED is around 2 V, if you use the highly recommended current-limiting resistors (220/330 ohms is good) in series between each cathode and its Arduino digital pin.
Without any resistors, you will be drawing a lot of current through each pin, in total, a lot more than the Nano can safely supply. Use resistors that limit the current through each LED to 10-20mA.


text:
Attach headers to servo wires?
I have these 3 wires coming from a servo motor. They're very thin and flimsy and despise staying in a breadboard.

Is it possible to add headers to these wires to make them easier to put in a breadboard? (Like the attached image) And if so, where would one procure such a thing?

The easiest solution is to put some solder on the wires to make them stiff. They usually become slightly larger than the hole, so maybe you'd better cut some of the copper wires before applying solder on them. Another solution is to solder some male pins, but again they are a bit larger than common breadboard holes

What I do in situations like that is get some of those breadboard hookup wires, like you have in your second photo, cut them in the middle (giving yourself two wires, each with a bare end, and a end with a plug on them).
Strip the bare end, and then solder it to the servo motor wires. Before commencing soldering, slip some heat-shrink tubing onto the wire. Once the wires are soldered together, move the heat-shrink tubing over the join and shrink it (with a hair-dryer, or heat gun).
You now have a plug for your breadboard which is designed to be mechanically strong, and the heat-shrink tubing over the join protects it from being flexed too much.
You could put some thicker heat-shrink over all three wires, to give additional stability.

If you do not have a hair-dryer or heat gun, you could use a lighter, but it's not recommended :)

You might even get away with some "screw-connectors" or a "wire nut" of you don't have an soldering iron.
And probably electrical tape (or just reasonable tape) if you don't have heat-shrink tubing (but you should have some :D)

I have bought a crimping tool. With the correct dice and crimps and crimp holders you get a professional finish.
The crimps and crimp holders themselves are cheap (buy in multiples of 100) but the crimping tool and dice are expensive.
It takes some practise before you make "high quality good contacting crimp" connections. You need to crimp in such a way that the strength comes from the connection between the wire insulation and the crimp and not loose electrical contact.
Also it is not so easy to find the "correct" crimps and crimp holders.
So this is only an option if you are willing to invest in your hobby (or you know someone who has ;-) )
If it is a DIY job I would go with nick solution.


text:
Analog sensing needs external power supply
I am using an Arduino Uno board for sensing analog input.
I have connected the board only through a USB cable to my laptop, but the board does not sense analog input,
Is it necessary to use an external power supply ?

What sketch are you using? What do you mean it "doesn't sense"? What sensor are you using? You don't have to use an external power supply for the ADC to work.

I am using "Analog Input" sketch from Examples, where A0 is used as analog in. I have connected 10k pot, to +5, and gnd, center pin to A0 input, 'does not sense' mean there is no effect on LED connected at pin 13 when pot is set to different positions, Later the board seems to have burnt when pot was set to minimum level (zero volt input to A0)

Setting the pot to minimum would not burn out the board, if the connections are as you say they are. An external power supply should not be needed, USB should supply enough power. When you say the board has burnt out, does power LED still work? Does the Arduino still respond to the IDE, if you try to upload "Blink" for example? If Blink still works then the board is probably not burnt out.

I think "burnt" = you blew the polyfuse. This means that you made the wrong connections to the potentiometer, connecting the cursor to either 5V or ground. If the led is always on then you probably connected ground to the cursor (and so the delay between turn on and off is around 1ms), while if the led blinksat about 0.5 Hz you connected +5v to the cursor (and so the period is always 2*1024ms). Double check the  potentiometer pinout with a multimeter, then triple-check it and, if you are really sure it is right, check it again...


text:
DS18B20 Temperature Sensor return as float function returning null 50% of the time
I just got an DS18B20 Temperature sensor and am trying to modify the example code to use a function instead. Below is my getTemp function. It's working but returning results with a 0 value part of the time for example:

Temperature = 72.39
  Temperature = 0.00

If I add Serial.print(fahrenheit); within the function I am always provided with the correct temperature. I though this may have to do with needing a delay but adding delay(5000); in my loop didn't help.
I'm assuming it's something simple I'm not understanding about how floats return.
#include <OneWire.h>

// OneWire DS18S20, DS18B20, DS1822 Temperature Example
//
// http://www.pjrc.com/teensy/td_libs_OneWire.html
//
// The DallasTemperature library can do all this work for you!
// http://milesburton.com/Dallas_Temperature_Control_Library

OneWire  ds(2);  // on pin 10 (a 4.7K resistor is necessary)

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

float getTemp(char tScale) {
  byte i;
  byte present = 0;
  byte type_s = 0;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    ds.reset_search();
    delay(250);
    return false;
  }

  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

  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();

  }

  // 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;
  if (tScale == 'C') {
    return celsius;
  }
  else if (tScale == 'F') {
    return fahrenheit;
  }

}
void loop(void) {
    Serial.print("Temperature = ");
    Serial.println( getTemp( 'F' ) );

}

Edit:
Interesting enough, adding an if statement to the loop fixes this, however. I'd still like to understand what is going on:
void loop(void) {
  if ( getTemp( 'F' ) == 0 ){
    Serial.print( "Temperature = " );
    Serial.println( getTemp( 'F' ) );
  }
}

Could you please clarify what you mean by 'fixes it' in your edit? Since your getTemp() occasionally returns 0, it's clear that you filter for zero by checking for getTemp('F') == 0.

I guess what I mean is that if getTemp is set to 0 then the correct temperature is being displayed to serial (never showing Temperature = 0.00 It only returns the actual temperature.

So you skip the problematic instances of !ds.search(addr) (by just polling the sensor twice in close succession), ignoring the underlying problem. :)

There are apparently a lot of alleged "DS18B20" devices on the market which do not meet the timing of the published spec.  To try to use them you will need to slow things down.  You can somewhat offset the time cost of doing so by running in a lower bits mode, but some of the published example code which appears to handle various bit widths in fact horribly misinterprets anything but the widest, and has to be fixed.  No, I don't have a repaired copy at hand to quote from.

@Chris Stratton: I think it's a good idea to look into the actual issue of the DS18B20 communication failing. BandonRandon: Why don't you try the DallasTemperature library? It even comes with a Tester sketch and other useful stuff.

You have intermittent communication problems.
Your address search occasionally fails and getTemp() returns false. In C++ (and many other languages) false will be implicitly cast to (int) 0, (float) 0.0f, and so on.
Your getTemp() function  also is difficult to debug because the multiple return statements have different meaning.
After the delay(250); you do a return false; in order to skip the rest.
In the example at https://www.pjrc.com/teensy/td_libs_OneWire.html the meaning of the return statement(s) is different. There the return happens within the void loop() function, where it simply means to interrupt the current execution (without returning a value) and continue with the next loop.
While it is generally okay to have multiple return, it can sometimes be problematic and I recommend to avoid it.
If you want to clean this up while still preserving the ability to detect a fault, you have a couple of options (order from most to least recommended):

do the setup/checking in a different function (and only call the second one if the first one succeeded), i.e. if (isReady()) { Serial.println(getTemp()); }
set a separate error variable, i.e. error = true; return 0; (and then check error later)
define a 'default' value that you interpret as an error (and never expect to be a temperature), i.e. return NAN; // not a number

Is there actually a reason why you use the sensor the hard way and not employ a library for it (like you do with OneWire)? There are Dallas temperature libraries that employ OneWire, e.g. https://github.com/milesburton/Arduino-Temperature-Control-Library.

Rather than -460.0f, which looks like a silly value, I would return NAN (i.e. not a number). It more clearly conveys the meaning of “not a valid value”. Serial.print() displays it as “nan”.

Yeah, out-of-range was just the first thing I came up with. And since it's my least recommended solution, I still regard it as inferior, even when using NAN. I edit my answer accordingly.

Thanks switched to the Miles Burton Library and everything is working as expected and my code looks much cleaner.


text:
Simplified timezone shapefile suitable for Arduino?
Is there a library or shape file available that allows an Arduino to approximate a timezone based on a latitude/longitude coordinate? There is a timezone shape file available, but it's too detailed and too large. I am hoping someone knows of a simplified version small enough for an Arduino and/or a library that's able to handle this task.

It isn't what you asked for, but would web services like in http://stackoverflow.com/a/16086964/1653571 be feasible?  I'd try to use UTC and avoid timezones and DST if I can get away with it, and make the display TZ a user-configured option if I had to.

Really looking for an actual solution. If you look at timezone shapes graphically, they really aren't that complex if you are willing to overlook, say, detecting a wrong timezone when you're within 10km to a border. In that case, the timezone shapes reduce to probably no more than a few dozen shapes with maybe a dozen vertices each. Something an Arduino can handle.

Foursquare have an open-source tool to do that. https://github.com/foursquare/shapefile-geo


text:
Send JSON via POST on SIM900 shield with AT commands
I'm trying to send a JSON POST in SIM900 shield with AT commands. After I call the  AT+HTTPACTION=1 command, it returns a 601 error: +HTTPACTION:1,601,0.
I saw here that the error was 601 Network Error. Could someone help me? Following is my code.
void connectInternet() {
  if(digitalRead(9 != LOW)) {
    Serial.print("\r\n");
    Serial.print("------------------------------------------------- \r\n");
    Serial.print(" CONNECT ON INTERNET \r\n");
    Serial.print("------------------------------------------------- \r\n");
    Serial.print("\r\n");
    Serial.println("Connecting...\r");
    cmdAT("AT");
    cmdAT("AT+CIPSHUT");
    cmdAT("AT+CIPMUX=1");
    cmdAT("AT+CSTT=\"zap.vivo.com.br\",\"vivo\",\"vivo\"");
    cmdAT("AT+CIICR");
    cmdAT("AT+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\"");
    Serial.print("IP Device: ");
    cmdAT("AT+CIFSR");
  }
}

void send2Api() {
  Serial.print("\r\n");
  Serial.print("------------------------------------------------- \r\n");
  Serial.print(" SEND TO API\r\n");
  Serial.print("------------------------------------------------- \r\n");
  Serial.print("\r\n");
  cmdAT("AT+CSQ");
  cmdAT("AT+CGATT?");
  cmdAT("AT+SAPBR=2,1");
  // Query if the connection is setup properly, if we get back a IP address then we can proceed
  cmdAT("AT+HTTPPARA=\"CID\",1");
  // Set the HTTP session.
  cmdAT("AT+HTTPPARA=\"URL\",\"http://api.com.br/endpoint\"");
  // set endPoint
  cmdAT("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
  // set content json
  cmdAT("AT+HTTPDATA=100,5000");
  // POST session start
  // JSON payload
  cmdAT("{\"timestamp\":\"2016-03-08T19:36:45.000Z\",\"latitude\":\"-24.9458581\",\"longitude\":\"-53.4968357\"}");
  delay(100);
  cmdAT("AT+HTTPACTION=1");
  // POST session start
  cmdAT("AT+HTTPREAD");
  // Read the data of HTTP server
  cmdAT("AT+HTTPTERM");
  // terminate http
  ShowSerialData();

Check out this. Hope it helps:)

The PDP context setup is missing from your code. I.e. you have to set up a connection to the GPRS APN what your GSM network provider gives to use as a gateway to the Internet.

Ok @Gee Bee. So, I don't need call my function connectInternet().
Should I define the PDP in send2Api() function ? Thanks

The PDP context setup is missing from your code. Many years ago I figured out that this initialization sequence works (i.e. extend your connectToInternet):
        //--if autobauding was enabled, send a blank AT
        command:='AT';
        send_gprs;

        //--switch to minimal mode - this is required to reset the SIM card
        command:='AT+CFUN=0';
        send_gprs;

        //--set dce speed
        command:='AT+IPR=57600';
        send_gprs;

        //--turn off command echo
        command:='ATE0';
        send_gprs;

        //--turn off command echo again - sometimes the first command is ignored
        command:='ATE0';
        send_gprs;

        //--turn on extended error messages
        command:='AT+CMEE=1';
        send_gprs;

        //--set module to full function
        command:='AT+CFUN=1';
        send_gprs;

Then it is very important to unlock your SIM card. The simplest solution is to disable PIN request (put your SIM to a real phone, and use the phone to set up this.) Verify if the module can proceed on SIM authorization:
        //--check pin
        command:='AT+CPIN?';
        send_gprs;
        //--right answer is +CPIN: READY
        //--wrong answer is +CME ERROR: 772

Then set up the APN. This will actually initiate an asynchronous APN request, and you shall not proceed until the AT+CSTT returns OK:
    repeat
        //--reset connection
        command:='AT+CIPSHUT';
        send_gprs;

        //--set GPRS APN
        command:='AT+CSTT="internet.vodafone.net"';
        send_gprs;
    until is_ok=1;

And finally, open a GPRS connection:
    repeat
        //--Open gprs connection
        command:='AT+CIICR';
        send_gprs;

        //--Get local address - for some reason this is required
        command:='AT+CIFSR';
        send_gprs;

        //--Suppress "SEND OK" after at+cipsend
        command:='AT+CIPSPRT=2';
        send_gprs;

    until is_ok=1;

(Ok sorry, this code is pascal and not especially golden, but you got the point about the sequence of the commands.)
Two very important things:

any command can fail - it is a good idea to send back the response to an AT command to your console window
AT+CIFSR is evil. If you don't use AT+CIFSR at the right sequence, the communication simply does not work. I was using SIM900D modules. Although you might feel it is optional to get your IP, actually it is not optional at all for some reason.

I was using AT+CIPSEND for the actual data communication. HTTP is so easy, and it is better to be in control.


text:
How do I learn C? (was Computer project)
Can you help me writing a code for this question guys??
You have an Arduino Uno with 8 LEDs connected to digital pins 2 to 9.
Create an array of 8 elements. Fill it with random numbers between 2 and 9 (all inclusive)
Write a program which determines the greatest number among them. Save this number in a variable named max. Print this number on serial monitor. Blink the LED connected to this number. Let the delay time be 0.5 second.
Note that the random function may result in duplicate numbers generated. For example, the generated array may be {3,4, 4, 7,6, 2,5,7}
The maximum number will be 7.Since it occurred twice in the array, then you should blink it twice ^_^
It the maximum number occured 3 times in the array, then you should blink it 3 times, and so for any number of occurrences
I have written this so far but I'm sure it's all wrong
int pins[8]={2, 3, 4, 5, 6, 7, 8,9};

void setup()
{
   pinMode(pins[8], OUTPUT);
}

void loop()
{
    x=random(0, 8);
    digitalWrite(pins[x], HIGH);
    delay(1000)
    digitalWrite(pins[x], LOW);
    delay(1000)
}

That's poorly stated homework since they only give one delay but expect patterned blinking.  Anyway, approach this by imagining you are a robot being shown the numbers one at a time.  What very efficient notes could you take on a re-writable scratchpad (ie, a minimal number of variables)  It will help in finding the best solution if you assume the list of numbers could be arbitrarily long...

@JRobert I'm stuck in the if statement and arrays I really can't understand them also there's supposed to be a for loop

How would you simulate this on paper/physically?  For example, using N head-tail coins as LEDs.....

Well for one improvement, pins[8] is undefined, since C indices start with 0, so there are only pins[0]...pins[7] defined in your code.  Maybe you could use your for(;;) loop there? Also, try compiling your code--if the compiler detects and reports errors, it might help you refine your logic.

This answer is for C, which is pretty similar to Arduino. Please read it carefully, it teach about arrays: http://www.dummies.com/how-to/content/how-to-use-arrays-in-c-programming.html

Frankly there is no sound reason to put the pins in an array at all, since their range is continuous.  The only array needed is the input data.  And only two local variables plus the iterator variable are required to solve the problem.  Basically, writing code is premature.  Figure out the algorithm.

@Chris Stratton.  Yes Yes.  Figuring out an algorithm before coding would be best. But since the OP was already has code without an algorithm, I figured I'd point them to step two of the edit-compile-test cycle.  Maybe the syntax errors would provide enough clues.

I'm sorry, but a question "How do I learn C" is a bit broad for this site. For one thing you might ask on Stack Overflow which is a programming site. But even there they will probably tell you to read a book or do a tutorial. Stack Exchange is designed to answer specific questions not "teach C" (or learn how to fly, or learn how to cook, for that matter). I'm going to close this question. Feel free to edit it with new information. Thanks for your understanding and cooperation!

First hint: pinMode() only applies to one pin at a time. You'll need to execute it 8 times to intialize 8 I/O pins' modes.
Second hint: As @ChrisStratton tried to suggest, generate the random number set first; then "figure out" (set some variables in memory that will tell you) what do with the terminal output and the digital I/Os; then do each of those things. It helps to partition a larger problem into smaller ones.
Update: Considering your updated title, How do I learn C?, and since the question reads like a homework assignment, aren't you already taking a class in C or C++? If so, how do you find it lacking, i.e., what additional resources or direction would be most helpful to you? There are a number of good books on the C language, and one of those would be a good place to start. If you don't already have a favorite one, you can't go wrong with The C Programming Language, by Brian Kernighan & Dennis Ritchie, the authors/designers of the C language and its early compilers. It is book on the C language, not on programming per-se, so if you are new to programming as well, a programming tutorial would be an excellent additional choice (sorry I don't have one to recommend).
Secondly, beat up on the example programs that come with the ArduinoIDE: click the "Open" button [uparrow icon on the IDE toolbar; not the File | Open menu] and you'll see a menu of your current sketches and, below the break, categories of example programs. Pick one of the examples, read it and try to understand what it does and why it is written the way it is. Then tweak the ###p out of it - both to understand how make it behave differently, and to break it. You'll learn a lot by a) interpreting error messages from the compiler, and b) finding and fixing your mistakes. If you're not breaking your programs at least twice as often as you're succeeding, you're not trying hard enough!