text:
Are function pointer assignments atomic in Arduino?
The following snippets are from TimerOne library source code:
// TimerOne.h:
void (*isrCallback)();

// TimerOne.cpp:
ISR(TIMER1_OVF_vect) // interrupt service routine that wraps a user defined function supplied by attachInterrupt
{
  Timer1.isrCallback();
}

// TimerOne.cpp:
void TimerOne::attachInterrupt(void (*isr)(), long microseconds)
{
  if(microseconds > 0) setPeriod(microseconds);
  isrCallback = isr; // register the user's callback with the real ISR
  TIMSK1 = _BV(TOIE1); // sets the timer overflow interrupt enable bit
  resume();
}

The question: if the timer is already running, and the main program calls attachInterrupt(), could the timer interrupt occur there during the function pointer assignment isrCallback = isr;? Then, with lucky timing, Timer1.isrCallback(); function pointer would consist partly of the old and partly of the new address, causing the ISR jump to a bogus location?
I suppose this might be the case, since function pointers are certainly wider than 1 byte, and accessing > 1 byte data isn't atomic. Possible workarounds could be:

Always call detachInterrupt() to make sure the timer isn't running, before calling attachInterrupt(), i.e. clarify Timer1 docs.
Or, modify Timer1, disabling timer overflow interrupts temporarily just before isrCallback = isr;

Does this make sense, or is there something in Timer1 sources or function pointer assignments that I've missed?

Have a look at the code for attachInterrupt() and detachInterrupt() in
/Applications/Arduino.app/Contents/Resources/Java/hardware/arduino/cores/arduino/WInterrupts.c (well, that's where they are on a Mac, anyway. Arduino file structure on other OSes' probably looks similar in the lower levels of the path).
It appears that attachInterrupt() assumes that the interrupt in question is not yet enabled because it writes the function pointer without taking any precautions. Note that detachInterrupts() disables the target interrupt before writing a NULL-pointer to its vector. So I'd at least use a detachInterrupt() / attachInterrupt() pair
I'd want to run any such code in a critical section, myself. It appears your first way (detach, then attach) would work, though I can't be sure it couldn't miss an unfortunately timed interrupt. The datasheet for your MCU might have more to say on that. But neither am I sure at this point, that a global cli()/sei() wouldn't miss it either. The ATMega2560 datasheet, section 6.8, does say "When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in this example", seeming to imply that it can buffer an interrupt while the interrupts are off.

It's indeed useful to dive to the sources:) TimerOne's attach / detach interrupt mechanism seems to be done similarly as the standard (WInterrupt's) and so has the same "features".

It looks like you have a point. The logical thing to do would be to disable interrupts in such a way that you don't re-enable them if they were disabled in the first place. For example:
  uint8_t oldSREG = SREG;  // remember if interrupts are on
  cli();                   // make the next line interruptible
  isrCallback = isr;       // register the user's callback with the real ISR
  SREG = oldSREG;          // turn interrupts back on, if they were on before

"When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in this example"

The intention of this is to let you write code like this:
  sei ();         // enable interrupts
  sleep_cpu ();   // sleep

Without that provision you might get an interrupt between those two lines, and thus sleep indefinitely (because the interrupt which was going to wake you has occurred before you slept). The provision in the processor that the next instruction, after interrupts become enabled if they were not enabled before, is always executed, guards against this.

Wouldn't it be more efficient to TIMSK1=0; TIFR1=_BV(TOV1); isrCallback=isr; TIMSK1=_BV(TOIE1);? It spares one CPU register and doesn't contribute interrupt latency.

What about the other bits, like ICIE1, OCIE1B, OCIE1A? I understand about the latency, but interrupts should be able to cope with a couple of clock cycles of not being available. There may be a race condition. The interrupt might be triggered already (ie. the flag in the CPU is set) and turning TIMSK1 off might not stop it being handled. You might also need to reset TOV1 (by writing 1 to it in TIFR1) to ensure that doesn't happen. The uncertainty there leads me to think that turning interrupts off globally is the safer course.


text:
Decimals missing when using radio.write(); with Arduino
I'm adapting a sketch I found to send sensor data over a wifi chip (Nrf2401), and although I get the message through, the value I send contains decimals (e.g. 24.59), but the received message will only be 24.
I'm sure there's something wrong on the transmitter part of the code, but I can't see what.
Here's my code:
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include <OneWire.h>
#include <DallasTemperature.h>

OneWire oneWire(4);

DallasTemperature sensors(&oneWire);

// ce,csn pins
RF24 radio(8,7);

// init data buffer to hold a sensor type byte and one uint16_t sensor data
unsigned char data[3] = {
  0};
unsigned long count=0;
void setup(void)
{
  sensors.begin();
  Serial.begin(57600);
  Serial.println("**************V1 Send Sensor Data***********");
  radio.begin();
  radio.setPALevel(RF24_PA_LOW);
  radio.setChannel(0x4c);

  // open pipe for writing
  radio.openWritingPipe(0xF0F0F0F0E1LL);

  radio.enableDynamicPayloads();
  radio.setAutoAck(true);
  radio.powerUp();
  Serial.println("...Sending");
}

void loop(void)
{

  sensors.requestTemperatures();
  float currentTemp;
  currentTemp = sensors.getTempCByIndex(0);

  //assign 'T' to represent a Temperature reading
  data[0] = 'T';

  data[1] = currentTemp;

  count++;

  sprintf(data, "T %5.2f\n", currentTemp);  // build command in data[]
  radio.txMode(strlen(data));               // set # bytes to xmit
  radio.write(data);                        // send bytes

  // print and increment the counter
  Serial.print("Temperature sent:  ");
  Serial.println(currentTemp);
  // pause a second
  delay(500);
}

In this example, when I print currentTemp, it will display the decimals, but if I print data[1], it won't.
What am I missing?
EDIT:
I've modified the code to include the answer from JRobert (updated code above), but it comes back the following error:
nrf24SendSensorDataV1_ino.cpp: In function 'void loop()':
nrf24SendSensorDataV1_ino:56: error: invalid conversion from 'unsigned char*' to 'char*'
nrf24SendSensorDataV1_ino:56: error: initializing argument 1 of 'int sprintf(char*, const char*, ...)'
nrf24SendSensorDataV1_ino:57: error: 'class RF24' has no member named 'txMode'
nrf24SendSensorDataV1_ino:57: error: invalid conversion from 'unsigned char*' to 'const char*'
nrf24SendSensorDataV1_ino:57: error: initializing argument 1 of 'size_t strlen(const char*)'
nrf24SendSensorDataV1_ino:58: error: no matching function for call to 'RF24::write(unsigned char [3])'
C:\Users\Zuh\Downloads\arduino-1.0.1\libraries\RF24L01/RF24.h:281: note: candidates are: bool RF24::write(const void*, uint8_t)

Any thoughts?
EDIT 2
I've made a dirty fix that will solve the issue.
In the transmitter code I've added:
uint16_t sensorValue = currentTemp*100;
//do the bit shift to put uint16 into uint8 array
data[1] = sensorValue >> 8;
data[2] = sensorValue;
// print and increment the counter
radio.write(data, sizeof(uint16_t)+1);

This will send the (temperature value)*100
On the receiver end, I just convert the uint16_t to a float element and divide it by 100.
uint16_t sensorValue = data[2] | data[1] << 8;
float temp = (float) sensorValue/100;
Serial.print("T: ");
Serial.println(temp);

Dirty, but effective!
Many thanks guys for the help, it really pointed me and my lousy programming skills to the right direction.

From the Arduino playground documentation for the Nrf2401 library, the .write method accepts either: a byte to transmit, a pointer to your unsigned char buffer; or a void argument meaning use the library's internal buffer. You must have called the .txmode() method first.
Since you're trying to use your own buffer, you'll need to make it long enough to contain the message you want to transmit (plus one byte for the terminating NUL). You'll need a character representation of the value you want to send, not the binary number itself. At a quick read of the library doc I didn't see the message format the library wants, but assuming it's something like:
  T<space>12.34<newline>, you'll need something like this (untested, it may need tweaking)
sprintf(data, "T %5.2f\n", currentTemp);  // build command in data[]
radio.txMode(strlen(data));               // set # bytes to xmit
radio.write(data);                        // send bytes

Ill test it tonite! Looks really good, thanks JRobert!!

I've tested it and I get the following error:
nrf24SendSensorDataV1_ino:54: error: stray '\' in program nrf24SendSensorDataV1_ino.cpp: In function 'void loop()': nrf24SendSensorDataV1_ino:54: error: 'f5' was not declared in this scope nrf24SendSensorDataV1_ino:55: error: 'class RF24' has no member named 'txMode' nrf24SendSensorDataV1_ino:55: error: invalid conversion from 'unsigned char*' to 'const char*'

nrf24SendSensorDataV1_ino:55: error: initializing argument 1 of 'size_t strlen(const char*)' nrf24SendSensorDataV1_ino:56: error: no matching function for call to 'RF24::write(unsigned char [3])' C:\Users\Zuh\Downloads\arduino-1.0.1\libraries\RF24L01/RF24.h:281: note: candidates are: bool RF24::write(const void*, uint8_t)

I fixed a couple typos in the sprintf() format string that should clean up some of the errors; you'll have to make sure your data types match what the library's requirements, especially with regard to const qualifiers. Sorry, I don't have the part to be able to debug this.

Updated question with your code. I'm using the RF24 library, maybe this interferes with it? Because the error mentions that 'class RF24' has no member named 'txMode'

Since I can't comment yet I will place this as answer.
But have you tried to use radio.print(data[1], DEC); ?
DEC stands for Decimal for if you want to force something to print it in Decimals. When you want something to be printed in Hexadecimals you can use HEX for example. Hope this will help you.

This post is simply not true. Decimal and decimals are two entirely different things. He's missing the . decimal when sending the data. DEC just specifies that the info given is presented in the decimal (base ten) system. This isn't related.

The info given huh? Now I don't get it that I can simply make a calculator using arduino and print everything in DEC and HEX without writing a new calculation. All I do is printing it as DEC and or HEX. I would love to hear a more specific explanation about it cuz this is what I learned on my college.

data[] is an array of three chars.  You assign the letter "T" to data[0] (the first char of the array), then data[1] = currentTemp attempts to assign a float to the second char in the data array - floats won't fit in chars.

I'm not familiar with the radio.* functions you are using.  In C, I'd use printf("%5.2f\n", currentTemp);  The %5.2f" tells the print function that the variable is a float, and it should be formatted with two digits after the decimal.

source: Stack Exchange

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

sort: votes


text:
How to interpret the data from GPS GY-NEO6MV2 using Arduino Uno?
I am trying to get GPS data from my GY-NEO6MV2, but the results are not readable with SoftwareSerial or other libraries. I have used the following code that has worked for others on the net, but I don't get any results from it. The GPS data appears perfectly in the serial monitor, but the interfaces such as SoftwareSerial fail to receive it. Instead, I receive a bunch of -1s. Here is the code:
#include "SoftwareSerial.h"

// Constants
#define txPin 1      //tx pin in GPS connection
#define rxPin 2      //rx pin in GPS connection

// Set up the GPS serial port
SoftwareSerial gps = SoftwareSerial(rxPin, txPin);
// Variables
byte byteGPS = 0;
int i = 0;
int state = 0;
char dataGPG[100] = "";
char *pch;
char *GGA[15];
int sat = 0;
void setup() {
  //setup for Serial Port
  Serial.begin(9600);
  Serial.flush();
  //setup for GPS Serial Port
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  gps.begin(4800);
  gps.flush();
  //setup satellites signal
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  // Turn off the led until a satellite signal
}

void loop() {
  gps.flush();
  Serial.flush();
  Serial.println("Waiting GPS data...");
  // Prepare all for reading GPS Serial Port
  memset(dataGPG, 0, sizeof(dataGPG)); // Remove previous readings
  byteGPS = 0; // Remove data
  byteGPS = gps.read(); // Read the byte that is in the GPS serial port
  delay(1000);
  // Find the desired string
  while (byteGPS != '$') {
    byteGPS = gps.read();
   /******* Here I just get -1 *************/
  }
  // Save the string in an array
  i = 1;
  dataGPG[0] = '$';
  while (byteGPS != '*' ) {
    byteGPS = gps.read();
    dataGPG[i] = byteGPS;
    i++;
  }
  dataGPG[i] = '\0';
  string(); // Call to the function that manipulates our string
}

/*
  This function will allow us to identify the data we need to get the longitude, latitude ...
*/

void string() {
  i = 0;
  memset(GGA, 0, sizeof(GGA)); // Remove previous readings
  pch = strtok (dataGPG, ",");
  // Analyze the saved interval in pch to see if it the needed string
  if (strcmp(pch, "$GPGGA") == 0) {
    while (pch != NULL) {
      pch = strtok (NULL, ",");
      GGA[i] = pch;
      i++;
    }
    plot(GGA, "$GPGGA");
    // Call to the function that is going to display the data
  }
}

/*
  This function organize the gps data received for printing in the serial monitor.
*/

void plot(char **GGAPrint, char *trama) {
  state = atoi(GGAPrint[5]);
  sat = atoi(GGAPrint[6]);
  if (trama == "$GPGGA" && state == 1) {
    digitalWrite(13, HIGH);
    // Then there are satellites, the LED switch ON
    Serial.println("");
    Serial.println("----------------------------------------------");
    Serial.print("UTC Hour -> ");
    Serial.println(GGAPrint[0]);
    Serial.print("Latitude -> ");
    Serial.print(GGAPrint[1]);
    Serial.println(GGAPrint[2]);
    Serial.print("Longitude -> ");
    Serial.print(GGAPrint[3]);
    Serial.println(GGAPrint[4]);
    Serial.print("GPS quality: 0=null; 1=GPS fixed -> ");
    Serial.println(GGAPrint[5]);
    Serial.print("Number of satellites -> ");
    Serial.println(sat);
    Serial.print("Horizontal Dilution of Precision -> ");
    Serial.println(GGAPrint[7]);
    Serial.print("Antenna altitude -> ");
    Serial.print(GGAPrint[8]);
    Serial.println(GGAPrint[9]);
    Serial.print("Geoid Separation -> ");
    Serial.print(GGAPrint[10]);
    Serial.println(GGAPrint[11]);
    Serial.println("----------------------------------------------");
    Serial.println("");
  } else {
    // If no satellite connection
    digitalWrite(13, LOW); // Turn off the LED
    Serial.println("");
    Serial.println("-----------------------------");
    Serial.print("|--- Satellites Used -->");
    Serial.print(sat);
    Serial.println(" |");
    Serial.println("|----Waiting location----|");
    Serial.println("-----------------------------");
    Serial.println("");
  }
}

The result wasn't correct and I only saw this sentence:

Waiting GPS data...

I updated the code by adding gps.available() and delay(2) before every gps.read() and it worked. I still don't know why, but this worked:
#include "SoftwareSerial.h"

// Constants
#define txPin 2      //tx pin in GPS connection
#define rxPin 3      //rx pin in GPS connection
char gps_data[200];

SoftwareSerial gps = SoftwareSerial(rxPin, txPin);
char byteGPS = 0;

void setup() {
  Serial.begin(9600);
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  gps.begin(9600);
}

void loop() {

  byteGPS = '0'; // Remove data
  memset(gps_data, '\0', 200);

  while (gps.available())
  {
    while (gps.available())
    {
      byteGPS = gps.read(); // Read the char that is in the GPS serial port
      if (byteGPS == '$') break;
    }
    int i=0;
    while (gps.available())  // Available3
    {
      delay(1);
      gps_data[i++] = byteGPS;
      byteGPS = gps.read();
      if ((byteGPS == '\n')) break;
    }
    if (i > 1)
    {
      delay(1);
      parse_gps_data();
    }
  }
}

The code in parse_gps_data() parses the data from gps. It works fine.

Do the flush calls in setup not in loop, or you'll loose data, possible the $ you are looking for.

Do you mean   "gps.flush()"    and  "Serial.flush()" ? I did, but I think this code has a bug and I can't understand very well, because when I reset the arduino I could see some numbers and strings ( those weren't correct actually) and It seems there is no loop!!

I mean both, but mainly gps.flush().  If you clear the input buffer that is receiving the GPS data every second or so its possible you will loose data.

I did it for both of them, but I don't know why I have to reset the arduino for receiving the data?

Your sketch has many problems:

The flush method waits for everything you have written to go out.  You haven't written anything to the GPS or Serial, so there's no reason to flush the output.  And you don't need to call it at the beginning of loop.

Calling delay is the surest way to lose GPS characters.  Never use delay in a GPS sketch.

You are calling read without calling available first.    Because you called delay, there are probably chars available, but not necessarily, and they will not be a complete sentence.  This explains the partial NMEA data in your question.

You are printing too much in the plot routine.  After 64 characters are printed (actually queued for printing), the Serial.print call must wait for some characters to be sent (making room in the output buffer). At 9600, each character takes 1ms to be sent.  During that time, the GPS device is still sending characters.  Eventually, the input buffer overflows and GPS characters are lost.  When properly structured (see below), there is barely enough time to print all those messages.

You have connected the GPS to pins 1 & 2, but pins 0 & 1 are the HardwareSerial pins (Rx & Tx), dedicated to Serial .  They are conflicting with each other, and may interfere with uploading new sketches via USB.

You do not have good satellite reception, according to the GPS data fragments you show.  Check the antenna, get near a window, or go outside.  It may take 10 minutes before a "fix" is acquired.

You are using SoftwareSerial for the GPS port.  SoftwareSerial is very inefficient, because it disables interrupts for long periods of time.  At 4800, the Arduino is dedicated to receiving each char for 2ms, an eternity for a 16MHz processor.  This will interfere with other parts of the sketch or other libraries.  This answer gives several alternatives, like AltSoftSerial, on different pins.

Solutions:
First, you have to get the hardware connections corrected.  The NEO-6M is a 3.3V device, so you shouldn't connect it directly to the 5V Arduino.  You could connect just the GPS TX to the Arduino, but you may not receive data reliably. Connecting an Arduino transmit pin to the GPS RX could damage the GPS module, as it is only rated for 3.6V MAX.  It is best to "level-shift" between the two devices.  You can use a few discrete parts (resistors + a diode, or resistors + FETs) or a level-shifting module.  I recommend the latter, because they are cheap, and they also work for high-speed interfaces like SPI.
When you have level-shifting ready to add, move the GPS RX & TX connections to Arduino pin 9 (to GPS RX) and 8 (to GPS TX).  This will let you use AltSoftSerial instead of SoftwareSerial.  If you configure the NEO-6M to run at 9600 (that is the default), you could use NeoSWSerial on any two pins (besides 0 & 1 !!!).  I'm not sure why your NEO-6M is running at 4800, unless you used the u-center utility to configure it permanently.
Finally, I would suggest trying my NeoGPS library.  It is smaller, faster and more accurate than all other libraries, and it includes distance and bearing calculations that you might eventually need.
The Installation instructions guide you through several examples, after which you should try NMEAloc.  NeoGPS also has a diagnostic program, and lots of tips on the Troubleshooting page.  You can download it from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.
After going through those first examples, you should be ready to try your own sketch.  Here is your sketch, modified to use NeoGPS and either AltSoftSerial, NeoSWSerial, or the built-in Serial1 on a Mega2560, Leo or Due:
// Set up the GPS serial port (pick *one* of these choices)

//#include <AltSoftSerial.h>
//AltSoftSerial gps_port; // always 8 & 9 on an UNO

//#include <NeoSWSerial.h>
//#define rxPin 2
//#define txPin 3
//NeoSWSerial gps_port( rxPin, txPin );

#define gps_port Serial1  // for a Mega2560, Leo or Due

// Variables
#include <NMEAGPS.h>
NMEAGPS gps;
gps_fix fix;

#ifndef NMEAGPS_PARSE_GGA
  #error You must uncomment NMEAGPS_PARSE_GGA in NMEAGPS_cfg.h!
#endif

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

  gps_port.begin(4800); // 9600 is the default for NEO-6M

  //setup satellites signal
  pinMode(13, OUTPUT);

  // Turn off the led until a satellite signal
  digitalWrite(13, LOW);

  Serial.println( F("Waiting GPS data...") );
}

void loop() {
  while (gps.available( gps_port )) {
    fix = gps.read();  // a new fix structure has been parsed
    plot();
  }
}

/*
  This function organize the gps data received for printing in the serial monitor.
*/

void plot() {

  if (fix.valid.location) {
  // or if (fix.valid.status && (fix.status >= gps_fix::STATUS_STD)) {

    digitalWrite(13, HIGH); // Then there are satellites, the LED switch ON

    Serial.println();
    Serial.println( F("----------------------------------------------") );
    Serial.print  ( F("UTC Hour -> ") );
    if (fix.valid.time)
      Serial.println( fix.dateTime.hours );
    Serial.print  ( F("Latitude -> ") );
    Serial.println( fix.latitude(), 6 );
    Serial.print  ( F("Longitude -> ") );
    Serial.println( fix.longitude(), 6 );
    Serial.print  ( F("GPS status: 0=NONE; 1=EST, 2=TIME, 3=STD, 4=DGPS -> ") );
    if (fix.valid.status)
      Serial.print( fix.status );
    Serial.println();
    Serial.print  ( F("Number of satellites -> ") );
    if (fix.valid.satellites)
      Serial.print( fix.satellites );
    Serial.println();

    #ifdef GPS_FIX_HDOP
      Serial.print  ( F("Horizontal Dilution of Precision (x1000) -> ") );
      if (fix.valid.hdop)
        Serial.print( fix.hdop );
      Serial.println();
    #else
      #error You must uncomment GPS_FIX_HDOP in GPSfix_cfg.h!
    #endif

    Serial.print  ( F("Antenna altitude (m) -> ") );
    if (fix.valid.altitude)
      Serial.print  ( fix.altitude(), 2 );
    Serial.println();

    #ifdef GPS_FIX_GEOID_HEIGHT
      Serial.print  ( F("Geoid Separation (m) -> ") );
      if (fix.valid.geoidHeight)
        Serial.print  ( fix.geoidHeight(), 2 );
      Serial.println();
    #else
      #error You must uncomment GPS_FIX_GEOID_HEIGHT in GPSfix_cfg.h!
    #endif

    Serial.println( F("----------------------------------------------") );
    Serial.println();

  } else {
    // If no satellite connection
    digitalWrite(13, LOW); // Turn off the LED

    Serial.println();
    Serial.println( F("-----------------------------") );
    Serial.print  ( F("|--- Status -->") );
    if (fix.valid.status)
      Serial.print  ( fix.status );
    Serial.println();
    Serial.println( F(" |") );
    Serial.println( F("|----Waiting location----|") );
    Serial.println( F("-----------------------------") );
    Serial.println();
  }
}

Note: Using #if statements, it verifies the configurations in NMEAGPS_cfg.h and GPSfix_cfg.h.  The Geoid Height field is not enabled in the default NeoGPS configuration.

Since I am using Uno, is it ok to use Serial instead of Serial1?

This code causes an error error: ‘pgm_read_ptr’ was not declared in this scope which is a result of __AVR__ not being defined. Is there a work around to this? I tried defining it in GPSfix_cfg and NMEAGPS_cfg, but it didn't work.

What IDE version?  1.6.8 and 1.8.1 work fine for an UNO.  1.7.x did not compile, but it had a different error.  I've updated NeoGPS_cfg.h to accommodate 1.7.x (again :-/).

My IDE version is 1.6.X but I updated NEoGPS_cfg.h and now I see more errors.

Which IDE exactly?  (1.6.x could be any of 13 IDEs.)  What errors?  If it is about "hdop", you have to enable HDOP in GPSfix_cfg.h, too.  I've added that check to the above sketch.

I updated the IDE to 1.8 and I got it compiled with no errors. However, I still have exactly the same issue; I get no results. The problem is that the GPS output appears in the "Serial Monitor" correctly, but SoftwareSerial, NewSoftwareSerial and NeoSWSerial fail to get it and pipe it to my program. I get a bunch of -1 s instead of actual characters.

I updated my question. The problem is that I am receiving -1 in gps.read() since the buffer is empty.

So the NeoGPS program displays the GPS data in the Serial Monitor correctly?  What do you mean by "pipe it to my program"?  The NeoGPS program is reading gps_port correctly, parsing the characters, and filling out the fix structure.  Then it prints the parsed values to Serial, but you could do whatever you want with fix.latitude() (for example).  Your original program would never work, for the 7 reasons listed above.  The -1 you get from gps.read() is reason #3.  You only fixed reasons #1 and #2.

After I updated my arduino from 1.6 to 1.8 things have changed. Now, when I do byteGPS=gps.read() and Serial.print(byteGPS), it works perfectly and prints the gps data in Serial Monitor. However, when I put it in an array, some data goes missing. I am not sure if it is because of the speed of arduino uno, which is less than the gps data coming or not.

Also, when I use your code, it says that gps is not available, but when I use my code, the gps is available. I have already made that change in my code.

Let us continue this discussion in chat.

Sorry I couldn't make it to the chat. I updated the code once again and it worked. I just needed to put gps.available() and a delay before every gps.read(). However, your code still doesn't work on my device.

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


text:
How can I use stepper for specific degree?
I use Arduino and I'm beginner. I use the code below, but I don't understand what stepper.step(num) and STEPS in Stepper stepper(STEPS, 2,3,4,5) are, and I want to use stepper for specific degree and I don't know what I can do. for example if I want to use stepper for 40 degree what are STEP and num?
#include <Stepper.h>

// change this to the number of steps on your motor
#define STEPS 100

// create an instance of the stepper class, specifying
// the number of steps of the motor and the pins it's
// attached to
Stepper stepper(STEPS, 2,3,4,5);

// the previous reading from the analog input
int previous = 0;

void setup()
{
  // set the speed of the motor to 30 RPMs
  stepper.setSpeed(100);
}

void loop()
{
  // get the sensor value
  //int val = analogRead(0);

  // move a number of steps equal to the change in the
  // sensor reading
  //stepper.step(val - previous);
  stepper.step(25);
  delay(1000000);
 // stepper.step(-5);

  // remember the previous value of the sensor
  //previous = val;
}

-----------------------------------------EDIT #2-----------------------------
my stepper is the first one in this link:
https://grahamwideman.wikispaces.com/file/view/28byj48_models_table.jpg/538898220/604x265/28byj48_models_table.jpg
( I think! )
and I don't know what it means?
------------------------------------------EDIT #3----------------------------
Thank you very much, I saw the link.

Step Angle (8-Step sequence: Internal Motor alone): 5.625° (64 steps
  per revolution)

and I run this code for 45deg :
#include <Stepper.h>

#define STEPS_PER_MOTOR_REVOLUTION 32
#define STEPS_PER_OUTPUT_REVOLUTION 32 * 64  //2048
Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 2, 3, 4, 5);

int  Steps2Take;

void setup()
{

}

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{

  Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 8.11;
  small_stepper.setSpeed(100);
  small_stepper.step(Steps2Take);
  delay(10000);
}

because I understand each turn has 2048 steps, for example if I want to have 1/2 turn, I have to have num=1024 ( 2048/2). ok, So, for 45deg, it's 1/8 turn so I have to set num=2048/8. but for example for 33 deg what should I do?
I thought num= 33*5.61
so for 45deg I use num=45*5.61
you know we have a lot of floating point and I'm not sure we do it correct. right? I'm a little confused.

stepper.step(num)is used to rotate your motor 'num'-step. i.e. num=25, then calling stepper.step will cause your motor do 25-step.
STEPS is number of steps per revolution for your motor. It will be depending on the motor you used. For more information, you can check here.
You have to check for your motor stepper resolution. Most common motor stepper has 200 steps per revolution, which means 1 step is 360/200 = 1.8 degree. If you try Stepper.step(1), your motor will rotate 1.8 degree.
So in your case, if you already found out the resolution of your motor stepper, just do a simple conversion task:
const float resolution  = xx.xx; // put your step resolution here
int step_degree(float desired_degree){
    return (desired_degree/resolution);}

This can be use by calling
stepper.step(step_degree(40)); //rotate 40 degree.

--EDIT--
You can check this link, since it (perhaps) using same motor stepper (24BYJ48)
Based on 24BYJ48 datasheet, it has 5.625 degree resolution / 64 steps per revolution.

Do you mean 1 step is 360/200 = 1.8deg?

https://grahamwideman.wikispaces.com/file/view/28byj48_models_table.jpg/538898220/604x265/28byj48_models_table.jpg

I sent a link, the firs one is my stepper. but I don't know what they are. Would you please tell me what is my resolution?

I set 200 and I expect with num=1 I have to see 1.8 degree but it wasn't.

Instead of put in comment, it will be better if you put edit your question so others can quickly notice it :)

Thanks , I edit it, but I don't know what is the correct step


text:
Limit on connector cable for HC-SR04 ultrasonic sensor
Is there a limit for the connector distance between an arduino and a HC-SR04 ultrasonic sensor?
I have a set-up for measuring a liquid's level in a tank. The benchtop version worked OK, but when I deployed it, I introduced a 10meter cat5 cable connecting the HC-SR04 to the arduino, it is giving me strange distance readings (they are showing the same distance, even though the level has changed significantly).
The 10m of cat5 is the only element that has changed from the benchtop tests.
Is this length of cat5 a potential problem? If so how can I diagnose it? I have a multimeter and basic oscilloscope?
Update:
I measured 4.77v across the sensor's 5v/GND on the breadboard with arduino and 4.65v on the sensor itself.

Check the voltage levels at the sensor and at the input of the Arduino (for the echo and trigger you might need the oscilloscope to get a good reading). Over that length you might have significant voltage drop.

Cat 5.e cable is specially designed to carry on differential (or balanced) signals (that is why it consists of four twisted pairs - each pair is like tunnel for signal)
On the other hand, the ultrasonic sensor utilizes non-balanced, non-differential signal of high frequency, so, the valid length of cable, that couldn't destroy the data in the signal accuracy is about 0.3-0.5 meter only.
You can check my words by comparing a plots of the signal (on controller input pin) with 10cm and 10m cables.
The digital signal must have nice, square form like this:

But the signal, which is passed through long line of wire can be look like this:

And this is bad, because now the controller could not interpret this signal shape correctly.

Is there a way of 'squaring' off the signal at the end of the long cable?

Yes and no, actually. The simplest way to do this - is to place the controller as near as possible to the sensor. The other way implies the idea of using differential signals - for example, use four of RS485 (i.e, the MAX485 integrated circuit) transceivers. Use one pair of them to send the Trig signal from the MCU, and another pair - to send the Echo signal

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


text:
Manchester Library Won't Compile for Attiny85
I am creating a wireless sensor using an Attiny85.  I want to send the data to an arduino uno, so I purchased the 315mhz rf link kit from spark fun.  Since the Attiny85 does not have a TX I decided to use the Manchester library however it won't compile on the Attiny85.
I followed the steps from this blog :
http://mchr3k-arduino.blogspot.mx/2012/01/wireless-sensor-node-part-2.html?showComment=1338749638806#c853067277980266192
Here is the code I am using:
    #include <WProgram.h> //otherwise it says it can't find Arduino.h
    #include <Manchester.h> //include the library to comunicate
    #define TxPin 2 //the pin that is used to send data

 int sensorPin = 4;
 int ledPin = 3;
 int count = 50;

 void setup(){
  pinMode (ledPin, OUTPUT);
  man.workAround1MhzTinyCore(); //add this in order for transmitter to work with 1Mhz Attiny85/84
  man.setupTransmit(TxPin, MAN_1200); //set transimt pin
}

void loop(){
  if (count == 50){
   digitalWrite (ledPin, HIGH);
   count = 0;
   }
   int data = analogRead(sensorPin);
   man.transmit(data); //transmits and reads the data
   delay (100);
   count ++;
 }

Here is the error message:
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp: In function 'void MANRX_SetupReceive(uint8_t)':
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:366: error: 'TCCR2A' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:366: error: 'WGM21' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:368: error: 'TCCR2B' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:368: error: 'CS21' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:369: error: 'OCR2A' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:379: error: 'TIMSK2' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:379: error: 'OCIE2A' was not declared in this scope
/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:380: error: 'TCNT2' was not declared in this scope

Which package are you using for ATtinyX5 Arduino support?

I tried the one from the blog I referenced but after google searching I found that the MIT High Low Tech Group had one so I tried that one as well.  The one from MIT High Low Tech is from this page http://highlowtech.org/?p=1695

Did you import the manchester library into the Arduino IDE? or Place it in the libraries folder?

attiny is missing an option required to allow the Manchester library to function properly on ATtinyX5 devices, specifically definition of __AVR_ATtinyX5__ when a device is selected. In fact, it's missing quite a few things.
The package I use for ATtinyX5 support is arduino-tiny. I have verified that it defines that symbol properly. I recommend that you dump your current support package and install arduino-tiny instead.

I downloaded the arduino-tiny-0150-0020.zip.  Unzipped the file then dragged the folder named tiny into the hardware folder I created inside the arduino folder.  However when I went to the ide I searched under boards and the Attiny series of boards did not show up.

What is the correct way to add the package to the ice?

Which version of the IDE are you running?

Arduino1.0.5 on mac osx 10.9.2

Then you'll need to download the support package for 1.0.x instead of the one for 1.5.x.

I just downloaded the package  arduino-tiny-0100-0018.zip  and inserted the folder tiny into my hardware folder and the boards are still not loading.

this is the file path /Users/joelsimonoff/Documents/Arduino/hardware/tiny

I renamed the file from tiny to attiny and the file prospective boards to boards and the boards now show up in the ide

the file just compiled successfully I am gonna try to hook it up to the chip

Having struggled through this myself, I can confirm that Joel's solution works.
There are quite a lot of posts around that suggests that you can't get the Manchester to work with Arduino1.0x and you need 0020. But you can.
The key is to use the arduino-tiny from the link above, put the tiny folder which you get from there in /hardware and then rename it to attiny and “prospective boards” to boards.
I realise that this doesn’t say any more than Joel already has, but there is so much conflicting and contradictory information around I thought it would be worth adding in my experience

Got the same problem using this lib with a 8 MHz Trinket, but managed to solve it by adding #define __AVR_ATtinyX5__ to the file hardware/attiny/variants/tiny8/pins_arduino.h. I'm using the Adafruit support package for ATtiny. Perhaps a bit of a hack, but I can still build for the UNO, by selecting board in Arduino IDE 1.0.5.


text:
Sketches not uploading to Micro from Ubuntu 14.04
I recently bought an Arduino Micro to see what all the fuss was about and I figured I'd use it with Ubuntu on an older Dell Latitude. I was able to install all of the files using some tutorials but I have this problem uploading sketches. After plugging in the board, the green top LED is consistently flashing so it seems to be working, but when I try to upload a sketch I get the following error
Connecting to programmer: .avrdude: Send: . [1b]
avrdude: Send: S [53]
avrdude: ser_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding

Any ideas how to fix this? I tried pressing reset during the send as some forums have suggested but it doesnt seem to be working.

I just successfully compiled and uploaded the blink sketch to a Mega on 14.04, so the update shouldn't be an issue. Are you using the correct serial interface and board type?

Unplug Arduino; type sudo dmesg -c; clear. Plug in Arduino, wait a couple seconds, then type dmesg and copy the output into your question. Also add the output for lsusb to your question.

@jippie how do you determine the correct serial interface?

It is in the dmesg output that you get when following above hint.

@jippie thanks for helping. not near the board at this time but i'll try and comment in a bit

lsusb is also useful (you may need to apt-get it first). It lists all currently connected USB devices. You should see the arduino there when you connect it (it may be called "FTDI Device" (the serial interface device) though)..

I have a Micro and Ubuntu 14.04. I have successfully uploaded sketches to the Micro using IDE 1.0.6. Thus that combination should work.
I suggest you get the sketch compiling OK. Then hold down the Reset button on the Micro, start an upload with your other hand, and release Reset when it says "Uploading".

Try typing
lsusb | grep Arduino

I found with a sketch uploaded which opens the Serial port:
Bus 003 Device 087: ID 2341:8037 Arduino SA
If you hit Reset and wait a second, then do the lsusb again you see a different device:
Bus 003 Device 086: ID 2341:0036 Arduino SA
That one (the 0036 one) is the one it will upload to. You might get 0037 rather than 0036 because I reflashed the bootloader to be the Leonardo one, but the concept is the same.

The only way I have been able to fix this is revert back to Ubuntu 12.04.
There is something about 14.04 that does not play nice with the Micro.
I've tried running avrdude on the command line as well with no luck. The Arduino IDE code jumps through some hoops to detect the proper USB port, so timing is probably critical. I don't know the secret sauce for 14.04 though. The micro is tricky since USB is disconnected and reconnected during programming.
If anybody has better luck with this please update.


text:
Calculating location with 4 piezo's
i've got the following problem i'd like to get solved and i'm breaking my head, so please help!
I have a rectangle with the following size 40 cm * 50 cm. On each corner of this rectangle I placed a Piezo element (it's an electronic element which measures the vibration)
The rectangle is defined as followed: the left upper corner = A the left lower corner = B the right lower corner = C the right upper corner = D
I'm trowing a ball on the surface and I'd like to calculate it's X and Y axis. The outcome of the piezo elements are as followed:
A,B,C,D - 0 lowest vibration, 1023 highest vibration These values can be mapped to a number I can decide, so that means I can make it whatever we need it to be. Example: map 0,1023,0,100, meaning the new mapping will be 0 - 100.
I found a possible solution here: http://mathafou.free.fr/pbg_en/sol114.html The problem I got is that i don't know where the ball will be and therefor I don't know the angle it will fall on.
The thing I do now is:
Example: We trow the ball. The outcome could be ABC or what would be best ABCD results.
I thought Pythagoras could come in handy here. The thing I did was: A*A+B*B=C*C (to get the square calculation done) A+B = AB, B+C = BC, A+C= AC, (to get the sides of a triangle) AB*BC=AC (We don't know AC but we can square root the outcome of AB*BC)
But then i realised I just know how long the side is and I still don't know where the ball landed :(
The following I already implemented to scale it when it works (maybe not relevant now) A+B+C+D = Total outcome we can possibly get at that point (as we are relying on vibration) A,B,C,D/Total = the scale we need to calculate with
I call this A1,B1,C1,D1 so I can re-use this in the code The reason I do this, is the follow up I need it for. Im going to use a projector to project a video on the exact X/Y position. But that's not relevant I guess for now.
I'm programming this in Processing 2 : http://processing.org

You'll need to do some trials to see the relationship between sensor value and distance from that corner/edge. Then you can get an equation where, given any sensor value, it will estimate distance.

Although I don't know how well this would work, but I'd try [average of top sensors - average of bottom sensors] to find a Y coordinate, and [average of right sensors - average of left sensors] to find the X coordinates. Note: the center would be the origin. Sample equation: ((A1+B1)/2)-((C1+D1)/2) and ((A1+C1)/2)-((B1+D1)/2). Try that and see how it works. If it works, I'll post an answer explaining some of the mechanics behind it. (The input values are the readings of the sensors.)

You might want to look into how LORAN works, as I believe you can do something similar.
First premise: You want to look for the initial transient caused by the impact propagating to sensors in various places on the periphery.  The signal in the material will end up bouncing around quite a bit before it dies out, but the leading edge of the initial transient should be unambiguous, so use that.
Second premise: You have no idea when the ball actually hits - you can also measure the difference in timing between when various sensors first detect it.
So take any two sensors, measure the time lag between when they detect the ball, and convert that via the speed of sound in your material.  This yields the difference in the distance of the impact point from the two sensors.  If you know the position of the two sensors, and plot the curves of points which satisfy the equation of the measured difference in distance from each of them you can a class of conic section called a hyperbola.
But so far you do not have an answer, but only a pair of curves along which the impact must lie.  So now take at least one new sensor, and repeate the exercise generation a new equation.
Combine the equations and solve to find the intersection of the curves - this is your point of impact.  It is possible to have more than one mathematical solution, but I think you will find that only one possible solution lies in the area between the sensors.
(Unfortunately, the ATmega328p A/D converter probably isn't fast enough to do a good job of this - at 10KSPS each sample is around 34mm in air, and around half a meter in typical solids - so you either need a much faster A/D, or else tune a comparator circuit to detect pulses and measure them with ATmega timer channels.)


text:
Is a HC-SR04 fast enough to make decisions on moving robot (4 Johnson motors 300 rpm)?
I am working on a project in which I have made a robot powered by 4 Johnson DC motors (300 rpm) and controlled by Arduino UNO R3. Now in my project I'd used ultrasonic sensor (HC-SR04) for detecting obstacles.
What I want is that as soon as my an obstacle is detected robot should turn by 180° but what actually happening is that sometimes robot takes turn very late (though I'd kept range of sensor approximately 50cm) and sometimes it just collides with obstacles.
As I'm new to Arduino I just want to know if an ultrasonic sensor is fast enough to sense obstacles and signal the Arduino about it, before it gets close enough?
Here's my code
int sense()
{
     analogWrite(trigPin, 0);
 // instead of digitalWrite(trigPin,LOW);
     delayMicroseconds(2);

/* as I'd used my digital pins for  motors and all i have to use pwm pin for  trigger pin of sensors i guess it doesn't make any difference*/

     analogWrite(trigPin, 255);
  // instead of digitalWrite(trigPin, HIGH);
     delayMicroseconds(10);

     analogWrite(trigPin, 0);
     duration = pulseIn(echoPin, HIGH);

     distance = duration/58.2;

      if (distance > maximumRange)
          return 0;
      else
          return 1;
}

Why are you using analogWrite()?

Use digital mode for the pins - analog pins are those with analog input capability but still digital outputs.  If it is fast enough depends on things like how far you move in the time spent waiting for out of range echoes to die.  Your more serious problem may be if objects are hard to detect due to size or angle.  You may also have algorithm problems.

i am using wall or my bag as obstacle i dont think it has any problem detectiñg such object and if you think problem is with pins then it is not, as i had tried blinking LED using those pwm pins and regarding algorithm i dont know anything about it because i copied this code from internet and it worked so i used it in my project but now i am façing problems in response time of sensor

@NISHANTDESAI Try attaching a USB cable and print out the value all the time and see, maybe the object is indeed not detected.

On it's max speed, how far is it's braking distance?
Then you should start braking atleast from before that distance of the object.
Let's say your braking distance is 25cm, you should start braking >25cm.
But this is only when you would instantly brake at the moment you're within 25cm reach.
So we have to know how many distance we will travel during the calculation, before we start braking.
You could just try it out, set the distance a little higher everytime you crash into it (Assuming it doesn't fail and is always at the same time).
We have to know the top speed of your motor, RPM doesn't say a lot in this story, we'll need to know how big your wheels are to be able to determine how many cm's you'll travel per revolution, and doing that times the RPM, you know your top speed. (Or you can also measure this, but it can change depending on how full your battery is)
Also, your code should be real-time you'll likely want to use timers to trigger the trigPin and use an interrupt on the echoPin to be sure none of your code will delay your sensor. This will improve execution speed aswell as reliability/deterministic timing. Also, it will make it possible to run it aside from your regular code.
So if you know, your top speed = 10cm/second.
And you know that 1 calculation+reaction-time is 200ms.
You can safely assume that you need >2cm extra.
To be honest, you should add a little for when it's slippery/another surface or just so you won't touch the object.
So. The ping sensor is almost always fast enough, only if the calculated range is outside your max range, it will not work.
You could however, use an IR proximity sensor which will trigger at a set distance. This way you don't have to do any calculations and just brake whenever you receive the interrupt. But it won't tell you the distance to the object.
The cool thing on the distance sensor is that you can also scale the brake distance on your driving speed, so that it will brake later when you're driving on half your speed. That way you can come very close to an object, but still be 100% sure that you won't crash into it.

Try using NewPing library. Ping sensors consistently and reliably at up to 30 times per second.

You can't achieve 30 times per second if you use the ping_median which basically does error correction. Best you can do is 1000/(29*5), or 6 readings (assuming using default 5 pings per median reading)

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


text:
Logging to multiple destinations (serial & SD card)
I am building a rover using an Arduino Mega and an Arduino Uno. The Mega has a sensor shield that has an SD card slot. The intent is for the rover to be autonomous, and I currently send logging info to the serial port (to log actions like boot, diagnostics, etc.)
Is there a simple way to redirect this output to BOTH the serial and the SD card? I would be happy with just a single file with lines added for each entry.
My complication here is to prevent using Serial.println as well as SD.println as two separate commands. Is there any other way around this?

Create something like a log function that does call both Serial.println and SD.println

Do you want to eliminate the two separate println() calls to keep the code concise or is there another issue that you're concerned with?

Do you have internet connection? I'd rather log to a server than to a SD-card, for faster access of the log and for less wearing out the SD-card.

The simplest thing you can do is to create a simple function that performs both tasks for you.  However, there are certain caveats that you should look out for.  The most basic function would be:
void log(const char *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

However that is not the best way of doing it since that requires all your messages to be in RAM.  So you should really use the __FlashStringHelper type as well as an overload function so you can use the F() macro to save RAM:
void log(const char *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

void log(const __FlashStringHelper *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

And that will pick the right version of log depending on what you pass.  But what if you want to pass some variables, like numbers?  Overloading can help again here.  Another pair of functions now that take two parameters instead of one:
void log(const char *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

void log(const __FlashStringHelper *msg) {
    Serial.println(msg);
    myFile.println(msg);
}

void log(const char *msg, int v) {
    Serial.print(msg);
    Serial.print(" ");
    Serial.println(v);
    myFile.print(msg);
    myFile.print(" ");
    myFile.println(v);
}

void log(const __FlashStringHelper *msg, int v) {
    Serial.print(msg);
    Serial.print(" ");
    Serial.println(v);
    myFile.print(msg);
    myFile.print(" ");
    myFile.println(v);
}

So now you have 4 functions called log, and they can be used in these different ways:
log("This is a message"); // Could be a char * variable
log(F("This is a message"));
log("The temperature is:", temp);
log(F("The temperature is:", temp);

And of course you can keep expanding and expanding the parameters in different ways for different combinations of parameters.  Just be warned that for some combinations of parameters the compiler won't be able to work out which is the right function to call (for instance if you have one that takes a long and one that takes a byte in the same place and you just pass a numeric literal), so you have to think carefully about how you arrange your parameters.


text:
Generate 2 PWM signals Vc and Vh from Arduino Uno
I want to generate two PWM signals VC and VH to give input to the gas sensor  with the duty cycle mentioned below. I also want to take the reading from the same sensor at the same time using Arduino Uno.
[
I am confused how to proceed with the code in Arduino Uno.

I'd not use PWM for this. It's a pretty slow PWM signal, and you probably need to synchronize the measurement with the PWM signal. Just toggle the pins and add a delay. It would be helpful if you specified the part nr.

I cannot use the delay and toggle the pin because that will be running in a loop function and i want to perform some other function too in that loop function. And as far as i know, it will execute other statement only if it has completed the pulse generation. I have found this technique in Arduino site   and it mentions that it has a second disadvantage - you can't leave the output running while the processor does something else.

I don't understand what you are saying? All you need to do is turn on the heater, wait a bit, turn on the sensor, wait a bit, read the sensor, turn off the sensor, wait a bit, turn of the heater, do whatever calculation needs to be done in the remaining 236ms, and repeat. What is it exactly? Something like a TGS2442 CO sensor?

Thank you Gerben.  Its TGS2444 ammonia sensor. But this is not what i want to do. I want to use the delay in reading my value, e.g. every 1 sec , etc. As i need to store the value for my future reference and analyse it. I don't want to store value after every 250ms. Along with this i will be using other sensors too like VOC's.

236ms is a lot of time to store an read other sensors.

Let me try. If it works i will inform you. Thank you.

You can use the millis() function to see how much time has passed and use this to create your waveform while still being able to perform other tasks. You will check in which part of the wave you are in each iteration of loop() and adjust your outputs accordingly.
E.g:
long vhtime;
uint8_t vhpin = 9;   // the VH output pin
uint8_t vcpin = 10;  // the VC output pin

long period = 250;   // the period of your pwm signal in ms
long vhduty = 14;    // amount of ms vh should be high
long vcdelay = 2;    // amount of ms we wait for vc to go high after vh has gone high
long vcduty = 5;     // amount of ms vc should be high

long curtime;        // this will hold our current position in one period of the waveform

void setup() {
  pinMode(vhpin, OUT);
  pinMode(vcpin, OUT);
  digitalWrite(vcpin, LOW);
  digitalWrite(vhpin, HIGH);
  vhtime = millis();
}

void loop() {
  curtime = millis() - vhtime;
  if (curtime > vhduty)        // we are in the last 236ms of the wave, vh should be low
    digitalWrite(vhpin, LOW);
  else                         // we are in the first 14ms of the wave, vh should be high
    digitalWrite(vhpin, HIGH);
  if (curtime > vcdelay && curtime < vcduty + vcdelay) // vc should be high during this time
    digitalWrite(vcpin, HIGH);
  else
    digitalWrite(vcpin, LOW);
  if (curtime > period) {
    // we should start a new period
    digitalWrite(vhpin, HIGH);
    vhtime = millis();
  }
  // do your other calculations here
}


text:
Trouble when avoiding delays
I am new to Arduino and I am learning how to avoid using delay.
I have written some code to move my servo by 20° using delays, but can only move the servo once with my current code. In setup(), I assign the servo 150. The next value the servo receives is 15, which it performs. It does not iterate through the following values though. I have been using this guide, BlinkWithoutDelay, with no luck.
Here is my code:
#include <Servo.h>
Servo myservo;
unsigned long previousMillis = 0;
const long interval = 1000;

    void setup() {
       myservo.attach(9);
       myservo.write(150);
    }

   void loop() {
       unsigned long currentMillis = millis();

       if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            myservo.write(15);
       }
       if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            myservo.write(35);
       }
       if (currentMillis - previousMillis >= interval) {
            previousMillis = currentMillis;
            myservo.write(65);
   }

You are resetting the timer on the first phase [write(15)] instead of after the last phase [after write(65)]! The previousMillis = currentMillis should be only after the last phase, before the loop repeats. Not only that, but the time at which each phase executes needs to be different. Currently every if() statement is set to run after interval has elapsed. If, for example, you wanted interval to be the delay between each phase, you could use interval*1 on the first phase, interval*2 on the second, and interval*3 on the third. For example:
   if (currentMillis - previousMillis <= interval * 1) {
        // Runs from interval*0 to interval*1;
        myservo.write(15);
   }
   else if (currentMillis - previousMillis <= interval * 2) {
        // Runs from interval*1 to interval*2;
        myservo.write(35);
   }
   else if (currentMillis - previousMillis <= interval * 3) {
        // Runs from interval*2 to interval*3;
        myservo.write(65);
   }
   else {
        // Runs once after interval*3;
        // *or* runs on first iteration when previousMillis is zero;
        previousMillis = currentMillis;// Reset the loop;
   }

To put the above logic in English:

write(15) while time is between 0 and 1 intervals;
write(35) while time is between 1 and 2 intervals;
write(65) while time is between 2 and 3 intervals;
reset the loop once time reaches 3+ intervals.

Note the use of else if instead of simply if on consecutive statements. This prevents more than one code block from running on the same iteration of the loop().
Edit: I highly recommend having a small delay (like 1ms) somewhere in the loop(), such as at the end. It would be a bad idea to constantly run the write() function when the value is the same as on the last call.
On the other hand, if your starting value is indeed 150 and the loop should start only after interval*1, you may want to iterate from interval*2 through interval*4:
   if (currentMillis - previousMillis <= interval * 1) {
        // Runs from interval*0 to interval*1;
        // Do nothing; servo is set to either 150 or 65 during this time;
   }
   else if (currentMillis - previousMillis <= interval * 2) {
        // Runs from interval*1 to interval*2;
        myservo.write(15);
   }
   else if (currentMillis - previousMillis <= interval * 3) {
        // Runs from interval*2 to interval*3;
        myservo.write(35);
   }
   else if (currentMillis - previousMillis <= interval * 4) {
        // Runs from interval*3 to interval*4;
        myservo.write(65);
   }
   else {
        // Runs once after interval*4;
        // *or* runs on first iteration when previousMillis is zero;
        previousMillis = currentMillis;// Reset the loop;
   }

If you want to change the servo every second, try to use a conditional expression in the timing structure. If you want to use more parallel structure with multiple intervals use different counters (example see: here).
Here is an example of the every second version:
#include <Servo.h>
Servo myservo;
unsigned long previousMillis = 0;
const long interval = 1000;
int angle = 150;

void setup() {
   myservo.attach(9);
   myservo.write(angle);
}

void loop() {
    unsigned long currentMillis = millis();

    if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;

        switch (angle) {
            case 150:
            case 65:
              angle = 15;
              myservo.write(angle);
              break;
            case 15:
              angle = 35;
              myservo.write(angle);
              break;
            case 35:
              angle = 65;
              myservo.write(angle);
              break;
        }
    }
}

EDIT: Add variable assignment angle in conditional expression.

You should probably also set the angle to the one you have just written in each switch case.

If instead of "previousMillis = currentMillis;" you do a "previousMillis -= interval'; then your intevals will absorb the other processing times and won't drift.

authors: Артем Леляков


text:
Problems reading I2C sensor when using a Xbee module
I'm developing a project where I can control a RC boat with GPS and a magnetometer. How ever, I was developing everything connected to my computer and worked pretty well. When I was going to make some test with a battery and a couple of Xbee's (PC and "Arduino"), the magnetometer signal was not updating. So, I read the first value and continued to transmit the same value (thing that never happened on computer). Has someone had the same issue before? How can I solve this? Oh, one thing. The GPS and magnetometer comes in the same module, and I'm having no problems with GPS coordinates. And even if I power de MCU with my computer and transmitting with the Xbee's it doesn't work either. Seems like a communication problem.
Hardware used:
GPS Module + Compass
ATmega1284P
UPDATE:
I want to share also the code I'm using for the I2C reading.
#include <Wire.h> //I2C Arduino Library
#define address 0x1E //0011110b, I2C 7bit address of HMC5883

void setup(){
  //Initialize Serial and I2C communications
  Serial.begin(9600);
  Wire.begin();

  //Put the HMC5883 IC into the correct operating mode
  Wire.beginTransmission(address); //open communication with HMC5883
  Wire.send(0x02); //select mode register
  Wire.send(0x00); //continuous measurement mode
  Wire.endTransmission();
}

 void loop(){

  int x,y,z; //triple axis data

  //Tell the HMC5883L where to begin reading data
  Wire.beginTransmission(address);
  Wire.send(0x03); //select register 3, X MSB register
  Wire.endTransmission();

 //Read data from each axis, 2 registers per axis
  Wire.requestFrom(address, 6);
  if(6<=Wire.available()){
    x = Wire.receive()<<8; //X msb
    x |= Wire.receive(); //X lsb
    z = Wire.receive()<<8; //Z msb
    z |= Wire.receive(); //Z lsb
    y = Wire.receive()<<8; //Y msb
    y |= Wire.receive(); //Y lsb
  }

  //Print out values of each axis
  Serial.print("x: ");
  Serial.print(x);
  Serial.print("  y: ");
  Serial.print(y);
  Serial.print("  z: ");
  Serial.println(z);

}

Maybe the battery is too weak. Or you are using voltage regulators with too high voltage drop. It can be anything.

Try and solve one problem at a time.  Make a simple circuit that reads the magnetomerter and check it works on the computer.  If it does try it on the battery.
Then try and solve the Xbee problem.

@KIIV I'm using a powerbank, so the battery is not a problem. Even if I supply my MCU from the computer and make the communication wireslessly, it doesn't work.

@Matt I have already done that, with every possibilities of connections and power supplies. Seems to be a communication problem when I'm using the Xbee's.

This sounds less like a battery problem and more like a Xbee problem.  I would, as @Matt said, test 1 thing at a time.  That is, test your Xbee with something simple like a fixed message that has nothing to do with your sensor.  Then, if it is a Xbee problem, change your question and question's title ... as you are attracting the wrong type of answer.

@st2000 you're right. At the beggining I was thinking it was a battery problem but seems to be a communication problem now that I have tried every possibilities. Already changed the title. Thanks.

@AlejandroHarrisBonet It might be worth flashing the light when the value changes, just to make sure it is changing.  I would also go back to the XBee equivalent of Hello World.  If that works you could be looking at libray conflicts.

Hey @Matt, thanks for commenting. The Xbee communication as it is, doesn't have any problems at all. I can receive data. The real problem is updating the data I'm getting from the sensor. Since I told it to work as a continuous measurement mode, it doesn't update the sensor values. Maybe there is a problem when I'm trying to tell the sensor to be at this mode, because every time I reset the MCU, it changes the value but it doesn't update.

I have solved the problem by adding a delay just before I select the continuous measurement mode.
void setup(){
  //Initialize Serial and I2C communications
  Serial.begin(9600);
  Wire.begin();

  //Put the HMC5883 IC into the correct operating mode
  Wire.beginTransmission(address); //open communication with HMC5883
  Wire.send(0x02); //select mode register
  Wire.send(0x00); //continuous measurement mode
  delay(100);
  Wire.endTransmission();
}

There are 2 possible problems:
Lack of power or libraries not supporting each other.
1 - Try powering the circuit with some USB 5V. Make sure that your other modules can support 5V. Also check your clock speed. High clock speeds with low voltages might cause your ATmega to function incorrectly.
2 - Some libraries for certain module / breakout uses software I2C which pretty much emulate I2C. They might not be compatible with another module that needs the wire library to function proprely. To debug it, test out 1 module at the time with the battery.

Hey, I'm using wire.h library and reading the sensor directly from its registers. The batteries I use for the supply is a cellphone powerbank, so pretty much is the same if I connected the MCU with my PC.

Any other libraries?

No, just wire.h, I updated the question, so you can have an idea of my issue. Thanks for commenting.


text:
I2C connection freezes Master if Slave disconnects
I am using I2C to successfully request critical data from a Slave device (I have to use requestFrom() in the Master) but if, for some reason, the power disconnects from the Slave device then the Master freezes altogether. I didn't realise I2C was so problematic in this regard and I have been a number of weeks trying all types of alternative setups to try and avoid this situation. I can't seem to find a way for example, to simply check if a Wire() connection exists before requesting data and freezing everything. Both devices are Arduino Uno r3.
Any ideas I may not have tried yet? Any way to send a single value to the Master and update it every 30 secs would do. Actually the data comes from a capacitive sensor, so would it be possible to just have both arduinos read from the same sensor?
In response to Nick Gammons suggestions (below):
I have edited the examples you gave to try and fit in with what I am trying to achieve. I would like to do the following. Catch a situation where the Master (Arduino Yun Shield) cannot communicate with the Slave ( Arduino r3 - with sensor) due to its power supply and/or sensor reading failing. In other words, an Arduino monitoring another Arduino. Here is my edited versions, however I am still not able to catch the "else" condition of the Slave being unreachable:
SLAVE
#include <Wire.h>

const byte MY_ADDRESS = 42;

// various commands we might get

enum {
    CMD_ID = 1,
    CMD_READ_A0  = 2
    };

char command;

void setup()
  {
  command = 0;
  pinMode (A0, INPUT);

  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveEvent);  // interrupt handler for incoming  messages
  Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted

  }  // end of setup

void loop()
  {
  // all done by interrupts
  }  // end of loop

void receiveEvent (int howMany)
  {
  command = Wire.read ();  // remember command for when we get request
  } // end of receiveEvent

void sendSensor (const byte which)
  {
  //int val = analogRead (which);
  int val = 125;//test only
  byte buf [2];
    buf [0] = val >> 8;
    buf [1] = val & 0xFF;
    Wire.write (buf, 2);
  }

void requestEvent ()
  {
  switch (command)
     {
     case CMD_ID:      Wire.write (0x55); break;   // send our ID
     case CMD_READ_A0: sendSensor (A0); break;  // send A0 value
     }
  }

MASTER
#include <Process.h>
#include <I2C.h>
#include <Bridge.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C  lcd(0x27, 16, 2);

const int SLAVE_ADDRESS = 42;

// various commands we might send
enum {
  CMD_ID = 1,
  CMD_READ_A0  = 2,
};

void setup ()
{
  Bridge.begin();
  Console.begin();
  //while (!Console);
  I2c.begin ();
  I2c.timeOut(100);  // milliseconds

  lcd.init();
  lcd.backlight();
}

void loop()
{
  int value = getA0();
  Console.print("A0 value:");
  Console.println(value);
  lcd.setCursor(0, 0);
  lcd.print("A0 value:");
  lcd.print(value);//displays first '0' reading then freezes code
  delay (5000);
}

int getA0() {
  if (I2c.write (SLAVE_ADDRESS, CMD_READ_A0) == 0) {
    byte buf [2];
    int val;
    if (I2c.read (SLAVE_ADDRESS, sizeof buf, buf) == 0)
   {
      val = buf [0] << 8 | buf [1];
      return val;
    }
    else {
      return 0;
    }
  }
  else {
    return 0;
  }
  delay(500);
}

Are both I2C lines low after the slave power supply disconnect?

Show a code, a schematic, and a what modules are you using

I am still not able to catch the "else" condition of the Slave being unreachable - try testing the I2c.write function calls as well, to see if they return a zero (which they should).

@NickGammon - I can confirm that it catches correctly even using the I2c.read (as above), however it only worked if the lcd I2C wasn't connected as well. There is no device address clash, but the code is frozen if the lcd is connected. Is there anything I should be aware of when connecting I2C lcd devices at the same time as using the Wire() and I2c() libraries?

Are you saying it hangs if you connect the LCD "live" but works OK if it is all connected up initially?

@NickGammon - I have updated the Master code to reflect where I am at the moment. I am simulating a faulty Slave by pulling the power supply to it. If I comment out all lcd code I get constant Console readings when the Slave is powered off. If using the lcd it prints out the first '0' reading and then freezes. It seems like the lcd library needs a similar timeout to your I2c library?

Is the LCD an I2C one? I guess it is. You might need to delve into that library and make it use the I2c library, making changes as appropriate (and add the timeout line).

@NickGammon - Yes the LCD is I2C. As for changing the lcd library, I will have to leave that project to a better C++ man than me! I made the decision that I needed the data much more than the readout anyway and have successfully managed to do that with your improved I2c library. Thanks for that and your help.

It wouldn't be that bad. Basically you get rid of beginTransaction, endTransaction and requestFrom, and replace Wire by I2c, and change the #include at the start. It is probably achievable with a little experimenting. Anyway, glad that I helped.

The dsscircuits domain is scrapped.
You can find the i2c master lib here:
https://github.com/DSSCircuits/I2C-Master-Library/blob/master/examples/HMC5883L/HMC5883L.pde

There is code inside the standard library that loops waiting for certain interrupts to complete transmission. If the transmission fails in the middle it can hang.
See my page about I2C. On that page I mention that there is an alternative library. That is written a bit differently so it times out if the transmission doesn't complete in time. An alternative download to the library is here - I2C_Rev5.zip - 6.6 KB.

As hinted by KIIV in a comment, maybe you don't have pull-up resistors. Make sure that you have pull-up resistors from both SDA and SCL to the +5V line. A reasonable value would be 4.7k (each).

Example code

would like a few more examples to show a similar setup to replace my current requestFrom

Borrowed from my page about I2C I am using the same slave code as on that page.
Slave
#include <Wire.h>

const byte MY_ADDRESS = 42;

// various commands we might get

enum {
    CMD_ID = 1,
    CMD_READ_A0  = 2,
    CMD_READ_D8 = 3
    };

char command;

void setup()
  {
  command = 0;

  pinMode (8, INPUT_PULLUP);
  pinMode (A0, INPUT);

  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveEvent);  // interrupt handler for incoming messages
  Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted

  }  // end of setup

void loop()
  {
  // all done by interrupts
  }  // end of loop

void receiveEvent (int howMany)
  {
  command = Wire.read ();  // remember command for when we get request
  } // end of receiveEvent

void sendSensor (const byte which)
  {
  int val = analogRead (which);
  byte buf [2];

    buf [0] = val >> 8;
    buf [1] = val & 0xFF;
    Wire.write (buf, 2);
  }  // end of sendSensor

void requestEvent ()
  {
  switch (command)
     {
     case CMD_ID:      Wire.write (0x55); break;   // send our ID
     case CMD_READ_A0: sendSensor (A0); break;  // send A0 value
     case CMD_READ_D8: Wire.write (digitalRead (8)); break;   // send D8 value

     }  // end of switch

  }  // end of requestEvent

The above code responds to requests to send one of:

Its ID (0x55)
An analog reading (A0)
A digital reading (D8)

Master using Wire library
The master from my page was this:
#include <Wire.h>

const int SLAVE_ADDRESS = 42;

// various commands we might send
enum {
    CMD_ID = 1,
    CMD_READ_A0  = 2,
    CMD_READ_D8 = 3
    };

void sendCommand (const byte cmd, const int responseSize)
  {
  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write (cmd);
  Wire.endTransmission ();

  Wire.requestFrom (SLAVE_ADDRESS, responseSize);
  }  // end of sendCommand

void setup ()
  {
  Wire.begin ();
  Serial.begin (115200);  // start serial for output

  sendCommand (CMD_ID, 1);

  if (Wire.available ())
    {
    Serial.print ("Slave is ID: ");
    Serial.println (Wire.read (), DEC);
    }
  else
    Serial.println ("No response to ID request");

  }  // end of setup

void loop()
  {
  int val;

  sendCommand (CMD_READ_A0, 2);
  val = Wire.read ();
  val <<= 8;
  val |= Wire.read ();
  Serial.print ("Value of A0: ");
  Serial.println (val, DEC);

  sendCommand (CMD_READ_D8, 1);
  val = Wire.read ();
  Serial.print ("Value of D8: ");
  Serial.println (val, DEC);

  delay (500);
  }  // end of loop

Master using I2C library
The beginTransmission() ... write() ... endTransmission() have been replaced by simply write() and the requestFrom() by read() like this:
#include <I2C.h>

const int SLAVE_ADDRESS = 42;

// various commands we might send
enum {
    CMD_ID = 1,
    CMD_READ_A0  = 2,
    CMD_READ_D8 = 3
    };

void setup ()
  {
  I2c.begin ();
  I2c.timeOut(100);  // milliseconds
  Serial.begin (115200);  // start serial for output

  I2c.write (SLAVE_ADDRESS, CMD_ID);
  byte id;

  if (I2c.read (SLAVE_ADDRESS, sizeof id, &id) == 0)
    {
    Serial.print ("Slave is ID: ");
    Serial.println (id, DEC);
    }
  else
    Serial.println ("No response to ID request");

  }  // end of setup

void loop()
  {

  I2c.write (SLAVE_ADDRESS, CMD_READ_A0);

  byte buf [2];
  int val;
  if (I2c.read (SLAVE_ADDRESS, sizeof buf, buf) == 0)
    {
    val = buf [0] << 8 | buf [1];
    Serial.print ("Value of A0: ");
    Serial.println (val, DEC);
    }
  else
    Serial.println ("No response to CMD_READ_A0 request");

  I2c.write (SLAVE_ADDRESS, CMD_READ_D8);
  uint8_t digitalVal;
  if (I2c.read (SLAVE_ADDRESS, sizeof digitalVal, &digitalVal) == 0)
    {
    Serial.print ("Value of D8: ");
    Serial.println (digitalVal, DEC);
    }
  else
    Serial.println ("No response to CMD_READ_D8 request");

  delay (500);
  }  // end of loop

Indeed, a master that waits eternally for an ack from a slave will hang if that ack never comes.

Thanks Nick, I initially avoided this Library due to the lack of slave functions (requestFrom) but i'll have another look this afternoon and update here if anything works.

Also if the device have protection diodes, it can be "powered" through I2C lines (and masters pull-ups) or it holds the lines under HIGH level threshold. Master can't start the communication then. Or it's recognized as clock stretching and master can't continue in communication.

@Nick - the pullup resistors have prevented the data becoming scrambled after a broken connection. I still get a hung script on my Master on a broken connection though, until its reconnected again. I've decided to give the alternate I2c library a go, but would like a few more examples to show a similar setup to replace my current requestFrom - Master and onRequest(requestEvent)-Slave setup. I take it that I would still have to include the Wire() library in the Slave?

The slave would look the same. Doesn't the library come with examples?

Theres only one example in the Library, Nick.

See amended answer.

@Nick - see edits to original question...

Thank you for digging his all up. This guy narrows it down to: twi.cpp https://github.com/panStamp/arduino_avr/issues/1 Do you have any new links of where I can find those alternative libraries by any chance?

@Pete I made a copy a while ago at http://gammon.com.au/Arduino/I2C_Rev5.zip

Or see here on Github

I ran into almost the same problem in an educational context. If the I2C bus has a line stuck low, the program hangs in the wire library. In my application everything is soldered together, but not always properly, so I can get by with a single test at startup. Before invoking Wire.begin. For the OP's issue, they will want to use this every time they restart communication after an idle period.
This is part of a device's self test on power up. When one thing is assembled wrong, frequently many things are wrong, so we want to continue on and test everything else. Then the user can fix all of the issues at once. Or perhaps they haven't even built the I2C part of the circuit yet, and they want to test other hardware. In any case, hanging is not an informative way of reporting an error.
// Written by Paul Haas for public use. This is public domain code.
// But please don't sue me if it doesn't work.
bool Would_I2C_Hang(int SDAPin, int SCLPin) {
  bool wouldHang = false;
  pinMode(SDAPin,INPUT);
  pinMode(SCLPin,INPUT);
  if ( digitalRead(SDAPin) != 1 ) {
    Serial.println("SDA pin is low");
    wouldHang = true;
  }
  if ( digitalRead(SCLPin) != 1 ) {
    Serial.println("SCL pin is low");
    wouldHang = true;
  }
  return wouldHang;
}

void setup() {
  Serial.begin(115200);
  for(int i=5;i>0;i--) {
    Serial.print(i);
    delay(1000); // I sometimes need a few seconds to restart the serial console.
  }
  Serial.println();
  if ( Would_I2C_Hang(20, 21) ) { // Adafruit Feather M0 sda and sdl arduino pins.
    Serial.println("The I2C bus will hang if we try to use it. Disabling it.");
  } else {
    Serial.println("Mark the I2C devices as ready to be tested.");
  }
}
void loop() {
  // put your main code here, to run repeatedly:
}

Had this same issue when using two Megas communicating over I2C, along with other items running on the I2C bus. I needed the system to continue running if one Mega went down due to loss of power. The other Mega should detect it and execute some abort commands.
Initially I wired the Megas up on the same I2C bus, just as I would any other device. When I unplugged one Mega, the other would freeze the next time it tried to address another device on the bus.
The solution was to use a hot-swappable I2C buffer. I used this one, and everything worked immediately without issue after wiring it up:
http://www.mouser.com/search/ProductDetail.aspx?r=595-TCA4311ADR
To integrate the SOIC-8 package onto a standard DIP breadboard for Arduinos, I used an adapter from Adafruit.

Regarding the TI I2C hot swappable buffer:
Apparently there is a similar one from Analog Devices, but I have not tested it:
http://www.mouser.com/search/ProductDetail.aspx?r=584-ADUM1250SRZ
To integrate the SOIC-8 package onto a standard DIP breadboard for Arduinos, I used this adapter from Adafruit:
https://www.adafruit.com/product/1212
Sorry for another post - limit of 2 hyperlinks per post due to lack of reputation :-)
Chris


text:
Why can't my bluetooth receive serial data from my android phone, but can send serial data from my bluetooth to my android phone?
I can receive serial data from my phone but I can't send serial data to the arduino using bluetooth. I can see my input from serial monitor to my Android but not the other way. I'm using ARF7044A bluetooth module if that matters. Any help would be appreciated please.
Arduino to Android: Working
Android to Arduino: Not working.
Here is the wiring:
Here is the code:
char state;
void setup()
{
pinMode(8, OUTPUT);
Serial.begin(9600);
}

void loop()
{

  if(Serial.available())
  {
    state = Serial.read();
    Serial.println(state);
  }
  if (state == 'a')
  {
    digitalWrite(8, HIGH);
  }
  else if(state == 'b')
  {
    digitalWrite(8,LOW);
  }
}

Please show us your wiring

@chrisl Hi, I have added the wiring to the post.

To me this looks like the same issue I encountered some time before.
In my case the SPP-C bluetooth device was able to receive from my computer but the communication did not work the other way around.

@Kwasmich hey thanks. I think my android phone might actually be the problem here. Brb gonna try another phone.

On a second look: You also don't need a voltage divider on Uart_tx.
The other one is fine because you want to use the Arduinos 5V TX pin on the 3.3V Uart_rx pin. But you already have a 3.3V output on your Uart_tx and then dividing it further down to 2.2V will be too low for the Arduino RX pin to recognize a signal.

@Kwasmich the divider doesn't work as a divider with the shown resistors in the reverse direction.  However it does with the output of the USB serial.

The reversed order makes it even worse. You have a 1:3 ratio instead of 2:3. So from your 3.3V only 1.1V reaches the RX pin. Just directly connect Uart_tx and Arduino RX. 3.3V won't harm a 5V tolerant pin.

Your erroneous level shifting attempt from Bluetooth TX to Arduino RX is the root of your problem.
Pins 0 and 1 are also connected to the on-board USB interface chip via a pair of 1kΩ resistors. These resistors serve two purposes:

To "weaken" the drive of the USB chip's UART interface (actually only needed on the USB chip's TX -> Arduino RX connection), and
To protect both the USB chip and the main MCU from damage should two connected pins be set to opposing levels, which would cause high currents to flow through both output drivers.

The TX pin of the USB chip is actively driven HIGH all the time when idle (stupid design by Arduino, it should be Hi-Z when the port is not open), and the RX pin is pulled up by the internal pullup resistor in the USB chip.  Further, when the Arduino's Serial is in use the TX pin of the Arduino is actively driven HIGH when idle (or LOW when transmitting a "1" bit).
The actual circuit you have looks more like this:

simulate this circuit – Schematic created using CircuitLab
Transmitting from the Arduino to the BT module is straight forward enough - the "high" point of the circuit is the Arduno's TX pin at 5V when idle.  Current flows through R2 to the USB RX pin, and through R5 to the BT RX pin, with a portion split off to ground, which is what you want for your level shifting.
Communication in the other direction, however, is different, because you have two balanced "high" points in your circuit - one at the USB TX and one at the Bluetooth TX - and the fact you have 1kΩ resistors in both branches means that neither transmitter is "stronger" than the other. This means that when the BT TX is LOW (0V) you have around 2.5V at the Arduino RX pin (5V over two 1kΩ resistors = 2.5V in the center tap - see here).
Since 2.5V is neither within the Arduino's HIGH nor LOW voltage ranges (which are more than 3.5V for HIGH and less than 1.5V for LOW when running from 5V) the input is completely ignored.
The 3.3V transmitted by the Bluetooth module is a little under the official threshold for a HIGH signal on an Arduino, but in practice, it usually is detected fine. So remove the resistor network from the Bluetooth's TX pin and connect it directly to the Arduino. Since the input threshold voltage is a function of the supply voltage (0.7 * Vcc) it depends very much on your power supply as to whether it will work reliably or not. If you find it doesn't, you should use some upward level shifting.  There are simple MOSFET based bi-directional level shifters available cheaply that are a better solution than resistors, and will allow proper operation in both directions, shifting a high voltage to a low one and a low voltage to a high one. These are good for lower frequency communications such as UART. If you should need higher frequency, or you find a simple MOSFET based shifter isn't working for you then a 74HCT08 or similar chip (be sure to use the HCT range not the HC range) or a dedicated level shifting chip may be in order.

For a reliable solution you must move the Bluetooth device to pins other than digital 0 and 1 and use a software serial instance to communicate with it.
Digital pins 0 and 1 are for communication with the host computer, and the USB-serial chip is permanently wired to them, even if you are not trying to communicate with the computer.
There is on many boards a series resistor which allows an external circuit to overpower the USB-serial, but your mis-conceived level shifter has enough resistance itself that it is not able to do this.
Fortunately, while ill-conceived the level shifter is still wired with the idea that the Arduino side is the higher voltage one, so while it adds some load to the Bluetooth, it mostly just adds series resistance.  If the Arduino pin were an ordinary high-impedance once, this would probably still work.  But instead it is one which the USB-serial is trying to control through its own comparable value resistor, and the result is an invalid logic level or a tug-of-war which the USB-serial wins.


text:
Reading from DHT22 with Arduino, powered by external source
I have the following situation. When I power my DHT22 with the 3.3V from the Arduino UNO (and Ground it there), then I can read the data perfectly fine using the DHT library from Adafruit.
However, when I connect the DHT22 to my own external power supply (and respective ground), it fails. The reason for using this external power supply is so I can hook it up to a ESP8266 later.
The power supply I build uses a 5V adapter, then an LD33V converter and (just for experimentation) an 100nF capacitor to reduce any noise on the line.
I measured this external power supply and it indeed gives off 3.3V after the LD33V. I check the datasheet of the LD33V and it should be able to 'give' 5mA, whereas the DHT22 needs less than 1mA for operation.
I don't know where to look at this moment. Can someone point me in the right direction? Much appreciated :)
Cheers

Have you connected the external power supply ground to the Arduino's ground? If not, one is "floating" with respect to the other. But they need to have the same reference - the ground sides of their power supplies.

Ah, I edited the question to make that a bit more clear. When I power with the arduino, I use the ground provided by the arduino. When I use my own power supply, I use the ground provided by that. So to my idea nothing is 'floating' if I understand you correctly

When I now attach the signal pin of the DHT22 to my Arduino, and power the DHT22 with my own power supply (and ground it there) AND connect a ground to the arduino. THEN I can measure the temperature on the arduino. Thanks

Perfect. "Floating" just means the two grounds are not (necessarily) at the same level. "... AND connect a ground to the arduino" is exactly what had been missing.


text:
DT-06 WIFI. How to program with Arduino Uno
I have a DT-06 wireless WiFi. I can connect using my phone but I cannot access 192.168.4.1/status.html or /wifi_set.html like in the tutorial
I put this module in wiring with Arduino Uno on 5v. I notice that the LED is low lighting until I put pin state in GND. Then I get full power red led. I put RX module to TX Arduino and TX module to RX Arduino but i can not access it using Arduino.
How can I program this module or how can I access? Any tutorial links are welcome.
Thanka. Sorry for my English.
L.E.
Module RX - Arduino TX
Module TX - Arduino RX
Module VCC - Arduino 5v
Module GND - Arduino GND
Module STATE - GND
My module has a red led on it. This led is low lighting until i put pin STATE in GND. After that the red led is full lighting.
After i put VCC and GND i can "see" my module using my phone wireless connection

I didn't really understand, what LED you mean exactly. Also provide a schematic or wiring diagram, so that we can see, how you connected the DT-06. It sounds, like as if you use a digital output pin to provide it with power. This would be absolutely wrong.

If you refere to a tutorial, please provide a URL to it.

Please check my edit in the question

Are you wiring it to Arduino pins 0 & 1? These are hard-wired to the other processor on the Arduino board that handles USB to/from your PC. There may be interference with the DT-06 unless you disconnect from your PC after upload. But then you'll need an alternate source of power to the Arduino.
You can pick another pair of pins and use the SoftwareSerial library (up to 9600 baud) to talk to the DT-06. Make sure Arduino and the DT-06 use the same baud-rate. You may have to experiment to find what baud-rate the device has now, in order to set it to 9600.
Update:

Do i have to use any resistence?

Two sites I looked at described the DT-06 voltage requirement as:
"Working voltage: 4.5V~6.0V, TTL working voltage: 3.3V (compatible with 5.0V);", so you should be OK without voltage divider resistors.

And what settings to make in arduino IDE before uploading code?

You won't need to change your IDE to upload code to the Uno.

Can you please make me a wiring scheme and also tell me the arduino code?

This discussion talks about using SoftwareSerial and setting the baud-rate. It was written about an ESP8266 module but most of it will apply to your module, too.

Do i have to use any resistence?

And what settings to make in arduino IDE before uploading code?


text:
ESP send data to Arduino
I'm trying to send data from my esp to my arduino using serial using the following codes :
esp :
server.on("/drive",HTTP_GET, handleDrive);
void handleDrive()
{
    server.send(200,"text/html", "Drive!");
    String sendToArduino = "";
    for (int i=0;i<server.args();i++)
    {
   sendToArduino = sendToArduino+server.argName(i)+"="+sendToArduino.arg(i)+"&";
    }
    Serial.println(sendToArduino);
}

and on arduino :
Serial.begin(9600);
esp8266.begin(115200);

if (esp8266.available())
{
   String  readString="";
   while (esp8266.available())
   {
     delay(2);
     char c = esp8266.read();
     readString += c;
   }
}

but when i send data from esp to arduino i get it with "noise"
Ex : "variable1=1234"   i recive it on arduino "variab@e=12"
What can i make to make sure that what i send is same in arduino ?

Two things: 1. read the serial properly (https://majenko.co.uk/blog/reading-serial-arduino), and 2. what baud rate are you communicating at?

Serial.begin(9600);  esp8266.begin(115200);   in arduino

Sorry, what is that delay(2)? You send one byte from the ESP in roughly 87us, and force to read it once every 2ms?

Firstly you need to write a more reliable serial reading routine on the Arduino. As it stands your routine is lucky you even get what you do. You need to write a routine that doesn't care about time, but instead cares about the terminating character of the line you are receiving.

Here is an article I wrote all about it.

Secondly, you cannot communicate reliably using SoftwareSerial at 115200 baud.  While the Arduino is capable of receiving a byte at that baud rate using bit banging, there typically isn't enough time between successive bytes to allow the Arduino to store what it has just received, and so it starts receiving partway through the next byte, corrupting both it and the following byte. That's the cause of the corruption you are seeing.
You should either slow down the baud rate (9600 is a good choice), or send the data one byte at a time and add a delay between each byte (somewhat hacky...).


text:
Uploading Sketches from Windows Command Line
The resources I've found regarding the Command Line interface seem to be out of date so I was hoping to find someone with experience using it. I'm currently running Arduino 1.5.6-r2 BETA on Windows 8.1 looking to upload code to an Arduino Leonardo.
I'm trying to create a script(Powershell) file that I can just use to upload code without user intervention. The actual upload part using Arduino CLI is just straight not working for me. If my understanding is correct I should have it already due to my version of the Arduino IDE but none of the functionality works so I'm doubting myself.
Source: https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc
This is the command I'm attempting to run from Windows Command Prompt:
C:\Program Files (x86)\Arduino\arduino.exe --board arduino:avr:leonardo --port COM3 --upload C:\Users\Dev\Documents\Arduino\myProject\myProject.ino

Any insight into what I'm missing would be very much appreciated!
EDIT: Additionally, if anyone could provide information regarding the build/upload process which could lead me to a solution from within C# that would be even more amazing.

Personally, I'd compile to a hex file (or even read it back out of the board) and use avrdude, rather than rebuilding from source each time, unless doing a fresh build is part of your goal.  At any rate, do you get any error output from your attempt?

@ChrisStratton Basically I'll be downloading updated versions of the code via Powershell, so I'm trying to figure out how to then deploy that code without having to manually go through the process using the IDE. If compiling to hex and using avrdude is a simpler solution capable of working for this, that fits my needs as well.

Turns out that the Ignoring Bad Library Name error that I had been receiving regardless of if I ran Arduino IDE through command line or standalone was the issue. For whatever reason it was blocking the script with a dialog that then failed the upload regardless of if I manually moved through the popup.
Final setup for those looking for this in the future:
Windows 8.1 x64 with Arduino IDE version 1.5.6-r2(I will revert to 1.0.5 and test with that, and report results) using a Leonardo board. Command is as follows:
Working Directory: C:\Program Files (x86)\Arduino
arduino --board arduino:avr:leonardo --port COM14 --upload C:\Users\Dev\Documents\Arduino\sketch_jun06a\sketch_jun06a.ino

EDIT: As promised, I attempted this with version 1.0.5-r2 and was unsuccessful. Potentially a 1.5.+ feature.

I recommend you to look into cross-platform tool named PlatformIO. It has support for Windows OS and doesn't require Arduino IDE or any tools.
From Get Started let's install platform and setup environment for your Arduino Leonardo:
Install new development platform
> platformio platforms install atmelavr

Initialize new PlatformIO based project
> cd path\to\empty\directory
> platformio init
# Project has been initialized!
# Please put your source code to `src` directory, external libraries to `lib`
# and setup environments in `platformio.ini` file.
# Then process project with `platformio run` command.

Setup environments in the Project Configuration File platformio.ini
[env:my_leonardo_board]
platform = atmelavr
framework = arduino
board = leonardo

Process the project’s environments
> platformio run --target upload

P.S: What is interesting, this tool allows you to manage libraries via CLI and then you can build Arduino-based source code with single line
#include <%HEADER_FILE_OF_INSTALLED_LIB>

You should point out that you are the author of PlatformIO