text:
CC3000 - Send GET request to an app on heroku
I'm struggling to get the CC3000 to connect to a heroku hosted app, and other examples posted online haven't turned on the light bulb quite yet for me.
The gist is that I collect some temperature and humidity readings, and then send those via a GET request using the CC3000. The heroku app then reads the parameters and displays them on a page.
The CC3000 hardware is A-OK, as I've tested it using the test sketches. The sketch I've put together (on github: https://github.com/jsimms/compost_monitor) works except for the last bit where it needs to connect to the server and send the HTTP request. Which makes me wonder if this is a heroku quirk, or if I'm just screwing something up right at the finish line.
First, I define everything
#define WEBSITE      "myapp.herokuapp.com"
String route = "/sensor";
uint32_t ip;
int port = 80;

Then during setup, I use getHostByName to assign the ip variable. I print it out, just to confirm it was able to snag an ip. I then close it to make sure I don't screw up anything during the loop.
  ip = 0;
  Serial.print(WEBSITE); Serial.print(F(" -> "));
  while (ip == 0) {
    if (! cc3000.getHostByName(WEBSITE, &ip)) {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }

  cc3000.printIPdotsRev(ip);
  Serial.println("");

  // Close the connection
  Serial.println(F("Closing connection..."));
  cc3000.disconnect();
  Serial.println(F("Connection closed."));

During the loop, I create a String with the request, and then call a function that actually does the request.
String request = "GET " + route + "?temp=" + temperature + "&hum=" + humidity + " HTTP/1.0\r\n";
send_request(request);

Finally, the send_request function is supposed to take care of connecting via TCP and sending it.
void send_request (String request)
{
  // Connect to server
  Serial.println("Connecting to server...");
  Adafruit_CC3000_Client www = cc3000.connectTCP(ip, port);

  // Send the request
  if (www.connected()) {
      www.println(request);
      www.println(F("User-agent: CompostMonitor/1.0\r\n"));
      www.println(F("\r\n"));
      Serial.println("Connected & data sent successfully...");
    }
    else {
      Serial.println(F("Connection failed."));
    }

    while (www.connected()) {
      while (www.available()) {

      // Read answer
      char c = www.read();
      Serial.println(c);
      }
    }

  // Disconnect
  Serial.println("Closing connection...");
  Serial.println("");
  www.close();
}

However, I never get anything but connection failed.
Any insight and help would be wonderfully appreciated. :)
UPDATE: Ok. So, through the comments below, I was able to identify by telnet'ing the web app, that there was something wrong with the HTTP requests. I made a small tweak to the app, but the real issue was that I wasn't including Host: weathervane.herokuapp.com in the header. FML! I'm going to test out sending the request with the Arduino later tonight. Hopefully that puts an end to this HTTP 101 lesson I've been doing.

Have a look at this code:  https://github.com/adafruit/Adafruit_CC3000_Library/blob/master/examples/SendTweet/SendTweet.ino
There is a delay after cc3000.connectTCP to wait for connection. Your code does not wait for the connection and thus gives 'connection failed' straight away.
Serial.print(F("OK\r\nConnecting to server..."));
t = millis();
do {
    client = cc3000.connectTCP(ip, 80);
} while((!client.connected()) &&
    ((millis() - t) < connectTimeout));

if(client.connected()) { // Success!

etc

Edit based on comment:
getHostByName returns positive value on success and negative on failure. Therefore the check should be
if (cc3000.getHostByName(WEBSITE, &ip) < 0)

Also try putting http:// in the website address

That's a very good point. I did put in the timeout, however, it still does not successfully connect. Part of me wonders if I'm missing something important in regards to Heroku architecture. In addition to the timeout, I tried two things - first, I tried using port 5000 - this did not work. Second, I moved the getHostByName lookup into the send_request function. This resulted in a "could not resolve" error message. Both for ports 80 and 5000.

@JakeSimms please see edits to answer

@JakeSimms I wonder if it wasn't getting the right address

@JakeSimms Oh, what happens if you don't disconnect? It might be that because you disconnect the socket you can't connect the TCP connection. That might be why getHostByName fails when you move it into send_request.

If you use http:// it actually hangs everything up. Even in their examples. Not sure why. One thing I did not do your other suggestions yet, mainly because I'm unsure if the sketch is the issue anymore. I'm getting bad gateway and bad request errors as you can see in the printout. Which is strange because things work fine in a browser.

One thing I want to make sure I understand. I do need to get connect to the host (getHostByName) and then I need to connect and send the TCP request. Is that correct? I then close the TCP and the getHostByName connection. Just like closing parent/child elements in html.

@JakeSimms I'm not sure. I haven't used the CC3300 before hehe. :P  From my browser http://weathervane.herokuapp.com loads. I used this site, http://www.hurl.it , to send a GET request to your heroku site and can confirm that it returns 502. BUT it does update. The full GET string is "GET http://weathervane.herokuapp.com/sensor?temp=-42&hum=-3" which includes the site address so you might need to have that in there. But it looks like something with Heroku.

Don't know if this helps: https://groups.google.com/forum/#!topic/openbadges/Hde8L6BPrUw

Thanks @geometrikal :) I the hurl.it test (and I did one with telnet) leads me to believe I still have work to do on the app.

There is something screwy with the app once it gets up on heroku. I get 200 ok responses when I test things locally. The second it is up on Heroku it starts spitting 400 errors and cutting off the second parameter.


text:
Is it possible to press a button from Arduino and my computer will get a key event?
My idea seems easy:
I connect a button with arduino, then write some code and upload it to arduino. Then I open the notepad(or any other editor) on my computer. When I press the button, there will be a character "A" displayed in the notepad.
I have tried with my Arduino uno, and use Serial.write/print function to send an A to serial port 9600, but it seems the character A only shows in the serial monitor GUI.
My question is:

Is "Arduino uno" is OK to implement this?
If not, what other board should I use?
Is Serial.write/print the correct function?
Or shall I use the Keyboard.??? function?
Do I have to write an application which runs on the computer and listens the serial port, and emit a real key event? (that's sad)

The Uno is not the best board for this. You may be able to get somewhere with the Virtual USB project but there are a couple of boards that are better suited for this.
Those are the Arduino Leonardo, Micro, and Due. In those, you can use the Keyboard Library just like you are using the Serial library now. This page has an example very similar to your project:
void setup() {
  // make pin 2 an input and turn on the
  // pullup resistor so it goes high unless
  // connected to ground:
  pinMode(2, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  //if the button is pressed
  if(digitalRead(2)==LOW){
    //Send the message
    Keyboard.print("Hello!");
  }
}

There is a micro designed more specifically for keyboard emulation, I haven't done any experimenting with it (yet), but it's very popular in the flight simulator world where these micro's are rigged up with buttons and switches and rotary encoders to simulate a cockpit. These inputs are converted to keyboard inputs (as far as I can see).
There are some general projects here: https://www.pjrc.com/teensy/projects.html
Some more keyboard specific stuff: https://www.pjrc.com/teensy/usb_keyboard.html
More info on the teensy in the arduino environment: https://www.pjrc.com/teensy/teensyduino.html
More specifically about what you're looking for, this could be quite useful: https://www.pjrc.com/teensy/td_keyboard.html
I'm not steering you away from Arduino, it's just something else to look into

Go for Teensy indeed. They're small, cheap and can be used just like 'official' Arduinos. You can keep using Arduino's editor, so aside from the board nothing will change. You do not only get keyboard emulation, you can also pretend you're a mouse, a MIDI interface and many other things.

Your example describes collecting text - does that meet your goal or do you need to generate any kind of key-event? If you don't need to generate system events, any terminal emulator (not just the Arduino IDE) should be able listen to that same port and to log whatever it receives to a file.

I need it to be some kind of key-events. My final goal is to make a custom keyboard by arduino

Check this video,
Arduino UNO as a USB keyboard (HID device) [Anything Arduino] (ep 6),
as I think this is what you are looking for.
From the youtube video you can get links to the library site and schematics.
You do need to build a small interface to connect your Arduino to a PC.
I got it for Uno and Micro, but other Arduinos with latest firmware would be OK.

When you link to an outside source it helps if you summarize what the link (the video in this case) is about or how it helps to solve the problem. This is especially useful if the link "rots." We're trying to build a durable resource here, try to think for the long term in your answers.

If you could edit your answer to provide the links in your answer that would be a good idea, as well as a copy of the schematics, quoting the source, if copyright allows that, in case the video is deleted.

I think you also need to install processing.
See this link
It enables you to program the computer-side of the application.

Do you mean I have to use some programming languages to write a program running on the computer-side? Do I have to use the "processing" language? I found it's interesting, but I'm sure why it's special with Arduino?

Processing, while a valuable addition to your arsenal when using Arduino, is not needed for your purposes. Instead, it will make things overly complex, if not impossible.

source: Stack Exchange

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

sort: votes


text:
How can I reset the program on an Arduino Uno while the device isn't recognised by my computer at all?
So I've recently been playing around with my arduino uno, and today it completely refuses to communicate with my computer at all. I've tried using other cables, switched OS (Tried Windows 8.1 and Ubuntu 14.04), and tried on my laptop, none of them recognise the device at all.
From what I've read, this problem can be caused my a program on it with a Serial.println() frequently used, which I believe is the case here. The solution for this problem is according to other answers, to hold the reset button while I upload an empty sketch to the arduino. However, I can't do this, since the computer doesn't communicate with the arduino at all.
Any ideas what could've gone wrong, and how to fix it?
EDIT: Alright, the problem seems to have resolved itself... I have no idea what made it work, I was frustrated and went to bed last night, and today it works without an issue..
EDIT #2: Scratch that.. now I get this error when I try to upload a program to the arduino:
avrdude stk500_getsync() not in sync resp=0x00

The device does show up in Device Manager, so I tried installing the arduino drivers for it, but it gives me the error code 10. Windows automatically installs some serial driver for it, but any attempts of serial communication with the arduino fails.

What do you mean by "they don't recognize the device at all"?

The uno doesn't show up in the Device manager in windows, and in Linux I can't find any ttyUSB or ttyACM  devices-

The state of the program on the '328 chip should not really effect the ability of the USB chip to present a functional peripheral interface to the computer.  But if you hold down the reset button, then unless you somehow programed the reset disable fuse on the '328, it will be entirely out of the way and not bothering the USB chip in the slightest.  Failure (even to be detected as a malfunctioning peripheral) with multiple hosts/operating systems at that point suggests hardware damage (or possible a USB chip which has come unprogrammed).  On linux you should check dmesg when plugging, too.

I agree with @Chris. Is there any signs of damage on your board? Does it light up? Did it work before this? Do you know what sketch is on it currently?

There are no signs of physical damage on the board, and it lights up just fine. I'm not sure to what extent it worked before I tried uploading a program to it, it's been a while since I used it. I believe the sketch on the board was for reading the analog input of something, using Serial.println(). I don't have the sketch saved, as I just used it for debugging a while ago.

As for the dmesg, I couldn't find anything usefull using 'dmesg | grep 'serial|tty''

Don't grep like that - look for things like complaints about a mysterious or malfunctioning USB device or hub port.

Which uno revision ? Not a clone ?
You didn't update the ftdi drivers on windows did you ? What driver version ?(if you updated the drivers trying going back to an earlier version pre-the version that damages clone fetid chips) If its a dip version can you swap the atmel chip ? (Can get clone uno boards from US$4)

I had the same problem with my Arduino Leonardo. But when I kept the reset button pressed and plugged it into my laptop, it got recognised again. But since you're using an arduino uno it might also be the atmega16u2 which isn't working properly. If holding the reset button while plugging in the arduino to the laptop doesn't work, try to reset your atmega16u2 chip on the arduino. This is the chip which makes the communication from USB possible.
To reset the atmega16u2 follow this tutorial

I also got same problem and actually the problem was is of arduino. Arduino ATmega328 IC and ATmega16u chip was damaged . After that I replace ATmega328 Damaged Ic With new one reprogram it and program in ATmega16u chip and upload firmwares to ATmega16u chip.

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


text:
Is it possible to use Arduino UNO programmer for other AVR microcontrollers?
I got an Arduino UNO which I started using with microc for avr to add more customizations.
I'm wondering if it is possible to use the Arduino UNO programmer to program other AVR microcontrollers (I know that it is possible using ATmega 328p and 168).

Are you using serial port programming or ISP?

Not entirely clear what you are asking. Are you familiar with: http://arduino.cc/en/Tutorial/ArduinoISP

It is not clear what do you mean by 'other AVR microcontrollers'. Can you please specify one specific AVR you plan to program using Arduino Uno?

The AVR microcontrollers that support ISP are all tinyAVRs other than the 4/5/9/10/20/40, and all megaAVRs.
The ATtiny4/5/9/10/20/40 requires TPI (Tiny Programming Interface). AVR XMEGA devices require the use of PDI (Program and Debug Interface). Neither can be programmed using ArduinoISP.

If you are using avrisp you can basically program every AVR compatible with ISP protocol.
For example you can program ATTINY85, ATMEGA8, ATMEGA16 etc...
Basically for cheap and usable project with a usable flash size i use ATMEGA8 or 88.
Avoid ATMEGA48, you have only 4 kb of flash and that mean you can not do anything instead of blinking LED.
Another way to do this is by using Raspberry pi GPIO for burning code on AVR.
Here is some doc from ozzmaker


text:
Reading the rpm of multiple fans
I am trying to build a fan controller for my pc, the problem is that the example code(http://playground.arduino.cc/Main/ReadingRPM) im using utilizes interrupts. On my uno I can then only read the rpm of one fan. I want to also control the rpm (via pwm) and monitor temperatures (via thermistors) Anyone know how I coud do it differently? I. E. Without interrupts. I would also like it to be as close to real time as possible

It may help to add some more detail. Do you just want to monitor the fans, or control them also? What is your desired outcome? How many fans? What RPM range? The more detail the better, as it makes the question more interesting and useful.

@jlbnjmn I want to monitor and control them and temperatures from thermistors

If temperature regulation is what you seek, why bother with the Tachometer signal at all?
Thermistors don't require interrupts. Why do you need fully closed loop fan control? A simple proportional control of each fan and each hot item would likely suffice in keeping your system cool. Noise concerns, perhaps?
A brief article on proportional temperature control
A data sheet on a TI chip that may have some inspiration for you

I'm wanting to use this on my pc so it's got to be quiet. And with monitoring rpm I can set up a fan failure alarm and other things.

Looking at that chip, it looks like it'll do exactly what I'm wanting. Am I mistaken or does it also have an i2c interface? Does that mean I could just read the values off of it?

If you only want 2 fans, the uno has 2 external interrupts, so you can use the same strategy as your example, just make another interrupt function for fan 2 and attach it on interrupt 1 instead of 0. the fan should be plugged in to pin 3 in this case. On a leonardo, you could have 5 fans on interrupts, and a mega has 6 external interrupts. See http://arduino.cc/en/Reference/attachInterrupt
If you need more than what your hardware can support, I would look into using a timed interrupt to check all the fans. If you find the minimum amount of time in-between reads to read your fans at max RPM and then use a timer interrupt to check some pins at that interval, you can probably read as many as you need, provided the interrupt routine stays fast enough. the function
attachInterrupt(function, period);

from the libraries on this page : http://playground.arduino.cc/Code/Timer1
should help you out with this.


text:
Unable to upload sketch to Leonardo
I'm really at my wits end. For a couple of hours I have been programming a custom board that uses everything as on the Arduino Leonardo. A few hours ago I am not able to upload anymore.
I get the following error:
   avrdude: error: buffered memory access not supported.
   Maybe it isn't a butterfly/AVR109 but a AVR910 device?

I've tried everything from re-installing the IDE, re-installing the board in Device Manager, changing the COM Port. I really just don't know anymore.
Here is some more data that might be relevant or useful:
     Using Port                     :\\.\COM6
     Using Programmer              : avr109
     Overriding Baud Rate          : 57600
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53

[EDIT]
I've now checked the battery (yes with a multimeter), it is fully charged, as it charges when the USB is connected. I've also tried a different computer, along with a different USB cable.

Did you try telling it to use the incorrect programmer?

Do you mean changing the programmer within the IDE?
It is currently set to AVRISP mkll. I've now tried all the alternatives available in the IDE, still no luck.

What IDE are you using? Do you have the arduino bootloader installed?

The standard Arduino IDE, tried both 1.0.6 and 1.5.8. And yes, the bootloader is installed as I have previously uploaded sketches to the board

Try this:
First: you must find the COMx used for your "Arduino Leonardo" in the "Device Manager" of Windows.
Second: make double click to see the properties of the device, and go to the "Port configuration tab"
Third: enter in "Avanced Options" and deactivate "Use FIFO buffers", and accept all changes.

Tried it, still nothing. Do you think the bootloader may have caused a random error, or get corrupted or something? - is that even possible. I'll try to reload the bootloader, and see if it works (this part is still new to me), but I would like to know what causes this error? Maybe then I can stop it from happening in the future. Thank you for the reply

Always check if you didn't accidentally blow the crystal!
But thank you, checked on another Leonardo board, this worked.


text:
Reading 2 numbers from serial
I try to send pairs of numbers over the serial port from a linux pc to the arduino. By now I did so always by piecing together the ASCII chars from the serial line and using Serial.read(). Now I need this same thing to run at 100-200Hz, and it turns out, that the Arduino does not receive all the data (even at 1Hz).
As turned out, my problem was in another portion of the code and all below code works perfectly as is!
How do I make sure, that every char (or better even byte without ASCII encoding) is received? I am aware, that each connection has errors, but this is a systematical error! I guess, that the bytes are lost during the processing within the main loop, or because of other callbacks I use (got some ISR running). I am not looking for error detection, but rather a concise way of reading the serial line, without loosing 70% of the data validity.
If important: the pairs i need to send are unsigned, 1 byte and another one with 2 bytes. The values are in the range of [0;7] and [1000;2000]. Thanks for any advice. Disclaimer, I read a lot, including this, but most questions go into detail about the packaging format, whereas I am concerned about the reading method.
Code I use at the moment:
// read numbers from the char representation!
// on the serial connection
// each DIGIT is sent separately

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
uint8_t channel; // holding the number of the channel to modify
uint16_t signal; // ppm signal length in us (1000-2000)

void setup() {
  Serial.begin(115200);
  inputString.reserve(200);

  pinMode(9,OUTPUT); // fixed pin 9 for PPM output
}

void loop() {
  if (stringComplete) {
    channel = uint8_t(inputString[0])-48;
    signal = 0;
    for (uint8_t n=1; n<5; n++) {
      signal = (signal*10) + uint8_t(inputString[n])-48;
    }
    Serial.print(F("ch: ")); Serial.print(channel);
    Serial.print(F(" signal: ")); Serial.print(signal);
    Serial.print(F("\n"));
    //PROCESS Data
    inputString = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    // if the incoming character is a
    // newline (10) or carriage return (13)
    // set a flag for a complete transmission
    if (inChar == 10 | inChar == 13) {
      stringComplete = true;
    }
  }
}

Another version I tried, without strings is:
// channel and pulse-length
uint16_t numbers[2] = {0, 0}; // channel,value
uint8_t buf[5];

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

void loop() {
  if (serial_input(numbers,buf)) {
    numbers[0] = buf[0]-48;
    numbers[1] = (buf[1]-48)*10+(buf[2]-48);
    Serial.print(F("channel: ")); Serial.println(numbers[0]);
    Serial.print(F(" signal: ")); Serial.println(numbers[1]);
    // Do Stuff
  }
}

uint8_t serial_input(uint16_t* num, uint8_t* buf) {
  uint8_t newData = 0;
  uint8_t k = 0;
  num[0] = 0; num[1] = 0;
  while(Serial.available()) {
    delayMicroseconds(2100);
    char ser = Serial.read();
    if (isDigit(ser)) {
      buf[k] = uint8_t(ser);
      k++;
      newData = 1;
    } else {break;}
  }
  return newData;
}

Another try inspired by an answer here, where I send "3 1500\n" over the serial line:
void serialEvent() {
  if (!newdata) {
    channel = Serial.parseInt();
    signal = Serial.parseInt();
    newdata = true;
  }
}

Turns out all of those methods work (more or less elegantly), but having a "delay" within an ISR isn't such a good idea - even intermediately...

there is a great function:
https://www.arduino.cc/en/Serial/ParseInt
I have tested the following script up 2kHz incoming, but it should go even faster.
Do something like this
int number = 0;
int number2 = 0;
bool get_data = false;
void setup() {
  Serial.begin(115200);
  inputString.reserve(200);

  pinMode(9,OUTPUT); // fixed pin 9 for PPM output
}

void loop() {
    if(get_data == true){
      Serial.print(number);
      Serial.print(number2);
      get_data = false;
    }
}
 void SerialEvent()
   if(!get_data){
     number = Serial.parseInt();
     number2 = Serial.parseInt();
     get_data = true;
   }
}

115200 baud at 200Hz means you should be able to transfer in excess of 50 characters between each "trigger". That is more than enough time to send the data even as ASCII encoded text.
serialEvent() is no better than manually looking at things like serialAvailable() in your loop since that is all it does anyway. It just runs after each iteration of your loop.
One problem that you have is that you're appending each character to a String object. This is very inefficient and should be avoided. Instead you should really use a character array:
// Input text in the form "123 456\n"
char instring[20]; // Room for 19 characters plus terminating null
int spos = 0; // Location in the array
int val1 = 0;
int val2 = 0;

void loop() {
    if (Serial.available()) {
        char *bita, *bitb;
        int c = Serial.read();
        switch (c) {
            case '\r': break; // ignore
            case '\n':
                 spos = 0;
                 bita = strtok(instring, " ");
                 bitb = strtok(NULL, " ");
                 if (bita && bitb) {
                     val1 = atoi(bita);
                     val2 = atoi(bitb);
                 }
                 // You now have two new values in val1 and val2
                 break;
            default:
                if (spos < 18) {
                    instring[spos++] = c;
                    instring[spos] = 0;
                }
        }
    }
}


text:
Arduino + CO2 + humidity + noise + temperature sensors on one board
I'm looking for an Arduino board that include this sensors out of the box:

CO2
Humidity
Noise
Temperature

I've found here Using the Waspmote Sensor Board something that could be enough, but I'm searching for more options.
I did a lot of searches on the Internet without good results.
Any suggestions?

For humidity and temperature you can plug the DHT11 or DHT22 to your arduino. DHT11 is cheaper but you'll get a more precise value with DHT22.
For noise you have ready made PCB like these : here
You'll only have to plug it to GND, 5V and analog input.
For CO2 this is more complicate. There is a cheap but very unprecise option, using a MQ135 sensor, here is a tutorial: here
Otherwise there are better sensors like the K30 but they are much more expensive.


text:
Why are my sensors not working (the reaction time is so slow)?

//testing the light sensor;
int sensor=A0; // setting as input is by default;
int sensorval;
int pin=13;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(pin,OUTPUT);
  pinMode(sensor,INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  sensorval=analogRead(sensor);
  Serial.println(sensorval);
  if(sensorval>900)
    digitalWrite(pin,HIGH);
  else  digitalWrite(pin,LOW);
    delay(1000);
}

I am using a photocell, a temperature sensor and a potentiometer with an Arduino Uno and it always gives me 1023 0 1023 0 1023 0 1023 ....... All my wires are connected properly and I tried all this stuff online and they are working correctly.

Link

For future reference, you don't need to start a new question if you want to add information. You can edit your existing questions. On this occasion though, I've deleted your previous one since it's no longer needed.

Ok thank you actually it is my first time ::D @PeterR.Bloomfield

what about this issue now @PeterR.Bloomfield

Perhaps you can add a Fritzing layout of your project. It seems like there's an issue with your pot.

It's "slow" because you have a 1 second (1000 mS) delay in the loop.

you should internalize value of sensorval equal to zero.
You do not require set analog pin.
you want get data quickly then reduce delay time because 1 second quite high.So, make it 500 mili second.

Have you tried with a different trimmer?
I dont seem to be able to find any issue with your code or your schematic, so can you please cross verify that the trimmer is not spoilt.
Can you also check if, when A0 is left floating (nothing connected) it give a random value.

Yes ! when A0 is floating it gives random values @evolutionizer

Have you tried with a new trimmer?

No ,but I've tried another analog device like a photocell or a temp. sensor and seems to have the same random values @evolitionizer

Can you confirm that your connection is similar to this http://bildr.org/blog/wp-content/uploads/2012/11/arduino-LDR-photoresistor1.png

By this way it is working but too slow .in light ,it reads 1023 then slowing down until reaches 0 and vice versa  @evolitionizer

@nohierhassan You might also like to attach a photograph of your setup so we can double-check your wiring.

link this is the wiring @Majenko

@nohierhassan That's not a photo, that's a wiring diagram. We need a real photo of your real wiring so we can make sure you haven't had a brainfart while wiring it up (it happens to the best of us).

@nohierhassan What do you mean by "By this way it is working but too slow .in light ,it reads 1023 then slowing down until reaches 0 and vice versa "
From this it sounds like it seems to be doing exactly what it is supposed to do. What exactly do you mean by it is too slow? The reaction time?

Yes, the reaction time . i saw videos the sensor works immediately (once the light turns off it reads 1023 ). @evolutionizer

@nohier can you please Post a picture of your setup, actual picture and if possible a video of the working

@evolutionizer check the photo

@nohier please connect a Jumper wire between the left and right most power rails. Please have a look at this image for a typical breadboard internal connection img.webme.com/pic/w/whitelinetracer/breadboard1.gif

Also if possible please upload a higher resolution picture


text:
ov7670 + Sd Card + arduino
I have three devices for making a motion activated security camera system:

this is the camera : LINK  OV 7670
this is the SD Card module: LINK
and a basic motion Sensor: PIR with 3 pin

I have an Arduino UNO and an Arduino Mega 2560.
I can connect the SD card and sensor, they work fine but I cannot connect the camera as there are not enough pins for it on UNO.
Is there a chance to connect all of them without any additional device?
I saw some working project with additional device (arducam) but I do not have much money to spend on this project.

Do this camera module have AL422 FIFO?

I think both the Camera module and the SD (can't see underside) require 3.3v logic, while the Uno and Mega have 5v I/O. So you probably need some logic level shifting. Other than that, I see no problem.

to Gerben: Yes camera need 3.3v logic, but SD card module also have 5v. @AndrewPaes I don't think so. It was cheapest module when I buy ($10). OV 7670+AL422 FIFO was $22. What is AL422 ?

I am facing the same problem as you mister LuffyTheKaizoku. I bought the non-FIFO and then bought the FIFO version of the OV7670 but still not found a way to program it. I am also trying to save the code to an SD card! Did you manage to find a solution for this problem?
If you did, I would really really need your help. Thank you very much in advanced!
Felipe

This camera module requires the use of additional hardware, as the camera and Arduino operating frequencies differ, which can result in loss of synchronization and changes to the image, and other connection problems.
Thus, we must use an integrated circuit intermediary, making the connection between the camera and the Arduino. The function of this chip is to receive the camera information, store them and then send them to the Arduino using the digital doors, much faster than if we used the serial communication.
An example of an integrated circuit that could be used is AL422, suitable for treating a video signal, which also is embedded in some OV7670 modules.
Looking like the connection pins behave in 7670, your module should be equal to it. So spare pins to be able to make other necessary connections.

Would better check the connection through the datasheets:
7670 datasheet
AL422 datasheet
An example of project
But to answer your question; You'll need to purchase a piece more if you don't have AL442.
Regards,

Thanks for your help Andrew. I found the same project yesterday and I realised that I need Al422. After all these research , I also learned there isn't any shop to buy AL422 in my country (internet shop). So I give up and order new camera module. Thanks a lot again.

Example link goes to an adware download site now :(


text:
Arduino PWM fading led
I am trying to blink an LED with PWM on Arduino.
I don't know what is wrong but my LED is not fading as expected. What is wrong?
I think that I have bad registers settings, but I am not sure.
LED is connected to Arduino pin 9.
Here is my code:
#include <avr/io.h>
#include <util/delay.h>
const int delay=1000;
void initialize_PWM()
{
    TCCR0A|=(1<<WGM00)|(1<<WGM01)|(1<<COM0A1);
    TCCR0B=1;
    DDRB|=(1<<PB1);
}

void set_pwm(uint8_t data)
{
    OCR0A=data;
}

int main (void)
{
    initialize_PWM();
    uint8_t brightness=200;
    while(1)
    {
        for(brightness=0;brightness<255;brightness++)
        {
            set_pwm(brightness);
            _delay_ms(1);
        }

        for(brightness=255;brightness>0;brightness--)
        {
            set_pwm(brightness);
            _delay_ms(1);
        }
    }
    return 0;
}

Which Arduino? You appear to be using port B1 which maps to D9 on ATMega328p, so Uno, perhaps? What do you see - A bright LED? A dark one? Is your LED wired right way round? Have you tried using that pin as digital I/O using library functions to confirm that the LED can work as wired? What else have you tried?

Arduino Uno with ATMega328p. I see dark LED. Wires are in right way. And LED is working when I plug it to +5V and resistor.

can't you use analogWrite( pwm )?

No, because I want use it without external libraries.

is this using the arduino ide?

From your code you are using Timer0 in FastPWM mode with top = 0xFF.
In this mode, as used in your code, OCR0A defines the pulse width rate (more precisely, OCR0A / 256).
Timer0 uses port OC0A and OC0B to ouput PWM signals, in your code, you are using only OC0A (which is perfectly fine).
Now if you take a look at ATmega 328 data sheet, chapter 14.3.3 you will see that pin OC0A maps to port D, pin PD6 (on Arduino UNO, this is port D6, according to http://arduino.cc/en/Hacking/PinMapping168).
So this means that you have used the wrong port in your setup (Arduino pin D9 maps to OC1A, which is pin PB1 of port B on ATmega328, OC1A is used by Timer1, not Timer0).
Hence you should do the following to fix the problem:

Plug the LED to Arduino pin D6 instead of D9
Fix initialize_PWM() by replacing DDRB|=(1<<PB1); with DDRD|=(1<<PD6);

Otherwise, if you want to keep Arduino pin D9, then you will have to change the timer you use: Timer1 instead of Timer0. Updating the code is left as an exercise!

The easiest way is to use the timer1 library written for arduino. You can download it here.
To install, simply unzip and put the files in Arduino/hardware/libraries/Timer1/

Prescaler set for 16Mhz
Prescale    Time per counter tick   Max Period
1   0.0625 uS   8.192 mS
8   0.5 uS  65.536 mS
64  4 uS    524.288 mS
256 16 uS   2097.152 mS
1024    64uS    8388.608mS

In general:
Max Period = (Prescale)(1/Frequency)(2^17)
Time per Tick = (Prescale)*(1/Frequency)

Instructions available using this library are:
initialize(period)
You must call this method first to use any of the other methods. You can optionally specify the timer's period here (in microseconds), by default it is set at 1 second. Note that this breaks analogWrite() for digital pins 9 and 10 on Arduino.
setPeriod(period)
Sets the period in microseconds. The minimum period or highest frequency this library supports is 1 microsecond or 1 MHz. The maximum period is 8388480 microseconds or about 8.3 seconds. Note that setting the period will change the attached interrupt and both pwm outputs' frequencies and duty cycles simultaneously.
pwm(pin, duty, period)
Generates a PWM waveform on the specified pin. Output pins for Timer1 are PORTB pins 1 and 2, so you have to choose between these two, anything else is ignored. On Arduino, these are digital pins 9 and 10, so those aliases also work. Output pins for Timer3 are from PORTE and correspond to 2,3 & 5 on the Arduino Mega. The duty cycle is specified as a 10 bit value, so anything between 0 and 1023. Note that you can optionally set the period with this function if you include a value in microseconds as the last parameter when you call it.
attachInterrupt(function, period)
Calls a function at the specified interval in microseconds. Be careful about trying to execute too complicated of an interrupt at too high of a frequency, or the CPU may never enter the main loop and your program will 'lock up'. Note that you can optionally set the period with this function if you include a value in microseconds as the last parameter when you call it.
setPwmDuty(pin, duty)
A fast shortcut for setting the pwm duty for a given pin if you have already set it up by calling pwm() earlier. This avoids the overhead of enabling pwm mode for the pin, setting the data direction register, checking for optional period adjustments etc. that are mandatory when you call pwm().
detachInterrupt()
Disables the attached interrupt.
disablePwm(pin)
Turns PWM off for the specified pin so you can use that pin for something else.
read()
Reads the time since last rollover in microseconds.

Example - Sets up PWM output on pin 9 with a 50% duty cycle, and attaches an interrupt that toggles digital pin 10 every half second.
/*
 *  Timer1 library example
 *  June 2008 | jesse dot tane at gmail dot com
 */

#include "TimerOne.h"

void setup()
{
  pinMode(10, OUTPUT);
  Timer1.initialize(500000);         // initialize timer1, and set a 1/2 second period
  Timer1.pwm(9, 512);                // setup pwm on pin 9, 50% duty cycle
  Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
}

void callback()
{
  digitalWrite(10, digitalRead(10) ^ 1);
}

void loop()
{
  // your program here...
}

Source: http://playground.arduino.cc/Code/Timer1

The OP mentioned in a comment that he does not want to use external libs (and that seemed to include arduino libs also)

Oh I've missed that probably. Sorry. Though, I'll keep this answer standing in case someone else who's searching for an answer like this.

It's much too soon to optimize. Get your LED working using the standard (known working) libraries. Only then - and perhaps never, unless you find a need to - should your optimize (use direct register I/O). If it works with the libraries but not with your direct I/O, you'll know the bug lies in the direct I/O code and nowhere else, ruling out failed hardware, improper or unreliable connections, and programming errors elsewhere in your project. Right now, you don't know even that much.


text:
What's the most accurate way to time-stamp analogRead data?
I want to sample an Analog sensor as fast as possible, and time-stamp each sample that I take as accurately as possible.
Currently, I'm doing the following:
val = analogRead(SENSOR_PIN);
clocktime = micros();

writeData(val, clocktime); // writes the values to an SD card

I'm wondering if there is a more-accurate way of time-stamping the data from the analogRead call. Put another way, I would like to record the exact time that the analogRead data was collected. My guess is that this is basically impossible on an Arduino, so what technique will let me get as close as possible?

For "as fast as possible", I'd

Rewrite your sampling code in assembly language (just those two statements, not the whole program); and
Buffer the raw data pairs in memory if you have enough of it, then store it to the card after the measurement burst. If you need more data space, consider that the timing of a tight assembly loop will be consistent (and fast!) and can be measured. You may not need to read the clock at all. Note that you can get the same timing consistency using C/C++ if you read the analog and clock ports directly, and maybe as fast. It's just that with assembly language, WYWIWYG (what you write is what you get); the compilers' code-generators and optimizers won't mess with it.

A possible issue with your code as you've written it is that writeData probably buffers the data on most calls, but whenever a call results in a full buffer, writes the whole buffer to the card, introducing jitter into your sampling.
Addressing your edit of June 3, 2014, "I would like to record the exact time that the analogRead data was collected":
Since you proposed using micros() (as opposed to a real-time clock), I assume you are satisfied with the relative time. Once you know your data collection code is completely predictable, then the offset from reading data to reading time is constant, and since we're using relative time anyway, can be discounted, or at least, corrected for.
It isn't completely predictable of course, since in this case, you're using an interrupt-maintained clock, and can expect that sometimes the interrupt will occur between the data read and the clock read, stretching the offset for that tuple. To get even more accurate, you'd need to keep interrupts off, read the timer yourself in an invariant way. f/ex, you might run the timer at such a rate that you could expect to take two or more samples between overflows of the low-order byte, read and store only the low order byte as your time sample, and post process the time data to reconstruct the high order byte by detecting wrap-around in the low-order.
With no interrupts running, and once you know the rate at which you can sample data without reading the clock, you could read and save the clock once immediately prior to taking the first sample, and infer the times of each subsequent sample based on the known sample rate.

There is no more accurate way of getting time on the arduino, but I would suggest you use millis() instead.
micros() returns microseconds, or millionths of a second, since the arduino was turned on. The issue is that the 32 bit unsigned integer used to store time on the arduino can only count about 70 minutes worth of micros before overflowing and resetting to 0. (see http://arduino.cc/en/reference/micros)
millis() is in thousandths of a second since the arduino turned on, and it will not reset for about 50 days. If you think one thousandths of a second is good enough resolution, it will probably be the better choice.
If you need time to be absolute, as in the current day/hour/minute, you will need to buy a real time clock to plug into the arduino. They are about 20 bucks, and available from all the standard arduino accessory stores like sparkfun, adafruit, ect.
On your question of the order, both commands run so quickly, I can think of no reason it would matter.

thanks for the reply. I am measuring very fast events that are near millisecond resolution and I only need to run the program for a few minutes at a time.


text:
How to integrate smoothing into project (HVAC thermostat / controller)
I am working on building a "simple" HVAC thermostat. This is my current sketch.
    // include the libraries for gizmos
#include <LiquidCrystal.h>
#include <dht11.h>

dht11 DHT11; // Figure out what this line does
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // initialize the library with the numbers of the interface pins

// These constants won't change:
const int ACledPin = 8;      // Air Conditioner LED (RED)
const int HTledPin = 9;      // Heat LED (YELLOW)
const int threshold = 77;    // an arbitrary threshold level that's in the range of the analog input

const int RELAY_01 = 6;    // RELAY 1 PIN 9
const int RELAY_02 = 10;   // RELAY 2 PIN 10

void setup() {
  DHT11.attach(7);       // Attach DHT11 sensor to pin 7
  lcd.begin(16, 2);      // set up the LCD's number of columns and rows:
  Serial.begin(9600);    // Serial setup

  pinMode(ACledPin, OUTPUT);  // initialize pin 8 as output
  pinMode(HTledPin, OUTPUT);  // initialize pin 9 as output
  pinMode(RELAY_01, OUTPUT);  // initialize pin 6 as output
  pinMode(RELAY_02, OUTPUT);  // initialize pin 10 as output

  // Leaves the relays in default "off" (no noise/click)
  digitalWrite(RELAY_01, HIGH);
  digitalWrite(RELAY_02, HIGH);

}

void loop() {

  float analogValue = (DHT11.fahrenheit()); // trying to set up the temp reading as an int variable
////////////// if then ////////////////
// if the analog value is high enough, turn on the LED:
  if (analogValue > threshold) {
    digitalWrite(ACledPin, HIGH);
    digitalWrite(HTledPin, LOW);
    digitalWrite(RELAY_01, HIGH);
    digitalWrite(RELAY_02, LOW);
  }
  else {
    digitalWrite(ACledPin, LOW);
    digitalWrite(HTledPin, HIGH);
    digitalWrite(RELAY_01, LOW);
    digitalWrite(RELAY_02, HIGH);
  }

Serial.println(analogValue);  // print the analog value:

// Set up the LCD Stuff
  lcd.setCursor(0, 0);      // Set cursor to top left
  lcd.setCursor(0, 1);
  lcd.print(analogValue, 1);
  lcd.print("F");

  delay(1000);

}

I want to add "smoothing" to the temperature reading. I Found this tutorial http://arduino.cc/en/Tutorial/Smoothing and have it working the way I want it.
// Define the number of samples to keep track of.  The higher the number,
// the more the readings will be smoothed, but the slower the output will
// respond to the input.  Using a constant rather than a normal variable lets
// use this value to determine the size of the readings array.
#include <dht11.h>
dht11 DHT11; // Figure out what this line does

const int numReadings = 5;

float readings[numReadings];      // the readings from the analog input
int index = 0;                    // the index of the current reading
float total = 0;                  // the running total
float average = 0;                // the average

void setup()
{
  DHT11.attach(7);       // Attach DHT11 sensor to pin 7
  Serial.begin(9600);    // initialize serial communication with computer:
  for (int thisReading = 0; thisReading < numReadings; thisReading++) readings[thisReading] = 0; // initialize all the readings to 0:
}

void loop() {
  // subtract the last reading:
  total= total - readings[index];
  // read from the sensor:
  readings[index] = (DHT11.fahrenheit()); //analogRead(inputPin);
  // add the reading to the total:
  total= total + readings[index];
  // advance to the next position in the array:
  index = index + 1;

  // if we're at the end of the array...
  if (index >= numReadings)
    // ...wrap around to the beginning:
    index = 0;

  // calculate the average:
  average = total / numReadings;
  // send it to the computer as ASCII digits
  Serial.println("");
  Serial.print("Realtime: ");
  Serial.println(DHT11.fahrenheit(),2);
  Serial.print("Average:  ");
  Serial.println(average);
  delay(2000);        // delay in between reads for stability
}

I'm new to Arduino and don't know the best way to do this. I'm not certain how to do multiple loops/delays in a single project, or if I even need to.
EDIT:
I've ended up with this based on the comments from @Craig. The only thing that needs some adjustment are the first 4 readings are low, so it would be nice to somehow ignore, probably not a big deal in the long run.
Example readings on startup;
Realtime: 77.00
Average:  15.40

Realtime: 77.00
Average:  30.80

Realtime: 77.00
Average:  46.20

Realtime: 77.00
Average:  61.60

Realtime: 77.00
Average:  77.00

Final code
// include the libraries for gizmos
#include <LiquidCrystal.h>
#include <dht11.h>

dht11 DHT11; // Figure out what this line does
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // initialize the library with the numbers of the interface pins

// These constants won't change:
const int ACledPin = 8;      // Air Conditioner LED (RED)
const int HTledPin = 9;      // Heat LED (YELLOW)
const int threshold = 77;    // an arbitrary threshold level that's in the range of the analog input

const int RELAY_01 = 6;    // RELAY 1 PIN 9
const int RELAY_02 = 10;   // RELAY 2 PIN 10

// START ADDITIONS ////////////////////////////////////////////////////////////////////////////////////////////////
const int numReadings = 5;
float readings[numReadings];      // the readings from the analog input
int index = 0;                    // the index of the current reading
float total = 0;                  // the running total

float get_smoothed_temp() {
    total = total - readings[index]; // remove oldest reading
    readings[index] = DHT11.fahrenheit();
    total += readings[index];
    index = (index + 1) % numReadings;

    return (total / numReadings);
}
// END ADDITIONS ////////////////////////////////////////////////////////////////////////////////////////////////

void setup() {
  DHT11.attach(7);       // Attach DHT11 sensor to pin 7
  lcd.begin(16, 2);      // set up the LCD's number of columns and rows:
  Serial.begin(9600);    // Serial setup
  for (int thisReading = 0; thisReading < numReadings; thisReading++) readings[thisReading] = 0; // initialize all the readings to 0:

  pinMode(ACledPin, OUTPUT);  // initialize pin 8 as output
  pinMode(HTledPin, OUTPUT);  // initialize pin 9 as output
  pinMode(RELAY_01, OUTPUT);  // initialize pin 6 as output
  pinMode(RELAY_02, OUTPUT);  // initialize pin 10 as output

  // Leaves the relays in default "off" (no noise/click)
  digitalWrite(RELAY_01, HIGH);
  digitalWrite(RELAY_02, HIGH);

}

void loop() {

  float analogValue = (get_smoothed_temp()); // trying to set up the temp reading as an int variable
////////////// if then ////////////////
// if the analog value is high enough, turn on the LED:
  if (analogValue > threshold) {
    digitalWrite(ACledPin, HIGH);
    digitalWrite(HTledPin, LOW);
    digitalWrite(RELAY_01, HIGH);
    digitalWrite(RELAY_02, LOW);
  }
  else {
    digitalWrite(ACledPin, LOW);
    digitalWrite(HTledPin, HIGH);
    digitalWrite(RELAY_01, LOW);
    digitalWrite(RELAY_02, HIGH);
  }

Serial.println(analogValue);  // print the analog value:

// Set up the LCD Stuff
  lcd.setCursor(0, 0);      // Set cursor to top left
  lcd.print("Real F:");
  lcd.setCursor(0, 1);
  lcd.print("AVG  F:");
  lcd.print(analogValue, 1);

  delay(1000);

}

What's the difference between the relay pins in the HT/AC pins?

Your running average code is fine.
A quick way to start up fast is to take your first reading in setup, and fill the array with that value instead of zero.  That way you always get a reasonable temperature from the smoothing, it just gradually drifts from the first reading to the average of multiple readings  (rather than from 0 - a bogus value - to the that average).
This can work for the exponential smoothing too (old average = first reading).
An alternative is to only average as many samples as you have put into the array (1 then 2, then 3 etc until it's filled).  That takes extra code to handle just the first few results, tho, and the simpler approach suggested above (initially fill the array with a legitimate reading) is usually fine.

Good idea. I'll give that a shot.

What you want to do is replace your call to DHT11.fahrenheit() with a call to a new function (e.g. get_smoothed_temp()) that keeps track of the last several readings and returns the smoothed value.
const int numReadings = 5;
float readings[numReadings];      // the readings from the analog input
int index = 0;                    // the index of the current reading
float total = 0;                  // the running total

float get_smoothed_temp() {
    total = total - readings[index]; // remove oldest reading
    readings[index] = DHT11.fahrenheit();
    total += readings[index];
    index = (index + 1) % numReadings;

    return (total / numReadings);
}

You will still need to set the readings array to all zeros in the setup function.

I'm not certain how to do multiple loops/delays in a single project

You can't do this.* Software threading is the only way to do something like what you want, but it's too complex for what you need. What you want is to use the millis() function to return the time and
// constants won't change. Used here to
// set pin numbers:
const int ledPin =  13;      // the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

You can then pull button changes while you wait for a new reading. Another way would be to use an interrupt to interrupt the flow of the program when a button changes. I won't get into that.
For your use, you can use this template I made:
long previousMillis = 0;        // will store last time temp was updated
long interval = 1000;           // interval at which to check the temp (milliseconds)

void setup() {
  //Foobar
}

void loop()
{
  //Bar of foo
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    //Check Temp
  }
}

*Not to be confused with the loop statement.

I've just done a fan controller (using digital sensors - DS18b20, in my case) and chose an exponential average for smoothing the readings because it doesn't require storing or managing old data and I could get the smoothing I needed. During setup I took a reading from each sensor and preset the averages to those values. That gives the system a "running start"; it doesn't need to wait for enough samples for the averages to settle.
The exponential average I chose was (3 * oldAverage + tempr)/4 because it gave the performance I needed and is easy and fast to calculate without floating point. Multiplying by 3 is done by shifting and adding; dividing by 4 is done by shifting.
Here's the routine I used. It could easily be put in-line; the compiler probably will:
int16_t xpavg(int16_t tempr, int16_t oldAverage)
{
   // (3*oldavg + 1*tempr)/4
   return( (((oldAverage<<1) + oldAverage + tempr) + 2) >> 2 );
}


text:
Binary serial transmission order of data
I'm implementing a filter for my IMU Sensor and thus I want close to real time data visualized on the computer. I use binary serial communication to facilitate the sending part for the arduino (as far as I know the serial.print is pretty slow). So I split my int16_t in two bytes and send it, like:
Serial.write((uint8_t)(gx >> 8)); Serial.write((uint8_t)(gx & 0xFF));

After that i directly send the next number (3 in total by now, maybe up to 7 2byte numbers in the future).
I read the thing in matlab with:
dt(k) = toc;
tic;
bindata([1:6],k) = fread(s,[6,1],'int8');
time = cumsum(dt(1:k));

Which reads 6 bytes (3 numbers) and then I recalculate the binary representation, concatenate them and get the original number (if someone can suggest an easier way.. I found matlab pretty unhandy here).
The problem is, that the numbers get mixed by the time. Somewhen one byte isn't read or anything, so the bytes get messed up and a nonsense number is produced.One full number (2byte) is skipped for one sample exactly. Instead of this number one number is there twice. The next sample the order is messed up (shifted, such that the first number is second). This process appears after maybe 30 sec, sometimes a few minutes. After the first time it keeps shifting and jumping around.
Can someone tell me, what to do here? Can I include some 'breakpoint'/line terminator, where the reader (matlab) knows, that we are at the start of the first number? Or how is this done actually?
I guess I have to add my main goal: I want to make the sending as fast for the arduino as possible. No extra calculations should be necessary (if possible).
And: the reason for these shifts seems to be the some time delay (slowness). I suspect it to be a slow matlab reading, since I saw fluent processing scripts in HIL reading. The errors have stopped however, since I turned the baude rate down. Only wrong numbers are the problem still.
May there be a possibility to loop around the fread and read just store the values after an added 'header'? So let's say a wrong ordering occures. Then I discard everything until the next 'a' char/byte and use the following 6 bytes to produce my 3 values. Then I wait for an 'a' again. For that I would have to loop fread(s,[1,1],'int8'); and search for the header.
Full arduino code:
// Program to send the gyro/accel data via serialport
// corresponding matlab programs: sensing.m and sensing_binary.m
// 2 security loops to guarantee a constant sampling time

// #define DEBUG
#include "GY86.h"
#include "Wire.h"

GY86 gy86;
int16_t ax, ay, az;
int16_t gx, gy, gz;

uint32_t currenttime = 0;
uint32_t starttime = 0;
uint32_t starttime2 = 0;

// #define OUTPUT_ACCEL_COUNTS
#define OUTPUT_GYRO_COUNTS

// #define OUTPUT_ACCEL_BINARY
// #define OUTPUT_GYRO_BINARY

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

void loop () {
  currenttime = millis();
  if (currenttime-starttime > 9)
  {
    while (micros()-starttime2 < 9000) { }
    starttime2 = micros();

    // read raw accel/gyro measurements from device
    gy86.getSensorValues(&ax, &ay, &az, &gx, &gy, &gz);
    // testing constants
    // gx = -29;
    // gy = 245;
    // gz = 17;

#ifdef OUTPUT_GYRO_COUNTS
    Serial.print((int)gx); Serial.print(F("\t"));
    Serial.print((int)gy); Serial.print(F("\t"));
    Serial.print((int)gz); Serial.print(F("\t"));
#endif
#ifdef OUTPUT_ACCEL_COUNTS
    Serial.print(ax);   Serial.print(F("\t"));
    Serial.print(ay);   Serial.print(F("\t"));
    Serial.println(az); Serial.print(F("\t"));
#endif
#if defined(OUTPUT_ACCEL_COUNTS) || defined(OUTPUT_GYRO_COUNTS)
    Serial.print(F("\n"));
#endif

#ifdef OUTPUT_ACCEL_BINARY
    Serial.write((uint8_t)(ax >> 8)); Serial.write((uint8_t)(ax & 0xFF));
    Serial.write((uint8_t)(ay >> 8)); Serial.write((uint8_t)(ay & 0xFF));
    Serial.write((uint8_t)(az >> 8)); Serial.write((uint8_t)(az & 0xFF));
#endif
#ifdef OUTPUT_GYRO_BINARY
    Serial.write((uint8_t)(gx >> 8)); Serial.write((uint8_t)(gx & 0xFF));
    Serial.write((uint8_t)(gy >> 8)); Serial.write((uint8_t)(gy & 0xFF));
    Serial.write((uint8_t)(gz >> 8)); Serial.write((uint8_t)(gz & 0xFF));
#endif

    starttime = currenttime;
  }
}

Edit: It seems as the problem is overflow. That means that the USB connection isn't keeping up with the data trying to be sent. To fix this you need to do one of the following things (or both):

Higher baud rate. The baud rate is the frequency that data is sent. From what I've heard, anything above 500,000 as a baud rate isn't helpful with the Arduino libraries.

The Arduino IDE only goes up so high. Try an application such as PuTTY to get higher baud rates on the serial monitor.
Doing very high rates like this are best suited on as short of a cable as you can manage. I'd say 4 feet max, although it depends on many factors, including cable quality. A shorter cable has less resistance (thus less errors).
The rest of the answer still applies. You might want to add a simple parity bit to make sure the data doesn't get corrupted while sent. Adding two or three characters greatly reduces the risk of corruption, but at the expense of cutting your sampling rate in half and it doesn't verify data integrity. I don't know your exact situation, so adding a bit might not be possible.

Lower sampling rate: you're sending too much, so a simple solution is just to add delay(250); at the end of the loop so you don't overload the port.

Original Answer:
The only thing that comes to mind that is very efficient is a parity bit with another bit that's always the opposite of the parity bit. Why? Having an accidental thing where there the last two bits are opposite of each other and they all add up to a even number (ignoring the last bit) would be really odd.
A parity bit is an extra bit so all the bits added up with the parity bit equals an even number. If it isn't quite right, then you know there's a problem. It works only for odd numbers of bits changed, so it isn't foolproof. An example is you have the bits 10010110. There are four 1s, so it's an even number, thus the parity bit will be 0. If it was an odd number, it would be 1 to make the total count an even number. If the computer calculates it doesn't add up right (excuse my lame pun) then it's corrupted and the computer can discard it.
To implement this you'd need to convert the number(s) and the parity bit to ASCII and then count the 0s and 1s. You can use a remainder function and divide by two so there will be a remainder of 1 if it's odd, thus it's corrupted. I'd personally take the latest bit and the x number before it, and just keep looping until you find a combination that satisfies the whole parity bit thing and is within a reasonable range that you've specified in the code.
A line-break would suffice, but it takes up more bits and discovers only missing data, not corrupt data.
Maybe you should be looking into why there's a problem. Could you reduce the length of the USB cable? Upgrade your cable/try a different one? Slightly reduce the baud rate?

The cabling is maybe 2m long. Baude Rate is 115200... what would be the benefit of a lower baude rate? And how do I know how much I need?

Since I thought the error is in my matlab code, I already opend a SE question for that, since this is now more concerning the delay, rathen than the swaps in bits, let's continue there.
Your suggestion works! 1/3s sample time gives valid/current time values! Pls help me to fully understand where this could have come from:
http://stackoverflow.com/questions/24368670/matlab-plot-serial-data-continously

@mike it's not a problem of the Matlab code, it's the Arduino then. You're sending more data than the serial chip can handle at the baud rate you specified. I know I said lower it (I thought info was getting corrupted), but you need to raise the baud rate and lower the sample rate.

25 Hz is possible. That's as high, as possible. However I wanted to debug a quadcopter filtering,... which doesn't quite make that much sense if I run 1/2 or even 1/4 of the planned sampling rate. (I try to get my 100Hz, or at least 50).
Also if I add more numbers this phenomenon gets occurs more often I guess? Because it's overflow, right? I'll try to get a shorter cabling, thanks for the advice!

@mike Glad I could help! Edited my question and I cleaned up the comments here.

You could add some kind of packet header/footer to the serial output. For example, if you sent the characters "ab" before the bytes for your number you could reject packets that only had 2 bytes in them. the serial would look like
"ab123ab123ab12ab123"
The matlab code could see another "ab" come in before the previous packet finished and ignore the packet that ended up as only "ab12", and then get itself back on track again. You should use 2 bytes for your header to avoid collisions with the actual data. Adding a checksum at the end of the packet would also allow you to detect bit swap errors. CRC or fletcher16 would work perfectly in this scenario, but in your case a checksum may be more than you need.

So I need to add Serial.write('ab') and then write the number bits. And in matlab fread 2+number-bits and check if the first 2 are ab. If not, re-read.
Is this the thing you suggest? What do you mean by collision with my data.. If I just read 1+num-bits, and they shift, I would still get an error if not all bits are there, or the first one is not "a"?

By collision I mean that if your data happened to be the characters 'ab' it would mess up a reading. Your correct about the arduino side, just send "ab" before the data. The matlab code should detect that the sequence "ab" happened and then look for the data bits next, but if another "ab" happens before the data bits are done dump what has already come in and start over. That way it will realign with the data if a byte is dropped.

Collision you mean the probability, that in my actual values one of the bytes contains the header by incidence? So a longer header would reduce the possibility of having real data = termination string. Correct?

Exactly. With two bytes there is a 1 in 2^16 probability of random data generating the header. A longer header than 2 bytes that might result in less data making it across since your packets are so small; Sending an extra character per packet would probably cost more time than losing one in 65536 packets.

Ok fine. I would implement this as Serial.write(219); Serial.write(128); Since what is sent is binary (thus the same as some char), and for matlab it is easier to directly read (&compare) the uint with 8 bit.
I mark this as solution, since I can remove the shifts. The whole thing is useless however, since there is some strange time delay that adds up. See:
http://stackoverflow.com/questions/24368670/matlab-plot-serial-data-continously

If what you want is high speed, the serial baud rate is your main concern. I assume that you are using an Arduino with a serial to USB converter chip, such as the Uno or Mega.
Transferring at 115200 baud, you send 11520 bytes/s at normal serial settings (1 start + 8 data + 1 stop bits = 10 bits to send 1 byte of data). With an Arduino running at 16 MHz clock, you can execute 16M / 11520 = 1389 instructions in the time it takes to transmit one byte. So you don't have to worry much about slow library routines, what you have to worry about is how many bytes you send. In that way you are right not to use Serial.print, as it will convert your int to ascii, making all number larger than 99 slower to transmit (for a uint16).
When you send data with Serial.write it is first stored in a ring buffer, then transmitted in the background by an Interrupt Service Routine. The ring buffer is typically 64 bytes. Once the the buffer is full, a call to Serial.write will block until a byte has been transmitted, so there is space in the buffer again. Therefore the timing in your main loop isn't really necessary, you can remove it and your sampling rate will adapt to your serial baud rate.
Once the data has reached the serial to USB converter chip, it will be transmitted on the USB bus at 12 Mbit/s. I don't know the exact data transfer rate since there's a lot more overhead on USB than on the serial, but you can rest assured that the bottleneck isn't here. I don't think you have to worry about USB cable lengths as there is built-in error detection and retransmit in the USB protocol, and the speed is so much faster than the serial link.
In the computer the data can be buffered in several places, it all depends on device drivers and serial libraries used. I'm not an expert here. With no flow control, the drivers/libraries probably have no choice but to drop data if it is receiving more than the end application or later layer can process. Maybe matlab or it's serial implementation or you computer is slow in some way (the data really isn't arriving very fast at all for a modern computer). So you could lower the baud rate or try to deal with lost packets.
I have a suggestion for dealing with lost packets: Reserve the upper x bits in each byte you transmit to hold the number of that byte in its sequence. You could f.ex. reserve 2 bits, allowing you to send up to 4 byte packets belonging together. Each byte-packet would have 6 data bits, enabling you to send numbers with 24 bits of precision.
To send a uint16:
void send_int16(uint16_t data)
{
  Serial.write((0 << 6) | (data & 0b00111111));
  data >>= 6;
  Serial.write((1 << 6) | (data & 0b00111111));
  data >>= 6;
  Serial.write((2 << 6) | (data & 0b00111111));
}

Then in matlab you should wait for a sequence of packets numbered 0, 1, 2 in the two uppermost bits, remove the numbering and put the packets together with bitwise operators.
If you get a malformed sequence, eg. 0, 2, can discard it and wait for the next byte starting with a zero.
I haven't really used matlab, so you are on your own.


text:
Text got scrambled on Tinyscreen+
Yesterday when I was trying to reset my Tinyscreen+ by using a needle to flick its power switch (because the case made it hard to do it with my fingers). It was a bit clumsy and I may had shorted some connections in the process. After that, the text on the bottom part of the screen become scrambled as shown in the attached image.
Does anyone have an idea on what caused that and if it's fixable?
Thanks for any help

you already said what caused it ... yes, it is probably fixable ... you have to determine where the failure is located ... you also have to decide if you want to spend time and money to repair it ... it is cheaper to replace it

If it still happens after you completely power off and back on you've probably destroyed the hardware. Time for a new screen and a $40 lesson learned the hard way.

You may be able to replace the OLED module itself if you're handy with a soldering iron. The controller is SSD1331, one likely part number for the display module is CFAL9664B-F-B2. Or, it looks like you're using monochrome images; you could replace with a much cheaper SSD1306-based display.

The schematic says it's a UG-9664HDDAG01 (not sure if it's just the controller or the whole thing). Although I think I'll just use the top 3/4 of the screen for now.

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


text:
QMC5883L automatic calibration
I have a QMC5883L magnetometer, and a pretty basic sketch which just prints the values from X, Y and Z axis to the serial monitor.
I want to use it in an application to detect changes in the magnetic field, and the sensor will be in a fixed position. However, it seems that when I start the Arduino, the values from the sensor are all over the place (looking at it in the serial plotter all 3 axis are going from 1 extreme to the other and back). If I move the sensor around a bit, the values calm down and become more steady, and usable to detect metal objects approaching the sensor.
Since the sensor will be installed in a fixed position, I can't move it around to calibrate it every time the Arduino restarts. Can I calibrate it programatically somehow? Note that I don't really need to know which way it is oriented, I simply want to detect when the magnetic field changes (i.e. when a metal object approaches/leaves the sensor).

https://web.archive.org/web/20150214163745/http://hobbylogs.me.pn/?p=17

https://github.com/helscream/HMC5883L_Header_Arduino_Auto_calibration

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


text:
Arduino Analog pins go all to high problem
I was taking measures from the  outputs of an OpAmp when all the sudden measure 5 volts from all pins of the Arduino Mega for no reason. I disconnected the Arduino and loaded the Firmata and test. All the pins are reading high to 1023.. 5 volts are been output for no reason even when I have the Analog Ping to input.
Sketches code are loading and the lights look normal. I did noticed the processor chip getting hot and the voltage in the breadboard line to the Arduino Analog pins reading 7 volts.
Is this a sign of a serious damaged to my device?

Probably. It should not get hot. Was something connected to the pins that draws so much current that it could get hot? What are the power voltages for the OpAmp? Higher than 5v?

I doubt. A voltmeter the same output line from the OpAmp read 7 volts. But the reading returned to normal 35 ml after  disconnecting the wiring to the  arduino analog  pin. Also, only 3 of the pins where connected to OpAmp device measuring input voltage, output and the ground.  All the arduino pins ( except A0) are stuck in HIGH.

The voltage of the atmega2560 can be -0.5v to +5.5v when the atmega2560 is powered with 5.0v. A voltage of 7v might damage it. It is possible to blow only a part of the chip. When you are sure that al least one pin is blown, then you should get rid of it because it is possible that other parts inside the chip are damaged as well. I'm still not 100% sure that the chip is damaged, because when uploading a sketch, pin 0 and 1 must be working.

Can this chip me removed and replaced easily? Please point to any source to this repair surgery.

Ask someone with smd soldering skills, but it is a large chip which makes it very hard. What was the cause? How did the 7V get to the pins of the atmega2560? A 5v opamp with rail-to-rail output is no problem. When using higher voltages, a voltage divider or protection resistor should be used.

That is exactly what puzzles me. First I was using an old OpAmp which is a NOT rail to rail operating under  a -12 to + 12  power supply. I had everything set up to amplified a small mV signals to a range of o to 5 V.  This last was going to Arduino Analog Pin.  Is ther any possibility that the USB power line from computer to Arduino spikes to 7 volts? Or this was something that got crossed at the OpAmp beardboard?

A USB port does not spike to 7v, so it must be something at the breadboard. For the atmega microcontroller it is allowed to push 1mA into a pin. It can be more but that is not specified, it might be in the range of 5mA continous and 20mA peak (just a wild guess). For example a protection resistor of 4k7 to a analog pin input will protect up to 10.2v (and a lot more when using the unspecified numbers). Just a simple protection resistor can prevent a lot of problems and it introduces only a little more noise and a little more inaccuracy.

@jot please change your comment to an answer to up-vote you accordingly

A high voltage at a pin can damage the microcontroller partially.
The ATtiny microcontrollers can sometimes survive a voltage of 7 V.
The ATmega microcontrollers are damaged by that voltage.
The ATmega2560 is older and even more critical with voltages, it can not work at 16 MHz below 4.5 V and gets easily damaged with voltages above 6 V.
When the microcontroller runs at 5.0 V, a input pin can have -0.5 V to +5.5 V.
When the microcontroller gets damaged, it can be damaged partially. It is impossible to determine which parts of the chip are still okay. Therefor a partially damaged microcontroller should not be used anymore.
Solution:
A simple solution is a protection resistor in the signal path to the analog input.

simulate this circuit – Schematic created using CircuitLab
According to application note AVR182, it is allowed to push 1 mA into a pin or pull 1 mA from a pin for the ATmega microcontrollers. That current flows via the internal ESD diodes to VCC or from GND.
With a protection resistor of 4k7 before an input, the microcontroller is protected up to: 1mA * 4k7 + 5.5V = 10.2 V.
The internal ESD diodes can have more than 1 mA, but the maximum is unspecified. It is also dangerous when for example the ATmega is put into sleep mode. Then the 1 mA can lift the VCC voltage and still damage the ATmega microcontroller.
When a voltage divider is used (two resistors, R1 and R2) and the internal reference is used, then the voltage divider can be designed to be protected against very high voltages. For example with a ATmega2560, internal reference of 2.56V, R1=47k, R2=10k. This can measure up to 14.6 V and be protected up to 78 V.

My understanding is that the ATmega implements sleep mode by gating the clock, with Vcc still applied to the whole chip.

@EdgarBonet yes, so a current pushed into a analog or digital pin can lift the vcc above 5v (if the voltage has nowhere else to go), and can damage the chip. Should I explain it better?


text:
Wolfram Mathematica reads but closes stream feeds from Arduino Serial port after a few data sets
This is a Wolfram Mathematica / Arduino serial feed problem , but I am posting here just in  for any suggestions on enhancing the Arduino code or the Mathematica notebook.  The original post is here Mathematica Exchange post and in here
The Arduino sketch monitor a sensor and returns a set of three intergers.
     #include <Wire.h>
#include "Adafruit_AS726x.h"

//create the object
Adafruit_AS726x ams;

//buffer para leer valores en bruto
uint16_t sensorValues[AS726x_NUM_CHANNELS];

//buffer para  guardar los valores calibrados( no esta siendo utilizado en este codigo)
//float calibratedValues[AS726x_NUM_CHANNELS];

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

  // inicializa el pin digital LED_BUILTIN como un output.
  pinMode(LED_BUILTIN, OUTPUT);

  //inicia y permite la comunicacion con el sensor
  if(!ams.begin()){
    Serial.println("could not connect to sensor! Please check your wiring.");
    while(1);
  }
}

void loop() {

  //lee la temperatura del sensor
  uint8_t temp = ams.readTemperature();

  //ams.drvOn(); // descomentar esto si quieres usar el led del sensor para hacer medidas
  ams.startMeasurement(); //begin a measurement

  //permite que el sensor lea la data cuando este disponible
  bool rdy = false;
  while(!rdy){
    //delay(1000);
    rdy = ams.dataReady();
  }
  //ams.drvOff(); //descomentar esto si quieres usar el led del sensor para hacer medidas

  //lee los valores!
  ams.readRawValues(sensorValues);
  //ams.readCalibratedValues(calibratedValues);

   //Serial.print("{");
  //Serial.print("Temp: ");
  //Serial.print(temp);
  //Serial.print(",");
  //Serial.print(" Violet: ");
  //Serial.print(sensorValues[AS726x_VIOLET]);
   //Serial.print(",");
  //Serial.print(" Blue: ");
  Serial.print(sensorValues[AS726x_BLUE]);
   Serial.print(",");
  //Serial.print(" Green: ");
  //Serial.print(sensorValues[AS726x_GREEN]);
   //Serial.print(",");
  //Serial.print(" Yellow: ");
   Serial.print(sensorValues[AS726x_YELLOW]);
    Serial.print(",");
  //Serial.print(" Orange: ");
  //Serial.print(sensorValues[AS726x_ORANGE]);
   //Serial.print(",");
  //Serial.print(" Red: ");
  Serial.print(sensorValues[AS726x_RED]);
  //Serial.print("}");

  Serial.println();
  //Serial.println();
  delay(400);

The Mathematica notebooks is
dev = DeviceOpen["Serial", "COM3"]

parseData[{val1__, 44, val2__, 44, val3__}] :=
 ToExpression@FromCharacterCode@# & /@ {{val1}, {val2}, {val3}}
parseData[___] := Sequence[]
rawReadings = {}
task = SessionSubmit[
  ScheduledTask[
   AppendTo[rawReadings,
    DeviceReadBuffer[dev, "ReadTerminator" -> 10]], {1, 100},
   "AutoRemove" -> True]]
test1 = parseData /@ rawReadings
ListLinePlot[Transpose[parseData /@ rawReadings],
  PlotLegends -> Automatic] // Dynamic
DeviceClose[dev]

But the Notebooks is not returning a dynamic feed of data from Arduino. It closes and not able to determine why.  It is suppose to stream a feed continously.

I think the outcommented code should be removed.

There is a whole class of these connection problems on Stack Overflow. Sample 1. Sample 2. Here too?

This thread has nothing to do with Processing , LabView or Matlab.  It applies to Wolfram Mathematica handle of Arduino serial port.  Can you explain how these contribute to my problem?

Jose! As I already mentioned in Mathematica SE, you need to remove the delay statements out of your code and additionally send the data to serial only if new data has arrived.

Thank you for the feedback. I posted a update in Mathematica Exchange with a revised code with you suggestions.   But so far no getting the dynamic stream to maintain continuously.


text:
Digital RGB LED animation
I've been trying to get colours fade into each other for a project I'm working on.
I have achieved this with the rainbow effect that some from Adafruit's example code, however I want to be able to choose the colours (eg. dark blue into light blue).
I've got the colours changing and fading, however the fade turns off all the LEDs and starts to increase the brightness of the new colour. I need the colours to blend rather than fade out and increase in brightness.
Is anyone able to point me in the right direction?
#include "LPD8806.h"
#include "SPI.h"
#define stripSize 64

int nLEDs = 160;

int dataPin  = 2;
int clockPin = 3;

// First parameter is the number of LEDs in the strand.  The LED strips
// are 32 LEDs per meter but you can extend or cut the strip.  Next two
// parameters are SPI data and clock pins:
LPD8806 strip = LPD8806(64, dataPin, clockPin);

// You can optionally use hardware SPI for faster writes, just leave out
// the data and clock pin parameters.  But this does limit use to very
// specific pins on the Arduino.  For "classic" Arduinos (Uno, Duemilanove,
// etc.), data = pin 11, clock = pin 13.  For Arduino Mega, data = pin 51,
// clock = pin 52.  For 32u4 Breakout Board+ and Teensy, data = pin B2,
// clock = pin B1.  For Leonardo, this can ONLY be done on the ICSP pins.
//LPD8806 strip = LPD8806(nLEDs);

void setup() {
  // Start up the LED strip
  strip.begin();

  // Update the strip, to start they are all 'off'
  strip.show();
}

void loop() {
  //turnAllOn(strip.Color(30,30,30),4000);
  fade(0, 127, 0, 100); //red, green, blue, delay - fade up all pixels one color
  //turnAllOn(strip.Color(30,100,30),4000);
  fade(50, 127, 02,100); //red, green, blue, delay - fade up all pixels one color
  //turnAllOn(strip.Color(100,30,100),4000);
  fade(50, 127, 50, 100); //red, green, blue, delay - fade up all pixels one color
}

void fade(uint32_t r, uint32_t g, uint32_t b, uint32_t wait) {
  int i, j;
  for (j=0; j < 384; j++) {
    for (i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, strip.Color((r*j)/1000,(g*j)/1000,(b*j)/1000));
    }
  strip.show();
  }
  delay(wait);
}

void turnAllOn(uint32_t c, uint32_t wait) {
  int i;
  for (i=0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, c);  // turn all pixels on
  }
  strip.show();   // write all the pixels out
  delay(wait);
}

uint32_t Wheel(uint16_t WheelPos)
{
  byte r, g, b;
  switch(WheelPos / 128)
  {
    case 0:
      r = 127 - WheelPos % 128;   //Red down
      g = WheelPos % 128;      // Green up
      b = 0;                  //blue off
      break;
    case 1:
      g = 127 - WheelPos % 128;  //green down
      b = WheelPos % 128;      //blue up
      r = 0;                  //red off
      break;
    case 2:
      b = 127 - WheelPos % 128;  //blue down
      r = WheelPos % 128;      //red up
      g = 0;                  //green off
      break;
  }
  return(strip.Color(r,g,b));
}

Currently, your fade function is starting at 0 and effectively interpolating up to the desired colour. To fade between colours, you would need the sketch to remember the previous colour it used, and start fading from that instead of from 0.
The approach I'd use is to start by calculating how much each component needs to change by on each step. For example, if you want to fade from 100 to 200 across 50 steps, then it needs to change by +2 on every step. If you wanted to do the same in reverse (200 to 100) then it would have to change by -2.
One of the problems is that each component will probably be changing by a different amount (red might go from 0 to 200, but blue might only go from 50 to 70). If you're using integers all the time then it could result in some uneven transitions, so I'd recommend using floating point instead. It's technically slower (less efficient), but probably not enough to worry about.
This is how I'd probably write it:
void fade(uint8_t oldR, uint8_t oldG, uint8_t oldB, uint8_t newR, uint8_t newG, uint8_t newB, uint32_t numSteps, uint32_t waitPerStep)
{
    // Guard against division by zero
    if (numSteps == 0) numSteps = 1;

    // Calculate how how much each colour needs to change on each step
    const float
        stepR = (newR - oldR) / (float)numSteps,
        stepG = (newG - oldG) / (float)numSteps,
        stepB = (newB - oldB) / (float)numSteps;

    // These values will store our colours on the way along
    float r = oldR, g = oldG, b = oldB;
    uint8_t byteR = oldR, byteG = oldG, byteB = oldB;

    // Go through each fade step
    const uint16_t numPixels = strip.numPixels();
    for (uint32_t step = 0; step < numSteps; ++step) {
        // Move one step towards the target colour
        r += stepR;
        g += stepG;
        b += stepB;

        // Round the colours to integers here so we don't have to do it repeatedly in the loop below
        byteR = (uint8_t)(r + 0.5f);
        byteG = (uint8_t)(g + 0.5f);
        byteB = (uint8_t)(b + 0.5f);

        // Apply the colour to each pixel
        for (uint16_t pixel = 0; pixel < numPixels; ++pixel) {
            strip.setPixelColor(pixel, byteR, byteG, byteB);
        }

        strip.show();
        delay(waitPerStep);
    }
}

As you can see, you pass it the old colour (which you're fading from) and the new colour (which you're fading to). As I mentioned above, this means your sketch has to remember which colour it previously used, as I don't think the library provides a way to read the current colour back.
I've included some optimisations in there to make it run faster. There's more you could do to optimise it even further, if necessary.
To use this, you'd do something like this:
// Fade from black to red and pause briefly
fade(0, 0, 0,  255, 0, 0,  100, 10);
delay(500);

// Fade from red to purple and pause briefly
fade(255, 0, 0,   255, 0, 255,  100, 10);
delay(500);

// Fade from purple to green and pause briefly
fade(255, 0, 255,  0, 255, 0,  100, 10);
delay(500);

I've made a couple of other changes compared to your own fade function function. First of all, I've made it so that you can set the number of steps to fade over. This can be quite useful because bigger colour changes will need more steps to look smooth.
I've also modified the wait parameter. In your code, you put the delay after the entire fade was complete, which seems like an odd approach. It makes more sense to allow a small delay between each step of the fade, so you can control how fast it goes.
In my example above, you can see the 100, 10 parameters at the end of each call to fade(). That means it will divide the colour change into 100 steps, with a delay of 10ms between each step. The result is that each fade will take roughly 1 second (not counting the time taken to actually update the LED strip).

Very well answered. Kudos for all code details, optimizations and explanations. Maybe a small bug: the from color never appears as you start your loop with the first step increment. You should add one more iteration and increment only at the end of the loop.

@jfpoilpret Thanks. Missing out the first step is actually deliberate. Based on the question, I'm assuming the LEDs are already showing the 'old' colour before fade() is called. You're absolutely right though. In other circumstances you may indeed want that extra step.

This is really great. Thanks so much for the detailed write up!


text:
Arduino works bad when powered by 9V battery
At first I am sorry for my bad English.
I am making robot which can do a lot of things...
If I connect arduino on my robot with PC via USB, the robot works properly. If I use external power supply (9V battery) the robot is doing almost nothing.. The diodes are little bit blinking and sometimes dc motors make motion... And thats all. Batteries are charged. Where's the problem?
Everything I want is make into motion dc motors.. With 5V USB it works. With external power supply not (9V battery).

9V batteries are crap for anything that needs any real amount of current.

Does it really show you 9V? If it is written on side it doesn't mean it's 9V

Yes, It really has 9V. I have 2 same 9V batteries. One for DC motors and one for arduino. DC motors are working properly with this battery but arduino is not.

probably you were right. If I disconnect all sensors from arduino, the DC motors are making some motion... they're really slow but they are moving.

what I should use instead this 9V battery?

The input voltage of the arduino external power supply needs to be at leased 7,2V or else it will fail. Make sure your battery is providing enough voltage to the arduino.

I got a fresh 9 V out of a packet and measured it.
 9.58 volts

Now with a load of 500 mA (which you quite likely would get with a robot) it dropped to:
 7.4 volts

With a load of 750 mA the voltage dropped to 6.6 V which is below what you are supposed to supply via the power jack.
And that was with a fresh battery, testing for a few seconds.
Those 9 V batteries are just not designed to drive motors.
I suggest a somewhat heavier-duty battery, like 5 x AA batteries, at least for the robot part.


text:
What is the difference between Accelerometer, Gyro, and Magnetometer Sensor?
I'm starting in the arduino world and I'm building an autonomous smart vehicle.
So, after some weeks building and adjusting the vehicle, I got to a point in this project that I want to log it's movements. Talking with a friend, he showed me an Gyro/Accel sensor and I really think that it would be an awesome upgrade to my vehicle
After reading some articles, I'm failing to understand the difference between an Accelerometer Sensor, a Gyro Sensor and a Magnetometer Sensor
So what is the main difference between those sensors?

The Accelerometer measures total acceleration on the vehicle, including the static acceleration from gravity it would experience even when its not moving.
The magnetometer measures the magnetic field around the robot, including the static magnetic field pointing approximately north caused by the earth. Being placed in/around a metal frame or any large motors, diving over/around underground metal pipes or electrical equipment will all make large and noticeable effects on its measurements.
The Gyroscope measures your instantaneous angular momentum around each axis, basically how fast its rotating. Note that angular momentum is not directly compatible with euler angles, but works out similarly for small angles. Very high quality signal in the short term because there isn't much noise, but since your angular position has to be integrated off of the gyroscope, it will build up error.
Gravity is your best reference for angular position, because it doesn't drift like the gyroscope and since your robot is operating in (and causing) a sea of magnetic disturbances, using north is risky. It will not work if you are experiencing a significant acceleration though.
The simplest code would just use the accelerometer for rotations around x and y, the mag for z, and ignore disturbances. The basic idea is "I know gravity is actually down, but its being measured on the accel X axis, so I must be pitched by some amount". The Better sensor fusion algorithms will use the accelerometer/magnetometer to correct for drift in the gyro, but get most of its information about rotational position from the Gyroscope.
Tracking lateral position using a standard 9-dof IMU is not possible. Only the accelerometer measures lateral motion at all, and it needs to be integrated twice to get position. Error builds so fast your position estimate is complete garbage within seconds.
Tracking angular position is possible because all three sensors measure it in one way or another. Angles are tricky though because they are not commutative. If the gyro measures a 90 degree yaw then a 90 degree pitch from north, you are facing down; if it measures a 90 degree pitch and then a 90 degree yaw from north, your facing east turned on your side. Be careful with the math, or download an arduino IMU library that has it taken care of for you.

The main difference is the way they operate and what they sense.  In other words, they are all very very different things.  Yet they can all measure motion in some way.

An accelerometer senses both the gravitational pull of the earth and the inertia / momentum of the motion of the device
A magnetometer senses the earth's magnetic field to get a compass heading.
A gyroscope senses changes in twist and angle.

They can all give information about motion and attitude, but each has both benefits and drawbacks compared to the others.  Some drift more than others, some are slower or lower resolution, etc.
So generally all three are used together to get the benefits of them all and, to some extent, negate the drawbacks of them.
For instance, a gyroscope isn't good at measuring inertia, but it is good at measuring changes in angles.  But those changes in angles drift over time and you lose accuracy.  A magnetometer is good at giving you an exact angle, but it takes longer to get an accurate result, and it's not good at fine changes in angle.  So a magnetometer is used to correct the drift of the gyroscope, and an accelerometer is used to measure inertia.
So to sum up:

Accelerometer for changes in speed
Gyroscope for changes in angle
Magnetometer to correct the gyroscope


text:
Can the 2nd MCU on the UNO R3 be used for keyboard emulation?
Following on from What's the 2nd ICSP header for in Arduino Uno R3? I was wondering how this could be hacked to our advantage.
For example, could that firmware be rewritten to have the UNO recognised as a mouse/keyboard input? Could this be done after the boot loader process and leave the uploading process in tact?
Given the limited IO, it seems it's functions might be limited. Plus I have no idea how much code is space is available.

As an extra to this question, feel free to add other ideas this could be used for whilst (in as far as possible), leaving the arduino environment in tact. That is, what else could be hacked into it to increase it's functionality?

It's flash is too small to hold multiple hacks, but the LUFA website (linked in my question) has a lot of different hacks that are compatible with the 16u2

Too small? 16kB is a lot of flash. I'm surprised they didn't stick with the 8U2 as in the original (although there may be availability issues involved).

I just checked Digi-Key and the price difference between the 8U2 and 16U2 is about $0.01. At that price it's a no-brainer, even if you don't need the extra flash.

This question is spawned from a project I saw on hackaday last year, and a friend and I have been discussing it on and off ever since. I just found this (only two weeks old): http://hackaday.com/2014/03/16/developed-on-hackaday-security-and-arduino-compatibility/

Yes, it is possible. using LUFA, you can burn new firmware to the Serial converter. The only problem is that you need to re-burn the USB-Serial converter to upload another program.
Info: http://www.fourwalledcubicle.com/LUFA.php
Specific page: http://mitchtech.net/arduino-usb-hid-keyboard/

Is there more information on the firmware that exists in the 2nd mcu? I haven't been able to find anything on it. I'm sure that someone somewhere has hacked it specifically. Personally, I'd love to see the code. Emphasis (for me) would to largely leave the environment in tact to allow for future reflashing. Which I don't think would be too hard to incorporate after there is nothing from the IDE after reset.

@Madivad it is a simple assembly file that converts USB signals to serial. You need to use bare AvrDude to flash it.

from one of those links I found: http://arduino.cc/en/Hacking/DFUProgramming8U2 I searched for this kind of info, obviously wrong search terms :) Thanks for your links Doc.

The second MCU is similar to that used in the Leonardo, but is smaller and less capable (ATmega16U2 vs. ATmega32U4). It is certainly possible to reprogram it to do what you like, but its limits means that you can have fewer USB "devices" at the same time.
I have not looked at the existing firmware, but it should certainly be possible to add your own custom code into it such that both the normal serial connection to the main MCU as well as your additional code can coexist.