text:
Send Processing color data into Arduino
I am trying to send color() data from Processing to Arduino.
Here is my code from Processing:
import processing.serial.*;
Serial myPort;

void setup(){
  myPort = new Serial(this, Serial.list()[7], 9600);
}

void draw(){
  color[] c1 = {color(99,0,0),color(255,0,0) };
  for (int i = 0; i < c1.length; i++ ){
    int value = int(red(c1[0]));
    myPort.write(value);
    println(value);
    delay(2000);
  }
}

It sends the 99.0 data to Arduino. Here is the Arduino code for getting:
void setup(){
  Serial.begin(9600);
}

void loop(){
  while(Serial.available() > 0){
    int recieved = Serial.read();
      Serial.print(recieved);
    }
}

The problem is when Arduino receive data it doesn't take one by one. When i watch Arduino serial monitor, the data comes at different chunks like, 9...99...999..9.. etc.
I am trying to send several color info from Processing into arduino, it might be a long array of value. What is the best way to achieve this?

The 'best' solution depends on many things, your skill, the performance of the system, and the other tasks it needs to do in the available time. There are some examples of doing data transfer between Processing and the Arduino in the Arduino example programs. So it is worth looking through them.
There seems to be some inconsistencies in your question.
You wrote "It sends the 99.0 data to Arduino", which has a decimal point.
Yet the code is printing an int i.e.
int value = int(red(c1[0]));
myPort.write(value);

Further, the processing code only looks at the red component of c1[0]:
int value = int(red(c1[0]));

so it can only send a sequence of '9'. So that looks like a bug.
There are a few basic strategies to write data that can be easily read. Two popular ways are:

send fixed length messages, or prefix a message with the size of the
data, and have a fixed format of data. For example, use a one byte
count to say how many colours are being sent, then send three bytes,
in the same order, for each colour
use non-data bytes to separate the data. For example use a ','
between R, G or B and '\n' to mark the end of the data. To keep
things simple, never use those values as data values. That is pretty
much how programming languages work. It is much more complex to read
than fixed format data, but can give more flexibility.

Data is often sent as printable characters (e.g. 173 would be three bytes havig the ASCII values '1', '7', '3'). If it is fixed format, it would always be three bytes. For your purposes, I'd probably send each data byte as two hex characters (ASCII '0' to '9' and 'A' to 'F'. This is slightly more complex than pure binary. However it is fixed format, and more importantly it is easier to test by hand using the Arduino serial monitor, you can just type stuff and it is relatively easy to do.
Pure binary data is much more difficult to fully test, and often relies on a piece of software which also needs testing.
Summary: There are a couple of ways, it is hard to say which is best. For simplicity try to make it simple by being fixed format.

I put the dots for trying to visualise serial monitor in real time. Take them as waiting intervals. My point was Arduino is receiving at different order or rate. i tried sending "\n" with looking at this example but it did not work. Anyway, thanks for the suggestions.

You have to implement a serial protocol.
This can be either binary or ASCII. Binary has the advantage that the messages are short and well structured due to fixed parameter size. ASCII has advantage that you can type the messages into the serial monitor for debugging and typically data bytes are numerical ('0', '1' etc) while message bytes are text ('setcolour' etc) which means conflicting bytes do not have to be escaped.
To get started, try the Messenger library. Note that #include "WProgram.h" has to be changed to #include "Arduino.h" in the .cpp and .h files.
For the set colour message, if you used something like:
setcolour,99,0,0,255,0,0\n
You could use Messenger to parse it like:
Preamble:
#include "Messenger.h"
Messenger message = Messenger(','); //Message values separated by ','

In setup():
message.attach(messageCompleted);

In loop():
while(Serial.available()) {
    byte inbyte = Serial.read();
    message.process(inbyte);
}

Then implement the callback function:
void messageCompleted()
{
    if (message.checkString("setcolour")) {
        colour1[0] = message.readInt();
        colour1[1] = message.readInt();
        colour1[2] = message.readInt();
        colour2[0] = message.readInt();
        colour2[1] = message.readInt();
        colour2[2] = message.readInt();
    }
}

where colour1 and colour2 store the two RGB values.

Thanks for the answer. I am going to try this method. I am so new to programming so excuse my noob questions. First of all, this library seems to be obsolete, can i still use this one? Second question is i do not understand the changing #include thing. i try to use your code as written and it gives 'Messenger does not name a type'.

The library is still good, even though the page recommends to use CmdMessenger I find that that library is more complex than for what I need. To use the library, unzip it and then copy the Messenger folder (under Firmware) into you Arduino library folder (check where it is in preferences) and restart the Arduino IDE. In the file Messenger.cpp the 7th line is #include "WProgram.h". Change this to #include "Arduino.h", as this is the new header file used by the 1.XX versions of the Arduino system.

The error means the compiler can't find the definition of the class Messenger. The fix is to make sure that Messenger library is in the right place (as described above) and to put #include "Messenger.h" near the top of you sketch.

I try sketch examples for Messenger and still not compiles.  Now it gives several errors which starts "WProgram.h: No such file or directory".

Change "WProgram.h" to "Arduino.h" in the examples.

Now it gives 'Messenger' has not been declared compile error.

int value = int(red(c1[0])); gives you 99 not 99.0
You could read a byte (that's what Serial.read returns; not an int), and make some decision based on that character, then read again.
Or, you could read all the available data till '\n' new line character comes. What println(value); line does it sends 99+'\n
Code:
// Buffer to store incoming commands from serial port
String inData;

void setup() {
    Serial.begin(9600);
    Serial.println("Waiting for Processing color...\n");
}

void loop() {
    while (Serial.available() > 0)
    {
        char recieved = Serial.read();
        inData += recieved;

        // Process message when new line character is recieved
        if (recieved == '\n')
        {
            Serial.print("Arduino Received: ");
            Serial.print(inData);

            inData = ""; // Clear recieved buffer
        }
    }
}

In case this is not working change your processing code line:
myPort.write(value);
to
myPort.println(value);
or
myPort.write(value);
myPort.write('\n');

The communication between the arduino and processing is 9600bit/s I suppose.
This will mean, that one bit needs 0.104ms to be sent. But with your Arduino code and the while-function you don't wait till the 8 bits of your byte are arrived and the arduino-loop is to fast for the serial connection. Wit other words: you cant use our wihile() function, use an if statement:
int x;
if (Serial.available()>0) {
  x = Serial.read();
}

and for debugging you can include once more the Serial.print()-function
(Sorry for my terrible English...)


text:
Multiple independent LED patterns
I have an problem, which at first thoughts (and being new to Arduino) I though was a perfect application for an Arduino. However, after trying and failing to implement it I am doubting myself!
Simply - I need to control many LEDs independently, many of which will have their own individual patterns - for example "5 seconds on - 5 seconds off". "continuous flashes" - or sequences such as "2 flashes, pause, 1 flash". Obviously without the luxury of threads I am becoming a little unstuck. Be great to hear if a) Arduino is the best choice and b) if it is - how can I go about this!
Thanks in advance :)

Have you looked into protothreads? There are a couple of Arduino libraries that let you easily incorporate protothreads in your project.

Use Arduino library NonBlockingSequece. It has many clean examples to answer this specific question.

Handling multiple patterns at the same time is certainly possible with a platform like Arduino, and there are a number of ways you could go about it.
One method I would consider is writing functions which effectively represent each pattern mathematically. You'd just pass it the total time that's elapsed in your program so far, and it will do the appropriate action for that specific moment in time. It will return immediately afterwards (no delays or anything).
To do that, you'll first need to know how long a single cycle of the pattern lasts. You can then use the modulo operator to figure out how far through the current cycle you are. From there, all you need to do is have some if conditions to determine what to do at any given time.
Here's what it might look like for your "5 seconds on, 5 seconds off" pattern:
function pattern5on5off(unsigned long totalTime)
{
  // Calculate how far through the current cycle we are
  const unsigned long cycleTime = totalTime % 10000;

  // If we're in the first 5 seconds of the cycle then turn the light on.
  // Otherwise, turn it off.
  if (cycleTime < 5000)
    digitalWrite(3, HIGH);
  else
    digitalWrite(3, LOW);
}

Admittedly, constantly calling digitalWrite() when you don't technically need to isn't very efficient. It shouldn't cause any harm though, and is fairly easy to optimise if necessary.
To use the above example in a sketch, you'd just need to call it in loop(), and pass the number you get from millis(); e.g.:
void loop()
{
  const unsigned long totalTime = millis();

  pattern5on5off(totalTime);

  // call other patterns here...
}

Other patterns will be more complex, but follow the same principle. You'd just to use appropriate if statements to express your logic.
The vital thing to remember is that the function represents a specific moment in time. It should never pause or delay the program, otherwise it will prevent the other patterns from running.
Edit: Timing on the first cycle
As jfpoilpret noted in the comments, the very first cycle will start at a random point. This is because the first time you call millis() in loop(), it won't start at 0 (the device will already have been running for a short time before loop() gets called). It's easy to resolve though, if necessary.
You would do it by offsetting the totalTime value by the whatever value you got on the very first time around loop(). For example:
unsigned long g_startTime = 0;

void loop()
{
  unsigned long totalTime = 0;

  if (g_startTime == 0) {
    // This is the first cycle.
    // Store the start time so we can compensate later.
    g_startTime = millis();

  } else {
    // This is not the first cycle.
    // Compensate for the start time.
    totalTime = millis() - g_startTime;
  }

  pattern5on5off(totalTime);
  // etc..
}

Thank you so much - makes perfect sense! Ive definitely been banging my head against a wall with the wrong approach... :)

The problem with the % approach is that the timing won't be correct the very first time, as it will be just random at first.

@jfpoilpret That's true. It's easy to fix though, so I've added it to my answer. :)

Another option would be, instead of running millis once in the loop and pass its value as a parameter to every led function, to have each function as a parameterless one, and run millis inside each one. That would allow each function to get a more precise value, which might or might not be important depending on how much time each function in the loop takes to run, and also the timing correctness requirements of the application.

Arduino is a fine choice for the task - easy to get started with. The key is to write non-blocking code. You could take a look at the BlinkWithoutDelay example.
I made a suggestion for your task:
// Timing suquences for the LED's in milliseconds
// First value is on time, second value is off time,
// third value on time and so on (up to 10 values)
// One row for each LED
unsigned int led_timing[][10] = {
  {5000, 5000},
  {100, 1000},
  {100, 100, 100, 1500, 100, 1500}
};

// The pins the LED's are connected to
byte led_pins[] = {11, 12, 13};

// Keep track of timing sequence
// Array size taken from led_pins
unsigned long last_change[sizeof(led_pins)/sizeof(led_pins[0])];
byte timing_i[sizeof(led_pins)/sizeof(led_pins[0])];

void setup()
{
  // Initialize LED's as output
  for (byte i = 0; i < sizeof(led_pins)/sizeof(led_pins[0]); i++)
  {
    pinMode(led_pins[i], OUTPUT);
    digitalWrite(led_pins[i], HIGH);
  }
}

void loop()
{
  // Current timestamp
  unsigned long now = millis();

  // Keep track of sequence for each LED
  for (byte i = 0; i < sizeof(led_pins)/sizeof(led_pins[0]); i++)
  {
    if (now - last_change[i] >= led_timing[i][timing_i[i]])
    {
      digitalWrite(led_pins[i], !digitalRead(led_pins[i]));
      timing_i[i]++;

      // Start over at the end of timing sequence
      timing_i[i] %= sizeof(led_timing[i])/sizeof(led_timing[i][0]);

      last_change[i] = now;
    }
  }
}

I know the post is old, but I checked the example with the array based approach and in my opinion:
sizeof(led_timing[i])/sizeof(led_timing[i][0])

will always yield the allocated size (number of elements) of the array - in this case 10. So the timing won't restart until you reached the "end" of the array, using undefined elements. For LED "0":
int led_timing[0][10]:
5000,5000, <undefined>, <undefined>, <undefined>, <undefined>, <undefined>, <undefined>, <undefined>, <undefined>

Greetings
 Tommy

source: Stack Exchange

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

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

sort: votes


text:
Programming Arduino Pro mini 328 with Arduino Uno SMD
I apologize in advance, because there is a lot of tutorials out there about programming arduinos with another arduino, however I can't find really simple one I could understand.
I have Arduino Uno SMD version and Arduino Pro mini 328. I want to upload sketch to Arduino Pro mini using Arduino Uno in ISP mode (I guess).
I want to know EXACTLY which pins need to be connected and if all I need is Arduino IDE to upload my sketch to Pro mini ?
Thank you for your help.

For  upload sketch to Arduino Pro mini, unless your code size is really big and run out of space, many people use FTDI style USB to serial board (6 finger nails sized) to download via bootloader. There are tons of tutorial with good diagram. Try search by these keyword. Sparkfun and arduino.cc should have needed info for you

@JohnWilliams Thanks for comment. However, I don't want to buy another board. I just want to use my 2 existing ones.

How exactly have existing guides and tutorials failed you?

@IgnacioVazquez-Abrams Well, I haven't actually found any which would cover exactly my scenario - meaning Arduino Uno SMD and Pro mini 328.

ISP via the Arduino is still done the same way regardless.

You should be able to take the Uno-as-target instructions and use them with the mini simply by connecting to the same (Arduino) pin names - digital 10 through 13 and RST (reset).

@ChrisStratton Ok, but what bothers me are advices about removing Atmel chip from its socket in Arduino Uno. But I have SMD version, so it's not possible. This really confuses me.

The ISP instructions do not involve doing that.  You might be thinking of instructions for using an Arduino with it's main processor removed as a USB-serial interface to talk to the bootloader of one without its own USB interface; but you said you wanted to use ISP programming rather than bootloader programming.

OK and could you point me to some comprehensive tutorial ? I am looking at http://arduino.cc/en/Tutorial/ArduinoISP but it's not about Arduino Pro mini - I don't know if there is something special involved or I can wire it as in first diagram. This tutorial talks about burning bootloader, but I want to upload my sketch, I am really confused here.

@Frodik, two different things. ISP programming is used to program the boot loader, which is a small program that runs on startup and allows for larger programs to be uploaded using serial. You need a USB to serial converter. It has a USB port and a female header that connect to the 6 pins on the arduino pro.

@geometrikal I apology for my confusion. Now your comment makes sense. So please, what do I do if I want to just upload my sketch ? I am pretty sure that my Pro mini already has Arduino bootloader.

You use the same setup you would as for burning a bootloader, only in the software you select something like upload using programmer and select arduino as ISP as the programmer.  Long term you are going to want that logic-level USB serial cable anyway, as it enables you to get debug output from your sketch.

check this tutorial:

http://www.instructables.com/id/Arduino-Examples-2-Use-an-Arduino-as-a-FTDI-Progr/

Works fine for me (I have a redboard, also with SMD microcontroller). In short this is the pinMap:
UNO BOARD (SMD)    Pro Mini 5V
       GND             GND
       5V              VCC
       RX              RX1
       TX              TX1
       Reset           GRN

Just to be sure, RX and TX on Uno board are digital pins 1 and 2, right ? But that would mean, that if I wanted to upload sketch to finished project which would have soldered all the digital pins to other modules, I couldn't use those 2 pins (RX,TX). That was the reason why I wanted to use ISP so I wouldn't have to sacrifice 2 pins.

@Frodik - ISP requires 3 pins plus reset, bootloader requires 2 plus reset.  That doesn't mean you have to reserve the pins, but it does mean you can't use them for things which conflict.  For example, you can use them as outputs from the ATmega to peripherals, as long as spurious operation of the peripherals during programming is not problematic.  But you shouldn't use them to read from peripherals which might problematically drive signals onto those pins during the programming.

@ChrisStratton But if I understand it correctly, ISP requires different pins than digital 1-13, right ?

@Frodik As Chris mentioned, 3 pins are used, these pins are D11, D12, D13. The arduino website shows this http://arduino.cc/en/Tutorial/ArduinoISP. Remember that a Pro Mini is literally an Uno that got shrunk.

Please check this tutorial if you want to upload sketches to Pro mini with Arduino UNO with SDM chip
http://www.instructables.com/id/Uploading-sketches-to-Pro-Mini-using-Arduino-UNO-b

It is preferable to answer questions directly rather than simply linking to external sites. Adding a summary of the Instructable text, specifically address the question asked by the OP about which pins are involved, would go a long way to helping the the OP, other people with the same problem, and getting your answer accepted.

Following the tutorial on http://www.instructables.com/id/Arduino-Examples-2-Use-an-Arduino-as-a-FTDI-Progr/ I was able to upload the blink sketch to the Pro Mini 5V version with an Arduino Nano. After I tried uploading the sketch that I really wanted to use but got many errors in the IDE I tried a couple more with no luck. I had stumble on another article earlier about using the Arduino Nano to program the Pro Mini http://www.electronicsmayhem.com/?p=31. I had tried that method but with no luck but using the first tutorial & only changing one thing from it with info from the article i mentioned I was able to upload the sketch without any errors. The only thing I changed was I didn't connect the TX from the Nano to the TXI of the Mini.
   Arduino Nano     Pro Mini 5V
       GND-------------GND
       5V--------------VCC
       RX--------------RX1
       Reset-----------GRN(DTR)

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


text:
Why echo "R" > /dev/ttyUSB0 doesn't work, but on the same PC Serial Monitor in Arduino IDE works?
I have a strange problem. I am running Ubuntu and NodeMCU si plugged into USB. I have very simple sketch running on it, when it reads letter "R" on serial, it turns ON relay.
When I open Serial Monitor in Arduino IDE and I type letter "R" and send it, it works perfectly. However when I run commands below, it does nothing:
stty -F /dev/ttyUSB0 115200
echo "R" > /dev/ttyUSB0

I tried running the same commands on different PC with Ubuntu and these system commands work just fine.
I also tried copying exact same configuration from stty -a -F /dev/ttyUSB from PC where it works to PC where it doesn't, but it didn't help either.
I don't think it's driver issue, because if it would, then I suppose it wouldn't work with Serial Monitor also.
Thank you for any help or hints in advance.

Do you have something else plugged through USB in the PC where it does not work? Maybe the NodeMCU is ttyUSB1?

Does this answer your question? How to connect Arduino device to Linux?

Are you waiting a bit between opening the port and sending the data? The Arduino might not yet be ready to receive data directly after opening the port (since it resets)

Try executing: stty -F /dev/ttyUSB0 -hupcl

OK, so I resolved this problem, but only half-way. I was using NodeMCU with CH340 ... and this controller worked only in Serial Monitor, not in command shell on one computer (it worked fine on other computer).
So I tried using different NodeMCU with CP2102 and it worked just fine. So I assume there must be some kind of issue with ch341 driver in my linux, I don't know.

I had the same issue.
After entering command that Majenko suggested:
stty -F /dev/ttyUSB0 -hupcl

I still wasn't able to send commands to Arduino nano.
Strangely, when I open Arduino IDE Serial Monitor and send command it works.
When I close it, I can send commands in terminal to Arduino for some time. Then it stops working again :/

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


text:
How to measure direction the car is coming to garage door?
my garage door is pretty narrow, about 10 cm (4") on each side of my car's rear mirrors. So every time I drive to garage, I need to go very slowly because I am afraid I might not be lined up correctly.
I am thinking about using Arduino and some sensors to help me. Output is pretty simple, just two leds, one for each side, showing me if I should turn little right or left to have perfect lineup to center. This I can handle with no problem
What I am asking for is idea how to measure the alignment of my car. I know how to use ultrasonic sensors for measuring distance. But I am not sure they are suitable for this project, because I want preferably to put arduino and sensors in my garage, not in my car.
Any idea how to work this out ?

It is very hard to determine position accurately there is a new project on kickstarter called Pozyx, you can look at that but that's expensive, to be honest this sounds like a job for hanging tennis balls or strings or something like that. But if you have a lot of money to blow and you just want a project go for it, you may be able to do this with ultrasonic sensors but I reckon that would be painful. Anyway good luck

It seems like an ultrasonic sensor on each door-post should do it. You need, I'm guessing, 30cm to the sides of your car as its nose enters the doorway. Smooth the sensor reading, compute a difference and display the sign of the differences as right/left lights. Keep a small dead-band around zero-difference or you'll drive the driver crazy!
Do Ultrasonic sensors have the range and accuracy you need for the job? Time for a feasibility study.
Update:
Is 10cm plus the length of a mirror = a couple of feet? But even if so, you have to keep to +/- 10cm of the centerline to prevent striking the mirrors, so you could project your sensors out into the doorway by an amount the still keeps them > 10cm away from the car. You could mount them hinged (like the mirrors are) and padded to limit any damage from the occasional accidental touch.

I am little afraid, that general ultrasound sensor SR04 will not be useful, because of its wide angle. It might work when the car is pretty close to sensor but it will get false readings when the car is far from the sensors (couple of feet). So I would have to slow down or stop anyway, which is the problem I want to avoid with this project :-)

Try to place two distance ranging sensors like ultrasonic or active infrared at the sides of the driveway or garage door. Make sure that their readings are similar so that you know that you are in the center. If one has a higher reading(farther distance) light an led to your right so you know  to go that direction and vice versa. Use communication through xbees, bluetooth, or something similar.


text:
How to fix memory-leak code in ESP8266/NodeMCU caused by string concenation?
I have following code in loop() in NodeMCU.
This part is before setup():
String serial_data_read = "";   // for incoming serial string data
String serial_data = "";   // for incoming serial string data

This part is in loop():
if ((last_weight_time < millis() - 1000)) {
   last_weight_time = millis();
   serial_data_read = "";
   Serial.print("P");
   while(Serial.available()) {
      character = Serial.read();
      serial_data_read.concat(character);
   }
   serial_data = serial_data_read;
}

I don't understand C programming that much, but I think it has something to do with memory leaking and eventually running out of memory. It runs for around 20 minutes and then just stops. When I manually restart NodeMCU it runs again fine.
I would be very grateful for any help, how to rewrite my code so it doesn't leak memory. Thank you very much.

Just don't use String, but char arrays instead

https://majenko.co.uk/blog/evils-arduino-strings

Re if ((last_weight_time < millis() - 1000)): This can fail badly if last_weight_time is right before a millis() rollover event. Use instead the idiom if (millis() - last_weight_time > 1000), which is rollover safe.

To write code that will not cause memory leak, you need to understand of where and what caused the memory leak first. The memory leak in this particular case is caused by the line
serial_data_read.concat(character);

When you instantiate a String object with String serial_data_read = "", Arduino String class create a memory allocation using dynamic memory allocation in the heap, and since your initialised it with "", it therefore create a minimum size of allocation. This is all good if you know how to the dynamic memory is created and how it going to be used.
The problem started when you start doing String concatenation with the line serial_data_read.concat(character), the original allocation for your global variable serial_data_read is no longer have enough space for the concatenated variable, so it create a temporary variable in the heap and do the concatenation, and then eventually put the result back to this newly allocated memory for serial_data_read on the heap, leaving a hole at the heap for the original serial_data_read variable (and the temp variable).
What make this worst is that this is happening for each iteration every 16 iterations(see Edgar Bonet's comment below) of the while loop. Theoretically the old serial_data_read prior the concatenation should be free-up at some point (e.g. if your while loop is within a function, the part of the heap might be free-up at the exit of the function), it however does not necessary be the case because your newly created serial_data_read stay on top of piles of to-be-free-up memory that blocking the free up(think of a piece of cheese with a lot of holes on it), so the heap memory get less and less at each iteration.
Short term fix - do not do String concatenation in a loop
String class is not always evil if you know what's going on and how to use it. One of the quick fix for your problem is simply do not do String concatenation within a loop. And if you are using it within a function, keep it local. This will minimise the heap fragmentation.
if ((last_weight_time < millis() - 1000)) {
   last_weight_time = millis();
   if (Serial.available() > 0) {
      String serial_data_read = Serial.readStringUntil('\n');
   }
}

BTW, you can add ESP.getFreeHeap() in your loop() to check if there is still memory leak.
Long term fix - Don't use String class
For a better fix, and especially for some one new to the programming or C/C++, do not use String class and learn how to use c string and array. Here is the version without using String class.
length = 80;
char buffer[length] = {0};
if ((last_weight_time < millis() - 1000)) {
   last_weight_time = millis();
   while(Serial.available()) {
      Serial.readBytesUntil('\n', buffer, length);
   }
}

Other resources to learn about
https://www.cplusplus.com/reference/cstring/ all the functions for c string and array manipulation to replace Arduino String class.
https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

Re “[heap allocation] is happening for each iteration of the while loop”: on the ESP8266, it happens once every 16 iterations, as the allocated size is grown by multiples of 16 bytes. Re “if your while loop is within a function, the part of the heap might be free-up at the exit of the function”: when concat() can't manage to grow the string in place, it will allocate a new buffer, copy the existing data, and free the previous buffer right away. This doesn't invalidate your point about the risk of memory fragmentation though.

The short answer is, don't use the String class at all. You need to read up on using C strings (which are simply null-terminated arrays of characters. There are C library functions for manipulating C strings. You'll want to avoid printf, scanf, and related functions, as the library that supports those is quite large
The basic idea is to use statically allocated C strings as buffers. Figure out the largest number of characters you need to store, and create a static array of characters at least one character larger (for the terminating null) and use that to collect the output you are building.

printf() and friends don't have much impact on - and cause no fragmentation of - data space. They take up more code-space than Serial.print() but most of us don't write sketches that push the code space limit.

@Duncan C - Thank you very much for your answer. Can you please add code example how my code would have to be rewritten ?

What @JRobert said. Avoiding String is good advice, avoiding printf, scanf is bad advice in this case; they don't cause issues with the heap and that's what this problem is.

Also the ESP8266 has plenty of code space (flash) even on a small variant. On small AVR chips the printf family use a cut-down version with floating point support removed to save space.

Good to know about the cut-down version of printf/scanf. To the OP: Disregard that part of my answer

even with printf support for floating point turn on via linker flags, it only impact the flash memory size by adding about 1500 bytes, it does not affect the use of SRAM.

SafeString is a great way to go.. only one instance of each SafeString can ever exist, and u can declare the length of each SafeString..


text:
error: redefinition of ' '
When I am trying to compile the following code,
int delayTime = 1;
int charBreak = 2.1;
#include <MemoryFree.h>

int rled1 = 1;
int rled2 = 2;
int rled3 = 3;
int rled4 = 4;
int rled5 = 5;
int gled1 = 6;
int gled2 = 7;
int gled3 = 8;
int gled4 = 9;
int gled5 = 10;
int bled1 = 11;
int bled2 = 12;
int bled3 = 13;
int bled4 = 14;
int bled5 = 15;

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

int ra[] = {4,288,18464,288,4};
int ga[] = {2,144,9232,144,2};
int ba[] = {1,72,4616,72,2};
int rb[] = {18724,16644,16644,2080,0};
int gb[] = {9362,8322,8322,1040,0};
int bb[] = {4681,4161,4161,520,0};
int rc[] = {2336,16388,16388,2080,0};
int gc[] = {1168,8194,8194,1040,0};
int bc[] = {584,4097,4097,520,0};
int rd[] = {18724,16388,16388,2336,0};
int gd[] = {9362,8194,8194,1168,0};
int bd[] = {4681,4097,4097,584,0};
int re[] = {18724,16644,16644,16388,0};
int ge[] = {9362,8322,8322,8194,0};
int be[] = {4681,4161,4161,4097,0};
int rf[] = {18724,16640,16640,16384,0};
int gf[] = {9362,8320,8320,8192,0};
int bf[] = {4681,4160,4160,4096,0};
int rg[] = {2336,16388,16420,16416,2084};
int gg[] = {1168,8194,8210,8208,1042};
int bg[] = {584,4097,4105,4104,521};
int rh[] = {18724,256,256,256,18724};
int gh[] = {9362,128,128,128,9362};
int bh[] = {4681,64,64,64,4681};
int ri[] = {0,16388,18724,16388,0};
int gi[] = {0,8194,9362,8194,0};
int bi[] = {0,4097,4681,4097,0};
int rj[] = {32,4,16388,18720,16384};
int gj[] = {16,2,8194,9360,8192};
int bj[] = {8,1,4097,4680,4096};
int rk[] = {18724,256,2080,16388,0};
int gk[] = {9362,128,1040,8194,0};
int bk[] = {4681,64,520,4097,0};
int rl[] = {18724,4,4,4,0};
int gm[] = {9362,2,2,2,0};
int bm[] = {4681,1,1,1,0};
int rm[] = {18724,2304,36,2304,18724};
int gm[] = {9362,1152,18,1152,9362};
int bm[] = {4681,576,9,576,4681};
int rn[] = {18724,2304,36,18724,0};
int gn[] = {9362,1152,18,9362,0};
int bn[] = {4681,576,9,4681,0};
int ro[] = {2336,16388,16388,2336,0};
int go[] = {1168,8194,8194,1168,0};
int bo[] = {584,4097,4097,584,0};
int rp[] = {18724,16640,16640,2048,0};
int gp[] = {9362,8320,8320,1024,0};
int bp[] = {4681,4160,4160,512,0};
int rq[] = {2336,16388,16420,2336,36};
int gq[] = {1168,8194,8210,1168,18};
int bq[] = {584,4097,4105,584,9};
int rr[] = {18724,16640,16672,2052,0};
int gr[] = {9362,8320,8336,1026,0};
int br[] = {4681,4160,4168,513,0};
int rs[] = {2048,16644,16644,32,0};
int gs[] = {1024,8322,8322,16,0};
int bs[] = {512,4161,4161,8,0};
int rt[] = {16384,16384,18724,16384,16384};
int gt[] = {8192,8192,9362,8192,8192};
int bt[] = {4096,4096,4681,4096,4096};
int ru[] = {18720,4,4,18720,0};
int gu[] = {9360,2,2,9360,0};
int bu[] = {4680,1,1,4680,0};
int rv[] = {18432,288,4,288,18432};
int gv[] = {9216,144,2,144,9216};
int bv[] = {4608,72,1,72,4608};
int rw[] = {18688,36,2304,36,18688};
int gw[] = {9344,18,1152,18,9344};
int bw[] = {4672,9,576,9,4672};
int rx[] = {16388,2080,256,2080,16388};
int gx[] = {8194,1040,128,1040,8194};
int bx[] = {4097,520,64,520,4097};
int ry[] = {16388,2080,256,2048,16384};
int gy[] = {8194,1040,128,1024,8192};
int by[] = {4097,520,64,512,4096};
int rz[] = {16420,16644,16644,18436,0};
int gz[] = {8210,8322,8322,9218,0};
int bz[] = {4105,4161,4161,4609,0};
int reos[] = {0,4,0,0,0};
int geos[] = {0,2,0,0,0};
int beos[] = {0,1,0,0,0};
int rque[] = {2048,16420,16640,2048,0};
int gque[] = {1024,8210,8320,1024,0};
int bque[] = {512,4105,4160,512,0};
int rexcl[] = {0,18692,0,0,0};
int gexcl[] = {0,9346,0,0,0};
int bexcl[] = {0,4673,0,0,0};

void displayLine(int line)
{
  int myline; myline = line;
  if (myline>=16384) {digitalWrite(rled1, HIGH); myline-=16384;} else {digitalWrite(rled1, LOW);}
  if (myline>=8192) {digitalWrite(gled1, HIGH); myline-=8192;} else {digitalWrite(gled1, LOW);}
  if (myline>=4096) {digitalWrite(bled1, HIGH); myline-=4096;} else {digitalWrite(bled1, LOW);}
  if (myline>=2048) {digitalWrite(rled2, HIGH); myline-=2048;} else {digitalWrite(rled2, LOW);}
  if (myline>=1024) {digitalWrite(gled2, HIGH); myline-=1024;} else {digitalWrite(gled2, LOW);}
  if (myline>=512) {digitalWrite(bled2, HIGH); myline-=512;} else {digitalWrite(bled2, LOW);}
  if (myline>=256) {digitalWrite(rled3, HIGH); myline-=256;} else {digitalWrite(rled3, LOW);}
  if (myline>=128) {digitalWrite(gled3, HIGH); myline-=128;} else {digitalWrite(gled3, LOW);}
  if (myline>=64) {digitalWrite(bled3, HIGH); myline-=64;} else {digitalWrite(bled3, LOW);}
  if (myline>=32) {digitalWrite(rled4, HIGH); myline-=32;} else {digitalWrite(rled4, LOW);}
  if (myline>=16) {digitalWrite(gled4, HIGH); myline-=16;} else {digitalWrite(gled4, LOW);}
  if (myline>=8) {digitalWrite(bled4, HIGH); myline-=8;} else {digitalWrite(bled4, LOW);}
  if (myline>=4) {digitalWrite(rled5, HIGH); myline-=4;} else {digitalWrite(rled5, LOW);}
  if (myline>=2) {digitalWrite(gled5, HIGH); myline-=2;} else {digitalWrite(gled5, LOW);}
  if (myline>=1) {digitalWrite(bled5, HIGH); myline-=1;} else {digitalWrite(bled5, LOW);}

}

void displayChar(char c)
{
  if (c == 'ra'){for (int i = 0; i <5; i++){displayLine(ra[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rb'){for (int i = 0; i <5; i++){displayLine(rb[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rc'){for (int i = 0; i <5; i++){displayLine(rc2[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rd'){for (int i = 0; i <5; i++){displayLine(rd[i]);delay(delayTime);}displayLine(0);}
  if (c == 're'){for (int i = 0; i <5; i++){displayLine(re[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rf'){for (int i = 0; i <5; i++){displayLine(rf[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rg'){for (int i = 0; i <5; i++){displayLine(rg[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rh'){for (int i = 0; i <5; i++){displayLine(rh[i]);delay(delayTime);}displayLine(0);}
  if (c == 'ri'){for (int it = 0; it <5; it++){displayLine(ri[it]);delay(delayTime);}displayLine(0);}
  if (c == 'rj'){for (int i = 0; i <5; i++){displayLine(rj[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rk'){for (int i = 0; i <5; i++){displayLine(rk[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rl'){for (int i = 0; i <5; i++){displayLine(rl[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rm'){for (int i = 0; i <5; i++){displayLine(rm[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rn'){for (int i = 0; i <5; i++){displayLine(rn[i]);delay(delayTime);}displayLine(0);}
  if (c == 'ro'){for (int i = 0; i <5; i++){displayLine(ro[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rp'){for (int i = 0; i <5; i++){displayLine(rp[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rq'){for (int i = 0; i <5; i++){displayLine(rq[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rr'){for (int i = 0; i <5; i++){displayLine(rr[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rs'){for (int i = 0; i <5; i++){displayLine(rs[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rt'){for (int i = 0; i <5; i++){displayLine(rt[i]);delay(delayTime);}displayLine(0);}
  if (c == 'ru'){for (int i = 0; i <5; i++){displayLine(ru[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rv'){for (int i = 0; i <5; i++){displayLine(rv[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rw'){for (int i = 0; i <5; i++){displayLine(rw[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rx'){for (int i = 0; i <5; i++){displayLine(rx[i]);delay(delayTime);}displayLine(0);}
  if (c == 'ry'){for (int i = 0; i <5; i++){displayLine(ry[i]);delay(delayTime);}displayLine(0);}
  if (c == 'rz'){for (int i = 0; i <5; i++){displayLine(rz[i]);delay(delayTime);}displayLine(0);}
  if (c == 'r!'){for (int i = 0; i <5; i++){displayLine(rexcl[i]);delay(delayTime);}displayLine(0);}
  if (c == 'r?'){for (int i = 0; i <5; i++){displayLine(rques[i]);delay(delayTime);}displayLine(0);}
  if (c == 'r.'){for (int i = 0; i <5; i++){displayLine(reos[i]);delay(delayTime);}displayLine(0);}
  if (c == 'ga'){for (int i = 0; i <5; i++){displayLine(ga[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gb'){for (int i = 0; i <5; i++){displayLine(gb[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gc'){for (int i = 0; i <5; i++){displayLine(gc2[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gd'){for (int i = 0; i <5; i++){displayLine(gd[i]);delay(delayTime);}displayLine(0);}
  if (c == 'ge'){for (int i = 0; i <5; i++){displayLine(ge[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gf'){for (int i = 0; i <5; i++){displayLine(gf[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gg'){for (int i = 0; i <5; i++){displayLine(gg[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gh'){for (int i = 0; i <5; i++){displayLine(gh[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gi'){for (int it = 0; it <5; it++){displayLine(gi[it]);delay(delayTime);}displayLine(0);}
  if (c == 'gj'){for (int i = 0; i <5; i++){displayLine(gj[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gk'){for (int i = 0; i <5; i++){displayLine(gk[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gl'){for (int i = 0; i <5; i++){displayLine(gl[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gm'){for (int i = 0; i <5; i++){displayLine(gm[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gn'){for (int i = 0; i <5; i++){displayLine(gn[i]);delay(delayTime);}displayLine(0);}
  if (c == 'go'){for (int i = 0; i <5; i++){displayLine(go[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gp'){for (int i = 0; i <5; i++){displayLine(gp[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gq'){for (int i = 0; i <5; i++){displayLine(gq[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gr'){for (int i = 0; i <5; i++){displayLine(gr[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gs'){for (int i = 0; i <5; i++){displayLine(gs[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gt'){for (int i = 0; i <5; i++){displayLine(gt[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gu'){for (int i = 0; i <5; i++){displayLine(gu[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gv'){for (int i = 0; i <5; i++){displayLine(gv[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gw'){for (int i = 0; i <5; i++){displayLine(gw[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gx'){for (int i = 0; i <5; i++){displayLine(gx[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gy'){for (int i = 0; i <5; i++){displayLine(gy[i]);delay(delayTime);}displayLine(0);}
  if (c == 'gz'){for (int i = 0; i <5; i++){displayLine(gz[i]);delay(delayTime);}displayLine(0);}
  if (c == 'g!'){for (int i = 0; i <5; i++){displayLine(gexcl[i]);delay(delayTime);}displayLine(0);}
  if (c == 'g?'){for (int i = 0; i <5; i++){displayLine(gques[i]);delay(delayTime);}displayLine(0);}
  if (c == 'g.'){for (int i = 0; i <5; i++){displayLine(geos[i]);delay(delayTime);}displayLine(0);}
  if (c == 'ba'){for (int i = 0; i <5; i++){displayLine(ba[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bb'){for (int i = 0; i <5; i++){displayLine(bb[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bc'){for (int i = 0; i <5; i++){displayLine(bc2[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bd'){for (int i = 0; i <5; i++){displayLine(bd[i]);delay(delayTime);}displayLine(0);}
  if (c == 'be'){for (int i = 0; i <5; i++){displayLine(be[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bf'){for (int i = 0; i <5; i++){displayLine(bf[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bg'){for (int i = 0; i <5; i++){displayLine(bg[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bh'){for (int i = 0; i <5; i++){displayLine(bh[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bi'){for (int it = 0; it <5; it++){displayLine(bi[it]);delay(delayTime);}displayLine(0);}
  if (c == 'bj'){for (int i = 0; i <5; i++){displayLine(bj[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bk'){for (int i = 0; i <5; i++){displayLine(bk[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bl'){for (int i = 0; i <5; i++){displayLine(bl[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bm'){for (int i = 0; i <5; i++){displayLine(bm[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bn'){for (int i = 0; i <5; i++){displayLine(bn[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bo'){for (int i = 0; i <5; i++){displayLine(bo[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bp'){for (int i = 0; i <5; i++){displayLine(bp[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bq'){for (int i = 0; i <5; i++){displayLine(bq[i]);delay(delayTime);}displayLine(0);}
  if (c == 'br'){for (int i = 0; i <5; i++){displayLine(br[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bs'){for (int i = 0; i <5; i++){displayLine(bs[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bt'){for (int i = 0; i <5; i++){displayLine(bt[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bu'){for (int i = 0; i <5; i++){displayLine(bu[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bv'){for (int i = 0; i <5; i++){displayLine(bv[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bw'){for (int i = 0; i <5; i++){displayLine(bw[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bx'){for (int i = 0; i <5; i++){displayLine(bx[i]);delay(delayTime);}displayLine(0);}
  if (c == 'by'){for (int i = 0; i <5; i++){displayLine(by[i]);delay(delayTime);}displayLine(0);}
  if (c == 'bz'){for (int i = 0; i <5; i++){displayLine(bz[i]);delay(delayTime);}displayLine(0);}
  if (c == 'b!'){for (int i = 0; i <5; i++){displayLine(bexcl[i]);delay(delayTime);}displayLine(0);}
  if (c == 'b?'){for (int i = 0; i <5; i++){displayLine(bques[i]);delay(delayTime);}displayLine(0);}
  if (c == 'b.'){for (int i = 0; i <5; i++){displayLine(beos[i]);delay(delayTime);}displayLine(0);}
  delay(charBreak);
}

void displayString(char* s)
{
  for (int i = 0; i<=strlen(s); i++)
  {
  displayChar(s[i]);
  }
}

void loop()
{
  displayString("sunil");
  Serial.print("freeMemory()=");
    Serial.println(freeMemory());
}

I am getting the following error.
sketch_jul17b:63: error: redefinition of 'int gm []'
sketch_jul17b:60: error: 'int gm [5]' previously defined here
sketch_jul17b:64: error: redefinition of 'int bm []'
sketch_jul17b:61: error: 'int bm [5]' previously defined here
sketch_jul17b.ino: In function 'void displayChar(char)':
sketch_jul17b:139: error: 'rc2' was not declared in this scope
sketch_jul17b:164: error: 'rques' was not declared in this scope
sketch_jul17b:168: error: 'gc2' was not declared in this scope
sketch_jul17b:177: error: 'gl' was not declared in this scope
sketch_jul17b:193: error: 'gques' was not declared in this scope
sketch_jul17b:197: error: 'bc2' was not declared in this scope
sketch_jul17b:206: error: 'bl' was not declared in this scope
sketch_jul17b:222: error: 'bques' was not declared in this scope

I don't know why this error is occurring.

Redefining variable names is a huge reason to avoid meaningless names like you're using. Use names like "RedLedPinNumber" and "RedLedCurrentState" and "GreenLedCurrentState" - MUCH easier to remember if you created one of those already. Variables take up the same amount of memory regardless of their names.

You have a combination of trying to define the same name twice, for example "gm"
int gm[] = {9362,2,2,2,0};
int bm[] = {4681,1,1,1,0};
int rm[] = {18724,2304,36,2304,18724};
int gm[] = {9362,1152,18,1152,9362};

And using others such "rc2" which you have never defined.
Your code won't compile and work until you make it self-consistent.

Please note that user2973 has found some additional problems in your code beyond the error messages you posted.

This can also happen if you have saved a version of the code (for example duplicate file for backup) within the current sketch folder.

No worries, thanks for the comment! I knew this was going to help some-one as it is an easy mistake to make. (I did it when I duplicated the file inside the sketch folder. This would be the same as creating a tab page inside the IDE so the code is double defined. Which is the same problem as the original question. Hence the same error.

The first errors happen because you are trying to define a variable with the same name in the same scope twice, like here:
int gm[] = {9362,2,2,2,0};
int bm[] = {4681,1,1,1,0};
int rm[] = {18724,2304,36,2304,18724};
int gm[] = {9362,1152,18,1152,9362};

gm is defined two times which is not allowed.
The other error happens because you are referencing variables you never declared like here:
if (c == 'rc'){for (int i = 0; i <5; i++){displayLine(rc2[i]);delay(delayTime);}displayLine(0);}

rc2 isn't defined anywhere.

Besides there are some other issues with your code:
int charBreak = 2.1;

int types can only contain whole numbers, so charBreak will be set to two and not two point one. You probably wan't to use a float.
In void displayChar(char c) you try to compare a char with two chars:
if (c == 'ra')

That won't work. The char type can only contain a single character, so the comparison will always be false. Two chars like this 'ab' in single quotes are interpreted as 16 bit number. Two chars in double quotes are interpreted as a null-terminated string:
char cstring1[] = "ab";
char cstring2[] = {'a', 'b', '\0'};

if (strcmp(cstring1, cstring2) == 0)
  // The two strings are identical

strcmp returns 0 on match-.

Thank you so much for the help with comparing characters. I was actually stuck there.


text:
GPS logging on SD card using TinyGPS
I'm a beginner in Arduino world and I want to create a simple SD datalogger that works with GPS (module NEO-6M) and light sensor. I know there are a number of tutorials on GPS logging including:

Create a GPS Data Logger Using The Arduino (Bob Cravens)
Geo Data Logger: Arduino+GPS+SD+Accelerometer (Instructables)
Making a SD card GPS logger with Arduino and MTK3329 GPS module (Arduinodev)

but my problem is that those tutorials are either too complex (i.e. include extra stuff like displays) or they don't use TinyGPS or TinyGPS++ library. In the first step I've managed to get GPS working and displaying the result on my laptop screen (via Serial.print()) using example code from TinyGPS library. In the next step I managed to use tutorial for Adafruit Data Logger to log data on SD card. The problem: light sensor logs ok, but for GPS it only logs a strings of 99.999999. Tried various tweaks but so far not sure what I got wrong. I use Arduino Uno, NEO-6M GPS, Catalex MicroSD Card Adapter, simple LDR. Here is my current code:
    #include <TinyGPS++.h>
    #include <SoftwareSerial.h>
    #include "SD.h"

    //input for the light detecting sensor (LDR)
    int LDR = A3;

    //inputs and triggers for GPS
    TinyGPSPlus gps;
    SoftwareSerial ss (7, 8); // TX=7, RX=8

    // digital pin 4 for the SD cs line
    const int chipSelect = 4;
    File logfile;// the logging file

    //data logger timing and other
    #define LOG_INTERVAL  1000 // mills between entries
    #define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
    uint32_t syncTime = 0; // time of last sync()
    #define ECHO_TO_SERIAL   1 // echo data to serial port
    #define WAIT_TO_START    0 // Wait for serial input in setup()

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

      #if WAIT_TO_START
        Serial.println("Type any character to start");
        while (!Serial.available());
      #endif //WAIT_TO_START

      // initialize the SD card
      Serial.print("Initializing SD card...");

      pinMode(10, OUTPUT);

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

      // create a new file
      char filename[] = "LOGGER00.CSV";
      for (uint8_t i = 0; i < 100; i++) {
        filename[6] = i/10 + '0';
        filename[7] = i%10 + '0';
        if (! SD.exists(filename)) {
          // only open a new file if it doesn't exist
          logfile = SD.open(filename, FILE_WRITE);
          break;  // leave the loop!
        }
      }

      Serial.print("Logging to: ");
      Serial.println(filename);

      logfile.println("date,time,lat,long,light");

      #if ECHO_TO_SERIAL
        Serial.println("lat,log,date,time,altitude,light");
      #endif// attempt to write out the header to the file
    }

void loop(void) {

   // delay for the amount of time we want between readings
   delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL));

   //here is GPS data (if I got it right)
   while (ss.available() > 0)
   gps.encode(ss.read());
   logfile.print(gps.date.value());
   logfile.print(", ");
   logfile.print(gps.time.value());
   logfile.print(", ");
   logfile.print(gps.location.lat(), 6);
   logfile.print(", ");
   logfile.print(gps.location.lng(), 6);
   logfile.print(", ");
   #if ECHO_TO_SERIAL
      Serial.print(gps.date.value());
      Serial.print(", ");
      Serial.print(gps.time.value());
      Serial.print(", ");
      Serial.print(gps.location.lat(), 6);
      Serial.print(", ");
      Serial.print(gps.location.lng(), 6);
      Serial.print(", ");
   #endif

   //Read light intensity
   float lux = 500/(10.72/(5-(photocellReading * 0.00488759))*(photocellReading * 0.00488759));
   logfile.println(lux);
   #if ECHO_TO_SERIAL
      Serial.println(lux);
   #endif //ECHO_TO_SERIAL

   //write data to disk
   if ((millis() - syncTime) < SYNC_INTERVAL) return;
   syncTime = millis();
   logfile.flush();
}

file.print maybe has different arguments - http://arduino.cc/en/Reference/FilePrint

have you seen Jeremy Blum's tutorial here?
http://www.jeremyblum.com/2012/07/16/tutorial-15-for-arduino-gps-tracking/comment-page-1/ I'm just trying to get it working with the UBlox LEA 6H at the moment. I think tinyGPS library may have changed slightly since he made the tutorial but it doesn't seem too hard to follow so far otherwise.


text:
Very long delay() possible?
I'm trying to make an opening and closing little door that should open or close every 12 hours. I was wondering if I could just make a small looping script with a delay() for 12 hours, delay(43 200 000 000); I guess? However, I have no idea if that's possible and/or recommendable. Some feedback/alternatives(if needed) would be nice :)

ok, i think delay has a max of 65535 µs, but now i need an alternative...

Timing in more mature, MCU-alone systems is usually done by programming a hardware timer channel of the MCU to fire an interrupt periodically, and then counting these - that lets the processor do other things in the meantime, and is cumulatively as accurate as the clock crystal.

Using delay will magnify an ever so slight overhead error. It is better to use an interrupt to time a known good period and then count from there. Here is a proof of concept on my personal website: http://blog.linformatronics.nl/213/electronics/timed-1-millisecond-interrupt-routine-for-arduino

If it doesn't have to be perfectly timed, you can use unconventional things, like a light sensor to sense morning and evening.

yes, I thought about that, however I only have a little light detector part and I'm not sure how to protect it from the weather (the little door is outside)

I want 20 minutes low and 3 minutes high program structure. I have arduino uno board

The real time clock method is the most accurate way but otherwise use millis
unsigned long startMillis = millis();
while (millis() - startMillis < LONG_DELAY_MS);

This will delay up to approx. 4294967295ms (2^32-1) or 49 days, after which the timer will catch up to the value of startMillis

What is wrong with just using delay(LONG_DELAY_MS)? The arduino implementation accepts unsigned longs. I'm also not entirely sure you code works correct when millis() wraps around, and is smaller than startMillis

Delay makes your arduino completely inactive while waiting if I'm correct. I don't know how this will act when millis is back to 0.

@Gerben good stuff, put it as an answer!

@FredPannekoek overflow will work fine, so long as unsigned long is used.

So, you want to have interrupts every ms, for 12h? Why just not putting the controller in sleep mode for 12h?

@23ars How are you going to wake up the controller after 12 hours exactly? Most elegant solution is an external RTC with 12 hour alarm.

take look at the Ricardo's answer. Or if you don't want the watchdog and sleep mode, a solution could be to set the timers to genererate an interrupt every second  (TIMERX_COMPA) and count second, not millis. with millis you generate every ms an interrupt and that's not quite ok. Even if it's Arduino, I'm, somehow, against using functions from libraries, like millis and others.

@23ars The main reason Arduino is so successful is its easy-to-use hardware abstraction library, if you are against functions from libraries you are limiting yourself somewhat. Anyway, the function of comments is to improve the answer, if you have a better solution, write your own answer.  ;)

@Gerben: Why do you say that the Arduino implementation accepts unsigned longs? Arduino Reference states that the argument for delay() has to be an unsigned int. (Your link to 'arduino implementation' is now dead).

@PimV updated link: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c#L106 . The Arduino reference website also says delay accepts an unsigned long. So I'm not sure which reference you are referring to, that says it has to be an unsigned int.

@Gerben: Thank you. I apologize, you are right. Can't find it back, probably looked with my nose.

You could use the watchdog interrupt and have your MCU sleep while waiting and save power.
But notice that you'll only save power if your board also saves it. That means you have to have a low quiescent voltage regulator instead of the usual regulators that equip the most common Arduino boards, such as the Uno. Otherwise, it doesn't matter whether your MCU saves energy if your board doesn't.
Here's the code (untested):
#include <avr/sleep.h>
// This variable is made volatile because it is changed inside an interrupt function
volatile int sleep_count = 0; // Keep track of how many sleep cycles have been completed.
const int interval = 720; // Interval in minutes between waking and doing tasks.
const int sleep_total = (interval*60)/8; // Approximate number of sleep cycles
// needed before the interval defined above elapses. Not that this does integer math.

void setup(void) {
    watchdogOn(); // Turn on the watch dog timer.
    // Disable the ADC by setting the ADEN bit (bit 7) to zero.
    ADCSRA = ADCSRA & B01111111;
    // Disable the analog comparator by setting the ACD bit (bit 7) to one.
    ACSR = B10000000;
    // Disable digital input buffers on all analog input pins by setting bits 0-5 to one.
    DIDR0 = DIDR0 | B00111111;
}

void loop(void) {
    goToSleep(); // ATmega328 goes to sleep for about 8 seconds
    // and continues to execute code when it wakes up
    if (sleep_count == sleep_total) {
        // CODE TO BE EXECUTED PERIODICALLY
    }
}

void goToSleep() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Set sleep mode.
    sleep_enable(); // Enable sleep mode.
    sleep_mode(); // Enter sleep mode.
    // After waking from watchdog interrupt the code continues
    // to execute from this point.
    sleep_disable(); // Disable sleep mode after waking.
}

void watchdogOn() {
    // Clear the reset flag, the WDRF bit (bit 3) of MCUSR.
    MCUSR = MCUSR & B11110111;
    // Set the WDCE bit (bit 4) and the WDE bit (bit 3) of WDTCSR.
    WDTCSR = WDTCSR | B00011000;
    // Set the watchdog timeout prescaler value to 1024 K
    // which will yeild a time-out interval of about 8.0 s.
    WDTCSR = B00100001;
    // Enable the watchdog timer interupt.
    WDTCSR = WDTCSR | B01000000;
    MCUSR = MCUSR & B11110111;
}

ISR(WDT_vect)
{
    sleep_count ++; // keep track of how many sleep cycles have been completed.
}

The code I copied is from this page: Low-Power Arduino Using the Watchdog Timer.

delay() has its uses, but for long delays it's no good. It simply tells the microcontroller to do nothing for x clock cycles. During that time, your Arduino can't do anything else.
Your best bet would be to use a thing called a Real Time Clock (RTC). These chips are specifically made to keep track of time, and you can connect them to your Arduino with ease. Here's an example of how you could do that.

+1 - The RTC solution is specially good if you want more accuracy than the MCU can give you.

@Ricardo - an RTC is not likely to be any more accurate than an MCU with a clock crystal using one of its hardware timers to fire a periodic interrupt; what it does usually get you is tracking across power loss, and perhaps some knowledge of calendar schemes.

Afaik uno does not use a quartz bit a ceramic resonator for its clock, thus with much less accuracy than an rtc.

@ChrisStratton - Right. Point taken. The RTC will be much better option if the OP has to open or close the door at a given time of day.

This will work:
longDelayInSeconds = 120; //two minutes;
while (p < longDelayInSeconds) {

        delay(1000);
        p++;

}

not the best solution and the OP asked for 12 hours, not 2 minutes.

I just use for loops when I don't want to do stuff in between:
for (int Hours = 0; Hours < 12; Hours++) {            //Creates 12 hours
  for (int Minutes = 0; Minutes < 60; Minutes++) {    //Creates 1 hour
    for (int Seconds = 0; Seconds < 60; Seconds++) {  //Creates 1 minute
      delay(1000);                                    //Creates 1 second
    }
  }
}

Well for starter it would be easier to modify how long you want to wait. Just change the number for each hour, minutes and seconds without needing to convert into miliseconds.

Do you have a sleep(unsigned int seconds) available?
If not, this would allow you to delay() a very long time:
for (unsigned int bigloop=0; bigloop<65535; bigloop++)
{
   for (unsigned int smallloop=0; smallloop<65535; smallloop++)
   {
      for (unsigned int tinyloop=0; tinyloop<65535; tinyloop++)
      {
         delay(65535);
      }
   }
}

I could try this if I don't manage to get an rtc like Tom said. Thanks for helping!


text:
Unsure how to connect the anode in this circuit
I am making a game of X and O’s and ran out of pins on the Arduino. After searching on the internet I found out about connecting it in a grid connecting all the anodes in columns and the different colours in rows but I don't know how to connect the anodes so it only turns on only one of the LEDs rather than the other 2 in the grid if they are all connected to ground. The wires I am unsure to connect are the orange ones in the diagram below (bottom left corner). Note the Red on the RGBs are not used so don't need to be connected

Firstly, you have made the classic rookie mistake with your circuit regarding your LED current limiting resistors.  You have one per LED group instead of one per LED within a group.  The arrangement you have at the moment means that at best some LEDs will be dim or not light at all, and at worst will result in LEDs burning out.
There should be a resistor in every red, green and blue wire in your diagram.
As for what to do with the three orange wires (once you have re-arranged the resistors) they connect to three spare IO pins on the Arduino - you then turn each column on or off as you need - only one column is on at a time.  If you need more than 20mA for a column (which is highly likely with up to 9 LEDs on at a time) then those lines should be connected to either +5V or GND (depending on if you are common anode or common cathode) via transistors and the transistors should be switched by the IO pins.

So you just connect it to the 3 analogue pins and how would you code it if it would normally go to the ground

If they are common cathode (normally connect to ground) then set a pin HIGH to turn a column off, or LOW to turn it on.  Cycle through them nice and fast.

Thanks for the help but I ended up abandoning this project in the end


text:
May arduino hang when current is changing over time?
As in title. I've got quadrocopter where Li-Po is parallely connected to motors as well as to arduino. May current driftage cause arduino hangs ?

What do you mean by "hang"?

Main loop freezeout.

There really isn't any such thing as "Current driftage". If you draw too much current from your battery it will cause the voltage to drop, and if it drops too much, the Arduino will stop working.
If you have high current devices like motors being switched on the same power supply as your Arduino you should add a reservoir capacitor as close to the input of your Arduino as possible. That will even out short term drops and spikes in supply voltage as your motors switch.
If you draw too much current continuously then your supply voltage will drop and stay dropped, and a reservoir capacitor won't help. In that case you need a higher current battery (or separate power supplies for your Arduino and motors.)
Edit: From your question it's pretty clear that you don't understand voltage and current and how they relate. I suggest you read up on the subject.
In short, the amount of current that flows through a component is determined by the voltage divided by the resistance: i = v/r. (Where i = current in amps, v = voltage, and r = resistance in ohms.)
The current that will flow will be limited by the max current that the power supply can provide.
For a non-regulated supply like a battery, the voltage from the supply will drop as you draw more and more current.
For a regulated supply, the supply keeps the voltage constant up to it's maximum current limit.

I understand voltage and current. I've just been thinking of "how can voltage drops and spikes (current driftage/drifts) affect arduino". Due to parallely connected motors I may experience such things right ?

May i ask why you don't have a separate battery for the arduino? If it is because of weight, an arduino can run of CR2032 batteries, gives it its own power supply, this should solve the problem.
If you want a battery with more longevity Google "6v 2/3 battery" (2/3 the size of an AA battery), small with loads of voltage for the arduino and with some skilled programming it should last for a flight or two, and the +side, you can get it rechargable.

I have limited space + its comfortable.

Throw in 1 or 2 CR2032 they cost less than $1 and they take virtually no space at all, and it is more comfortable than loosing power mid air.


text:
How to serial connect arduino galileo to alarm system
i'm a little new in this.
I have an alarm system panel which has TX,RX wires with 12V output/input.
how can i  read the output with arduino and control it with serial communication?

First of all, you'll need to make sure this is UART and not another protocol. Don't worry, if it's not UART the worst thing that could happen is jumbled data.
After that, you will need a 12v to 5v (or 3.3v) logic level shifter. When you have that you'll need to connect the Arduino to the system through the level shifter to pins 0/1.
You won't know what you'll receive or can send without looking at the serial output and doing a little tinkering. You don't even know what the serial port does. It could just be for setting up the system.

what is logic level shifter? cant i ues simple voltage divider ?

@NorisS you could from the system to the Arduino but you need a way to increase the signal for the receiving line on the system. A logic level shifter just translates voltages.

can you recommend me specific model?

@Nor my phone isn't loading the datasheet but comments seem to say that this will work: https://www.sparkfun.com/products/12009 remember to use a common ground.


text:
Simple question about && vs ||
I want to skip all '\r' and '\n' chars and I have IF statment:
char c = Serial.read();
if (c != '\r' || c != '\n') { // <- This line interesting
   mAnswer[mAnswerLength] = c;
   mAnswerLength++;
}

VS
char c = Serial.read();
if (c != '\r' && c != '\n') { // <- This line interesting
   mAnswer[mAnswerLength] = c;
   mAnswerLength++;
}

What is better and what is the difference?

Think about it "logically" (pun intended...):
You read a character.  Say it's "A".  You then compare it to both '\r' and '\n'.
char c = Serial.read();
if (c != '\r' || c != '\n') { // <- This line interesting
    mAnswer[mAnswerLength] = c;
    mAnswerLength++;
}

That is saying "If A is not CR or A is not LF then add it".  Since it's A and not LF or CR then it's going to add it.  Now imagine it's CR.  "If CR is not CR or CR is not LF then add it".  CR is CR, so the first part will be false.  But CR isn't LF, so the second part is true.  If it's OR, then if either part is true then it will be true.  So since CR is not LF it will add it.
Now:
char c = Serial.read();
if (c != '\r' && c != '\n') { // <- This line interesting
    mAnswer[mAnswerLength] = c;
    mAnswerLength++;
}

That is saying "If A is not CR and A is not LF then add it".  Since it's A and not LF or CR then it's going to add it.  Now imagine it's CR.  "If CR is not CR and CR is not LF then add it".  CR is CR, so the first part will be false.  But CR isn't LF, so the second part is true.  Just as before.  However, if it's AMD, then if BOTH parts are true then it will be true.  So since CR is CR it won't add it.
In summary, the first one will ALWAYS be true since one half is always going to be true.  The second one will ONLY be true if BOTH parts are true.  So the first one just plain isn't going to do what you want.

Thanks for this. Just needed someone explain this :) My head is overflowed...

You can rewrite first condition to be more obvious
if (c != '\r' || c != '\n') {

as
if (!(c == '\r' && c == '\n')) {

Which is always true (c have only one value), i.e. it makes no sense.

|| means logical OR
&& means logical AND

Thanks, i know the meaning.  I want to know the difference and which one is better in this situation. My head is not working properly at the moment;)


text:
How does serialEvent gets into main()?
Ok, serialEvent "runs after loop()" and it is not an interrupt.
AS far as I know main() has two functions  - setup and "infinite" loop.
So where does serialEvent comes in?
And if I do not want loop()  to run and use only setup than  I cannot use serialEvent.

Yes you are correct, the event handlers will not do anything in setup. Main runs "setup()", then loops infinity through "loop()", but gives the serial event handlers a chance to run in between. The actual main that runs on the arduino is this:
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

this is found (on linux at least) in arduino/hardware/arduino/avr/cores/arduino/main.cpp
"serialEventRun()" is in HardwareSerial.cpp, but is not very interesting.
To be clear, Serial itself will still work fine in setup(). If you want to use the same event handler function, all you have to do is call "serialEventRun()" yourself periodically.

To be fair, you only need to call serialEventRun() if you define a serialEvent{,1,2,3}() function.

That was what I intended to get across, I'll edit for more clarity.

Thanks,I feel that 120% people using Arduino main() should have this posted on their refrigerator.

To clarify, this "serial event" callback is for handling incoming data over Serial, right? If I'm not receiving any data on the device, and I'm merely Serial.printing things, I should be unaffected if I have an infinite loop in setUp, correct?


text:
How do I connect this display to an Arduino Uno
I am completely new to this, and a novice when it comes to electronics but I want to learn.
Can someone pls tell me how I would connect the display in the photo here with an Arduino Uno (which I have ordered).  The plan is to interface my car with this transparent display to produce a form of HUD.
I have done some searching but to no avail so far, would appreciate being pointed in the right direction.
many thanks

What do you know about this display? Do you have a datasheet, a make/model, any information to go on? We really can't tell you much from a picture.

Thank you. Not yet but I will try to find out.  This was the only transparent display that I could find available for purchase.

Can can always scrap the electronics and drive the LCD yourself. But you need quite a few IO pins, looking at that ribbon cable. Also it's not really a beginners project.

You don't need a transparent display. You can project a bright LED up to the windshield and it will be reflected in your line of sight, you will have to deal with projecting a flipped image so it appears correct to the observer.

You're in for a lot of work. Everything on the PCB is useless to you, so you'd have to interface the raw panel to the Arduino.
The first matter is to remove the panel from the board. You will need to desolder all of the connections, and then solder either some sort of rigid connector or individual wires to the large ribbon connector. The only advice I can give you is "be prepared to fail".
Once you've done that, you will need to read AVR340 in order to learn how to drive the panel. Note that the Uno itself does not have enough pins to drive the panel directly, so you will need to get an I/O expander or two for this.
Did I mention that you're in for a lot of work? Well, I'm mentioning it again. Good luck though.

Thank you. I suspected it wouldn't be straightforward. This is the info I was looking for - somewhere to start.

@DrT Do you have an update on how the project went. I'm interested in whatever, even if it failed, as I learn a lot from HOW / WHY things fail.


text:
Use an Arduino as a user interface for the computer
I wanted to use either Arduino Mega or Uno as a form of an interface between me and the computer. I want to apply it to the following scenario; if I press a button on a circuit board I want it to trigger an action on my computer, like scroll down.
How can I achieve this? How would the code look like and what programs would I need to translate from Arduino to Windows?

You need to clarify what OS you're working with. Linux or Windows? What versions, too, since this may require more than just Arduino code.

For the sake of completeness, on the more traditional boards where the USB interface is not implemented from the main "sketch" processor, there are three other potential possibilities:

Use the (USB) serial data interface, and have software on the host computer which accepts commands over that.  Obviously, the downside is requiring installation of something on the host system - installation which may require admin privileges or even disabling code signing requirements in some cases (especially if it is to inject the data into the host operating system as if it came from a keyaboard)
On boards such as the Uno and comparable-generation Mega which use a secondary ATmega "u" series part as a USB-serial converter, this chip can be reprogrammed to act instead as a keyboard.  That could make loading sketches tricky - though it might be possible to come up with a dual-mode firmware that could switch roles under control of an external hardware or software signal.
The main ATmega "sketch" processor can generally implement a "not quite compliant, but workable" approximation of a low-speed USB interface in software on arbitrary I/O pins with some external matching/protection componenets.  A USB keyboard is a common demo application of that.

For the second one, you don't need a dual firmware. IIRC you just need to flash the standard USB firmware, upload, and reflash the keyboard/mouse one again. No where near ideal, but workable.

Arduino Yun, Leonardo, Esplora and Due have  the ability to appear as a native Mouse and/or Keyboard to a connected computer by use of the Mouse and Keyboard libraries.
Here's an example of how you would use SWITCH3 on the Esplora to active PAGE UP on your keyboard.
if (!Esplora.readButton(SWITCH_3)) {
  Keyboard.press(KEY_PAGE_UP)
  delay(100);
  Keyboard.releaseAll();
  }

Here's an example of using the Esplora to control the Keyboard and Mouse to control the Flight Simulator option of Google Earth.
If you want to use the Uno it's more difficult but it can be done by sending data from the Uno to a Python program running on the PC. The Python program uses the pywin library to control windows.
Here's a fully worked out Instructable on how to do it.


text:
How do I add additional compiler switches in Visual Studio
Using Visual Studio to program my Arduino. I want to add additional compiler switches and include paths.
How can this be done?

Use the ExtraFlags in the project properties. The flags can be specified for the currently selected configuration or for all builds of the current project.
The feature was released in the 15.06 version of the Visual Micro Arduino plugin for Visual Studio.
This guide shows how to access the project properties


text:
how to build rc transmitter and receiver with an old rc transmitter
I've got an Arduino Mega, an Arduino Nano, two NRF24L01 wireless modules and a old Multiplex Transmitter system.
I want to get the PWM signal and send it to the other arduino which should control the servos and the motor controller.
Is there a good instruction or know somebody how to do that easily?
I need it for a rc plane and the range should be 1km.

1km is pretty much impossible with the NRF24L01

Do you know another wireless modules??

If you are controlling an RC plane, you should probably just buy a transmitter and receiver specifically designed for that. They are cheap and reliable and will generate PWM signals on their own.
If you must use an Arduino for some reason, NRF24L01 are not going to cut it as they are not powerful enough to reach 1 km. You should probably look into something like an XBee Series 1. With about 60 mW transmit power, its range is up to 1.6 km.


text:
Why is one part of my code being executed over the part before it?
The following code doesn't behave the way I would like it to. Inside the loop function im measuring the distance in front of the robot and if it is less than 15cm than the robot should move back and if it is less than 15cm on the left then move forward. When i run the program however only the left side is being checked and acted upon whilst the the if statement about the front and moving back is not doing anything. Something to note also is that when i swap the if statements and put the front checking ahead of the left checking it works but the left side is no longer being checked. Why is it that the if statement block in front is being executed over the previous one?
     void loop(){

     if(front.calculateDistance() < 15){
     MoveBack(200);
     }else{
      stopMoving();
     }

      if(left.calculateDistance() < 15){
     MoveForward(200);
     }else{
      stopMoving();
     }
   }

This is what the move methods do (move back and stopmoving just change input directions):
void MoveForward(int rspeed) {
 // turn on motor A
 digitalWrite(in1, HIGH);
 digitalWrite(in2, LOW);
 analogWrite(enA, rspeed);
 // turn on motor B
 digitalWrite(in3, HIGH);
 digitalWrite(in4, LOW);
 analogWrite(enB, rspeed);
}

The problem is with your logic. You are saying:

If it's too close in front then move backwards
Otherwise stop all movement
If it's too close on the left then move forwards
Otherwise stop all movement.

That means that if it's too close in front, but not too close on the left, then it will think about moving backwards, but then immediately stop because it's not too close on the left.
You need to think more about the whole space at once, not just one individual direction. For instance, what do you do if it's too close in front and too close on the left? At the moment you'll crash into whatever is in front.
So you should be thinking about four conditions:

Too close in front AND too close on the left
Too close in front BUT NOT too close on the left
NOT too close in front BUT too close on the left
NOT too close in front AND NOT too close on the left.

Then you can choose the right action to perform.
If your specific setup means that it can never be too close in front at the same time as being too close on the left you can collapse it into a simpler form:

IF it's too close in front then move backwards
ELSE IF it's too close on the left then move forwards
ELSE stop all movement.


text:
Strobe Frequency Calculation, how its done?
I'm using the Arduino sketch for LED stroboscope found here: http://mehax.blogspot.co.uk/2011/02/arduino-stroboscope.html.
Also below, I've inserted the loop part where this calculations are made:
void loop() {
// this while is a workaround for timer limitations using micros vs millis
sensorValue = analogRead(analogInPin);   //take potentiometer reading
hold = sensorValue*55 + 400;             //add some time to scale and for code execution
microsCurrent = micros();                // collect current time
if (microsCurrent > microsPrev + hold){  //set up timing loop
frequency = 1000000/(microsCurrent - microsPrev);
microsPrev = microsPrev + hold;            //set up millis for delay stuff

//set all 6 LEDs high (they were already plugged in)
digitalWrite(3,HIGH);
digitalWrite(5,HIGH);
digitalWrite(6,HIGH);
digitalWrite(9,HIGH);
digitalWrite(10,HIGH);
digitalWrite(11,HIGH);
delayMicroseconds(.02*hold);  //leave LEDs on long enough to see

//set all LEDs low
digitalWrite(3,LOW);
digitalWrite(5,LOW);
digitalWrite(6,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
digitalWrite(11,LOW);

if(millis() > millisSerial + 200){
  millisSerial=millis();    //reset timer
  holdFrequency = 1000000/hold;
  //do some math to find values
  rpm = frequency * 60;

I want to use this code in my project, but I don't really understand how this code calculates the stobing frequency.
So, I have following questions:

Why "hold" variable is calculated in the given way?
Why "microsCurrent", "microsPrev" and all other timings are executed?
How "frequency is calculated"?
What is "hold frequency" variable?

Sorry, I'm very new to Arduino and don't know much coding.
Will appreciate very much your help!

About that program you are using: you may want to take a look at the comment I just posted in the author's blog.

Why "hold" variable is calculated in the given way?

hold stores the intended delay between the strobe pulses, i.e. the
stroboscope period. It is computed as an affine function of the
potentiometer cursor position because... well, that's the simplest way
to make it user-adjustable. 400 µs is the shortest period that
(according to the program author) one may reasonably want to set.

Why "microsCurrent", "microsPrev" and all other timings are executed?

See the Blink Without
Delay Arduino
tutorial.

How "frequency is calculated"?

From the code:
frequency = 1000000/(microsCurrent - microsPrev);

The frequency is the inverse of the period. The period is the time
elapsed between this strobe and the previous one. The numerator is a
conversion factor to get the frequency in hertz from a period in
microseconds.

What is "hold frequency" variable?

It's the intended frequency (inverse of the intended period),
disregarding the timing jitter that makes the actual instantaneous
frequency slightly different.

Thanks for your prompt reply!
This made almost everything clear in my head.
So, the "frequency" variable shows the real strobe frequency (taking into consideration the possible delays), while "hold frequency" is the intended freq., but it's not used to display anything in this code, right?
and what kind of delays there might be?
Thank you.

@George: I am still examining the code, and I believe there is a bug. holdFrequency seems to have the correct average frequency, which is probably the most relevant datum. frequency is computed from the difference between the actual time of the current pulse and the intended time of the previous one. It can therefore carry a slight bias.


text:
Motor Shield and HC-06 Bluetooth Module competing for pins
So my problem is this, I have an Arduino Uno with an Adafruit Motor Shield (1.0) and an HC-06 Bluetooth Module and I want to use them at the same time, the problem is that the Motor Shield uses all the ports that I need for the HC-06 (TX, RX, GND and VCC). In addition to all that, my project needs to be light weight (It's a quadcopter). Is there any way that I could use both of them at the same time?
Thanks in advance!

The motor shield doesn't actually use the TX and RX pins. Though as a shield it will go into all the arduino pins.
You could either solder some wires to the TX and RX pins, or use something like the proto shield to sandwich in the middle of it, and connect the BT module onto this shield.
You could also remove all the male headers from the motor shield, and replace them with stacking headers

Thank you, but what about the ground pin? Could I find an alternate power supply or something?

Unlike the digital pins, you can connect multiple devices to a single Vcc or GND pin. The motor shield also has some free pads that you can use for 5v and GND (near the analog pins).

I was wondering if is not easier to just solder some stacking headers on the analog, ground and +5 area

Ok so i had the same problem but i found like the easiest solution. So what i did was scrape the wire end to the copper using a knife or a wire cutter. And then place it in the Arduino holes and then squeeze the motor shield on top of it. Works like a charm!


text:
Error on Arduino Code (unknown type name 'LiquidCrystal')
I am using Arduino IDE 1.6.8 and I am trying to compile the following code Wheatstone Bridge. I have currently a really weird error:
unknown type name 'LiquidCrystal'

This error seems to come from the header file:
// Include the Wheatstone library
#include <WheatstoneBridge.h>

// Include the LCD library
#include <LiquidCrystal.h>

// Declare external global lcd
extern LiquidCrystal lcd; <<<Error

I have already installed the LiquidCrystal library but I don't know if this trouble is due to the compiler (and the IDE) or something is wrong. The compiler seems to find the right libraries...

"I have already installed the LiquidCrystal library" ... It already comes with the IDE, so what exactly did you install?

@IgnacioVazquez-Abrams  You are right. I don't install it. This library is installed with the IDE and the compiler find it well.

Using "extern" when instantiating a class is unusual.  We can not tell what your intentions are because this is only part of your code.  However it would be my guess that this code:
// Declare external global lcd
extern LiquidCrystal lcd;

Should actually be written like this:
// Declare external global lcd
LiquidCrystal lcd((12, 11, 5, 4, 3, 2);

This is making a BIG assumption that you are using an LCD similar to the one used in the HelloWorld example and you have connected it using the same pins!  Comments from the HelloWorld example to help you out:
 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)

Background:
Arduino sketches are written mostly in C while the libraries take advantage of C++.  As such the libraries can use a C++ feature called "overloading".  This is where you can have several different functions with different parameters all with the same name. The advantage is that you can call upon slightly different functions (or in this case different classes) simply by altering what is passed.  The LiquidCrystal class has defined all these possibilities:
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
        uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
  LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
  LiquidCrystal(uint8_t rs, uint8_t enable,
        uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);

But in none are there no parameters.  That is why the compiler could not find the class in your code.  You needed to match one of the above class types.

Removing extern change nothing. Obtain the same error unknown type name 'LiquidCrystal'.

In the Arduino IDE: 1) Click on Sketch -> Import Library, do you see the LiquidCrystal library? 2) Double check the spelling in your code, I've been tripped up by this more than once. 3) Try compiling the HelloWorld example in the LiquidCrystal library example directory.

no trouble when compiling the HelloWorld example of LiquidCrystal library

Hang on, I think I need to edit my comment to pass values to the constructor.

Finally this error is not the right. When I read the compilation log I have found an other error. In fact Arduino IDE try to compile using gcc and not g++ due to the fact the example folder contains one .c file. Changing the extension to .cpp solves the problem.

Please verify the code you posed in the question compiles unaltered.

The code I have proposed in the initial question doesn't work (the github repository is not mine). But if you change the extension, it will compile.

Download the Liquidcrystal.zip file from this link,
Crystal link
Now add that file into documents/Arduino/libraries folder.
Now check if the library is added in the library.
It should probably work.

Thank for your proposal but I have the same error with this library.

Have read your solution, at the end of discussion. I was having similar issues, saying "IDE try to compile using gcc and not g++". Close this problem


text:
Bit shifting fails with warning: left shift count >= width of type
Given the following minimal working example. I tested this initially with uint16_t and it worked with no warnings. After that, I adjusted everything to work with uint32_t.
#include <stdint.h> /* needed for the uint16_t type*/
#include <inttypes.h> /* needed for sscanf uint16_t format placeholder  */
#include "printf.h"

#define SET_CMD_ID(ID)    ( (ID) << 27)
#define SET_CMD_CMD(CMD)  ( (CMD)  << 25)
#define SET_CMD_TYPE(TYPE)  ( (TYPE) << 19)
#define SET_CMD_PKT(PKT)  ( (PKT)    )

void setup() {
  Serial.begin(115200);
  printf_begin();
  Serial.print(F("\n\rExample command\n\r: "));

}

void loop() {
  uint32_t payload = 0;

  uint8_t id = 3;   // 00000 - 5
  uint8_t cmd = 2;  // 00    - 2
  uint8_t type = 1; // 000000 - 6
  uint32_t pkt = 0; // 0000000000000000000 - 19

  payload =
        SET_CMD_ID(id)   |
        SET_CMD_CMD(cmd)  |
        SET_CMD_TYPE(type) |
        SET_CMD_PKT(pkt);
  Serial.print(F("Now sending "));
  Serial.println(payload);
  delay(2000);        // Try again soon
}

Verifying this sketch outputs:
/path/to/ino/Arduino32bitTest.ino: In function 'void loop()':
/path/to/ino/Arduino32bitTest.ino:5:37: warning: left shift count >= width of type [enabled by default]
 #define SET_CMD_ID(ID)    ( (ID) << 27)
                                     ^
/path/to/ino/Arduino32bitTest.ino:28:9: note: in expansion of macro 'SET_CMD_ID'
         SET_CMD_ID(id)   |
         ^
/path/to/ino/Arduino32bitTest.ino:6:39: warning: left shift count >= width of type [enabled by default]
 #define SET_CMD_CMD(CMD)  ( (CMD)  << 25)
                                       ^
/path/to/ino/Arduino32bitTest.ino:29:9: note: in expansion of macro 'SET_CMD_CMD'
         SET_CMD_CMD(cmd)  |
         ^
/path/to/ino/Arduino32bitTest.ino:7:41: warning: left shift count >= width of type [enabled by default]
 #define SET_CMD_TYPE(TYPE)  ( (TYPE) << 19)
                                         ^
/path/to/ino/Arduino32bitTest.ino:30:9: note: in expansion of macro 'SET_CMD_TYPE'
         SET_CMD_TYPE(type) |
         ^

Sketch uses 3,174 bytes (9%) of program storage space. Maximum is 32,256 bytes.
Global variables use 216 bytes (10%) of dynamic memory, leaving 1,832 bytes for local variables. Maximum is 2,048 bytes.

Executing the sketch on an Arduino Uno results in:
Example command

: Now sending 0
Now sending 0
Now sending 0
Now sending 0

I googled the message of the warning and found out that it could mean that I'm trying to shift 32bit which is undefined, but I'm not sure on that. So my question is:
What am I doing wrong here? How can I get this to work?

It is basically duplicate of Problem with bitwise OR

@KIIV : Thanks, the thread pointed me in the right direction

It's basically an inability of the compiler to auto-promote the source variables to a size big enough to fit the shifted version.
The default type for all operations, unless otherwise specified, is 16-bit. By shifting more than 16 bits you are overflowing that default type.
To get around it you have to manually tell the compiler that you want to work with 32-bits:
#define SET_CMD_ID(ID)      ( ((uint32_t)ID) << 27)
#define SET_CMD_CMD(CMD)    ( ((uint32_t)CMD)  << 25)
#define SET_CMD_TYPE(TYPE)  ( ((uint32_t)TYPE) << 19)
#define SET_CMD_PKT(PKT)    ( ((uint32_t)PKT)    )

Another solution would be to not shift values at all.
It seems to be very common in Arduino and other micro-controller projects to use antique ANSI C. But ALL major compiles support "bit fields". The language removes your headache of packing bits into and unpacking bits from a larger type.
It goes like this:
struct {
    uint32_t pkt  : 19;
    uint32_t type :  6;
    uint32_t cmd  :  2;
    uint32_t id   :  5;
} payload;

As long ans 19 + 6 + 2 + 5 does not exceed 32, the struct will still take up only 32 bits.
Setting values works like this:
payload.id = 3;
payload.cmd = 2;
payload.type = 1;
payload.pkt = 0;

Reading values works the same way. No need to shift mask or do any other operations by hand. The compiler does everything for you without making any mistakes or without forgetting about to mask when reading...
The only thing you have to remember is that bitfields are packed from least significant bit to the most significant bit. So a struct like this:
struct {
    uint8_t r :  2;
    uint8_t g :  3;
    uint8_t b :  2;
    uint8_t a :  1;
} someType;

Will result it a byte where the values are layout like this:
abbgggrr

This also works for signed values. But you have to make sure they fit and be aware of the twos complement representation.
Hopefully more Arduino and micro controller developer will adopt this and take advantage of the compiler.

Note: depending on the compiler and version you may need to manually pack the struct by adding __attribute__((packed)) to the end of it. I do that always by default to ensure proper packing regardless of compiler version or target chip.

The order of the fields in the word, and whether a field can straddle a byte boundary, is implementation defined. Thus your usage of bit fields is not portable.


text:
Using softwareserial with a TFT, how can I use a variable to position cursor?
I have tried several different ways to do this, but in the line:
myTFT.println("DS32(32,g,'Hello!',4);");
where g is an int, it simply doesn't print. If I just replace the g with a value of any kind, all is well.
I'm using an Uno (well, an Orion board from Makeblock) and the Makeblock TFT.
All my other print lines work fine but of course, none contain variables.

Just split the print into three parts:
myTFT.print("DS32(32,");
myTFT.print(g);
myTFT.println(",'Hello!',4);");

My problem was that I didn't stop to think that the entire line being passed was a string. As soon as that dawned on me, I changed the int to a string and split it just as you showed. Worked perfect. THANK YOU!

authors: Александр Вохминцев