text:
How to retrieve the data type of a variable?
I am using Arduino and I would like to know if there is a function that returns the data type of a variable. That is, I would like to run something as like the following:
// Note: 'typeof' is a sample function that should return the data type.
Serial.println(typeof(myVar));

Why do you need to do this? the type of the variable should be known since you declared it

@sachleen Not true. Arduino Reference info is infamous for not telling you what function return types are. I have to define as auto, then use a bunch of function overloads to find out. RTTI would be simpler to find out.

In a typical C++ program, you would use the typeid operator, like this:
std::cout << typeid(myVar).name();

However, that requires a compiler feature called Runtime Type Information (RTTI). It's disabled in the Arduino IDE, presumably because it tends to increase the runtime memory requirements of the program.
You can get more information about the resource cost here: https://stackoverflow.com/questions/579887/how-expensive-is-rtti
Any fully-featured C++ compiler will definitely support RTTI though. If you want to try using a 3rd party IDE (such as Eclipse with the Arduino plugin) then you could easily enable it. It's probably not worth the hassle just for that though.

Alternative
A higher-performing (but less flexible) solution would be to use a traits class approach. This involves some funky template meta-programming:
// Generic catch-all implementation.
template <typename T_ty> struct TypeInfo { static const char * name; };
template <typename T_ty> const char * TypeInfo<T_ty>::name = "unknown";

// Handy macro to make querying stuff easier.
#define TYPE_NAME(var) TypeInfo< typeof(var) >::name

// Handy macro to make defining stuff easier.
#define MAKE_TYPE_INFO(type)  template <> const char * TypeInfo<type>::name = #type;

// Type-specific implementations.
MAKE_TYPE_INFO( int )
MAKE_TYPE_INFO( float )
MAKE_TYPE_INFO( short )

You can add MAKE_TYPE_INFO(..) lines for any type you want, including the names of custom classes. You could then use it like this:
int myVar = 17;
Serial.println( TYPE_NAME(myVar) );

Anything you don't define using MAKE_TYPE_INFO(..) will show up as "unknown".
That's some fairly advanced stuff in there, so I won't try to explain how it all works here. There are various tutorials on the web though about C++ template programming if you're interested.
EDIT: It's worth noting that the typeof operator isn't standard C++, but is supported by a few compilers, such as GCC. It's basically an older equivalent of decltype, which appears in the C++11 standard.

very informative and thorough answer! would appreciate more of this kind

I use a simple stupid approach...
// serial print variable type
void types(String a) { Serial.println("it's a String"); }
void types(int a) { Serial.println("it's an int"); }
void types(char *a) { Serial.println("it's a char*"); }
void types(float a) { Serial.println("it's a float"); }
void types(bool a) { Serial.println("it's a bool"); }

This is the concept of function overloading where multiple functions with different parameter types are created but with the same function name. During run time, the function matching the right number of arguments and argument type(s) will get called. Hope this explanation helps.

Could you expand your answer a little, briefly explaining how it works?

i had to rewrite it by hand because copy paste led to issues i didn't understand. After retyping it by hand just as it is to the sketch it worked like a charm. Quite usefull...

Simple, easier to understand without knowledge of templates. Could be expanded to return enum of type.

Building on @snakeNET's answer (which I regard as function overload rather than polymorphism)...
A more generic way would be to pass in a pointer to Print, allowing any Print related class to be used (not just Serial); also pass objects by reference e.g.
void types(Print* p, const String&) { p->print("it's a String"); } // for each type
...
Serial.print("Type is "); types(&Serial, myStr); Serial.println();

Note that I has changed 'println' to 'print'; again, making it more generic.

I think the meaning of the term polymorphism has morphed somewhat over the decades to now include function overloading outside of OOP classes as well as overloading of member functions within classes. When I started learning programming, it only referred to overriding of virtual class methods in descendant classes.

I tested the template form, the long-hand form, and the __PRETTY_FUNCTION__ macro and got different results. See the last two rows of the table for the differences.
Template Form 1
Attribution: Peter Bloomfield
MAKE_TYPE_INFO( bool )
MAKE_TYPE_INFO( bool* )
MAKE_TYPE_INFO( char )
MAKE_TYPE_INFO( char* )
MAKE_TYPE_INFO( double )
MAKE_TYPE_INFO( double* )
MAKE_TYPE_INFO( float )
MAKE_TYPE_INFO( float* )
MAKE_TYPE_INFO( int )
MAKE_TYPE_INFO( int* )
MAKE_TYPE_INFO( short )
MAKE_TYPE_INFO( short* )
MAKE_TYPE_INFO( String )
MAKE_TYPE_INFO( String* )
MAKE_TYPE_INFO( char[5] )
MAKE_TYPE_INFO( char(*)[5] )

Long-Hand Form
Attribution:

SnakeNET
brewmanz
Tweaked by me to be more generic.

const char* TypeOf(const bool&)   { static const char type[] = "bool";    return type; }
const char* TypeOf(const bool*)   { static const char type[] = "bool*";   return type; }
const char* TypeOf(const char&)   { static const char type[] = "char";    return type; }
const char* TypeOf(const char*)   { static const char type[] = "char*";   return type; }
const char* TypeOf(const double&) { static const char type[] = "double";  return type; }
const char* TypeOf(const double*) { static const char type[] = "double*"; return type; }
const char* TypeOf(const float&)  { static const char type[] = "float";   return type; }
const char* TypeOf(const float*)  { static const char type[] = "float*";  return type; }
const char* TypeOf(const int&)    { static const char type[] = "int";     return type; }
const char* TypeOf(const int*)    { static const char type[] = "int*";    return type; }
const char* TypeOf(const String&) { static const char type[] = "String";  return type; }
const char* TypeOf(const String*) { static const char type[] = "String*"; return type; }
//const char* const TypeOf(const char[5])    { static const char* type = "char[5]";    return type; }  // Decays to char* so generates compiler redefinition warning.
const char* const TypeOf(const char(*)[5]) { static const char* type = "char(*)[5]"; return type; }

Template Form 2: __PRETTY_FUNCTION__ Macro
Attribution:

Original String version by Vladimir Talybin
Tweaked char array version by me.

Using String
template <class T>
String type_name(const T&)
{
    String s = __PRETTY_FUNCTION__;
    int start = s.indexOf("[with T = ") + 10;
    int stop = s.lastIndexOf(']');
    return s.substring(start, stop);
}

Using char array
This variation has lower memory requirements.
template <typename T>
char* type_name(const T&)
{
    char* pf = __PRETTY_FUNCTION__;
    char* begin = strstr(pf, "[with T = ") + 10;
    char* end = strrchr(pf, ']');
    *end = 0;
    return begin;
}

Test Code
bool b = false;
char c = 'a';
double d = 1.2;
float f = 3.4;
int i = 5;
String s = "6789";
char chars[] = "1234";

Serial.println(F("TypeOf() Test"));
Serial.println(TypeOf(b));
Serial.println(TypeOf(&b));
Serial.println(TypeOf(c));
Serial.println(TypeOf(&c));
Serial.println(TypeOf(d));
Serial.println(TypeOf(&d));
Serial.println(TypeOf(f));
Serial.println(TypeOf(&f));
Serial.println(TypeOf(i));
Serial.println(TypeOf(&i));
Serial.println(TypeOf(s));
Serial.println(TypeOf(&s));
Serial.println(TypeOf(chars));
Serial.println(TypeOf(&chars));

Serial.println(F("TYPE_NAME() Test"));
Serial.println(TYPE_NAME(b));
Serial.println(TYPE_NAME(&b));
Serial.println(TYPE_NAME(c));
Serial.println(TYPE_NAME(&c));
Serial.println(TYPE_NAME(d));
Serial.println(TYPE_NAME(&d));
Serial.println(TYPE_NAME(f));
Serial.println(TYPE_NAME(&f));
Serial.println(TYPE_NAME(i));
Serial.println(TYPE_NAME(&i));
Serial.println(TYPE_NAME(s));
Serial.println(TYPE_NAME(&s));
Serial.println(TYPE_NAME(chars));
Serial.println(TYPE_NAME(&chars));

Serial.println(F("type_name() Test"));
Serial.println(type_name(b));
Serial.println(type_name(&b));
Serial.println(type_name(c));
Serial.println(type_name(&c));
Serial.println(type_name(d));
Serial.println(type_name(&d));
Serial.println(type_name(f));
Serial.println(type_name(&f));
Serial.println(type_name(i));
Serial.println(type_name(&i));
Serial.println(type_name(s));
Serial.println(type_name(&s));
Serial.println(type_name(chars));
Serial.println(type_name(&chars));

Results

TypeOf()
TYPE_NAME()
type_name()

bool
bool
bool

bool*
bool*
bool*

char
char
char

char*
char*
char*

double
double
double

double*
double*
double*

float
float
float

float*
float*
float*

int
int
int

int*
int*
int*

String
String
String

String*
String*
String*

char*
char[5]
char [5]

char(*)[5]
char(*)[5]
char (*)[5]

Some Conclusions

TypeOf() has an issue with a decaying pointer.
TypeOf() and TYPE_NAME() have to have individual definitions with long-hand form or MAKE_TYPE_INFO.
type_name() uses the __PRETTY_FUNCTION__ macro to automatically get the type name within the template function, therefore there is no need to individually define the different types.
Template Form 1 has the lowest memory requirements.

Questions

Since Template Form 2 has higher memory requirements than Template Form 1, how could it be converted from Form 2 to Form 1?
How would a static const char * be initialised from a substring of a char array obtained from the __PRETTY_FUNCTION__ macro and passed as a template argument at compile-time?

Something like this pseudo code?
static const char * name = substr(__PRETTY_FUNCTION__, begin, end);

Perhaps this constant expression which can be assigned to a template struct member at compile-time? (I used a for loop because strstr and strrchr are not constexpr.)
template <typename T>
constexpr char* type_name(const T&)
{
    char* pf = __PRETTY_FUNCTION__;
    char* begin;
    char* end;
    begin = end = pf;
    bool found_open_square_bracket = false;
    for (; *pf != 0; pf++)
    {
      if (!found_open_square_bracket && *pf == '[')
      {
        begin = pf + 10;
        found_open_square_bracket = true;
      }
      if (*pf == ']')
      {
        end = pf;
      }
    }
    *end = 0;
    return begin;
}

Note that: 1. When you pass an array as a function argument, it decays to a pointer to its first element. 2. char*[5] is an array of pointers, whereas &chars is a pointer to an array.

@Juraj, Sorry. I thought the first paragraph covered it in the context of this thread. I'll make it clearer.

It is more a limitation of  C÷+ version in Arduino. On PC I would return std::string_view in this case. On Arduino you may return a struct of const char* and size_t. This will solve you mem issue.

I would also split the template part and parsing part in 2 functions to make compiler generate less code for each requested type.

There also a trick using compiler predefined macro. The advantage is it can print any type.
template <class T>
String type_name(const T&)
{
    String s = __PRETTY_FUNCTION__;

    int start = s.indexOf("[with T = ") + 10;
    int stop = s.lastIndexOf(']');

    return s.substring(start, stop);
}

Use it like this
double pi = 3.14;
const char* str = "test";

Serial.println(type_name(pi));
Serial.println(type_name(str));

EDIT:
Some improvements based on tim's analyze.
First I have a comment on variation that has lower memory requirements. __PRETTY_FUNCTION__ is a literal string (a constant) that should not be changed. So my const version that do not use heap is following.
template <size_t N>
const char* extract_type(const char (&signature)[N])
{
    const char* beg = signature;
    while (*beg++ != '=');
    ++beg;

    const char* end = signature + N;
    for (; *end != ']'; --end);

    static char buf[N];
    char* it = buf;

    for (; beg != end; ++beg, ++it)
        *it = *beg;
    *it = 0;

    return buf;
}

template <class T>
const char* type_name(const T&)
{
    return extract_type(__PRETTY_FUNCTION__);
}

A less safe but more efficient version using the fact that offset to type we want extract is a constant (always the same). If function signature changes (like put it in a namespace) the offset will change too. But come on, set it once, write a comment and it will work forever :).
template <size_t N>
const char* extract_type(const char (&signature)[N])
{
    const char* beg = signature + 42;
    const char* end = signature + N - 2;

    static char buf[N - 43];
    char* it = buf;

    for (; beg != end; ++beg, ++it)
        *it = *beg;
    *it = 0;

    return buf;
}

template <class T>
const char* type_name(const T&)
{
    return extract_type(__PRETTY_FUNCTION__);
}

While above is ok ofcourse it can be improved further. Here is a my version of constexpr function mentioned by @tim. It uses constant offset as above to keep it short. This code generates only extracted string of type, the proof is here.
#include <utility>

template <class T, std::size_t... I>
const char* type_name(std::index_sequence<I...>)
{
    static constexpr char name[] = { __PRETTY_FUNCTION__[I + 60]..., 0 };
    return name;
}

template <class T>
const char* type_name(const T&)
{
    return type_name<T>(
        std::make_index_sequence<sizeof(__PRETTY_FUNCTION__) - 44>());
}

The minimum requirement for this is C++14 because of sequence traits. These can be re-implemented (see definition here) to adapt it to C++11.

That's great, but int stop = s.lastIndexOf(']'); is better because some types have [] in them.

@tim True, thank you! Will change it.


text:
Controlling Arduino through MATLAB?
I had a Roboteq motor controller, but it wasn't fast enough. I'm hoping Arduino will be faster.
Supposing that the transfer is fast enough for my purposes, how can I read angular velocity, given that I have an encoder? Honestly, I'm not totally sure how to hook it up to an Arduino board.
I can't find a name for my encoder... This is the datasheet though.
Can anyone help me with how to hook it up, and what commands to use in MATLAB?
Thanks.

Do all the processing on the Arduino, and supply the results to Matlab over serial.
I'm not 100% sure about your particular encoder, but generally encoders talk in "Grey Code".  This is a series of bits which allow you to know the direction the encoder has turned.
There are a number of libraries and tutorials for Arduino dealing with encoders.

http://playground.arduino.cc/Main/RotaryEncoders
http://www.hobbytronics.co.uk/arduino-tutorial6-rotary-encoder

The one I use comes from here:

http://www.pjrc.com/teensy/td_libs_Encoder.html

It would be best to use a library with interrupt routines on pins 2 & 3 (these support external hardware interrupts), so whenever the pin gets a signal from the encoder, the Arduino can act on it immediately.  If you do not use these pins, and have time-consuming processing in the loop(), it's easy to miss 'ticks' from the encoder.
#include <Serial.h>

// Rotary Encoder (Interrupt Driven)
#define ENCODER_PIN_A       2 /* must be pin2 for interrupt */
#define ENCODER_PIN_B       3 /* must be pin3 for interrupt */
#define ENCODER_OPTIMIZE_INTERRUPTS
#include <Encoder.h>
Encoder encoder(ENCODER_PIN_A,ENCODER_PIN_B);

void setup()
{
    Serial.begin(115200);
    // Gentlemen, start your encoders
    pinMode(ENCODER_PIN_A,INPUT_PULLUP);
    pinMode(ENCODER_PIN_B,INPUT_PULLUP);
}

void loop()
{
    unsigned long start_time = millis();
    Serial.println("Dear Matlab...");

    while (1)
    {
        unsigned long now = millis();
        unsigned int encoder_value = encoder.read();

        // Do whatever angular velocity processing is needed here
        unsigned long ticks_per_ms = encoder_value / (now - start_time);

        // Send the result back to Matlab
        Serial.println(ticks_per_ms,DEC);
    }
}

I think for your encoder the "A" and "B" outputs are where the grey code will be coming from.  These would be connected to Arduino pins 2 & 3.
Obviously the code above is not a complete solution, and needs to take care of edge-conditions like overflow of millis() after some time, etc. etc.

Hmm... Interesting. Do you know how many iterations per second that could run? I'm just afraid that a serial connection would be too slow. Could I do it over USB somehow?

115200 baud gives you over 10,000 bytes per second.

source: Stack Exchange

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

sort: votes


text:
Use UTP Cable to transmit/receive data?
I was wondering if it was possible to use the utp port of a computer/laptop to transmit and receive data to an external device?
If you take a cat5 cable there are 8 wires, so lets say you have an Arduino would it be possible to use those wires for serial communication? If so how can I program the utp port? And is there a specification for this (for example use wire x for output and wire y for input..)
Thanks in advance,
Regards
Ps: I had no idea on which sub.stackexchange to ask it hopefully it suits here.

There is no such thing as a "UTP port".

@Vazquez-Abrams Sorry didn't know that, I assumed the ethernet port in a computer was called the utp port. How do you call it then?

You call the Ethernet port the "Ethernet port". Because it talks Ethernet.

By "UTP", I'm assuming you're referring to Unshielded Twisted Pair. The shielding and twisting aren't really relevant, because they're just physical characteristics of the cable itself. They don't have any bearing on the sender or receiver.
The salient point about UTP is that it uses differential transmission. That is, the data is sent down two wires at the same time, but one is inverted. The receiver uses the difference between the two signals to reconstruct the original data, eliminating any interference which may have been introduced en route.
Assuming the voltage level is safe (0-5v for most boards), you could connect each wire directly to an analog pin on the Arduino. If you read both continuously, and apply suitable thresholds/triggers in software to identify level changes, you could probably reconstruct the original signal.
It's definitely not ideal though, as ADCs are comparatively slow, and you would never be able to read both at exactly the same time. That means the transmission would have to be quite slow in order to work. The exact speed would depend on how quickly your program could poll the ADCs and process the result.
It would be much better to use some external circuitry to handle the differential signal. It could then produce a nice clean digital output which you could feed directly to any input on the Arduino. It should be able to run a lot faster, and leave your program free to do other things. Any good electronics vendor will stock a variety of ICs which would do the job, depending on your exact requirements.
Setting up your computer/laptop as a sender is a totally separate issue though. Many different ports use differential signals in some form, including ethernet, USB, and RS-232 (old DE-9 serial ports). Unfortunately, it would be very difficult to get direct control of their signal lines. You would almost certainly have to write your own device drivers, which is a pretty huge undertaking.
If you want to send serial data from your computer to an Arduino, the easiest way is just USB-to-TTL conversion. Most Arduino boards have this built-in, connected directly to the hardware serial lines on the microcontroller (which is how you upload programs/sketches). Alternatively, you can get external cables which do the conversion, and you can connect it manually to other pins, processing it using software serial.

Thanks for this answer, so I can't (easily) use that cable to communicate with my computer and an external circuit?

If you're using it as an Ethernet cable, then you can connect your Arduino to a network (usually via a switch/router). You would either need an Ethernet shield for your Arduino though, or an Arduino board which has Ethernet built-in. You can then program the Arduino to send/receive network traffic, using the Ethernet library.

At best you can connect at 10BaseT, which is the slowest implementation available for UTP. I believe I've seen a project in Elektor doing just that with only an AVR to do raw Ethernet. But you can't control the interface pins directly. The signals on ethernet are AC by nature because of the output transformer.

The Elektor article is called "Software-defined NIC, Ethernet-broadcasting op een AVR" (110733). The article was published in NL in April 2013, but I believe it was published earlier in other regions. It uses an ATmega644 clocked at 20MHz and is used with an old webcam to send images to a PC (approx. 2 images per second).

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


text:
Using SoftwareSerial for the serial monitor
Most programs follow this route: They have a Serial.begin() for the serial connection between PC and Arduino (the serial monitor) and they use SoftwareSerial for a device.
Can you go the other way around? Can you use SoftwareSerial for the communication between PC and Arduino, and Serial for a device?

Short answer: no.
Pins 0 and 1 an an Uno are directly wired to the PC communication chip. You could make a board that was wired differently and connected SoftwareSerial to the PC, but you would have to switch it back to pins 0 and 1 when uploading to the arduino somehow.
On an arduino leonardo "Serial" for communicating with PC over USB is different from "Serial1", which is connected to pins 0 and 1 on the board. You can use both simultaneously, so if you really need to use hardware serial and PC comms at the same time, I recommend you buy a leonardo.

But of course, you can omit the communication with the pc and have the hardware serial dedicated for communication with a device correct? And use the softwareserial for communicatoin with another device.

Yes that is correct, If you don't communicate with the PC hardware serial can be used for anything you please, and at the same time as Software Serial.

Yes you can. If you use a USB FTDI type cable to connect your computer to the SoftwareSerial pins, you can use a terminal emulator program (HyperTerm, putty, etc) to communicate with the Arduino.


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

It's explain in the datasheet.

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

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

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

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

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


text:
Auto acknowledge failed with nRF 24L01+ and Arduino
My transceivers are running fine. I've written a few code and got them running. Then I decided to check the auto acknowledgement feature wherein we can return data back to the sender WITHOUT manually changing the radio modes on both units. But I find that the serial monitor always shows "failed to transmit". Why is this happening, because otherwise they work fine?
I am using maniacbug's RF24master library.
The Tx code is:
#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>

int msg[1] = {1};
int rec[1] = {0};
bool stat = true;
RF24 radio(9,10);
const uint64_t pipe[1] = {0xF0F0F0F0E1LL};

void setup()
{
  Serial.begin(57600);
  radio.begin();
  delay(1000);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.openWritingPipe(pipe[0]);
  radio.setRetries(15,15);
 }
void loop()
{
  if(stat)
  {
    radio.stopListening();
    bool ok = radio.write(msg,sizeof(msg));
    delay(100);
    if(ok)
    {Serial.println("transmitted successfully !!");}
    else
    {Serial.println("faileed to transmit");}
    msg[1]++;
    if(msg[1]>=200)
    {msg[1]=1;}
    stat = false;
    //delay(20);
  }
  if(!stat)
  {
    if(radio.isAckPayloadAvailable())
    {
      radio.read(rec,sizeof(rec));
      Serial.print("received ack payload is : ");
      Serial.println(rec[1]);
      stat = true;
    }
  }

}

and the Rx part is:
#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
const uint64_t pipe = 0xF0F0F0F0E1LL;
RF24 radio(9,10);
int rec[1] = {0};
int ack[1] = {1};
void setup()
{
  Serial.begin(57600);
  radio.begin();
  delay(100);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.openReadingPipe(1,pipe);
  radio.startListening();
  radio.setRetries(15,15);
}
void loop()
{
  if(radio.available())
  {
    Serial.println("payload available....");
    bool ok = radio.read(rec,sizeof(rec));
    if(ok)
    {
        Serial.println("message received !!");
        Serial.print("integer got is : ");
        Serial.println(rec[1]);
        radio.writeAckPayload(1,ack,sizeof(ack));
    }
    else
    {Serial.println("failed to receive the message");}
  }
}

Note that you need to provide the AckPayload before you receive a message, not after.

no,no we have to provide the ack payload after we receive a msg.my code is buggy.i wrote a new and better one and it is working !!! btw thanks for checking out the ques!!

If you found a solution to your question, please post it as an answer and accept it, so that people who have a similar problem an benefit from your experience.

my blog is up and running. the auto ack code and discussion is here http://shantamraj.wordpress.com/2014/07/19/exploring-the-auto-ack-feature-of-the-transceiver/ @jfpoilpret .

@jfpoilpret Please post the answer and accept it here.

I'm voting to close this long abandoned question because the issue has never been clearly stated, and the asker seems to have long since found their own solution and published it on their blog.

To achieve that you have to do the following -
if ( radio.available() ) { // make sure the read will succeed
radio.writeAckPayload( 1, buf, len ); // prep the ack payload
radio.read( &got_time, sizeof(unsigned long) ); // also shunts out ack payload
}

So your program finally becomes -
#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
int msg[1] = {1};
int rec[1] = {5};
bool stat = true;
RF24 radio(9,10);
const uint64_t pipe[1] = {0xF0F0F0F0E1LL};

void setup()
{
  Serial.begin(57600);
  radio.begin();
  delay(100);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  radio.stopListening();
  radio.openWritingPipe(pipe[0]);
  radio.setRetries(15,15);
 }
void loop()
{
if(stat)
{
    if(radio.write(msg,sizeof(msg)))
    {
      Serial.print( msg[0] );
      Serial.println("...tx success");
      if(radio.isAckPayloadAvailable())
      {
        radio.read(rec,sizeof(int));
        Serial.print("received ack payload is : ");
        Serial.println(rec[0]);
      }
      else
      {
        stat = false; //doing this completely shuts down the transmitter if an ack payload is not received !!
        Serial.println("status has become false so stop here....");
      }
      msg[0]+=3;;
    if(msg[0]>=100)
    {msg[0]=1;}
    }
 }
}

And the RX part becomes -
#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
const uint64_t pipe[1]= {0xF0F0F0F0E1LL};
RF24 radio(9,10);
int rec[1] = {2};
int red;
void setup()
{
  Serial.begin(57600);
  radio.begin();
  delay(100);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  radio.openReadingPipe(1,pipe[0]);
  radio.startListening();
  radio.setRetries(15,15);
}
void loop()
{
  if ( radio.available() ) {
    radio.writeAckPayload( 1, rec, sizeof(int) );
    radio.read( &red,sizeof(red) );rec[0]+=2;
    Serial.print("integer got is : ");
    Serial.println(red);
}
}

Know more about it at the following pages -
https://shantamraj.wordpress.com/2014/07/19/exploring-the-auto-ack-feature-of-the-transceiver/
https://shantamraj.wordpress.com/2014/11/30/auto-ack-completely-fixed/


text:
HC-0# Bluetooth module questions
I've been playing with the HC-06 BT module lately, but now I want to do more with it and I'm not sure how to. I was wondering if it's possible to get signal strength from the module, or would I have to purchase another HC-0# module to do so? Also the HC-05, can initiate connection if I'm understanding documentation right, and return available devices in the area?

I was wondering if it's possible to get signal strength from the module

No, it doesn't appear so from the data sheet / AT command list.

Also the HC-05, can initiate connection if I'm understanding documentation right, and return available devices in the area?

Yes, and it can get the signal strengths.  You should be able to get an HC-05 module on a breakout board from Ebay for less than $10 delivered.  There's also a method to update the HC-06 firmware to be an HC-05 but it's probably easier for you to buy one.


text:
I cannot find the I2C device by scanning
I've been trying to get a LCD I bought from deal extreme to work for some time with my ATTiny85 chip. It should be capable.
I've tried googling the device but there is no proper documentation, so I figured the best way to get the address is to scan for it. How ever, the code below does not work :( any pointers? Anyone else who has gotten this I2C LCD display to work with Arduino?
As I have no other output then the screen, the thought behind the code is to scan for devices and then when it finds one (the LCD is the only one connected to the bus) should then print the address :)
I only have a serial programmer and attiny85 chips, so I have no way to bring it to a full Arduino UNO or whatever for further debugging.
#include <TinyWireM.h>
#include <LiquidCrystal_I2C.h>

void setup()
{
  TinyWireM.begin();
}

void loop()
{
  byte error, address;

  for(address = 1; address < 127; address++ )
  {
    TinyWireM.beginTransmission(address);

    error = TinyWireM.endTransmission();

    if (error == 0) break;

    delay(5000);
  }

  LiquidCrystal_I2C lcd(address, 16, 2);

  lcd.init();
  lcd.backlight();
  lcd.clear();

  lcd.setCursor(0, 0);
  lcd.print("Hello World - " + address);
}

I2C LCD: http://www.dx.com/p/iic-i2c-2-5-blue-screen-lcd-display-module-for-arduino-green-black-266170#.U6f_B_l_vIc

I'd double check your connections then. Is the module getting power? Are you using pull ups?

Why has this question been downvoted? I'm curious, because it seems a legitimate problem the user is having, he has shown research, and although it isn't an arduino chip he's using, he's obviously using the arduino library to compile the hex file. He didn't post the question to Arduino SE, it's been migrated here. I don't mind downvoted questions for crap questions, but when there is at least an honest attempt, why not post constructive comments as to how he could improve it.

I'm not sure on your program, but I bought a LCD display from Deal Extreme. I use the following address to communicate with the display:
LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27

It seems as that is the correct address for the LCD.


text:
Arduino and XBee Series1
I have actually reap 3 numerical values (3 sensors) from a remote XBee module and then manipulate these 3 signal with an Arduino card attached to another XBee module. To do this, I chose to use the IO line passing because it proved the easiest. My problem is this: for the XBee transmitter, I set:
ATID 3001
ATDL 2
ATMY 1
ATIU 1 / / to activate the IO option
ATD0 3 / / where is plugged a pushbutton
ATD1 3 / / where is plugged another pushbutton
ATD2 3 / / where is plugged proximity sensor (presence)

For the XBee receiver (the one connected with the arduino board):
ATID 3001 ATDL 1 ATMY 2 ATIA 1
ATD0 4
ATD1 4
ATD2 4

Where I'm stuck is on the Arduino programming. Which command is used to determine the change of state of xbee remote? because I want to know if the states of the sensors on input are high or low.

possible duplicate of communication xbee and arduino

There are two ways this could be tackled:

physically through connections between the xbee and arduino and read the xbee pins directly (I've never done this, and it comes down to your shield supporting it). Each of the desired output pins of the receiving xbee would be tied to a GPIO pin of the arduino. Alternatively,
serially using AT commands via the serial connection.

I have never worked with series one, but essentially:

setup a serial connection to your arduino
send the desired AT command requesting the pins value
read the serial port response

Make sure to read the manual for the series 1 xbees for the right AT commands and in how to interpret the results. Register at digi and download the datasheet.
Also, just realise reading the xbee data is going to be different depending on how you have the xbee setup, ie API vs AT mode.
Here is someone who has done some work with series 1: http://www.johnhenryshammer.com/WOW2/pagesHowTo/xbeeSeries1.php#index
I'll leave the actual implementation to you since this sounds a little like a homework assignment. Give it a go using the second method above and see how you go. Then post back here (ie update the question) including source code and exact layout (schematic preferred) and we'll see where we can help you from there.
Hint: google such terms as: "read data pins xbee arduino" (without the quotes).


text:
For which type of serial communication is Arduino Severino designed?
Arduino has become quite costly where I come from (2/3 of the price of Raspberry PI) so I have created an Arduino Severino clone.
I had used the device with the RS-232 Usb-Serial converter. But after a (long) while, the device stopped working. My friend came up with a point that RS-232 communication ranges between +6 to -6 V (with thresholds at +3 and -3 volts).
So I have tried FT232 which uses 0 to 5 volts instead. I have a little Chinese FTDI chip designed to do that:

However, after connecting it, it behaves unexpectedly. (it had crashed my PC, one of the communication LEDs is on all the time...) I realised that the Arduino board might get broken for a different reason (an accidental short-circuit is very likely).
So for which type of communication is this "Arduino" designed?

Please see my updated answer.

Looking at the schematic of that board it uses a very crude signal inversion for the RS-232.  This allows it to work of a standard RS-232 signal direct from a computer - just.
It's far from ideal and really should use a MAX232 (or similar) chip for the interface.
Your FT232 adaptor should bypass that chunk of the circuit and connect direct to pins 0 and 1 of the Arduino clone.  The DTR pin of the FT232 should connect to the RESET pin of the Arduino clone via a 100nF capacitor to allow the IDE to reset the board to enter the bootloader.  Oh, and of course, connect the ground to your Arduino clone too (something Arduino users often forget).
You can follow the serial breakout board portion of the Arduino breadboard tutorial and apply it to your board.

The arduino you linked to is designed for RS232-level serial signals, which can be guessed from the use of a DB09 connector.
The FT232 print you show is for 5V TTL (or maybe 3.3V 'TTL') signaling. Not compatible with your arduino. (BTW: that chip is not Chinese at all, it is made by www.ftdichip.com IMO they make the best usb-to-serial chip/driver products.)

Thanks for the additional info. I've edited my question thanks to you.

You are assuming, of course, that it is a REAL FT232 chip, and not a dodgy Chinese copy... http://zeptobars.ru/en/read/FTDI-FT232RL-real-vs-fake-supereal

The Arduino Severino (Single Sided Serial version 3 - S3V3rino) is designed to work with RS-232 serial interface, not with the TTL serial signal levels of your FT232 board.
So, to use your FT232 board to connect your Severino to a USB port, you'll need connections like those in the schematics below:

So, basically you need these connections:
  FTDI |  ATmega328           | Arduino Severino
----------------------------------------------------
  DTR  |  Pin 1 (thru cap C6) | RESET (thru cap C6)
  RXI  |  Pin 3               | TX (D1)
  TXO  |  Pin 2               | RX (D0)
  VCC  |  Not connected       | Not connected
  CTS  |  Not connected       | Not connected
  GND  |  Pin 8 & 22          | Ground

That's basically the same Majenko suggested (but with a picture added).
I'm not sure you can make these connections directly into the Severino without damaging the board or anything else. You'll probably need to cut the TX/RX traces that go from the ATmega328 to the DB9 female connector on the Severino and wire them to the FTDI header pins.
Best would be to modify the Severino EagleCAD schematics to remove all the RS-232 circuitry and replace it by TTL connector as shown in my schematics above and, with that, etch and assembly a new board. It's a lot of work, but can be done.
I hope this helps.

A typical 5V Arduino will use logic-level serial - that is 0 and 5V signalling.
RS232 has signal levels of plus or minus 3 to 15 volts. RS-232 drivers and receivers must be able to withstand indefinite short circuit to ground or to any voltage level up to ±25 volts
From Wikipedia
Many RS232 interfaces will receive 0-5V signals.
I believe the original serial Arduino had circuitry to tolerate RS232 signal levels on it's inputs.
Since most computers now have USB rather than RS232 ports, Most users of Arduinos use a USB to logic-level serial interface. Some of the most popular chips for this are from FTDI such as the FT232RL on your Chinese clone of a "FTDI Friend". In this case all the signals are logic-level 0-5V (or 3.3V if you change the jumper link).
So the following are probably OK
 PC DE-9 RS232    ----- Severino DE-9
 PC DB-25 RS232   ----- Severino DE-9
 PC USB port ---- "FTDI Friend" ---- Arduino 0(RX), 1(TX), Reset, GND and (optionally) VCC.

Well, no I've got two responses claiming exactly the opposite. What should I do? :D

@TomášZato: I suspect you don't have a true RS232 signal level anywhere. I'd use a voltmeter if in doubt.


text:
Understanding arduino shield schematics
I am researching the schematic of the arduino GSM shield.
Link is this:
https://www.sparkfun.com/datasheets/DevTools/Arduino/cellular%20shield-v12.pdf
What i do not understand is the upper right part, wich says ARDUINO_SHIELDNOHOLES.
What i want to do is understand which pins are used for Rx and which for Tx.
But there are four usable pins on the arduino side and six(?) pins on the other side which says jumper, where are six pins on seeminly two jumpers...
Can anyone understand what is going on here?

"ARDUINO_SHIELDNOHOLES" is a connector in the SparkFun EAGLE libraries which is basically, well, an Arduino shield. It provides the schematic symbol as well as the PCB landing pattern for such.
The pins on the top right of the schematic are two sets of 3, which should have jumpers connecting either 1 and 2, or 2 and 3. To use hardware serial to connect the Arduino to the SM5100B you connect 2 and 3 of the "top" one and 1 and 2 of the bottom one. This connects D0 (RX) and D1 (TX) of the Arduino to TXD0 and RXD0 of the SM5100B. If you want to use software serial instead, connect the other pairs. D2 will then be connected to TXD0 (and will become the software RX), and D3 will be connected to RXD0 (and will become the software TX).
As for "TXD0" and "RXD0" themselves, those are net names, and all wires with the same net name, such as those and the ones connected to pins 19 and 20 of the SM5100B, are considered to be the same wire even if they aren't connected in the schematic.

A lot of good shields will give you the option to use hardware or software serial, and that is what's happening here.
While you think you see four pins on the arduino side and six on the jumper side, what you're actually seeing is (yes) the four pins on the arduino, but those four pins go to four pins on the jumpers.
The other two pins on the jumpers (the ones in the middle) go to the TX and RX of the shield. The shield itself only has one TX (TXD0 pin 2 on JP4) and one RX (RXD0 pin 2 on JP6). So the jumpers form the connection between your arduino and the shield. This is why they are the middle pins, because you put the jumper on the first two, or the last two, depending on what it is you want to achieve.
You will note the net names of pin 2 of JP4 and JP6 relate directly to (and are connected to) pin 19 and 20 respectively of the chip on the shield.
The whole benefit of the jumpers is you connect JP4 and JP6 pins 1 and 2 to which closes the circuit and uses the inbuilt hardware serial (pin 1 of the jumper being arduino hardware and pin 2 being the TXD0 source from the shield). Connecting pins 2 and 3 means you close the circuit between the shields TX and RX to the arduino GPIO pins D2 and D3 which you can assign when initialising your software serial.


text:
Arduino diy wireless
Is it possible to do simple wireless on an Arduino, digital, or analog (SDR)? I would like to hook one pin to an antenna (or piece of wire) and generate signals with simple modulations (analog or digital).

You really need to expand on your question: what is it you are trying to achieve, what data rates are you looking for, what range. Be more specific

"AVR-based FM-transmitter" describes a FM audio transmitter implemented by an overclocked ATTiny45. Within limits, this idea should be adaptable to an unmofdified Arduino but probably this would cause an FM transmission on a frequence not covered by common receivers.

"Hook an antenna to your Propeller, and listen to the radio! (New shortwave prog)" describes a shortwave receiver implemented unsing a Parallax P32x8A controller. Maybe some other readers here can estimate the power needed for this hack... perhaps a DUE could do this too?

You might also like this (quite unrelated) raspberry PI PWM FM modulation.

here there's a nice tutorial on how to obtain it.
Basically it sets the registers so that a pin outputs a PWM signal at 800 kHz and then modulates that signal in code by just switching the pin and off (pinMode set to INPUT or OUTPUT). If you plug a cable (20 cm and on) to pin 8, and tune your radio to 800Khz you'll hear some noise going on and off.
If you read down the forum you'll see people suggesting how to actually send tones, by putting a very small delay (delay(1)) between the on/off of the pin.
In this link they guys have ogn further and they even implemented a morse code library.
Now I am trying to figure out a way to do the same for a receiver.

Based off of what you have said, the simplest way to achieve what you want to do with your Arduino would be to use a WiFi shield, and setup the Arduino to function as a web server. I have included two links: the first link shows you Arduino's sponsored WiFi shield and explains the basics of how to use it. The second link addresses your question of using the Arduino+WiFi shield to generate WiFi signals, by setting it up as a web server. Both links contain sample codes from Arduino that you can copy and paste. Assuming that you are using the native Arduino software, you can also go to: File > Examples > WiFi > WiFiWebServer, and the same code from the Arduino websites that I listed will be there for you to use.
http://arduino.cc/en/Tutorial/WiFiWebServer
http://arduino.cc/en/Guide/ArduinoWiFiShield
Personally, I would always recommend that whenever you want to accomplish a certain task, such as WiFi signal generation, displaying characters on a LCD, or anything else, you search for a shield to use for that application. Shields always make life extremely easier. I hope this helps. :)


text:
ATMega32u4 (Leonardo) Serial Baud Rate
Does anyone know what the actual baud rate that the CDC Based virtual serial port on the Leonardo runs at is? Serial::being() for the CDC version is just empty, so it's not setting a baud rate anywhere.
Basically, I'm debating between using the 32u4 or the 328p with an FTDI chip and trying to figure out if the 32u4 will be slower... since it uses a virtual COM port I'm assuming it is, but I'd be happy if I was wrong :)

I'm not sure if the concept of an "actual baud rate" is really meaningful in a pure USB connection.
In my experience, the 32u4 is faster than the 328p at serial-heavy tasks. There is no intermediate chip, and USB has much larger hardware buffers than the serial port does. I don't know how much processing you're planning to do on your data, but I would expect that a 32u4 can process serial data pretty much as fast as you can generate/process it.
On the host side, it seems to me that there is very little difference in whether the "virtual COM port" has an FTDI or a 32u4 on the other end, so I don't see why one should be faster than the other (though admittedly they go through different device drivers).


text:
What background do I need to have before starting Arduino?
Like: basics of electrical circuits, etc..
In order to go far in Arduino and electronics.

I am a Electrical technician and bought the starter kit from the Arduino team for my 13 year old son. My plan was to try the kit to teach my son about electronics.
The end result is that he is the one showing me new stuff.
In my opinion, you do not need any special background before starting with Arduino. You should have a interest in learning something new, and in learning about electronics. To get started, buy a tutorial book and a starter kit. (Many starter-kits comes with a tutorial book) When you have gone through the book, you will have some basic knowledge and a base to continue learning from.
Good luck

It might help alot to have some basic knowledge about the law of Ohm etc. It may be that these tutorial books of Arduino will explain these thingss since I've never bought such a book.
When you've finished the book you might consider to continue learning from other example projects for Arduino on the internet and reading lots of datasheets. Try to open some applications and rebluid small parts of it with your Arduino.
Oh, and not to forget. Read the datasheet of the Arduino before experimenting your self so you won't blow it up. (How many volts can an Arduino recieve, how many amps etc)

You need a basic understanding of programming because you will need to program in C++.
You need basic computer literacy, but I bet you've got that if you are on this website.
You need some understanding of electronics, such as a High-School level textbook. You need to understand resistors, diodes, voltages, current etc. Otherwise you'll get very frustrated.

While knowing all this helps, this is not actually true. It is possible to, as they say, learn.

You need to learn some absolute basics about electronics so you don't fry your arduino. (Don't exceed the current limits on the i/o pins. How to use Ohm's Law to calculate current. How to tie inputs to ground with a resistor. How to tie inputs to +5 through a resistor.  How to estimate the total current load of your entire circuit to make sure it doesn't overload the +5 regulated power from the Arduino. Basic precautions against static electricity.)
Beyond that, it makes a great learning tool, and you should be able to learn as you go. Build the sample projects that are on the Arduino website.
You might want to buy a book on logic circuits. I read "The CMOS Cookbook" years ago, and it gave me a good strong grounding.
You'll also want to learn programming, since you need to use C or C++. Again, though, you can use the Arduino as a learning tool. Looking at the sketches from the website and modifying them will help you learn.


text:
Arduino core for ATMega16u2
I've looked around a ton so it's probably not available but does anyone know if there is a usable core for the ATMega16u2 (the chip the Uno and Due uses for USB to Serial). I have a project I was going to use the 32u4 for but they aren't really available for several months and the 16u2 has all the functionality that I would really need.

"171 in stock"

I need the actual IC, NOT a board that already has it.

:O I... I don't think I've ever seen so many 0s before... Newark has a few -MUs, but I think someone bought up the world's supply of -AUs.

Yup :( Was very dissapointed that basically no one has them...

I think it's pretty much the same as the 32u4 but has less flash memory and less RAM. I think avr-gcc handles the RAM part. As for the flash memory, just copy and modify the atmega32u4 section in boards.txt to handle that.

I forgot about the bootloader. But I think you can just recompile it for the atmega16u2 without many, if any, changes.

Or use a programmer and forgo the bootloader entirely.

Don't need the bootloader actually. As long as it can be programmed via an ISP I'm good.

A thought just occurred to me. If a 16U2 will do, then why not use a 16U4 instead? All you'd need to change is the amount of flash available. And DigiKey has a few hundred of those in stock in -AU.

As @IgnacioVazquez-Abrams said, a 16u4 is virtually identical with a 32u4, so you can use a Leonardo or Micro core with a tiny modification to boards.txt. A 16u2 is a rather different animal, with fewer timers, many fewer pins, and no A/D converter, so you’d have to do a fair amount of editing to obtain a usable Arduino core.
That said, if you’re reasonably fluent in C++, building your own Arduino core is not very difficult, and I found it an instructive exercise. If you care about getting your project up as quickly as possible and not get sidetracked, however, go with the 16u4.


text:
How can I send serial over RF?
I've got the following:
#include <SoftwareSerial.h>

const int rx = -1;
const int tx = 4;

SoftwareSerial mySerial(rx, tx);

void setup()
{
  mySerial.begin(2400);
  pinMode(tx, OUTPUT);
}

void loop()
{
  if(mySerial.available())
  {
    String data = "Hello World";

    for(int k = 0; k < data.length(); k++ )
    {
      mySerial.write(0xAA);
      mySerial.write(data[k]);
    }

    mySerial.write(0xA9);
  }

  delay(1000);
}

Which I'm trying to send to to a RF transmitter module. It all compiles just fine, but am I forgetting something? And does pin 4 = physical pin 3?

You haven't told us what doesn't work! And how you are testing it? What is on the receiving end. PS arduin-pin-4 is indeed on attiny-pin-3, i.e. in most cores.

In your loop function you have:
if(mySerial.available())
{
  String data = "Hello World";

  for(int k = 0; k < data.length(); k++ )
  {
    mySerial.write(0xAA);
    mySerial.write(data[k]);
  }

  mySerial.write(0xA9);
}

The available() function returns the number of bytes available in the receive buffer. You say your module is a transmitter, so there will never be any data to receive (I can see the module doesn't even have a tx pin). Hence you will never transmit any data.
That said it's not a good idea to send data plain over wireless. It might work to some extent, but you'll likely get much more lost data. Look at the virtual wire library or google "manchester coding" if you wan't to roll your own.

First off, are you trying to send to the 433MHz transmitter? This will not work.
If you mean you are using the 433MHz transmitter to send data to a receiver, the VirtualWire.h library work.
If you are using another transmitter please add more info on the transmitter used in this project.
HumanHarddrive on youtube got a tutorial on the DX transmitter and receiver.
Tutorial


text:
Arduino standard libraries location
I want to read the source code of an arduino library that comes with the IDE.
Specifically the GSM.h
I dont know the location of the standard libraries that come with the IDE.
I only know the location of the user installed libraries.
So where is the source code of GSM.h?

Ok, i found out the location.
In Win 7, it is C:\Program Files (x86)\Arduino\libraries

Those are the standard libraries. If you want to add libraries, it's (I think) preferred to add them to the My Documents\Arduino\libraries\ folder.

Definitely preferred. Otherwise you lose your user-installed libraries when you upgrade to the next version.


text:
Buffering data from EthernetServer clients
I was trying to write a Telnet server that would be able to accept commands of sorts using the Arduino Ethernet library, and in order to access what the client was saying (to compare it to strings to check what command the client entered), I made a buffer string that would read until \n, which is part of the standard Telnet library. However, the string would never get printed to the serial connection (just for debugging purposes). Here's my code:
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xFE, 0xED };  // this client's MAC address

EthernetServer server(23);  // telnet is 23
boolean alreadyConnected = false;

void setup() {

  Ethernet.begin(mac);

  server.begin();  // open the socket

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial to start, Leonardo only
  }

  Serial.print("Connect to ");
  Serial.print(Ethernet.localIP());
  Serial.println(":23.");

}

void loop() {

  EthernetClient c = server.available();

  if (c) {
    String messageBuffer = "";

    if (!alreadyConnected) {
      c.flush();
      Serial.println("New client");
      c.println("test post, please ignore");
      alreadyConnected = true;
    }
    if (c.available() > 0) {

      char thisChar = c.read();

      //server.write(thisChar);

      //buffer until the client sends a new line
      if (thisChar == '\n') {
        Serial.println(messageBuffer);
        messageBuffer = "";
      } else {
        messageBuffer += thisChar;
      }
    }
  }
}

Most of this code was copied from the Telnet chat server example, but I changed the Serial.write(thisChar) line, because I wanted to put it into a string first. When this is run, and a user telnets to the IP, the Arduino prints New client, but when the user sends data, it doesn't print anything.
Any suggestions for what I'm doing wrong?

Can you send the complete code?

That is the complete code. As I've said, I fixed the problem.

Well, I asked on the #arduino IRC channel, and realized my stupid mistake. I was setting the buffer to "" inside the loop.


text:
Cheap medium range wireless communication with a linux PC
I have a project that's currently using Arduino Uno with a cheap class-2 bluetooth serial adapter from ebay to send and receive data and control a LED light strip.
However, it struggles to establish connection at distances more than couple meters. I'd like to expand that range a bit - 15 meters with two load-bearing walls in the way. Bandwidth requirements are next to none - it should just move couple integers around.
Any suggestions how to do that on the cheap? From what I've seen, class-1 bluetooth adapters go for ~60$, two xbee modules + usb adapter end up costing even more, and wifi solutions seem to reside in the same price range. At that price point, it seems better to get a raspberry pi, wifi dongle and a couple beers for the software re-write. Am I overlooking some solution?

Since one end is a PC I would look into a Wifi shield for the arduino. That way you would not need any extra hardware on the PC side.
You can get a Wifi shield for less than 2 xbee modules. But using wifi will require changes to your code since it won't be using the serial port for communication.
Another wireless option that I have no personal experience with is NRF2401 modules -- you can get them dirt cheap on ebay (caveat emptor) but they use an SPI interface so you can't directly interface with them directly on the PC side.
Be aware that depending on the LED strip you may not be able to drive it directly from a raspberry pi.  For example WS2811 driven LEDs (AKA adafruit NeoPixels) need precise timing that you can't get (or is tricky to get) with the raspberry pi.

I'd suggest the NRF24L01 too. Though you'd need to attach something like an arduino to the PC, to receive the serial commands over usb, and send it to the RF24 module.

"Smart home automation webserver on OpenWRT router WR703N interfaced to Arduino, compared to Raspberry Pi and Ubuntu" may lead you to some answers...
Just think of that solution as a kind of "homegrown Arduino YÙN"... just older and cheaper: "Nah, you don’t need an Ethernet module for your Arduino"


text:
What pins should I use when blinking AtTiny13 with arduino IDE?
I'm trying to program AtTiny13 using Arduino IDE. I have connected the atTiny to my PC using USBasp programer.
I want to write a simple blink application to test whether it works or not. Which pins should I blink?

You'll need an Arduino library that supports that chip, to make it appear in the Tools > Board list.  The library docs will tell you which pins then correspond to which Arduino digital I/Os. From that you can decide which pin to attach an LED to (with resistor) and how to edit the blink sketch.
Example: http://www.instructables.com/id/Pimp-Your-Chocolates-with-Arduino-IDE-and-ATtiny13/step2/Program-the-ATtiny13/

There's already Attiny13 in the menu. Should I then just use pins 1-8?

You could of course just try using software "pin 1" and seeing if that works... it's likely that this is ATTiny Port B bit 0 (PB0) which appears on physical pin 5 of the 8-pin DIP chip (see http://www.atmel.com/images/doc2535.pdf for other packages).

For more insight, look at file pins_arduino.h for the ATTiny13 somewhere within your ...\arduino\hardware\arduino??? directory.  I am assuming that at some point you added the core definition files that included ATTiny13, as I don't have them on my machine. Note that different core definitions could assign the Arduino pins to different physical pins.

Shoot, I meant that Arduino digital ZERO (D0) should appear on pin 5 (PB0) of the DIP8, etc.

I have just downloaded Arduino IDE. Maybe ATTiny13 was included - or it just appears to be included but doesn't work as my current experience with it would suggest.

Programming the ATTiny is of course a separate problem. And I'm guessing you can't tell if your problem with blink is in the programming or the program pin assignments. Hmmm.

When you use AVRDUDE to check the device signature, do you at least get a consistent signature value? If not there's something wrong with the electrical connection.

I can't tell, but as soon as I get over uploading problem, I'll face the unknown pin number problem. So I'm solving them simultaneously.

And don't get any value, it just says that Expected signature for ATtiny13 is 1E 90 07 but doesn't output the wrong value. Avter strungling with avrdude for a second time, I find it a very unhelpful software for anyone, who is not 100% sure that he's doing everything right.

avrdude -p t13 -t
... should return device signature. See http://www.nongnu.org/avr-libc/user-manual/using_avrprog.html and this tutorial looks helpful tho not for t13: http://www.ladyada.net/learn/avr/avrdude.html

And presumably you have docs: http://www.nongnu.org/avrdude/user-manual/avrdude.html, specifically command line flags: http://www.nongnu.org/avrdude/user-manual/avrdude_4.html#Option-Descriptions

I would try to install the attiny13 board as per the instructables page. There shouldn't have been a attiny13 in the default install of arduino. As you don't know where it came from, and what core it is using, you're better of starting from scratch. That way you also know how the pin numbers are mapped. avrdude is a pain in the ***, but in my experience it was always right when complaining about signatures.

Because pins 0 and 1 (physical 5,6) are PWM's you should keep them for later ...
and you still have A3 and A2 for analogWrite so,
you should use Pin 2 (Physical 7, next to +5V) like this :
add this in the setup function
pinMode(2, OUTPUT);

And add this in your loop function:
digitalWrite(2,HIGH);

For reference :
SparkFun's Help guide
Remember : Physical pin "1", reset, has a dot  marked on it.


text:
How to add the -F switch for avrdude in Arduino IDE
So, before starting to learn with something else, I'll give it one last try. The avrdude is complaining that the device signature doesn't match. Whatever, I don't care. To me, what's written on it is what counts.
So I'd like to force it to upload the program. It promises to ignore the problem if -F is specified.
Where are settings for avrdude parameters, like other IDEs have settings for their compilers?

Have you determined that avrdude works with -F outside the IDE yet?

Are you sure you have the correct board type set up and are trying to connect to the correct board?

In the verbose output of the message window at the bottom of the IDE, you could copy and paste the avrdude command line and add the option yourself. I've never manually compiled or tried it this way, give it a go and see if it works

Well, I also don't seem to able to find where is the temporary folder for compiled code. And as of are you sure question - I'm not sure about anything. And avrdude is not helping me to be sure with it's unhelpful errors.

If you have an incorrect device signature, using -F won't fix anything, since it'll be trying to program the wrong microprocessor. What is the actual device signature avrdude is reporting?

The avrdude doesn't bother to report what signature did he get. It just throws an error and fails. As soon as possible, I'll add the actual error in the question.

The error probably means that you have selected a wrong configuration.
To modify the IDE to insert the -F seems to be the hard way,
however the easy way is to make a wrapper to avrdude:
$ cd ./arduino/hardware/tools/
$ mv avrdude avrdude.orig
$ cat >avrdude.sh
  #!/bin/sh

  ./avrdude.orig -F $@
  ^D
$ chmod +x avrdude.sh
$ ln -s avrdude.sh avrdude


text:
Best Arduino board to play sound
I'm looking to purchase an Arduino for a little robot I'm going to make.  The reason I've chosen Arduino is because it's much easier to use with servos and LEDs than a Raspberry Pi, but a nice little touch would be to have it play some sounds (voice recordings and mechanical SFX).  I was just wondering (now I'm not after opinions here, but looking more at how each of the boards have been designed) what the best Arduino board for playing sound is, or if they are all pretty much the same in this regard.
(Note 'pins' was the best tag I could find for this post for lack of a 'sound' or 'speakers' one.  If you want to edit it to something more appropriate please do)

(Sorry, I can't add this as a comment) If you're looking for a good audio processing chip then I would recommend you the VLSI VS1003 chip. It costs $2.30 (standalone) or $7 as a module (on eBay today) and it's able to play MP3 (even VBR), WMA, WAV (ADPCM) and even MIDI. Also it can record sound from mic or line in and encode it as ADPCM WAV. Supports streaming and has other powerful features, like filters and bass boost and is well documented (see the datasheet). You would need some data source for it, so either a st

If all you need is to play back lo-fi audio then any with PWM will do, which means that any Arduino will do. If you want hi-fi sound then you'll need a DAC, which means either choosing the Due or using a discrete DAC via SPI. If you need decoding of complex audio formats such as MP3 or Vorbis then you'll need either the Due for its power, or a separate audio playback shield that supports the formats you're interested in.

I believe Due had proper DAC's. It also has a fair bit more muscle to do some processing besides playing the sound.

The Due has dual 12-bit DACs, and runs a 32-bit ARM core at 84MHz versus the 8-bit AVR core at 16MHz of most other Arduinos.


text:
Mac Power via Keyboard Shortcut?
many mac keyboards have a power button. Is there a way to mimic this power button shortcut from an arduino?

Perhaps you could be clear what you mean by "mimic". Do you want your Arduino to be able to turn on (or off) your Mac without manual intervention?

Also, what keyboard? Some Mac laptops have a power button for the computer, where others have one to shut off the wireless keyboard.

You have to research HID keyboard codes and its protocol. The power button is a regular key on the keyboard with a specific key code and specific a data frame. Leonardo can probably do it, most somewhat older design Arduino's can't act as a USB HID.

The Arduino can emulate a keyboard from which you can send a series of keystrokes to turn off the computer. Not sure you'll be able to mimic the hardware button. There are a few questions that are related: http://arduino.stackexchange.com/search?q=hid+is%3Aquestion

I have a mac mini rack holder that has a front panel with power button. It connects and controls the mac mini with USB only. I want to replicate this power signal sent over the USB with an arduino instead.

@Brian you'll have to try connecting that USB device to another OS (that most likely won't respond to the press) and use some kind of keylogging software to detect what character code it sends to the computer. If you can figure that out, it's easy to do this on the Leonardo (although still possible on the Uno, but a bit harder).

There are multiple ways to do that.

You could use an Arduino Leonardo as a keyboard, then send a shortcut command to shut down or sleep the computer. You can edit these from System Preferences>Keyboard>Shorcuts>Services.
The keycode 0x66 does not work for mac, but may for other operating systems source
You could write a small program (I'd do it in Python) which communicates with the Arduino over the serial port and shuts down the Mac if the Arduino wants it to.
You could sacrifice an USB keyboard and use a relay to "press" the power key.

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


text:
Frequency will not change
I am working on a project where I am trying to get an input signal filtered according to its frequency. I checked the signal before it went into my DSP algorithm to see where the problem was and I found that the frequency was remaining the same no matter if I put in 30Hz 120Hz or 58kHz. This leads me to think I have a problem with the sampling rate. Does that sound like it is the actual issue? Or am I barking up the wrong tree?
I was just using the readADC command to read in the data
void setup()          //Setup Function to intialise ADC and Serial Communication
{
DDRC=0x00;            //PORTC as INPUT
DDRD=0xFF;            //PORTD is OUTPUT
DDRD=0xFF;
for(i=0;i<N;i++)
  {
    InitADC();
    a=ReadADC(4);
    x[i]=a;
  }
  Serial.begin(9600);
}

How exactly are you sampling the signal? It would help if you can show the circuit and source code.

post your entire code

Could you trim down your program to a short program that demonstrates the issue, and then post the complete program? I see you posted a "setup()" routine, but a complete Arduino program also has a "loop()" routine.

I am not sure how you are sampling the frequency because you have not shown us your code.
At work we use a ATMega328P to sample frequency. This is done in 2 different ways:

We use the pin that counts (using an internal counter) every time it transitions (ie from low to high and from high to low). After 1 second that counter is read and then that counter is cleared. With the number read in, it is divided by 2 to get the frequency.
We use another pin that counts every time it transitions from low to high. From memory the counter is not very large so we count the number of times it overflows. When the 1 second interrupt fires we multiply out the number of overflows by the counters capacity. Lastly the remainder from the counter is added to the result to get the frequency. Again the counter is cleared.

The above examples use the AVR's internal counters. A less efficient way of getting the frequency is to have an interrupt to count the number of times a pin changes. Again this can be read and reset at one second intervals. This slows the overall execution of the program down when very high frequencies ( > 40K Hz) are being presented on the input.


text:
Bluetooth Master and Slave to track device's locations
I'm trying to create an app for my science fair that uses bluetooth to track people in a determined place.
I was thinking about one Arduino system to receive all the information and transmit through a network and some Arduino slaves to duplicate the signal and cover the hole place.
Resuming...
I'll have:

Arduino slaves placed all over the place to track people
One Arduino connected to the network to receive all the information from the slaves and pass it through the network.
Some kind of web app inside the main Arduino with an API to manage the data and make it friendly for third-party apps

I was wondering of what kind of equipment should I buy to make this happen. Thanks!

Each cellphone with it's bluetooth enabled will work as a person (sending signal) - my Arduino slaves will receive the signal (find bluetooth around it) and send the device name and signal strength to the arduino master - The arduino master (connected to the network) will interpenetrate the responses and send the results to the built-in web server - Apps will make requests to the web app to get this data and show in a plant where're these people.
Basically it will work like these bluetooth stickers that you can plug in to your keys, phone e etc... and with the app you can search for them in your house via bluetooth from your cellphone.
Here's a better explanation:
Link

Google "sensepost snoopy".  Also note that most phones are not discoverable unless they are put into pairing mode so you won't be able to detect them unless you already know their bluetooth ids in which case you can poll for them.

Classic bluetooth is not a solution for this.  BLE could be crudely, though signal-strength based positioning as commonly used there is only crudely accurate.  Time of flight measurement would require substantially better hardware than you have available.

Bluetooth generally support only one to one connection. Atmost 6 bluetooth can be connected to single module in latest bluetooth version(the basic model probably used by you connects only 1 device). Hence it is not a good idea to use bluetooth. Also if you need a web based platform you should switch to some more powerful platform like raspberry pi, beagle bone etc.


text:
Is there some sample code for operating a servo with an Adafruit Motor Shield?
I have an Adaruit Motor Shield v2, and a Tower Pro SG92R micro servo. I've got it setup so the shield works with my Arduino Uno, and I've successfully tested using other types of motors on the shield. I could not find any sample code for working with a servomotor though. The shield has two dedicated spots for a servo (labeled "Servo 1" and "Servo 2"). I'm planning to use wall wart transformer to power the motor separately from the Arduino. Any pointers/links to documentation/sample code would be appreciated.

Does the standard servo example work?

With the shield mounted on the Arduino, I don't have access to those pins. Also I if I understand correctly, that would not let the servo be powered by a separate power supply.

On the Motor shield the servo headers are directly connected to pins 9 and 10 (I think 9 is servo 2 and 10 is servo 1).  So you can use the standard servo examples using pins 9 and 10.
If you need to power the servos with an external power supply you must cut a trace on the back of the board -- the silk screen tells you where to cut.  Then you need to connect power to the "Opt Servo" input.
The power to the servos is not changed by the power jumper used for the DC/stepper motors.


text:
Need some help with controlling a fan through PWM
So lately I've been trying to control the speed of a 120mm 4-pin computer fan using PWM. This is what I've got so far, with the part above void loop() being from this thread
// Definition of Arduino type
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define  IS_MEGA  (1)
#define  IS_UNO   (0)
#else
#define  IS_MEGA  (0)
#define  IS_UNO   (1)
#endif

// Analog output (i.e PWM) pins. These must be chosen so that we can change the PWM frequency without affecting the millis()
// function or the MsTimer2 library. So don't use timer/counter 1 or 2. See comment in setup() function.
// THESE PIN NUMBERS MUST NOT BE CHANGED UNLESS THE CODE IN setup(), setTransistorFanSpeed() AND setDiodeFanSpeed() IS CHANGED TO MATCH!
#if IS_UNO
// On the Uno we can only use the OC1B pin, so these pin numbers are both 10
const int transistorFanPin = 10;     // OC1B
const int diodeFanPin = 10;          // OC1B
#else
// On the Mega we use OC1B and OC1C
const int transistorFanPin = 12;     // OC1B
const int diodeFanPin = 13;          // OC1C
#endif

// Definitions for PWM fan control
const unsigned char maxFanSpeed = 80;   // this is calculated as 16MHz divided by 8 (prescaler), divided by 25KHz (target PWM frequency from Intel specification)

void setup()
{
  // Set up the PWM pins for a PWM frequency close to the recommended 25KHz for the Intel fan spec.
  // We can't get this frequency using the default TOP count of 255, so we have to use a custom TOP value.

#if IS_UNO

  // Only timer/counter 1 is free because TC0 is used for system timekeeping (i.e. millis() function),
  // and TC2 is used for our 1-millisecond tick. TC1 controls the PWM on Arduino pins 9 and 10.
  // However, we can only get PWM on pin 10 (controlled by OCR1B) because we are using OCR1A to define the TOP value.
  // Using a prescaler of 8 and a TOP value of 80 gives us a frequency of 16000/(8 * 80) = 25KHz exactly.
  TCCR1A = (1 << COM1B1) | (1 << COM1B0) | (1 << WGM11) | (1 << WGM10);  // OC1A (pin 9) disconnected, OC1B (pin 10) = inverted fast PWM
 #ifdef FAN_AUDIO_TEST
  // test code to get 440Hz output (= concert A) to test the logic
  OCR1AH = 0;
  OCR1BL = 71;  // 50% duty cycle
  TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12);  // TOP = OCRA, prescaler = 256

  OCR1AL = 141; // TOP = 141, 16000000 / (256 * 142) = 440.014
  OCR1BH = 0;
 #else
  OCR1AH = 79;
  OCR1AL = 0;  // TOP = 79
  TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);  // TOP = OCR0A, prescaler = 8

  OCR1BH = 0;
  OCR1BL = maxFanSpeed;  // max fan speed (i.e. pin 5 initially low all the time)
 #endif

  TCNT1H = 0;
  TCNT1L = 0;
#else

  // On the Mega we use TC1 and OCR1B, OCR1C
  TCCR1A = (1 << COM1B1) | (1 << COM1B0) | (1 << COM1C1) | (1 << COM1C1) | (1 << WGM11) | (1 << WGM10);  // OC1A disconnected, OC1B = OC1C inverted fast PWM
  TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS11);  // TOP = OCR1A, prescaler = 8
  TCCR1C = 0;
  OCR1AH = 0;
  OCR1AL = 79;  // TOP = 79

  OCR1BH = 0;
  OCR1BL = maxFanSpeed;
  OCR1CH = 0;
  OCR1CL = maxFanSpeed;

  TCNT1H = 0;
  TCNT1L = 0;
#endif

  // We have to enable the ports as outputs before PWM will work.
  pinMode(transistorFanPin, OUTPUT);
  pinMode(diodeFanPin, OUTPUT);
  pinMode(A0, INPUT);
  Serial.begin(9600);
}

// Set the transistor fan speed, where 0 <= fanSpeed <= maxFanSpeed
void setTransistorFanSpeed(unsigned char fanSpeed)
{
  OCR1BH = 0;
  OCR1BL = fanSpeed;
}

// Set the diode fan speed, where 0 <= fanSpeed <= maxFanSpeed
void setDiodeFanSpeed(unsigned char fanSpeed)
{
#if IS_UNO
  OCR1BH = 0;
  OCR1BL = fanSpeed;
#else
  OCR1CH = 0;
  OCR1CL = fanSpeed;
#endif
}

void loop() {
  if (analogRead(A0) >= 800) {
    setTransistorFanSpeed(80);
    Serial.println("HIGH");
    Serial.println(analogRead(A5));
  } else {
    setTransistorFanSpeed(0);
    Serial.println("LOW");
    Serial.println(analogRead(A5));
  }
  delay(100);
  Serial.println("I'm running.");
}

In the serial monitor I'm getting the output I'm expecting ("HIGH" and 1023 when I've bridged the arduinos 5V pin to A0), but the signal doesn't seem to have any effect on the fan at all. In the thread linked above there's talk about this being an inverted fast PWM signal, and that it's assumed I'm using an opto isolator. Could this be why the signal doesn't have an effect on the fan? If anyone out there has any experience on this and are able to help me, that would be greatly appreciated.. :)

How did you connect the fan? What does "no effect" mean? Is the fan not running, or doesn't it run slower than usual? More info on these kinds of fans

The fan runs at full speed with and without a PWM signal.

@Gerben also, I connected the fan correctly according to the article you linked. Negative and positive power directly connected to a 12V power supply, and the 4th pin (PWM) to the arduino.

Did you connect the ground of the fan (/12volt powersupply) to the ground of the arduino? If you don't connect the grounds, there is no path for electrons to flow.

What is the frequency of pulses in Arduino PWM? I've seen a passing reference to it only being 500 Hz. If the fan needs a 25KHz signal, that wouldn't do it. In fact, if it is anything other than the frequency the fan is wired for, it won't work.

@DuncanC Both the thread I linked in my original post, and the comments in the code I pasted explain how the frequency is changed to 25KHz.

@Gerben thanks, this solved it for me. :)

Little side note, turns out the fan inverts the meaning of the duty cycle, so a 0% duty cycle means the fan runs at 100% speed, and a 100% duty cycle means no speed, or slowest speed the fan can go (varies from fan to fan it seems). This also explains how the fan runs at 100% when there is no PWM signal present.

Kind of makes sense. If you connect the fan to an old motherboard with only 2 pins, you'd want the fan to run at full speed.

You need to connect the ground of the fan (/12volt power-supply) to the ground of the Arduino. If you don't connect the grounds, there is no path for electrons to flow.


text:
MCP7940 RTC Library
I am looking to implement a Microchip MCP7940 real time clock into my sensor data logging circuit that I have based on the Uno. Would the most logical solution be to attempt at changing an existing library to work with this clock (ie RTClib), or to begin from scratch and do the configuration directly in my program?

Have you compared the MCP7940 to another RTC chip for which a working library exists? You'll need the datasheets. The more alike they are, the easier it will be to modify one's library for the other. At the higher levels - the interface functions - there shouldn't be too much difference; you'll need methods to set the clock, read the clock, and maybe 'hack' the clock (start it running in sync with some reference signal after you've pre-set the time). But the devil, as they say, is in the details. If the chips differ much, one library won't help much with the the low-level details of the other.

Looking at the datasheet, it is very very similar to the DS1307. I wouldn't be surprised if the DS1307 library would work for the MCP7940 without modifications. So definitely use an existing library as a starting point.

@JRobert The pinouts of the DS1307 and MCP7940 are identical. The major difference between the two is that the MCP7940 has an alarm output (which is the reason I'm using it over the DS1307). I'd assumed it would be fairly simple to modify a library to work with it. Now it just becomes a question of how long that will take with my limited programming knowledge/experience.

Then you're far better off starting with a working library. You'd always have a known-good state to revert to when you need to. That beats the heck out of every line of code being experimental! You don't say much about your programming experience, but if the library is moderately well documented, you should at least be able to identify what part of the library needs modifying and what needs to happen there. Then, if you need it, it would be relatively easy for someone to guide you from there to working code.

@JRobert My programming experience is assembly on PIC controllers, and directly with the Arduino. I know enough about programming to know that the libraries are constructed using something more in depth than what is being used in the IDE.

Did you ever get your library working?

Yes, I used the RTClib by jeelabs, and added instructions to set and check the alarm function.

In case anyone comes looking for an answer to this question, here is my solution:
I started with the excellent library by jeelabs (link: https://github.com/jcw/rtclib)
To create my new library, I changed a few of the register addresses, and added the few functions that I wanted it to do (set alarm, create an ordinal date, manually adjust the time with user input)
I posted my code to a Git project: https://github.com/crako1t/MCP7940-library-for-logger.git


text:
Clear existing array when getting new serial command
I'm starting to build my first Arduino project but I'm running into some problems with serial communication.
I get serial data from the console and store it in a char array called "data".
Then, when I send a new console message to the Arduino, I want it to clear the existing "data" array and store only the new data in that array.
I don't understand exactly what's wrong with my code: I believe those nested Serial.available() statements don't work but I have no ideas on how to fix the code.
Data is correctly stored by the Arduino but it concatenates the newer string to the old one.
int count = 0;
char data[30];
boolean dataComplete = false;

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

void loop() {

  if (Serial.available() > 0){
    if (dataComplete == true){
    Serial.println("There is data already, clearing...");
    char data[30];
    dataComplete = false;
  }
    if (dataComplete == false){
      Serial.println("New command, collecting...");
      while (Serial.available()>0){
        char character = Serial.read();
        data[count] = character;
        count++;
      }
     dataComplete = true;
    }
  }
  Serial.print("Command received: ");
  Serial.println(data);
  delay(1000);
}

Thanks in advance!

To clear an array you would do:
for( int i = 0; i < sizeof(data);  ++i )
   data[i] = (char)0;

or
memset(data, 0, sizeof(data));

, which does the same thing using a library function.
However, because strings of characters (not referring to 'String' objects here) are terminated by a zero byte, only the first byte needs to be zeroed:
data[0] = (char)0;

will do it.

First of all, this is an excellent example why whitespace matters. Your code is really hard to read as it is, as skimming over it, it seems as the second if statement is outside of the first one.
Fixed code:
int count = 0;
char data[30];
boolean dataComplete = false;

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

void loop() {
  if (Serial.available() > 0){
    if (dataComplete == true){
      Serial.println("There is data already, clearing...");
      char data[30];
      dataComplete = false;
    }
    if (dataComplete == false){
      Serial.println("New command, collecting...");
      while (Serial.available()>0){
        char character = Serial.read();
        data[count] = character;
        count++;
      }
     dataComplete = true;
    }
  }
  Serial.print("Command received: ");
  Serial.println(data);
  delay(1000);
}

Also, it seems as it prints "Command received:" every iteration, regardless of if there's new data or not (although, this could be the intended feature).
Like mentioned, you don't clear the variable, you just create a new one. You'll need to clear and reset count to fix this issue. However, just resetting count won't work if the second command is shorter than the one before.
Also, why do you complicate the code with the dataComplete variable? I simplified the code below:
int count = 0;
char data[30];
boolean dataComplete = false;

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

void loop() {
  if (Serial.available()){
    Serial.println("New command, collecting...");
    count = 0;
    data[] = "";
    while (Serial.available()){
      char character = Serial.read();
      data[count] = character;
      count++;
    }
  }
  Serial.print("Command received: ");
  Serial.println(data);
  delay(1000);
}

This probably doesn't do what you intend it to do:
Serial.println("There is data already, clearing...");
char data[30];

Your output says you are clearing the data array, but you're doing no such thing. In fact, you are declaring a new local variable called data, which is independent of the global data you already have declared at the top of your program. Local variables only exist within the scope in which they are declared (inside their nearest enclosing { }).
Instead, your count variable keeps track of how much data you have received. So perhaps do the following:
Serial.println("There is data already, clearing...");
count = 0;

This is not the only thing that might cause your program to operate unexpectedly, but it should at least fix the problem stated in your question.

Also a null terminator is needed for data: Add data[count]='\0'; after dataComplete = true;

Yes, that's true, but the larger problem is that there is no way for the sender to indicate the end of a data transmission other than to pause. And since this is serial, there is going to be a long enough pause in between every character transmitted.

Thanks to both of you guys. My code was wrong and changing it to "count = 0" worked. I also added a delimiter to indicate the end of an input command and it works as intended now. However, the only way that worked to empty the "data" array was using a for loop as indicated by @JRobert: this way newer commands work even if they are shorter than older ones.

To speak to the point of the question, and what the author was attempting to accomplish.
None of this code actually works as a whole. The data would get over written and just keep looping continuously... anyway here is a working example of the original code.
This method I prefer to clear an array:
    for( int i = 0; i < sizeof(data);  ++i )
    data[i] = (char)0;

Here is working example. ( Make sure to select Carriage Return on the serial monitor )
    char message[32];
    uint8_t incomingByte = 0;
    uint8_t BufferPos = 0;
    int clearbyte = 0;

    void setup() {
    Serial.begin(9600);
    Serial.println("\n String conversion testing");

    }

    void loop() {

       if (BufferPos >= 32) {
              Serial.print("Buffer Full\n");
              BufferPos = 00;
              incomingByte = 0;

       }

      if (Serial.available()) {
             incomingByte = Serial.read();
             message[BufferPos++]= incomingByte;

         switch(incomingByte)
      {
           case '\n':
           case ' ':
             break;
           case '\r':
              Serial.println(message);

          for( int i = 0; i < sizeof(message);  ++i )
         message[i] = (char)0;
              BufferPos= 0;
              incomingByte= 0;

      }
      }
    }

I was read all comments on this question, but all codes was share so verbosing. After that, i create a code with simple functions and less of line. in this case, i think this code will working fine
if you set baudrate under 115200, must be add delay() for saving message to char array
void loop() {
    char data[255];
    uint8_t k = 0;
    while (Serial.available()) {
        data[k] = Serial.read();
         k++;
    }
    for (int i = 0; i < k; i++) {
        Serial.print(data[i]);
        data [i] = '\0';
    }
    //delay(50);
}

char data[] = {}; will give you a zero-length array. Trying to put data into it is a bad idea.

I agree with @NickGammon .  Please edit your answer to replace "I think... will work fine" with a definitive yes/no, once you have tested the code.

@NickGammon thanks for the correction, i was revision my code


text:
Arduino IDE crashes without any warning
I'm a beginner in Arduino. I just installed Arduino IDE (arduino-1.0.5-r2-windows) but when I try to run its not responding and crashes after few minutes. I tried re-installing it and removing the temporary files but none of those helped.
Can anyone tell me what causes this problem and how to debug it?

It might be helpful to know some more details about your system, e.g. what version of Windows are you using? Is it 32 or 64 bit?

Additionally, what does "crash" mean? Any error messages? Slows down? After a specific action?

Not really a fix, but you might want to try an older version of the IDE.

And if you run it from a terminal?

The ide was slow and closes after sometime without any notice. I didn't try running it from terminal. But I switched to arduino 1.5.6 , it works fine. Thanks.

Installing Arduino 1.5.6 solved the issue.


text:
Teensy USB Core on Leonardo
The USB Serial speed on the teensy is WAY faster then on the Leonardo. Looks like because they have greatly improved the USB code. Has anyone had any luck using the Teensy core libraries on a Leonardo? I would imagine it should work as the hardware is basically the same.

Have you tried selecting a higher speed in your serial client?

Yes, I've cranked it all the way to 1Mbps.

Looking at the schematics of both, I don't see why it wouldn't work. Just note that e.g. you'll lose the tx and rx led functionality (which might account to the slower speed), but you could reuse those leds for something else (-:. Also be aware that pin numbering is a bit different.

Unless you are comparing to the teensy 2.0 (not +), the hardware is much different (i.e. microprocessor) - that alone could account for a large performance difference

The discontinued Arduino Leonardo uses an ATmega32U, (https://www.arduino.cc/en/Main/ArduinoBoardLeonardo)  as is the Teensy2.0, which, USB-hardware-wise is very similar to the AT90USB1286.  Teensy's hardware USB system acts as a virtual serial port and completely ignores the Serial.begin(xxxx) baud rate and operates at a full 12Mbi ratet:  https://www.pjrc.com/teensy/td_serial.html


text:
How is stack memory used for fuctions and local variables?
I wanted to save some values to the EEPROM and also wanted to free up SRAM by avoiding some variable declarations, but EEPROM memory is byte wise.
If I want to store an int value, I have to use some expressions repeatedly. I thought I would make some functions for those. But I am concerned that, if I create a function, it would still occupy SRAM memory, better I declare an int variable instead of using EEPROM.
How are the functions and the local variables stored in SRAM? Does it only store the address of the fuction pointer from the flash memory or all the variables and commands are stored on the stack?

Do remember that EEPROM is only writable for a limited number of times, reading it is unlimited. According to the AVR datasheet EEPROM only has 100000 cycles, which sounds as a lot but when you try to use it as SRAM, it will only last a fairly short period.

OMG! After that, will the EEPROM be useless? I am going to check the datasheet!

The Flash memory also has a lifecyle. It's wiser to not burn the program a lot.

With normal use the numbers given for flash and EEPROM are no problem at all. The equation changes when you start using it like you use SRAM.

Only the function's data is stored on the stack; its code stays in flash.
You can't really reduce SRAM use by using EEPROM instead because, as you have seen, EEPROM isn't addressable in the same way. The code to read and store EEPROM also needs to use some SRAM - probably as much SRAM as you were trying to save! EEPROM is also slow to write, and has a limited lifetime (in number of writes to each byte), both of which make it impractical to use for storing the kind of temporary data we usually put on the stack. It is better suited to saving infrequently changed data, like the unique device configuration for mass-produced devices, or capturing infrequent errors for later analysis.
Edited:
There is no stack for that function until the function has been called, so yes, that is when any of the function's data get's put there. What happens after the function returns is that its stack-frame (its reserved area of SRAM) is no longer reserved. It will eventually be re-used by another function call. Here is a diagram of a C stack in memory. When a stack frame is no longer useful, it is simply released and its memory becomes available to be re-used.

I am thinking this way, when the function is called, only then the data inside it is stored in the stack. After execution of the function, the data are erased from stack/SRAM. Am I right?

Local variables and function parameters are stored on the stack. However, that is not a reason not to use them. Computers are designed to work that way.
Stack memory is only in use while a function is active. As soon as the function returns, the memory is freed. Stack memory is a GOOD Thing.
You don't want to use recursive functions with lots of levels of recursion, or allocate lots of large structures on the stack. Normal use is fine however.
The 6502 stack is only 256 bytes, but the Apple II works just fine.

So, you mean the function will be saved with all its local variables, parameters and expressions to the stack temporarily, only when it is called? Otherwise it will stay in the program/flash memory? After execution, will it be erased from stack? I was talking about Arduino actually, as it is Arduino Forum, I didn't mention that.

No, only the function's parameters and local variables are on the stack. The code of the function is not saved on the stack. Don't over-think this.

The AVR (the microcontroller family traditionally used on Arduino boards) is a Harvard Architecture, meaning that executable code and variables are in two separate memories - in this case flash and SRAM. The executable code never leaves flash memory.
When you call a function the return address is usually pushed to the stack - the exception is when the function call happens at the end of the calling function. In this case the return address of the function that called the calling function will be used instead - it is already on the stack.
  Whether any other data is put on the stack depends on the register pressure in the calling function and in the called function. Registers are the working area of the CPU, the AVR has 32 1-byte registers. The registers can be accessed directly by CPU instructions, whereas data in SRAM will first have to be stored in registers. Only if arguments or local variable are too big or too many to fit in registers will they be put on the stack. However, structures are always stored on the stack.
You can read the details of how the stack is used by the GCC compiler on the AVR platform here: https://gcc.gnu.org/wiki/avr-gcc#Frame_Layout
Read the sections "Frame Layout" and "Calling Convention".

Immediately upon a function call entering the function, the first code that is executed is to decrement the stackpointer by an amount equal to the space required for temporary variables internal to the function. The brilliant thing about this is that all functions therefore become re-entrant and recursive, because their variables are built on the calling program's stack.
That means if an interrupt halts execution of one program and transfers execution to another, it too can call the same function without them interfering with eachother.

I've been trying quite hard to make an example bit of code to demonstrate what the excellent answers here are saying, without success so far. The reason is that the compiler aggressively optimizes things. So far my tests have not used the stack at all, even with local variables in a function. The reasons are:

The compiler may in-line the function call, thus the return address might not be pushed onto the stack at all. Example:
void foo (byte a)
      {
      digitalWrite (13, a);
      }
    void loop ()
      {
      foo (5);
      }

The compiler turns that into:
void loop ()
      {
      digitalWrite (13, 5);
      }

No function call, no stack used.

The compiler may pass arguments in registers, thus saving it having to push them onto the stack. Example:
digitalWrite (13, 1);
Compiles into:
158:  8d e0         ldi r24, 0x0D ; 13
15a:  61 e0         ldi r22, 0x01 ; 1
15c:  0e 94 05 01   call  0x20a ; 0x20a <digitalWrite>

The arguments are put into registers and thus no stack is used (apart from the return address for calling digitalWrite).

Local variables may well be put into registers, again saving having to use RAM. This not only saves RAM but is faster.

The compiler optimizes away variables you don't use. Example:
void foo (byte a)
   {
   unsigned long bar [100];
   bar [1] = a;
   digitalWrite (9,  bar [1]);
   }
 void loop ()
   {
   foo (3);
   }  // end of loop

Now that's got to allocate 400 bytes for "bar" doesn't it? Nope:
00000100 <_Z3fooh>:
   100: 68 2f         mov r22, r24
   102: 89 e0         ldi r24, 0x09 ; 9
   104: 0e 94 cd 00   call  0x19a ; 0x19a <digitalWrite>
   108: 08 95         ret
 0000010a <loop>:
   10a: 83 e0         ldi r24, 0x03 ; 3
   10c: 0e 94 80 00   call  0x100 ; 0x100 <_Z3fooh>
   110: 08 95         ret

The compiler optimized away the entire array! It can tell that we are really just doing a digitalWrite (9, 3) and that is what it generates.

Moral of the story: Don't try to out-think the compiler.

Most non-trivial functions use the stack to save some registers, so that these can be used to hold local variables. Then we have this funny situation where the function's stack frame contains local variables belonging to it's caller.