text:
How does the Space Replay record audio?

The Space Replay
A hovering object that explores and manipulates transitional public
spaces with particular acoustic properties. By constantly recording
and replaying these ambient sounds, the levitating sphere produces a
delayed echo of human activity.

In this project, the Arduino board and an Adafruit Wave Shield is used. The Wave shield is not designed to record audio however, they say that they use the board for both recording and playback.

The sphere responds sonically to people and its surroundings by means of a battery-powered Arduino, an Adafruit Wave Shield hacked to record and playback audio on-the-fly and a small speaker.

This generates a few questions.

How would this be done?
Where would the microphone be placed inside the balloon for decent audio capture?
Would there be a better way to design this?

No you can't use the board for recording. You can however use the Arduino's own ADC to record sound.

It seems to be possible to record with the shield using a library called waverp

WaveRP is an Arduino library for recording and playing Wave files with
  the Adafruit Wave Shield. It records 8-bit mono files at 4,000 to
  44,100 samples per second.

Some details adafruit blog:

It records 8-bit mono files at 4,000 to 44,100 samples per second.

As jippie said, you can use the Arduinos ADC to record audio, and presumably save that to the Arduino's RAM (the SD card is probably too slow for directly saving it). Then it writes the buffer to the SD card.

But an Arduino has 2K of RAM, so even at low quality sampling rates like 8kHz 8 bit samples, that would cover only about 250ms.

Maybe is kind of late but I found the code for the Space Replay
is in here at the bottom of the last image, specifically in here
/*------------------------------------------------------------------------------

        __-__         Code for Space Replay, a floating black orb that records
      .X+..   Â·       and plays back ambient sounds. This sketch was adapted by
    .Xx+-Â·..    Â·     Francesco Tacchini, with the help of Oliver Smith & Brock
    XXx++-...         Craft, from the original WaveRecordPlay example sketch
    XXxx++--.....Â·    written by Bill Greiman.
    `XXXxxx++---'     This project was created as part of a university project at
      `XXXxxxx'       the Royal College of Art. It's a collaboration with Julinka
         """          Ebhardt and Will Yates-Johnson. See more: vimeo.com/88992597

------------------------------------------------------------------------------*/

#include <SdFat.h>
#include <WaveRP.h>
#include <SdFatUtil.h>
#include <ctype.h>

#define MIC_ANALOG_PIN 0             // Define the analog pin
#define RECORD_RATE 44100            // Define the record rate
#define ADC_REFERENCE ADC_REF_AVCC
#define PRINT_FILE_INFO 0            // Useful for debug: print file info and
#define PRINT_DEBUG_INFO 1           // bad wave file size or SD busy errors
#define MAX_FILE_SIZE 104857600UL    // 100MB or 150 min at 11025 samples/second
#define DISPLAY_RECORD_LEVEL 1

// debugging led
int playLED = 7;
int recLED = 8;
int delStopLED = 9;

// global variables
Sd2Card card;           // SD/SDHC card with support for version 2.00 features
SdVolume vol;           // FAT16 or FAT32 volume
SdFile root;            // volume's root directory
SdFile file;            // current file
WaveRP wave;            // wave file recorder/player
int16_t lastTrack = -1; // Highest track number
uint8_t trackList[32];  // bit list of used tracks

//------------------------------------------------------------------------------
// print error message and halt
void error(char* str) {
  PgmPrint("error: ");
  Serial.println(str);
  if (card.errorCode()) {
    PgmPrint("sdError: ");
    Serial.println(card.errorCode(), HEX);
    PgmPrint("sdData: ");
    Serial.println(card.errorData(), HEX);
  }
  while(1);
}
//------------------------------------------------------------------------------
uint8_t trackName(int16_t number, char* name) {
  if (0 <= number && number <= 255) {
    strcpy_P(name, PSTR("TRACK000.WAV"));
    name[5] = '0' + number/100;
    name[6] = '0' + (number/10)%10;
    name[7] = '0' + number%10;
    return true;
  }
  PgmPrint("Invalid track number: ");
  Serial.println(number);
  return false;
}
//------------------------------------------------------------------------------
// start file playing
uint8_t playBegin(char* name) {
  if (!file.open(&root, name, O_READ)) {
    PgmPrint("Can't open: ");
    Serial.println(name);
    return false;
  }
  if (!wave.play(&file)) {
    PgmPrint("Can't play: ");
    Serial.println(name);
    file.close();
    return false;
  }
#if PRINT_FILE_INFO
  Serial.print(wave.bitsPerSample, DEC);
  PgmPrint("-bit, ");
  Serial.print(wave.sampleRate/1000);
  PgmPrintln(" kps");
#endif // PRINT_FILE_INFO
#if PRINT_DEBUG_INFO
  if (wave.sdEndPosition > file.fileSize()) {
    PgmPrint("play Size mismatch,");
    Serial.print(file.fileSize());
    Serial.print(',');
    Serial.println(wave.sdEndPosition);
  }
#endif // PRINT_DEBUG_INFO
  PgmPrint("Playing: ");
  Serial.print(name);
  return true;
}
//------------------------------------------------------------------------------
// play all files in the root dir
void playTracks(void) {
  dir_t dir;
  char name[13];
  uint8_t np = 0;
  root.rewind();
  while (root.readDir(&dir) == sizeof(dir)) {
    //only play wave files
    if (strncmp_P((char *)&dir.name[8], PSTR("WAV"), 3)) continue;
    // remember current dir position
    uint32_t pos = root.curPosition();
    // format file name
    SdFile::dirName(dir, name);
    if (!playBegin(name)) continue;
    PgmPrintln("");
    while (wave.isPlaying()) {
      uint8_t c = Serial.read();
    }
  }
  file.close();
}
//------------------------------------------------------------------------------
// delete a track
void trackDelete(int16_t track) {
  char name[13];
  if (!trackName(track, name)) return;

  if (SdFile::remove(&root, name)) {
    PgmPrintln("Deleted!");
  }
  else {
    PgmPrintln("Delete failed!");
  }
}
//------------------------------------------------------------------------------
// Finally we have the normal SETUP and LOOP functions -------------------------
//------------------------------------------------------------------------------
void setup(void) {
  Serial.begin(9600);
  if (!card.init()) error("card.init");
  if (!vol.init(&card)) error("vol.init");
  if (!root.openRoot(&vol)) error("openRoot");

  pinMode(playLED, OUTPUT);
  pinMode(recLED, OUTPUT);
  pinMode(delStopLED, OUTPUT);

}
//------------------------------------------------------------------------------
// loop to play and record files.
void loop() {
  digitalWrite(delStopLED, HIGH);
  if (file.isOpen()){
    file.close();      // Make sure file is closed
  }

  int16_t track = -1;
  uint8_t c;
  if (track < 0 ) {
    track = lastTrack;
  }

  char name[13];
  if (track < 0) track = lastTrack + 1;
  if (!trackName(track , name)) return;
  if (file.open(&root, name, O_READ)) {
    file.close();
    trackDelete(track);
    return;
  }
  digitalWrite(delStopLED, LOW);
  digitalWrite(recLED, HIGH);
  Serial.println( "Recording" );    // Record new file...

  if (!file.createContiguous(&root, name, MAX_FILE_SIZE)) {
      PgmPrintln("Create failed");
      return; }
  if(!wave.record(&file, RECORD_RATE, MIC_ANALOG_PIN, ADC_REFERENCE)) {
      PgmPrintln("Record failed");
      file.remove();
      return; }

  delay(5000);     // ...for x milliseconds
  digitalWrite(recLED, LOW);
  wave.stop();
  wave.trim(&file);
  file.close();     // Stop the recording, trim and close the file

  digitalWrite(playLED, HIGH);
  playTracks();     // Play the file
  digitalWrite(playLED, LOW);
}

About your questions,

In the latest WaveRP library there's a folder where it explains how to attach a microphone to the waveshield. And I'm guessing I don't know for sure, but I'd say they're using a contact mic, the contact mics are both, mics and speakers, some cheap walkies also use them. So I'm guessing that they're using only one?
Contact mics pick up vibration so, I think the plastic cone that they're using is for de contact mic to pick up the vibrations of the surroundings sounds.
A better way to design it? I think that it depends. In a way is an art piece. So, a better way to design it... is like to ask VanGogh a better way to paint sunflowers.
But I think always the sound can be better. A way to improve it could be  making a better amplifier circuit for reduce the noise or separating the mic and the speakers... But I don't know, I think it depends what you want to make and what you want to achieve. Because if you want it to float is better to have the leastest components. But if the sound is the priority I think it can be much more better using an amplifier, a better mic, etc.

Also, now in the Adafruit Wave Shield's page there is a project of realtime voice changer, that also record and playbacks. More information here


text:
Connection problem with Arduino Mega 2560 and GSM shield ( official M10)
As I don't want to stack the shield over the mega 2560 board, I try to connect only the pins that used for GSM communication. Here are my connection:
Pin 3 on Mega <==> Pin GSM Rx on Shield
Pin 10 on Mega <==> Pin GSM Tx on Shield
Pin 4 on Mega <==> Pin 4 on Shield
Pin 5V on Mega <==> Pin Vin on Shield
Pin GRD on Mega <==> Pin GRD on Shield
Code I used is from the Examples library, GsmScanNetworks:
#include <GSM.h>

// PIN Number
#define PINNUMBER "8888"

// initialize the library instance
GSM gsmAccess;     // include a 'true' parameter to enable debugging
GSMScanner scannerNetworks;
GSMModem modemTest;

// Save data variables
String IMEI = "";

// serial monitor result messages
String errortext = "ERROR";

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

  Serial.println("GSM networks scanner");
  scannerNetworks.begin();

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while(notConnected)
  {
    if(gsmAccess.begin(PINNUMBER)==GSM_READY)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  // get modem parameters
  // IMEI, modem unique identifier
  Serial.print("Modem IMEI: ");
  IMEI = modemTest.getIMEI();
  IMEI.replace("\n","");
  if(IMEI != NULL)
    Serial.println(IMEI);
}

void loop()
{
  // scan for existing networks, displays a list of networks
  Serial.println("Scanning available networks. May take some seconds.");
  Serial.println(scannerNetworks.readNetworks());

    // currently connected carrier
  Serial.print("Current carrier: ");
  Serial.println(scannerNetworks.getCurrentCarrier());

  // returns strength and ber
  // signal strength in 0-31 scale. 31 means power > 51dBm
  // BER is the Bit Error Rate. 0-7 scale. 99=not detectable
  Serial.print("Signal Strength: ");
  Serial.print(scannerNetworks.getSignalStrength());
  Serial.println(" [0-31]");

}

Questions:

After opening the serial port, only a line "GSM network scanner" is read. Seems that the program is stuck ongsmAccess.begin(PINNUMBER), how shall I fix that?
Is it a must that I shall supply 5V 2A power to the shield seperately in order for the shield to work? (with connection mentioned above, the ON led light on the shield does turns on with an orange light)
For the PINNUMBER defined in the program, my SIM has default PIN 8888. I checked with a mobile phone that the SIM card does work. But my phone shows that the SIM card is not locked with PIN. So shall I define the PIN as 8888 for ''?

EDIT:
GSM shield link
Note for using GSM shield with Mega
* And yes! The shield did work when stacked! (Orginally I don't want to bend pin 2...but...unnh...stacking and bending out pin 2 did work)
* Tried the examples "GSMScanNetwork" and "SendSMS", works fine. But for "GsmWebServer", an IP address is shown, but when I enter the IP address on my browser, chrome/ie says they cannot find the IP address.....Any clues?
* And does the status LED on the GSM board have anything to do with power? It goes on and off and on and off.....
* For question 1 & 3, PINNUMBER is set to ''. Worked fine.

On point #2, yeah, you'll most likely need to provide an adequate supply. I have a GSM module and it'll turn off as it's trying to connect when I don't give it enough current.

Does it work when you do directly stack the boards together?

I see pin 3 as input but no where in your code are you setting the pin to input. As I missing something?

I have done this, and had (some limited) success.
A couple of your connections are wrong;
Connect both the pin 7s on the shield and MEGA, not the pin 4s. Pin 7 is the reset pin - I think that GSM.begin resets the shield before doing anything. This might help with Q1.
Make sure that you use the regulated 5V output on the MEGA, and not the Vin to power your shield. Vin is whatever voltage is connected to the MEGA power socket, and could damage your shield. I personally have not noticed any difference when powering the MEGA+Shield from USB or external 12V supply.
I had problems with interference when I used wires to connect shield to MEGA. The stacking seems to have reduced this problem, but not eliminated it by any means...
The GSM Web server is unlikely to work except maybe from within your SIM provider's own network. Some of the limitations are mentioned here;
https://www.arduino.cc/en/Tutorial/GSMToolsTestWebServer

source: Stack Exchange

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

sort: votes


text:
Sending serial data to Arduino from Matlab(not using support package)
I am learning Arduino and trying to understand how integers and strings are sent across the serial port.
I tried a small program in arduino which reads a number as a string and tries to blink led 13 according to that number. Below is the arduino side of code.
const int ledpin = 13;
int value = 0;
int blinkrate;
void setup()
{
   Serial.begin(9600);
   pinMode(ledpin,OUTPUT);

}

void loop()
{
    if (Serial.available())
      {
         char ch = Serial.read();
         if (isDigit(ch))
            {
               value = (value*10) + (ch - '0');
            }
         else if (ch == 10)
            {
               blinkrate = value;
               Serial.println(blinkrate);
               value = 0;
            }
      }
    blinkled(blinkrate);
}

void blinkled(int blinkrate)
 {
   digitalWrite(ledpin,HIGH);
   delay(blinkrate);
   digitalWrite(ledpin,LOW);
   delay(blinkrate);
 }

When i try to send a string from MATLAB, the RX led blinks once indicating something is coming, but the LED on pin 13 is not behaving accordingly(it should blink according to the number i send). Here is the matlab side of code.
pre_open = instrfindall;
delete(pre_open);
serial_port = serial('COM3');
set(serial_port,'Terminator','CR');
set(serial_port,'BaudRate',9600);
set(serial_port,'DataBits',8);
set(serial_port,'StopBits',1);
set(serial_port,'Parity','none');
fopen(serial_port);
num = 200;
fwrite(serial_port,int2str(num));
data = fscanf(serial_port,'%d');
pause(2);
fclose(serial_port);

When i try to read the return string from arduino, MATLAB shows me a timeout error.
I would be grateful if anybody points me to the right solution.
Thank you.

Got it, instead of depending on the Serial object, i sent the line feed to arduino. All this time it has been waiting for the Line feed that never arrived.
delete(instrfindall)
s = serial('COM3', 'BaudRate', 9600); %38400
fopen(s);
pause(0.1);
text = input('enter','s');
fprintf(s,'%s\n',text,'sync');
pause(0.1);
d = fscanf(s,'%s');
pause(0.1);
delete(instrfindall)

You're setting the terminator to be 'CR'.  CR, or Carriage Return, is character 13.  In your Arduino program you are looking for character 10.  That is 'LF' or Line Feed.
Either are commonly used to denote a line ending, but both ends must agree on which it is.
For instance, Unix files use a single LF for a line ending.  Windows files use the combination of both a CR and an LF.  Many networking protocols use a single CR for the line ending.  It really doesn't matter what is used as long as it is consistent.

Thanks for the answer,I also had the same doubt, i tried putting linefeed(LF) in the code, but its not working

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


text:
Extracting high and low bytes from long
I am learning Arduino from "Arduino cookbook by Michael Margolis", i was reading about bitwise operations and extracting low and high bytes from int. He said that there is no function in Arduino to extract high and low bytes from long at the time of his writing. He stated an alternative to the problem by adding two line of code.
#define highWord(w) ((w) >> 16)
#define lowWord(w) ((w) & 0xffff)

The first line i clearly understood like this, please make corrections if i am wrong.
32bit binary of 16909060 is 0000 0001 0000 0010 0000 0011 0000 0100

by right shifting last 16 bits we will arrive at
32bit binary of 16909060 after right shifting 16bits is 0000 0000 0000 0000 0000 0001 0000 0010

I am not able to interpret the second line.
#define lowWord(w) ((w) & 0xffff)

I would be very grateful if some body explain how the above line of code works?
Thanks.

The second line masks off the top two bytes using a bitwise AND.
When you use a bitwise AND it follows the normal rules for any boolean truth table.  1 & 1 = 1, 1 & 0 = 0...  Since the value is being ANDed, effectively, against 0x0000FFFF, the top two bytes will be cleared to zero while the bottom two bytes are preserved.  In this way you can extract the lower two bytes out of the four byte long.

So  0x0000FFFF is a hexadecimal representation of
0000 0000 0000 0000 1111 1111 1111 1111

Yes.  We use hex because it's much more easily digested when inspected visually. :)  Binary gets really long really fast.

An alternative way of seeing the two operations is through the operators "integer division" and "reminder of the integer division".
In a more generic fashion:
#include <limits.h>
#define highBits(value, number_of_high_bits) \
 (value / (1 << (sizeof(value) * CHAR_BIT - number_of_high_bits)))
#define lowBits(value, number_of_high_bits) \
 (value % (1 << (sizeof(value) * CHAR_BIT - number_of_high_bits)))
This will work regardless the number of bits used for value and with an arbitrary number of high_bits to either keep or shave.


text:
Arduino Interface with Serial device and LCD display
I want to connect my Arduino UNO to a serial device that once powered displays signature numbers. I want to then display those numbers on an LCD display. I have my 16x2 LCD wired correctly and it works fine even when I use the SerialDisplay example code from the library.
My questions are:

Can I use a USB to TTL serial cable to connect the RX/TX pins of the serial device to the TX/RX pins of the arduino?
The two numbers are more than 16 characters. How can I cut the numbers down and then display the two numbers on two seperate lines of the LCD display?

Let me know if I should provide further details.

You can only use a USB serial converter with something that is a USB host.  Watch out for mismatched voltage standards when directly connecting logic serial lines.  An easy way to split moderately consistent strings is either to count characters or look for a specific character you want to split on.

If the device is serial and you want to connect it to the Arduino serial port, why would you use a usb-to-serial converter?
For a serial to serial connection, you have to connect TX, RX and GND.
This is the bare minimum for bidirectional communication, if your device is really read only, you can use just the TX and GND.
it depends how you receive data from your "serial device" - btw, what is it? If the data comes as either ascii or individual characters, then it's easy: treat them as strings and display them separately. If the numbers arrive in binary format, you have to perform the conversion to string.

Questions like this should have attached at least a snippet, if not all, of code.

That's true! All I need is to connect TX of the device to the RX of the arduino and vice versa. I'm a newb. It's a handle of a medical device that I'm working with for a bionstrumentation school project.
Also, I used a USB to TTL serial cable to see how the data is transmitted on the terminal on my computer and it looks like the data comes as individual characters. I was thinking to display them as strings too.
I don't have much code yet apart from code that just gets input from the serial monitor. Thanks.


text:
error: ‘sleep’ was not declared in this scope
I am trying to use the sleep function in lieu of delay(), but when I include sleep(), I get Sweep.cpp:60:10: error: ‘sleep’ was not declared in this scope
I read some place, about #include <avr/sleep.h> but that is a fail.
#include <avr/sleep.h>
void setup() {
}

void loop() {
  digitalWrite(13, HIGH);   // set the LED on
  sleep(1);              // wait for a second
  digitalWrite(13, LOW);    // set the LED off
  sleep(1000);              // wait for a second
}

I was able to locate sleep.h:
$ locate sleep.h | grep avr
/usr/lib/avr/include/avr/sleep.h

So then I started reading avr/sleep.h, and it seems like I'm doing it right, according to the examples. So, why might this be failing?

formating baffles me in these site please help!

"I am trying to use the sleep function in leu of delay()" Why?

delay halts all  other processes, I need to not do that. sample code is sample.

There are no "all other processes", there is only the rest of the code.

"sleep()" is not a function on arduino. The sleep.h file contains functions for the hardware sleep functionality used to reduce power consumption when processing isn't necessary. "delay()" is the right thing to use.
AVR only has one thread, and so there is no meaning to pausing execution by deferring to another thread. Hardware interrupts will always interrupt the current code no matter what it is doing, they are not equivalent to threads (although they can introduce similar bugs).
If you want to wait and still do other calculations you will need to write code that can wait for a time without blocking. This can be done many ways, one way being to use the arduino library function "millis()" to repeatedly check if it is time to do a certain action, and doing something else for a while if not.
Also, vanilla arduino should be using its own packaged avr lib, for example:
arduino/hardware/tools/avr/avr/include/avr/sleep.h

instead of the one located in your usr/lib directory.

The Arduino IDE as packaged by a distro will more than likely use the distro's AVR Libc, of course.


text:
Arduino function to fade from one RGB color to the next
For my Arduino project I have a Neopixel RGB Strip with 72 LED's.
I can successfully change the colour of any of the LED's (at the moment I'm only setting the first one 0 for testing purposes) so I know my wiring isn't the problem here, it's my coding.
What I would like to do is be able to select a color and then another color and have the first color fade to the next color and so forth (much like the LIFX bulbs behave when using the iPhone application).
This is what I have at the moment:
I am logging output of all the variables to give you an indication of what's going on. I'm not 100% sure on where I'm going wrong or whether there's a much easier way to do what I'm after (I'm open to suggestions).
The function takes a parameter called command, which is a string separated by commas:
e.g. 255, 0, 0 (RED) or 0, 255, 0 (GREEN).
/*******************************************************************************
 * Function Name  : tinkerSetColour
 * Description    : Sets the strip with the appropriate colour
 * Input          : Pin and value
 * Output         : None.
 * Return         : 1 on success and a negative number on failure
 *******************************************************************************/
int Rstart = 0, Gstart = 0, Bstart = 0;
int Rnew = 0, Gnew = 0, Bnew = 0;

int tinkerSetColour(String command)
{
    sprintf(rgbString, "Rstart %i, Gstart %i, Bstart %i", Rstart, Gstart, Bstart);
    Spark.publish("rgb", rgbString);

    sprintf(rgbString, "Rnew %i, Gnew %i, Bnew %i", Rnew, Gnew, Bnew);
    Spark.publish("rgb", rgbString);

    // Clear strip.
    strip.show();

    int commaIndex = command.indexOf(',');
    int secondCommaIndex = command.indexOf(',', commaIndex+1);
    int lastCommaIndex = command.lastIndexOf(',');

    int red = command.substring(0, commaIndex).toInt();
    int grn = command.substring(commaIndex+1, secondCommaIndex).toInt();
    int blu = command.substring(lastCommaIndex+1).toInt();

    int Rend = red, Gend = grn, Bend = blu;

    sprintf(rgbString, "Rend %i, Gend %i, Bend %i", Rend, Gend, Bend);
    Spark.publish("rgb", rgbString);

    // Larger values of 'n' will give a smoother/slower transition.
    int n = 200;
    for (int i = 0; i < n; i++)
    {
        Rnew = Rstart + (Rend - Rstart) * i / n;
        Gnew = Gstart + (Gend - Gstart) * i / n;
        Bnew = Bstart + (Bend - Bstart) * i / n;

        // Set pixel color here.
        strip.setPixelColor(0, strip.Color(Rnew, Gnew, Bnew));
    }

    sprintf(rgbString, "Rnew %i, Gnew %i, Bnew %i", Rnew, Gnew, Bnew);
    Spark.publish("rgb", rgbString);

    Rstart = red, Gstart = grn, Bstart = blu;

    sprintf(rgbString, "Rstart %i, Gstart %i, Bstart %i", Rstart, Gstart, Bstart);
    Spark.publish("rgb", rgbString);

    return 1;
}

The problem is the colors are not fading between themselves.
Apologies if any of this is confusing. I can provide more information if necessary.
Here's the output selecting RED to begin with:
Rstart 0, Gstart 0, Bstart 0
Rnew 0, Gnew 0, Bnew 0
Rend 255, Gend 0, Bend 0
Rnew 253, Gnew 0, Bnew 0

Here's the output selecting GREEN directly afterwards:
Rstart 255, Gstart 0, Bstart 0
Rnew 253, Gnew 0, Bnew 0
Rend 0, Gend 255, Bend 0
Rnew 2, Gnew 253, Bnew 0

And then the output selecting BLUE after that:
Rstart 0, Gstart 255, Bstart 0
Rnew 2, Gnew 253, Bnew 0
Rend 0, Gend 23, Bend 255
Rnew 0, Gnew 25, Bnew 253

There is no delay in there. It will fade very quickly, add a delay e.g. 5ms with n = 200 for a 1 second fade:
int n = 200;
for (int i = 0; i < n; i++)
{
    Rnew = Rstart + (Rend - Rstart) * i / n;
    Gnew = Gstart + (Gend - Gstart) * i / n;
    Bnew = Bstart + (Bend - Bstart) * i / n;

    // Set pixel color here.
    strip.setPixelColor(0, strip.Color(Rnew, Gnew, Bnew));

    delay(5);
}

The other thing is your last value of n in the loop is 199, not 200, and thus Rnew etc don't have the correct final value. Change the comparison to be <= not <:
for (int i = 0; i <= n; i++)


text:
Raspberry Pi Outputting Signal to arduino
I have been trying to get my raspberry pi to output a signal of High or Low, which is then picked up by digital pin 4 on my arduino.
On the raspberry pi, I have connected the output to GPIO 24 and have set up a simple to circuit with an led and 220 ohm resistor in series to check if there was any output. I did manage to get the led to turn on and off due to typing commands into the console on the raspberry pi, so that can't be the problem.
For the raspberry pi side of things, I have installed the WiringPi library and typed these commands:
gpio -g mode 24 out

This set up the GPIO pin and then to turn them off, I used these independently.
gpio -g write 24 1
gpio -g write 24 0

For my code on my arduino, I have adapted a rtc with stepper motor piece of code that I am working on to go with this sub project.
#include <DS3231.h>
#include <Stepper.h>

//---( Number of steps per revolution of INTERNAL motor in 4-step mode )---
#define STEPS_PER_MOTOR_REVOLUTION 32

//---( Steps per OUTPUT SHAFT of gear reduction )---
#define STEPS_PER_OUTPUT_REVOLUTION 32 * 64  // 2048

// Init the stepper object with sequence 1-3-2-4 for proper sequencing
Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 8, 10, 9, 11);

// Init the DS3231 using the hardware interface
DS3231 rtc(SDA, SCL);

const int raspiPin = 4;
int raspiSwitch = 0;

int  Steps2Take;

void setup()
{
  // Setup Serial connection
  Serial.begin(115200);
  pinMode(raspiPin, INPUT);

  // Initialize the rtc object
  rtc.begin();

  // The following lines can be uncommented to set the date and time
  // rtc.setDOW(SATURDAY);     // Set Day-of-Week to SUNDAY
  // rtc.setTime(22, 32, 50);     // Set the time to 12:00:00 (24hr format)
  // rtc.setDate(3, 6, 2017);   // Set the date to January 1st, 2014
}

void loop()
{
  // Read the state from the raspi
  raspiSwitch = digitalRead(raspiPin);

  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  // Declare variable for later testing against
  String myTime = rtc.getTimeStr();

  if (myTime == "17:00:00") {

    Serial.println("Rotating stepper motor at " + myTime + ".");

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

  } else if (myTime == "08:00:00") {

    Serial.println("Rotating stepper motor at " + myTime + ".");

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

  } else if (raspiSwitch == 1) {

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

  }

  delay (1000);

}

When I use the else if statement to turn the stepper motor if there is a high signal from the raspiPin, the motor will turn even when the signal is low.
I used Serial.println to output the state of the raspiSwitch variable to the serial output and for some reason, it changes by itself between 1 and 0. I do not know why and would like to resolve this so I can move onto the next stage of connecting it to the internet on a php webpage.
If anyone could help, I would greatly appreciated it

First delete everything except initializing and printing the value of the pin from a copy of the sketch; especially disconnect the motor driver.  Then use something else like a wire connected to Vcc or Ground to source the input, and verify that you are reading the pin you are switching.

Is the ground of the Arduino connected to the ground of the Pi?

@ChrisStratton I will try that, thank you for your input.

@Majenko I have not currently got the ground from the arduino going to the ground on the pi, but the signal from the pi is grounded on the pi itself.

https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/


text:
Trying to understand the bottleneck of sensor sampling rate
Lets say I have a sensor connected to Arduino Uno Rev3's I2C Bus. I am reading the sensor output and using Serial.print() to send the sensor reading back to a my laptop.
I am trying to understand the bottlenecks that limits the sensor sampling rate received at the laptop.
The sampling rate of the sensor depends on many factors. Lets assume sensors sampling rate is not limited. That would mean I am limited by how much data each intermedia bus can carry before it reaches the laptop. For example, I am limited by I2C bus atmega328p is using to read the sensor data. I am also limited by the UART bus atmega16u2 is using to send the data to my laptop. Am I correct so far? Also, on what bus atmega328p and atmega16u2 are connected over?

refer to the sensor datasheet

Are you using I2C Fast Mode (400kHz) (if the sensor is even capable of that)? If not, then the I2C interface is probably the bottleneck (assuming that the sensor samples fast enough)

@chrisl I am using MPU6050 on I2C 400KHz. On Spec, the sensor can sample from 4 to 1kHz, but I am applying a digital low pass filter that adds 19ms delay. So the sensor sampling rate is too slow already. But still I am trying to understand the intermediate steps so better understand the hardware.

If there had been a specific scenario you were considering, it might help to share. There's quite a lot to think about with just theoretical assumptions.

That would mean I am limited by how much data each intermedia bus can carry before it reaches the laptop

Yes, mostly yes. The bandwidth of the entire transmission interface which includes the I2C interface, ATMEGA328P, connection to ATMEGA16U2, and the USB interface would account for the theoretical max sampling rate of the sensor.
For some cases, you may need to consider the latency as well as the bandwidth of the transmission media, which would include the I2C interface, ATMEGA328P, ATMEGA16U2, and the USB interface. The sensor may require some calculations which may result in some delay. The I2C interface or the UART interface could introduce some delay too, especially if it's driven by bit-banging(although probably not with 328P).
Also from 328P's perspective here, it has to receive data from the sensor, make calculations from the incoming raw data if needed, and send over the UART interface to the 16U2. Most of these processes will happen step by step and if the combined processing time takes longer than the delay between each sample coming from the sensor, the 328P itself could theoretically be a bottleneck too.

Thanks for the detailed answer. That cleared things up.

Also, on what bus atmega328p and atmega16u2 are connected over?

See:
https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf
They are connected by TxD and RxD.
Without seeing your code (hint) it is extremely difficult to say. Perhaps a faster baud rate would help.

Thanks, I just wanted to know that atmega16u2 and atmega328p are connected via UART.  Do Serial.begin also set the baud rate of this connection as well?

@QuaziIrfan, only there

@Juraj Sorry, I don't get what you mean.

@QuaziIrfan, USB line doesn't use that baud rate

So, is there a fixed baud rate that's set during the manufacturing process?

USB doesn't have a baud rate. It's all quite complex, but the protocol involves NRZI (search for stuff about that). However when you do a Serial.begin you set the baud rate of the USB interface chip. That is, the rate at which it expects data from the Atmega328p. The USB interface will be able to handle virtually any baud rate you choose to set.

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


text:
How to use control a 48 000 motor with Arduino
I am new to Arduino and I am just playing with it, I wanna control a 48,000rpm motor with 9v voltage via Arduino the plobrem is how could I make that motor slow down, slowly. Any ideas? I am using Arduino mega

Can you post more details about the motor, for example link to data sheet.  Also, what driver you are using. If you are using PWM it should be straightforward to control the speed.

So far you haven't added any information about the motor so I am going to assume it is a standard DC motor.
With this type of motor, you can change the speed by varying the voltage. So at 9V it will go full speed (theoretically 48,000 RPM). At 4.5V it should go at about (roughly) half. Of course this varies with the load you are applying to the motor.
You can control the motor speed using the PWM output of the Arduino. If you would like to read more about Pulse-width Modulation (PWM) I highly recommend that you read the Sparkfun article here.
This presents 2 problems.

The Arduino Mega PWM only gives you an adjustable voltage between 0V to 5V.
The current provided on these pins is only small and would not be able to power the motor fully.

To overcome both you need to add a MOSFET. I suggest a N-Channel MOSFET that switches on the low side.

simulate this circuit – Schematic created using CircuitLab

Looks super easy, would a IRFZ44N N-Channel MOSFET  work?

Without looking too deeply into it (which I recommend you do), it seems a good fit. The max voltage is 55V, tick. The max current is 49A, tick. The gate threshold is less than 4V, tick. 11A output at 5V gate voltage, tick. You may need to add an additional fly-back diode to handle back EMF - but that is more of a question for [electronics.se].

I am gonna do it tonight and check it works or not btw thanks for this helpful answer

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


text:
error using String class to convert a double to a string
i wanted to convert a double to a string i tested several examples online i allawys get the same error.
the code :
void setup()
{
  Serial.begin(9600);

}
void loop()
{
  double val =3.2222;
  String stringOne =  String(val, 3);
  Serial.print(stringOne);
}

the errors :
sketch_jun02c.ino: In function ‘void loop()’:
sketch_jun02c.ino:10:36: error: call of overloaded ‘String(double&, int)’ is ambiguous
sketch_jun02c.ino:10:36: note: candidates are:
In file included from /usr/share/arduino/hardware/arduino/cores/arduino/Arduino.h:192:0,
                 from sketch_jun02c.ino:2:
/usr/share/arduino/hardware/arduino/cores/arduino/WString.h:70:11: note: String::String(long unsigned int, unsigned char)
  explicit String(unsigned long, unsigned char base=10);
           ^
/usr/share/arduino/hardware/arduino/cores/arduino/WString.h:69:11: note: String::String(long int, unsigned char)
  explicit String(long, unsigned char base=10);
           ^
/usr/share/arduino/hardware/arduino/cores/arduino/WString.h:68:11: note: String::String(unsigned int, unsigned char)
  explicit String(unsigned int, unsigned char base=10);
           ^
/usr/share/arduino/hardware/arduino/cores/arduino/WString.h:67:11: note: String::String(int, unsigned char)
  explicit String(int, unsigned char base=10);
           ^
/usr/share/arduino/hardware/arduino/cores/arduino/WString.h:66:11: note: String::String(unsigned char, unsigned char)
  explicit String(unsigned char, unsigned char base=10);
           ^

Which IDE version are you using? The fact it's showing /usr/share/arduino tells me you installed it with apt-get (or similar), so you're probably on something ridiculously ancient.

Yes i used apt-get, the version i am using is: ARDUINO 1.0.5 - 2013.05.15, is there a way to update it without deleting the old version ?

Download the new version from the website, extract it, and run it.

Yea I have done that already thanks Majenko ;)

The current Arduino SDK version is 1.8.2.  So 1.0.5 is really old.  Package managers do not necessarily stay up to date.  Especially with packages that don't make up the core of the OS.  In C++ the types of the arguments are just as important as the name of the function you are calling.  No (perfect) match means no function will be called.  So it does not look like there is a matching "Strings()" function.  That is, a "Strings()" function where the type of the argument is a double.

Yea thank you, after upgradign the IDE to 1.8.2 the program worked fine !

@LookAlterno Thank you for telling me it is done

I had installed arduino using apt-get and I didnt notice that I had an old version. I upgraded my arduino and it worked fine.


text:
Errors creating instance MenuBackend and MenuItem attributes in a display class
I am doing a display class using 2*8 lcd on an arduino to display and navigate my menu using MenuBackend library but i can make instance of these variables. I tried using static variable it did not work either.
here is the codes
GPSMenu.h :
#ifndef GPSMENU_h
#define GPSMENU_h
#include "Arduino.h"
#include <MenuBackend.h>
#include <LiquidCrystal.h>

class GPSMenu
{
public:
GPSMenu(LiquidCrystal* lcd);

  void navigateMenus( byte read);

  private:
  void menuChangeEvent(MenuChangeEvent changed);
  void menuUseEvent(MenuUseEvent used);
  void menuSetup();
  LiquidCrystal *_lcd;

  MenuBackend menu =  MenuBackend(menuUseEvent,menuChangeEvent);

  //beneath is the list of menu items needed to build the menu
  MenuItem Battery     = MenuItem(menu, "Battery ", 1);//----usable
  MenuItem Iteneraire  = MenuItem(menu, "Itener  ", 1);
  MenuItem Start       = MenuItem(menu, "Start   ", 2);//----usable
  MenuItem Stop        = MenuItem(menu, "Stop    ", 2);//----usable
  MenuItem FileOpn     = MenuItem(menu, "FileOpn ", 2);
  MenuItem NewFile     = MenuItem(menu, "NewFile ", 3);//----usable
  MenuItem OverWr      = MenuItem(menu, "OverWr  ", 3);//----usable
  MenuItem PtOpn       = MenuItem(menu, "PtOpn   ", 2);
  MenuItem Seconde_1   = MenuItem(menu, "Court   ", 3);//----usable
  MenuItem Secondes_15 = MenuItem(menu, "Moyen   ", 3);//----usable
  MenuItem Minute_1    = MenuItem(menu, "Long    ", 3);//----usable
  MenuItem GPSData     = MenuItem(menu, "GPSData ", 1);
  MenuItem Coord       = MenuItem(menu, "Coord   ", 2);//----usable
  MenuItem Time        = MenuItem(menu, "Time    ", 2);//----usable
  MenuItem Status      = MenuItem(menu, "Status  ", 2);//----usable
  MenuItem SpdAlti     = MenuItem(menu, "SpdAlti ", 2);//----usable
  MenuItem Filemnger   = MenuItem(menu, "Filemngr", 1);//----usable

};
#endif

GPSMenu.cpp:
#include "Arduino.h"
#include <MenuBackend.h>    //MenuBackend library - copyright by Alexander Brevig
#include <LiquidCrystal.h>  //this library is included in the Arduino IDE
#include "GPSMenu.h"  //this library is included in the Arduino IDE

GPSMenu::GPSMenu(LiquidCrystal* lcd){
 _lcd = lcd;
 _lcd->begin(8, 2);
 _lcd->clear();
  GPSMenu::menuSetup();

}

//this function builds the menu and connects the correct items together
void GPSMenu::menuSetup()
{
  //add the file menu to the menu root
  menu.getRoot().add(Battery);
  Battery.addRight(Iteneraire).addRight(GPSData ).addRight(Filemnger);
  Iteneraire.add(Start ).addRight(Stop).addRight(FileOpn).addRight(PtOpn);
  GPSData.add(Coord).addRight(Time).addRight(Status).addRight(SpdAlti);
  FileOpn.add(NewFile).addRight(OverWr);
  PtOpn.add(Seconde_1).addRight(Secondes_15).addRight(Minute_1);
}

//  This is where you define a behaviour for a menu item

void GPSMenu::menuUseEvent(MenuUseEvent used)
 {
   _lcd->setCursor(0, 0);
   _lcd->print(used.item.getName());
   _lcd->setCursor(0, 1);
   _lcd->print("Used    ");
}
/*
  Here we get a notification whenever the user changes the menu
  That is, when the menu is navigated
*/
void GPSMenu::menuChangeEvent(MenuChangeEvent changed)
{
  _lcd->setCursor(0, 0);
  _lcd->print(changed.from.getName());
  _lcd->setCursor(0, 1);
  _lcd->print(changed.to.getName());
}

void GPSMenu::navigateMenus( byte read) {
  MenuItem currentMenu=menu.getCurrent();

  switch (read){

  case 1:

    if(!(currentMenu.hasAfterChildren())){  //if the current menu has a child and has been pressed enter then menu navigate to item below
      menu.use();
    }
    else{  //otherwise, if menu has no child and has been pressed enter the current menu is used
      menu.moveDown();
    }
    break;

  case 2:
    menu.moveLeft();

    break;
  case 3:
    menu.moveRight();

    break;
  case 4:
    menu.moveUp();
    break;
  }
}

And the errors on my terminal :
In file included from GPSMenu.cpp:4:0:
GPSMenu.h:20:46: error: ‘void GPSMenu::menuUseEvent(MenuUseEvent)’ cannot appear in a constant-expression
       static MenuBackend menu =  MenuBackend(menuUseEvent,menuChangeEvent);
                                              ^
GPSMenu.h:20:59: error: ‘void GPSMenu::menuChangeEvent(MenuChangeEvent)’ cannot appear in a constant-expression
       static MenuBackend menu =  MenuBackend(menuUseEvent,menuChangeEvent);
                                                           ^
GPSMenu.h:20:74: error: invalid in-class initialization of static data member of non-integral type ‘MenuBackend’
       static MenuBackend menu =  MenuBackend(menuUseEvent,menuChangeEvent);
                                                                          ^
GPSMenu.h:20:74: error: initializer invalid for static member with constructor
GPSMenu.h:20:74: note: (an out of class initialization is required)
GPSMenu.h:23:46: error: ‘GPSMenu::menu’ cannot appear in a constant-expression
       static MenuItem Battery     = MenuItem(menu, "Battery ", 1);//----usable
                                              ^
GPSMenu.h:23:65: error: invalid in-class initialization of static data member of non-integral type ‘MenuItem’
       static MenuItem Battery     = MenuItem(menu, "Battery ", 1);//----usable
                                                                 ^
GPSMenu.h:23:65: error: initializer invalid for static member with constructor
GPSMenu.h:24:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Iteneraire  = MenuItem(menu, "Itener  ", 1);
                                                          ^
GPSMenu.h:25:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Start       = MenuItem(menu, "Start   ", 2);//----usable
                                                          ^
GPSMenu.h:26:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Stop        = MenuItem(menu, "Stop    ", 2);//----usable
                                                          ^
GPSMenu.h:27:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem FileOpn     = MenuItem(menu, "FileOpn ", 2);
                                                          ^
GPSMenu.h:28:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem NewFile     = MenuItem(menu, "NewFile ", 3);//----usable
                                                          ^
GPSMenu.h:29:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem OverWr      = MenuItem(menu, "OverWr  ", 3);//----usable
                                                          ^
GPSMenu.h:30:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem PtOpn       = MenuItem(menu, "PtOpn   ", 2);
                                                          ^
GPSMenu.h:31:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Seconde_1   = MenuItem(menu, "Court   ", 3);//----usable
                                                          ^
GPSMenu.h:32:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Secondes_15 = MenuItem(menu, "Moyen   ", 3);//----usable
                                                          ^
GPSMenu.h:33:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Minute_1    = MenuItem(menu, "Long    ", 3);//----usable
                                                          ^
GPSMenu.h:34:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem GPSData     = MenuItem(menu, "GPSData ", 1);
                                                          ^
GPSMenu.h:35:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Coord       = MenuItem(menu, "Coord   ", 2);//----usable
                                                          ^
GPSMenu.h:36:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Time        = MenuItem(menu, "Time    ", 2);//----usable
                                                          ^
GPSMenu.h:37:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Status      = MenuItem(menu, "Status  ", 2);//----usable
                                                          ^
GPSMenu.h:38:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem SpdAlti     = MenuItem(menu, "SpdAlti ", 2);//----usable
                                                          ^
GPSMenu.h:39:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Filemnger   = MenuItem(menu, "Filemngr", 1);//----usable

You can't set the value of a variable in the header file (class definition).
class foo
{
  int a = 1;  // This doesn't work
};

This works
class foo2
{
  static int b;
};
int foo2::b = 2;

why do we have to precise int in :int foo2::b = 2; since we have allready declared b as int.
I did what you said but i get
In file included from GPSMenu.cpp:4:0:
GPSMenu.h:59:70: error: invalid use of non-static member function
MenuBackend GPSMenu::menu =
MenuBackend(menuUseEvent,menuChangeEvent);

why do you have to declare int again in int foo2::b = 2; I don't know, but I d know it doesn't work if you don't.  That's because GPSMenu::menu is not a static member.

GPSMenu::menu is declated as static ...
in the class
public:
GPSMenu(LiquidCrystal* lcd);
void navigateMenus( byte read);
static  MenuBackend menu;
static  MenuItem Battery; ect.....

and outside it
MenuBackend GPSMenu::menu =  MenuBackend(menuUseEvent,menuChangeEvent);
MenuItem GPSMenu::Battery= MenuItem(menu, "Battery ", 1); ect...


text:
Arduino snake on 5110 screen - some help needed
I'm trying to make a snake game using the u8g lib. But for now, only the second body part of the snake follows the head, where I want the whole body to follow the snake's head and I don't understand why it doesn't work.
Here is the code:
#include "U8glib.h"

U8GLIB_PCD8544 u8g(13, 11, 10, 9, 8);    // SPI Com: SCK = 13, MOSI = 11, CS = 10, A0 = 9, Reset = 8

const int SNAKEMAXSIZE = 10;

bool title = true;
bool gameRunning = false;

enum direction {HAUT, BAS, GAUCHE, DROITE};

int snakeDirection = GAUCHE;

class snakeCell
{
  private:
  int x;
  int y;

  public:

  snakeCell(int x, int y)
  {
    this->x = x;
    this->y = y;
  }

  snakeCell()
  {
    x = 42;
    y = 24;
  }

  void setX(int x)
  {
    this->x = x;
  }

  void setY(int y)
  {
    this->y = y;
  }

  int getX()
  {
    return x;
  }

  int getY()
  {
    return y;
  }

  void draw()
  {
    u8g.drawBox(x, y, 5,5);
  }
};

class Pomme
{
  public:
  int x;
  int y;

  Pomme(int x, int y)
  {
    this->x = x;
    this->y = y;
  }

  Pomme()
  {
    x = 42;
    y = 24;
  }

  void randomSpawn()
  {
    x = random(48);
    y = random(84);
  }

  void draw()
  {
    u8g.drawCircle(x, y, 5);
  }
};

snakeCell snake[10] = {snakeCell(), snakeCell(47,24), snakeCell(52,24), snakeCell(57,24), snakeCell(62,24), snakeCell(62,29), snakeCell(62,34), snakeCell(57,34), snakeCell(52,34), snakeCell(52,39)};

Pomme pomme = Pomme();

void draw(void) {
  // graphic commands to redraw the complete screen should be placed here
  u8g.setFont(u8g_font_6x13);
  //u8g.setFont(u8g_font_osb21);
  u8g.drawRFrame(0, 0, 84, 48, 0);   //Screen frame
  printTitle();
  game();
}

void setup(void) {
  // flip screen, if required
   //u8g.setRot180();

  // set SPI backup if required
  //u8g.setHardwareBackup(u8g_backup_avr_spi);

  // assign default color value

  randomSeed(analogRead(0));

  if ( u8g.getMode() == U8G_MODE_R3G3B2 ) {
    u8g.setColorIndex(255);     // white
  }
  else if ( u8g.getMode() == U8G_MODE_GRAY2BIT ) {
    u8g.setColorIndex(3);         // max intensity
  }
  else if ( u8g.getMode() == U8G_MODE_BW ) {
    u8g.setColorIndex(1);         // pixel on
  }
  else if ( u8g.getMode() == U8G_MODE_HICOLOR ) {
    u8g.setHiColorByRGB(255,255,255);
  }

}

void loop(void) {
  // picture loop
  u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );

  // rebuild the picture after some delay
  delay(50);
}

void printTitle()
{
  if(title == true)
  {
    u8g.setFont(u8g_font_6x13);
    //u8g.drawStr( 26, 30, "SNAKE");
    delay(2000);
    title = false;
    gameRunning = true;
  }
}

void moveSnake()
{
  //move head accordingly to movement
  if(snakeDirection == GAUCHE)
  {
    snake[0].setX(snake[0].getX() - 1);
  }
  else if(snakeDirection == DROITE)
  {
    snake[0].setX(snake[0].getX() + 1);
  }
  else if(snakeDirection == BAS)
  {
    snake[0].setY(snake[0].getY() + 1);
  }
  else if(snakeDirection == HAUT)
  {
    snake[0].setY(snake[0].getY() - 1);
  }

  //tail follow head
  for(int i = 9; i > 0; i--)
  {
    snake[i] = snakeCell(snake[i-1].getX(),snake[i-1].getY());
  }
  delay(100);
}

void restart()
{
  //snakeCell snake[10] = {snakeCell(), snakeCell(47,24), snakeCell(52,24), snakeCell(57,24), snakeCell(62,24), snakeCell(62,29), snakeCell(62,34), snakeCell(57,34), snakeCell(52,34), snakeCell(47,34)};
}

void drawSnake()
{
  for(int i = 0; i < SNAKEMAXSIZE; i++)
  {
    snake[i].draw();
  }
}

void spawnApple()
{
  pomme = Pomme();
  pomme.randomSpawn();
}

void checkCollision()
{
  // detect if apple eaten
  for(int i = 0; i < SNAKEMAXSIZE; i++)
  {
    if((snake[i].getX() == pomme.x) && (snake[i].getY() == pomme.y))
    {
      pomme.randomSpawn();
    }
  }
  // detect if snake hit wall
  for(int i = 0; i < SNAKEMAXSIZE; i++)
  {
    if((snake[i].getX() >= 84) || (snake[i].getX() <= 0) || (snake[i].getY() >= 48) || (snake[i].getY() <= 0))
    {
      //gameOver();
      restart();
    }
  }
}

void gameOver()
{
  gameRunning = false;
  //u8g.setFont(u8g_font_6x13);
  //u8g.drawStr( 14, 30, "GAME OVER");
  //delay(1000);
  restart();
  gameRunning = true;
}

void game()
{
  if(gameRunning == true)
  {
    checkCollision();
    moveSnake();
    drawSnake();
  }
}

Thanks in advance.

There might be a problem with going through your snake array from the back.
I'm not sure if you're filling it from front or back, but you should read it from there aswell.
And, every time you re-draw your snake, you're creating a new snakeCell?
//tail follow head
  for(int i = 9; i > 0; i--)
  {
    snake[i] = snakeCell(snake[i-1].getX(),snake[i-1].getY());
  }

You should differentiate between a snakeCell that is active or not. And just re-position and draw it when it's active.
Be sure to check if you're not placing them ontop of eachother. You should put each piece of the tail in the previous position of the preceding part.
Also: You shouldn't really be mixing up French and English naming in your code.


text:
Turn LEDs on in binary sequence
Could I have some help getting the following code work?
My purpose is to turn on 4(or N) LEDs in a binary sequence with 4 (or N) bits, A,B,C,D. When bit=1, LED on, otherwise LED off,...
I will have 16 combinations, 2^4=16, so:

0000 => All leds off
0001 => All leds off except the one on the right
...

Here's the code I came up with:
int LEDblu=4;
int LEDgiallo=2;
int LEDrosso=5;
int LEDverde=7;
int num_led;
String numeri="";
String output;
int i=0;
int p;

void setup() {
    // put your setup code here, to run once:
    pinMode(LEDblu,OUTPUT);
    pinMode(LEDgiallo,OUTPUT);
    pinMode(LEDrosso,OUTPUT);
    pinMode(LEDverde,OUTPUT);

    Serial.begin(9600);

    if(Serial.available())                //Dimmi numero LED
    {
        num_led=Serial.readString().toInt();
        Serial.print(num_led);
    }
}

void loop() {
    // put your main code here, to run repeatedly:
    int vect[num_led];
    for(int i=num_led-1, c=0; i>=0; i--, c++)
    {
        int num=2^i;
        vect[c]=num;
    }

    output="";

    if(i<2^num_led)
    {
        p=i;

        for(int c=0; c<num_led; c++)     //Convert binary to decimal
        {
            if(p>=vect[c])
            {
                output+="1";
                int d=vect[c];
                p-=d;
            }
            else
                output+="0";
        }

        Serial.println(output);

        if(output[0]=="1")
            digitalWrite(LEDrosso,HIGH);
        else
            digitalWrite(LEDrosso,LOW);

        if(output[1]=="1")
            digitalWrite(LEDverde,HIGH);
        else
            digitalWrite(LEDverde,LOW);

        if(output[2]=="1")
            digitalWrite(LEDgiallo,HIGH);
        else
            digitalWrite(LEDgiallo,LOW);

        if(output[3]=="1")
            digitalWrite(LEDblu,HIGH);
        else
            digitalWrite(LEDblu,LOW);
    }

    delay(1000);
    i++;
}

^ is XOR. I think you want << bitshifting

@Majenko I guess he thinks ^ is for power. For powers use pow (e.g. pow(2, num_led))

For powers of 2 use bitshifting. pow() is very heavyweight.

Note that this is one of those situations where direct port access
just makes things easier. You did not specify what board you are using,
and I will assume you have some AVR-based board. On those boards, I/O
pins come in groups called ports, with up to eight pins per port. You
can update all the pins of a port at once by writing a number to the
port output register. And guess what? The number you write comes out the
pins in binary, jut like everything works in binary inside the
microcontroller.
For example, on an Arduino Uno, you could wire your LEDs to the first
four pins of port B: i.e. pins 8 (lest significant bit) through 11 (most
significant bit). Then you can output a number to the LEDs just by
writing PORTB = number, and your loop would become:
void loop()
{
    static uint8_t number;
    PORTB = number;              // output to pins 8..11
    Serial.println(number, 2);   // print the value in binary
    number = (number + 1) % 16;  // increment modulo 16
    delay(1000);
}

I don't see any specific initialization of num_led; it should be set to some appropriate value, like 4.
As noted in some comments, the ^ operator is bitwise exclusive-Or.  For example, 2^2 is 0, 2^4 is 6, 2^7 is 5, etc.
To compute the nth power of 2, say 1<<n.
Your convert-binary-to-decimal code is clunky and unnecessary.  Instead, do something like the following, which repeatedly strips off the least significant bit of t:
t = p;
digitalWrite(LEDrosso,t&1);   t>>=1;
digitalWrite(LEDverde,t&1);   t>>=1;
digitalWrite(LEDgiallo,t&1);  t>>=1;
digitalWrite(LEDblu,t&1);

If you want the blue LED instead of the red one to represent the least significant bit, reverse the order of color names in the digitalWrite statements from rosso, verde, giallo, blu to blu, giallo, verde, rosso.
To print data out in binary, use the Streaming.h library, and say, for example,
Serial << _BIN(p) << endl;

Serial.println(p, BIN); should be working too. But Streaming library is usually more usefull.

@KIIV, thanks for that note.  I didn't remember the syntax for Serial.println(p, BIN) and was short of time for looking it up.


text:
How to update a text file dynamically
I have Two Arduinos, One with the help of sensors it will dynamically updates in to my server database. Other Arduino, reads the stored contents from the server database and sends sms to phones.
Now, I have a text file in my server which updates dynamically for every 5 min - 10 min. I am trying to read that text file contents.
I want my server to be always connected, So It must be in setup() function.
I want update only to my text file which dynamically changes, so it must be loop() function.
How to implement this ? Any Suggestion ?

Does the content change via web interface or with a sensor/other function on the Arduino?

Is the Arduino the server or the client?

I have Two Arduinos, One with the help of sensors it will dynamically updates in to my server database. Other Arduino, reads the stored contents from the server database and sends sms to phones.

Is your server actually running on an Arduino?

@PeterR.Bloomfield My server is separate. I am just using Arduino to submit the sensor information to my Server database and with other Arduino, I am sending sms to any phone number that request for the server data.

So which part do you need help with then?

I want the server connection in setup() and In loop() I want to updated only current content in the text file. How to update the client.print("GET /current.txt"); dynamically in loop()

It's difficult to answer without details of how your server works.
If your arduino is simply connected to the server, the server could open the arduino serial port (e.g.: COM5: or /dev/ttyUSB0) and simply read data.  The arduino would only need to serialWrite() data for the server to parse and store.
If your arduino is not connected but has ethernet support you could do a HTTP request to your server, and pass the data as a parameters to the request, e.g.:
http://your.server.ip/send_data?param1=10.3&param2=5.6&param3=foo

When your server processes this HTTP request, it appends param1, param2, param3 to that text file.
The arduino could also beam data back to your server via IR, or bluetooth, etc.
There's lots of ways to do this.


text:
Error while connecting Arduino to Macbook: “serial port already in use. try quitting any programs that may be using it”
I'm trying to connect to my Arduino board through a macbook pro with mac os x 10.9.3 installed. I'm following the instructions from the arduino guide and in the connection section:

" Connect the Arduino board to your computer using the USB cable. The green power LED (labelled PWR) should go on.
  If you're using the Arduino Uno or Arduino Mega 2560, a dialog box will appear telling you that a new network interface has been detected. Click "Network Preferences...", and when it opens, simply click "Apply". The Uno or Mega 2560 will show up as "Not Configured", but it's working properly. Quit System Preferences.

I cannot see any ports that hold the USBModem port.
How to setup the connection in the right way?
I read some articles about making a lock folder and I followed them but they didn't work for me, I also tried following this article but the solution there didn't work as well.

Try this What's keeping me, is a program that tells you which process is using something

I've found the free terminal utility CoolTerm helpful in resolving "port already in use" problems. Mac Serial is a bit flakey. http://freeware.the-meiers.org/

Sorry about providing this as an answer, rather than comments; however, I do have some suggestions to troubleshoot the connection.
First, check the usb connections with lsusb
    lsusb |grep -i arduino

Similarly, you can try following the output of dmesg; though, I'm not sure about the version of dmesg your system's installation is running.  Newer version of dmesg have a "follow" option available. On my Fedora system it's:
    dmesg -wH

Check the output as you plug in the arduino for messages related to the device, such as the resulting location of the tty. As a desperate measure, you can also look in the /dev/ folder for the last modified device, and search your logs for those devices:
    ls -alrth /dev/

This is not a applicable answer, as the system in question is not running Linux.

Under what circumstances does this happen? I see this message whenever I try to download to the Arduino but I've left my terminal program connected to that port. The fix in that situation is to disconnect it (after a <face-palm> to remind myself, yet again....  :-)


text:
Upload a .hex file, using a standalone ISP, without overwriting bootloader
Is it possible to flash a .hex file on an AVR MCU, which already contains the Arduino bootloader, using an AVRISP mkII, without overwriting the bootloader?
In my concrete situation, I have an Arduino Uno that I would like to program sometimes over an AVRISP mkII, and sometimes using the built-in programmer (i.e. by just connecting the Uno via USB to a computer).
For reference, given a compiled .hex file, this is what I use to upload it using the built-in programmer:
avrdude -c arduino -p atmega328p -P/dev/ttyACM0 -b115200 -D -Uflash:w:_build/image.hex:i

By default, this works as expected. I  can also use avrdude to upload it using the AVRISP:
avrdude -c avrisp2 -p atmega328p -U flash:w:_build/image.hex:i

This gets my image on the board as well; however, it also seems to overwrite the bootloader, i.e. after this, I can only use the AVRISP, and not the built-in one, to upload images. The only way back, at this point, is to re-flash the bootloader (via the AVRISP) on the Uno.
If I try to instruct avrdude to upload via the AVRISP without overwriting the bootloader:
avrdude -c avrisp2 -p atmega328p -D -U flash:w:_build/image.hex:i

then it fails in the verification phase:
avrdude: verification error; content mismatch

Based on @ChrisStratton's answer, I understand this means my problem actually starts before I even try to upload it, by the compiler emitting code which has addresses that should belong to the bootloader.
Here is the command I use to compile and link (I am not using the Arduino IDE at all)
avr-g++ -c -g -O3 -w -std=c++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -I.. -mmcu=atmega328p -DF_CPU=16000000L blinkPB5.cpp -o _build/blinkPB5.cpp.o -MMD -MF _build/blinkPB5.cpp.m
avr-g++ -Os -Wl,--gc-sections -mmcu=atmega328p -o _build/image.elf _build/blinkPB5.cpp.o
avr-objdump -S _build/image.elf
avr-objcopy -Oihex -R.eeprom _build/image.elf _build/image.hex

As explained above, I can use the same resulting .hex file both via the bootloader (by just uploading it via serial) and the AVRISP (by overwriting the bootloader).

To preserve the bootloader, you should use the -D option in the ISP command line just as it was used in the bootloader upload command line. This will disable usage of full-chip erase.
I expect you would end up with something like
avrdude -c avrisp2 -p atmega328p -D -U flash:w:_build/image.hex

However, it is important to add something which I overlooked when first posting this answer, which is that the ATmega series cannot do a partial flash erase via the ISP interface in the way that it can when the bootloader causes the chip to program itself.  This effectively means that you only get one shot at loading a program to an already blank area of the chip this way - after that, to load a different one to the same area you will have to do a mass erase of the entire chip and reload both the bootloader and the sketch, or else command the bootloader to erase the blocks where the sketch would reside.
Of course you will also need a hex file for your sketch with no contents that conflict with the bootloader, as while the bootloader would refuse to overwrite any of its own blocks when programming a sketch, the ISP is perfectly happy to try to write over the top of the bootloader, which would likely result in a logical AND of the bits of two different pieces of code, and cause the chip to boot to nonsense.  A typical Arduino board configuration reserves space for the expected bootloader, so if the one you are using matches the size reserved in the chosen configuration, you should not have a conflict.
Another option could be to combine the bootloader and sketch hex files, literally concatenating their contents one after the other into the same file.

Newer Arduino IDE version already create a hex file without and with bootloader

OK, I've tried that and that fails with
verification error; content mismatch, so I guess that confirms that the compiled .hex file starts at the wrong address. I'll edit my question to include details of how I am compiling.

@Cactus - the verification issue might be a limitation I overlooked when first posting this, which is that an ATmega cannot be partially erased over ISP.  So while this method would work the first time you load something to the sketch area, the second time you will get the garbled result of programing a new sketch over an old one without erasing it, which would indeed be likely to cause a verification error.


text:
What happens if there is a runtime error?
What happens if there is a runtime error in a program? Will execution of the program just stop? Is there some way I can get the Arduino to tell me what the error is?

First, let's see a few examples of what can go wrong.
Uninitialized local variables
void setup() {
  int status;
  pinMode(13, OUTPUT);
  digitalWrite(13, status);
}

As pointed out by Edgar Bonet in the comments, local variables like status in the code above are not implicitly initialized by the C++ compiler. So, the outcome of the code above is indeterminate. To avoid that, make sure you always assign values to your local variables.
Things are a bit different with global and static variables:

Global and static variables are guaranteed to be initialized to 0 by the C standard.

Source:
AVR Libc Reference Manual - Frequently Asked Questions - Shouldn't I initialize all my variables?
That means you shouldn't worry about initializing them to 0 in your code. In fact, you should really avoid it, as the initialization may waste memory. Only initialize them to values other than 0.
Memory overflow
int array[10];
int v = array[100];
array[-100] = 10;

The first problem here is that you don't know what will be assigned to v, but worse is that you don't know what you messed up with the assignment to position -100 of array.
Jump to an illegal instruction
void doSomething( void ) {
    for (int i = 0; i < 1000; i++);
}

void setup ()
{
    void (*funcPtr)( void );

    funcPtr = &doSomething;
    funcPtr(); // calls doSomething();

    funcPtr = NULL;
    funcPtr(); // undefined behavior
}

The first call to funcPtr() will actually be a call to doSomething(). Calls like the second one may lead to undefined behavior.
Other bad things that may happen
Well, you can run out of RAM, for example. What else. In any case, I think your program will keep running, probably not the way you intended it to.
Kinds of Protection
In computer systems, problems like these are usually dealt with at various levels:

By the compiler
By the programming language runtime (as in Java for example).
By the operating system or the processor (if your memory access a position outside the boundaries of the address space reserved to your program, the OS or the processor may have safety mechanisms to prevent that)

Arduinos only have limited protection of the compiler, and probably nothing else. The good news is that they aren't multi-tasked, so the only program being affected is yours. In any case, any of those bugs will lead to erratic behavior.
The Answers
The assumptions are the all of the problems I stated above are runtime problems.

What happens if there is a runtime error in a program?

The program will continue and what happens will depend on the side-effects of the runtime error. A call to the null function pointer will probably make the program jump to an unknown location.

Will execution of the program just stop?

No, it will keep going as if nothing extraordinary happened, probably doing what you didn't intend it to do. It may reset or act erratically. It may turn some inputs into outputs and burn a sensor or two (but that's highly unlikely).

Is there some way I get the Arduino to tell me what the error is?

I don't think so. As I said earlier, the protection mechanisms aren't there. There's no runtime support from the language, no OS, no hardware checks for out-of-bounds memory access (the bootloader doesn't count as either). You just have to be careful with your program and probably set your own safety nets.
The reason for the lack of protection is probably because Arduino controllers are too cheap, have too little memory, and should not run anything too important (yes, there seems to be a disclaimer by AVR somewhere for you not to use the MCUs normally used by Arduino in life support systems).

Great! The best answer I have seen on Arduino.SE so far!

Thanks!! I think we should strive to give great answers as much as possible. But it worries me a little the fact that we don't have that many REAL EE EXPERTS that could look at answers like mine and find any glaring mistakes. Actually, that's the reason I posted the answer even though I don't know that much about AVR MCUs. That's to see if we get someone to correct it. We sure don't want smart pents like me saying stuff that isn't right and getting away with it. But that's probably a discussion for the Meta site.

Would any of this damage the Arduino?

@AnnonomusPerson - The only likely mechanism for damage would be code that changes pin state in a manner that results in a bus contention (e.g. the ATmega trying to set a pin high, while external hardware is setting it low). It's also possible that if there is external hardware the ATmega is controlling that cannot handle certain control-input states, the external hardware could cause some manner of failure and damange, but an arduino with nothing connected it pretty bulletproof. The arduinos have series resistors to prevent possible contention issues on the serial lines.

@Ricardo - One comment I would make is that non-explicitly initialized variables are not necessarily uninitialized. Variables defined outside of functions generally have what's termed "automatic storage duration", which then get default-initialized to zero. See http://en.cppreference.com/w/cpp/language/default_initialization for more information. The initialization behaviour is complex enough that it's probably dangerous to rely upon, but making blanket statements is probably not a great idea.

Furthermore, the SRAM is initialized to 0 at reset or startup, so you can make some informed guesses about uninitialized variables, if you want to live dangerously. You shouldn't rely on this behaviour, but it is interesting.

There is an interesting example of what happens when you run out of SRAM here: http://electronics.stackexchange.com/questions/42049/arduino-serial-print-changes-behavior-of-program-undesireably/42069. Basically, the stack clobbers part of the heap, or vice versa. This can do interesting things like corrupt some part of the stack-frame (breaking function returns, etc), or writing invalid data to variables.

Also relevant is the question about recursion: http://arduino.stackexchange.com/questions/355/how-much-can-i-recurse-how-much-can-i-recurse-how-much-caqfsdrfw since recursion is one of the easy ways to blow the stack.

@FakeName - Right! I'll edit my answer to fix the statement about uninitialized variables. As for the other great suggestions you posted, why don't you make them an answer and I'll add a reference to it from mine? Glad to see you (or maybe just the picture of your annoyed cat) around here.

@FakeName - BTW, that picture always reminds me of the great Cat Yodeling technique from Engineer's Guide to Cats at 4:57min.

One note: The good news is that you only messed up with RAM and not with the EEPROM, thus your program is safe.. The program running on the ATmega is stored in the Flash memory, not EEPROM. The EEPROM is generally only 1-2 KB, and is more for storing small amounts of non-volatile data (think: user configuration settings, serial number, etc...), not actual code.

@ConnorWolf Right! Well spotted. Just edited and fixed my answer.

the C++ compiler does that for you. It sets it as zero Local variables are not initialized. I interpret status to be local in your example therefore this is wrong. it's not considered good practice to rely on that behaviour it actually is considered good practice to rely on that behavior for global variables since it's guaranteed that they will be zero-initialized and zero initializing globals in your code can waste memory(though current compilers should be smart enough to avoid this) see http://www.atmel.com/webdoc/AVRLibcReferenceManual/FAQ_1faq_varinit.html

You wrote: “array[-100] = 10; [...] you only messed up with RAM [...] thus your program is safe.” You may well end up writing into the IO space of the MCU, which is memory-mapped right below the RAM on the AVRs. This is definitely not safe. “[Calling a NULL function pointer] that's equivalent to a soft boot”. Not exactly. The program will restart from the very beginning: it will initialize the stack pointer, the RAM, call main, etc. But, unlike a soft boot, this does not reset the IO registers to their default initial state.

@Connor Wolf: You wrote: “the SRAM is initialized to 0 at reset or startup”. This is incorrect. Unlike the IO registers, the SRAM is not initialized by the hardware at startup. The BSS section of the RAM (and only this section) is initialized to zero by the C runtime. The DATA section is initialized to whatever contents the programmer requested. All the remaining RAM is left uninitialized.

@EdgarBonet - Point taken. Too bad I can't edit my older comments.

@EdgarBonet - Thanks for pointing out the problem with my answer. I read the link you provided and have tried to correct the statements about local variables. Would you please check it out? Thanks!

Your statement about the program restarting when calling a NULL function pointer was correct, at least on the AVR. I was just pointing out that restarting the program is not quite the same as a reset. BTW, there is no illegal instruction involved in the process. “Would you please check it out?” I cannot find anything wrong in your answer.

There are no runtime exceptions. There is only undefined behaviour.
Really, there are no exceptions at all. If you try to perform an invalid operation, it's results will be unknown.
There is no runtime checking at all, except what you implement. Your program is running on bare-metal hardware. It's the Desktop equivalent of running in ring-0 all the time, because the ATmega doesn't have rings.

There is one mechanism that can get MCU from erratic state and it's the watchdog timer. If you're implementing some code that will repeatedly run in a loop, that will not run anytime longer than some fixed time, you can set this time as watchdog period and enable the timer.
Then, you have to repeatedly reset the timer in the loop. If your code freezes at some condition loop that will never end, then the watchdog will count to zero and eventually reset the MCU.
This way you are losing data, but if you run the AVR WDT in interrupt mode, you can store some data before resetting the MCU.
So the watchdog timer can guard your code from occasional unintended endless loops.
Documentation: AVR132: Using the Enhanced Watchdog Timer

You'd need a hardware debugger for something like this. But usually you'll see the program not behaving as you expect it to and will have to look at that section of the code to identify the problem.
A common/quick/easy way to do this is to add print statements to print out the values of variables or just anything so you know the program gets to that point in the code without a problem. This will help you isolate the problem further.
I believe VisualMicro has some debugging functionality built in.

I would assume the AVR CPU doesn't have any error detection or recovery tools. It may just stop, or keep going ignoring the error and the consequences. Like sachleen said, you should add some debug statements in your program that print out data in the middle of an operation, to test if it's working. If you use an emulaor and set breakpoints, you could easily find a problem.

I wrote an *.ino environment:
// Testing environment for Arduino sketch files.
// Aduino IDE 2.3.0
// Author   : Anders Munck
// Released : 2024 02 09

#include <iostream>

const bool LOW=false;
const bool HIGH=true;
const bool INPUT=false;
const bool OUTPUT=true;
const unsigned char LED_BUILTIN=13;

using namespace std;

void where(std::string hank)
{ cout <<"Where : "<<hank<<"\n"; }

int random(int max)
{ return std::rand(); }

unsigned long klokken=0;
unsigned long int millis()
{ klokken++;
  cout <<"When : "<< klokken <<"\n";
  return klokken;
}

class SERIAL
{ public:
    void begin(int Baud)
    { cout<<"Arduino sketch : Serial.begin()\n"; };
    void end()
    { cout<<"Arduino sketch : Serial.end()\n"; };
    void print(std::string A)
    { cout<<"Arduino sketch : print()\n"; };
    void println(std::string A)
    { cout<<"Arduino sketch : println()\n"; };
} Serial=SERIAL();

void digitalWrite(unsigned char A,bool S)
{ cout << "Arduino sketch : digitalWrite()\n"; }

void pinMode(unsigned char A,bool S)
{ cout << "Arduino sketch : pinMode()\n"; }

// Include Your Arduino sketch file here:
#include "signal.ino"

int main()
{ setup();
  for(int i=0;i<100;i++){ loop(); };
  return 0;
}

The purpose is to get run time error messages from the *.ino sketch.
You will not get usefull timing information this way, as the program is running on another processor.
I run it with a GPU C++ IDE.
Please regard my code as preliminary ad-hoc program; You may need to develop further for Your needs.

The downvote is not mine. You need to explain your code and what it does.

the Question is 10 years old. just saying in case you didn't notice


text:
Why does opening the Tools menu take so long?
Every time I open the Tools menu, the IDE freezes for a few seconds. Why is that? It happens on both of my computers, and nothing I do makes a difference in how long it takes. I've tried restarting the IDE, unplugging my Uno, and many other things, but nothing helps.
I'm on windows, running IDE version 1.0.2.

Which OS are you running on?

@PeterR.Bloomfield Windows

This is one part of the IDE that I haven't seen as slow in either Mac or Windows version.

It's an RXTX issue. RXTX is the native serial library used to make the IDE talk to the boards.
On some Windows installation, with some Bluetooth things (both dongles or integrated), when enumerating serial devices, these dongles scan the air for remote serial devices. Hence, the IDE stays stuck, waiting for RXTX serial device enumeration to end. This issue has been acknowledged a lot of times, see for example #1375, #532, #200 and #143
As far as I understand, this issue does not affect linux or mac because of the different way the scan occurs. On linux it's a plain filtered file listing of /dev. Similarly it's on mac. On windows, it uses native API calls.
Some fixes are available in the 1.5 series but I suggest switching to the latest 1.5.6 release as RXTX was replaced by JSSC, a more modern and simpler library.

Could you elaborate? What is the issue? If it is known, then is there a bug report? Whats going wrong? Why is it happening only on Windows and not Linux/Mac?

@AsheeshR elaborated

FYI, in the past I have been successful, in using a different version of RXTX library file. basically copying it over from other sources. Where I do recommend going forward with 1.5.+. Being natively fixed.

FYI: latest nightly, soon to become 1.6.2, speeds up tools menu a lot

Frederico Fissore already pointed out that this delay is due to the serial libraries. From a functional perspective: The Arduino IDE tries to enumerate all available COM ports which simply takes some time.
Quote from the official troubleshooting guide:

Why does do the Arduino software and the Tools menu take a long time to open (on Windows)?
If the Arduino software takes a long time to start up and appears to freeze when you try to open the Tools menu, there by a conflict with another device on your system. The Arduino software, on startup and when you open the Tools menu, tries to get a list of all the COM ports on your computer. It's possible that a COM port created by one of the devices on your computer slows down this process. Take a look in the Device Manager. Try disabling the devices that provide COM ports (e.g. Bluetooth devices).

As sofware engineer I should add that it is a bug obviously. Devices should be enumerated in background, before any kind of menu is opened. To keep internal state correct, a system hook should be set. The problem is that software is written in Java, and such low-level programming in Java is very hard as it's positioned as cross-platform language and makes it hard to depend on system features. (This time it's a design problem.)

I was having the same problem under Windows 7 x64 and had already removed all com ports and unknown devices as suggested above. For me, the solution was to rename "ListComPorts.exe" in the hardware\tools subfolder to "ListComPorts.exe.xxx" - this prevents the Arduino IDE from using this file and appearently it reverts to using the internal COM port detection mechanism (using DEVICE_ARRIVAL/DEVICE_REMOVAL messages??) . The tool menu now opens immediately every time.

I had the same issue on my laptop (win 7, 64). Renaming file ListComPorts.exe to ListComPorts.exe.xxx as mentioned above worked. I also had to switch to a standard USB port (not 2.0) for sketch to load properly.

Welcome to Arduino Stack Exchange! As it stands, this answer does not help answer the question any more than the answers above. If you have more information about this particular way of fixing the tools menu bug, please edit your answer to add that information.


text:
Is my ATmega broken, and would replacing it with another break that one, too?
I was communicating between my computer and my Arduino Uno R3 through Bluetooth using this Bluetooth module. The connector I use has a red wire where it connects to GND, and a black wire where it connects to +5V.

                ↓        ↓  to Uno ↓       ↓
               +5V      GND       pin 0  pin 1

I forgot this one time when I connected the Bluetooth module to the Uno, so the polarity was reversed. This fried the Bluetooth module.
After getting a new module, I discovered that the Uno was apparently fried too. Plugging a USB cable into the Uno made the little green integrated LED turn on, but that was all that happened; none of the pins put out any electricity. When I tried to upload a program, it gave the infamous avrdude: stk500_getsync(): not in sync: resp=0x00 error. I could upload programs to my other Uno fine, and I could not upload to the broken Uno on my other computer.
Two of the Arduino experts I know told me that the ATmega328 chip might be the only broken part. Is this likely to be the case? I have an Uno R2 with a working ATmega328. Would temporarily replacing the R3's ATmega with that R2's ATmega have a change of damaging anything?

Generally the black wire is ground and the red wire is +5v

@TheDoctor I know. The connector I used looked sort of like this. When I connected it to the Bluetooth module, the pins on the bluetooth and the wires on the connector were ordered in such a way that the connector's red wire represented the bluetooth's ground.

looks like youre having the same problem as discussed here: http://arduino.stackexchange.com/questions/17/some-dude-named-avr-wont-let-me-upload-my-program-aka-avrdude-stk500-getsync

@TheDoctor Not exactly. That problem is a symptom of this problem.

Another possibility is that the bootloader got erased by the accident. Since you have another Uno, you could try using the ArduinoISP sketch on your working Uno to try reprogramming your non-working Uno.

Besides breaking a pin while removing the IC from its socket, or static electricity during manipulation, I don't see what could fry the ATmega.
However, it is possible that the R2 ATmega has a different bootloader and that may be an issue.
If I was you I would just remove the ATmega from the R3 board and test it on a breadboard (don't need a lot of components to do that); at least that could tell you if it is fried or if it is the R3 board that is fried...

Although bootloaders may be different, they don't rely on board revision. I know there was a switch of bootloaders in the past because the new one was smaller and therefore left more flash for the program. The board release is mainly different for couple signals being routed to extra pins on the headers.


text:
How can I transmit data to/from arduino from up to ~750 ft away?
I am working on a design project for school (non-capstone non-electrical engineering project) where we are building a system to remotely control a winch on a boat that will lower an independently operating meter to specified depths using a pressure transducer (controlled from the shore).
My current idea is to have an arduino collecting data from the pressure transducer while being connected to the winch (adjusting it up/down as needed, based on the desired inputted depth). The arduino would then be connected to the a Raspberry Pi B via USB. The Raspberry Pi would then communicate via wifi USB adapter to a router @ 2.5 GHz 802.11n on the shore, which would then communicate with the laptop on the shore. The important thing is that the laptop on the shore will be recording data as well as changing the input depth for the arduino.
Arduino <==> Raspberry Pi <==> Router <==> Laptop on shore
I saw [this information][2] talking about connecting to an arduino via wifi, but I was unable to determine the potential range.
A related project using a boat that uses the Xbee shield.
Once concern is that we will not be able to specifically point any antenna on the boat back to shore, so we are looking for a non-direction-oriented solution.
I was wondering what potential ways I could communicate back to the shore to control the winch depth (output display on shore showing depth, then being able to change the depth from shore). Furthermore, I was wondering if my setup would be feasible and what your suggestions might be.
Thanks!

The previous thread was located at this link: http://%20https://arduino.stackexchange.com/questions/432/how-can-i-connect-to-an-arduino-using-wifi

Although your project includes an Arduino, your question does not look like an Arduino-related question, since you describe WIFI plugged into your Raspberry Pi. If you had the intent to use a Yun for instance, then your question would make more sense on arduino.SE

@jfpoilpret I believe he's looking for a way to accomplish this without the Pi. He mentions it because that's how the linked related project accomplishes it

Oops thanks @JohnB my mistake, I misread this part. Then the question seems OK for arduino.SE. However the use of 'would' or 'will' throughout the question makes me think that there is nothing at all currently. I think the OP should edit his question to make it clearer what is looking for: Arduino WIFI (including the distance issue), or something else including Raspberry Pi

Note that a directional antenna on either end will dramatically improve the range. A directional antenna could therefore be pointed at the boat from shore..

@jfpoilpret, you are correct that I currently do not have anything at this time. I am in the process of ordering parts for a design project in school.
I am looking for a solution in general and had planned to use the arduino for its analog inputs/outputs because it is what we have learned to use in class -- I do not have an extensive background in circuitry nor coding (beyond VBA for spreadsheets), so I am not entirely sure which direction to take with this problem.

@JohnB is correct that I would prefer to approach this without a pi, but it is a solution I came up with.

@jlbnjmn I didn't realize it could come from one source - I don't have a background in networking.
Would something along these lines be sufficient for improving the range work?

Google for '433MHz transceiver'

There are a number of considerations that need to be made when considering any wireless communication solution over long distances and over water.
WiFi is capable of working over long distances especially with higher power cards (1W ones are now readily available) and directional antenna (anything from 3dBi to 30dBi of gain). There are advantages and disadvantages to using WiFi like this for your purposes:

WiFi uses 2.4GHz which is attenuated by the presence of water and water vapour. If you are close to the surface of the water surface, this can cause variable range with weather conditions increasing humidity and spray - even slight choppiness can massively increase the humidity close to the surface.
WiFi is a fairly heavyweight protocol that has several layers that need setting up each time a connection is made. This takes time and means marginal connections will have zero throughput as they will never get setup.
WiFi is intended to have high throughput (>1MBps) and doesn't degrade gracefully below this point. There isn't often a need to shift data this fast on an Arduino project. Speed and range are a trade-off.
Directional antenna on boats can be hard work. The more gain an antenna has, the more directional it is, which in turn means you need to aim it better. Even mild rocking can make this difficult to impossible. It depends if you are on a smooth pond or the sea really.

If you do want to go with WiFi, Ubiquiti make some neat products like the Nanostation that allow long range connections to be set-up over long ranges.
Personally I would stay away from 2.4GHz near water, and go with one of the other ISM bands. Depending on your location, this could mean 315MHz 433MHz, 868MHz, or 915MHz. It depends which region of the world you are in which ones you are allowed to use.
These lower frequencies are suited to longer ranges and penetrating object and water. There are a lot of different solutions in this space, all of which have ups and downs.
The Hope RFM12B is a very popular small RF board that has several easy to use libraries available - I use Jeelib personally. These are just capable of the 750ft range you require. They are available in all most ISM bands, and personally I have found the 868MHz best outdoors, whilst the 434MHz is better indoors.
The newer Hope RFM69W is a similar board but with more functionality and more power. It has 13dBm (20mW) of power vs 0dBm (1mW) of power on the RFM12B. I have been seeing an increase in range of ~50-100% with these boards.
The RFM69HW is a high power version has 20dBm (100mW) of power. I haven't range tested this, but would expect up to 3-4 times the range of an RFM12B.
Ciseco, a UK company, also make a series of boards that use CC1110 chips as transceivers. These are in an XBee like form. One of their boards, the ARF, has a power amplifier. These have 26dBm output power (400mW) and in a brief test in a built up area, I have seen a range of about 2km.
It's important to note that these are transceivers so that they can send and receive, which means you can acknowledge if packets have been received.
There are boards like the nRF2401L which use 2.4GHz, but use a much lighter weight protocol than WiFi so work better on marginal ranges. They are dirt cheap (~£2). They have the same disadvantage of water impacting range.
I don't like Xbee at all. The boards are overpriced and I find the range isn't great even with the higher powered modules.
You could also "roll your own" and use simple 434/868/915MHz on-off-keyed (OOK) transmitter/receivers. Protocol design isn't easy though, and you lose a lot of hidden functionality that the more advanced boards have.

Thanks for the reply, @Cybergibbons. What would be a relatively easy system to implement? I am not extremely experienced on the software side, but I am willing to put forth the effort to learn, given it doesn't take too much effort -- I have a decent workload this semester.
I am overloaded with options  from you (for which I am grateful), so please give me your expert advice! This is a project that I am hoping to do a good job on while hoping to finish up within a semester.

I would use RFM69HW modules with Jeelib. There is an active and helpful Jeelib forum, they are very widely used. I am going to range test these this week.


text:
How can I concatenate these two values as a string?
I've tried all the supposed solutions for the exact error, pasted into google, that I could find on every forum including this one and no matter the alleged solution I will either get the error about unsigned int to char*, the error below, or invalid pointers.
Why is this platform so completely unfriendly in data type conversion? It's almost as if the creator/s never wanted any data types to be able convert.
Here's my code that is apparently useless:
  char* DeviceName = "Device-" +  ESP.getChipId();
  wifiManager.autoConnect(DeviceName);

Error: invalid conversion from 'const char*' to 'char*' [-fpermissive]
   char* DeviceName = "Device-" +  ESP.getChipId();
Then I tried to use the pointers, but I have no idea what I'm doing and I keep getting invalid pointer errors, and/or invalid conversion errors.

Hint: Try using sprintf(). http://www.cplusplus.com/reference/cstdio/sprintf/

char buffer [50];
char DeviceName = sprintf(buffer, "Device-%d", ESP.getChipId());
wifiManager.autoConnect(DeviceName);

error: invalid conversion from 'char' to 'const char*' [-fpermissive]
wifiManager.autoConnect(DeviceName);

You can use the c function sprintf(, , ...)
The char array has to be big enough to hold your text plus a null to terminate the string.
#include <Arduino.h>

void setup() {
  Serial.begin(115200);
  delay(1000);
  char out[20];
  sprintf(out, "Device-%08X",ESP.getChipId()); // %08X\n formats the hex and pads with 0s.

  Serial.println(out);
}

void loop() {}

Output:
Device-005D4D9D

Thank you! I tried this and it does output a numeric ID, but I wanted the string ID.
ESP8266 Chip ID = 005D4D9D <- this should be the ID...
Device-6114717 <- not the numeric conversion here

you are welcome - helpful user changed the format string to output 8 hex digits instead since that is what you seem to be looking for.

Learning is good. To eliminate extra characters you can also use sprintf(out, "Device-%X",ESP.getChipId());