text:
Bluetooth HC-05 module returns encoded data
I have searched online, and haven't found anyone hitting this issue. Strangely my Bluetooth HC-05 is returning encoded data. I have tried using different boards - Induing, Uno, Freeduino and I have the same problem with them all.
The Bluetooth module I am using is a HC-05 Bluetooth Module.
When I pass 'AT' command, I expect the return to be 'OK'. I get data as
CF  A7  86  85

This is 8-bit data, and if I drop the MSB I would be:
4F  27  06  05

Instead I should have received:
4F  4B  0D  0A

I looked at the binary pattern to understand if this is something like 7 bit encoding used in GSM.
Actual Data
CF       A7       86       85
11001111 10100111 10000110 10000101

Expected Data
4F  4B  0D  0A
01001111 01001011 00001101 00001010

I have tried other AT commands and everything appears to be encoded.
The code I have written is pretty standard, module is blinking at 2 sec pulse (in command mode). I get encoded output for all AT commands. I even tried ORGL, INIT and other commands as suggested on various discussion threads.
#include <SoftwareSerial.h>

SoftwareSerial BtDongle = SoftwareSerial(10, 11);

void setup() {
  digitalWrite(9, LOW);
  delay(100);
  digitalWrite(9, HIGH);
  delay(100);
  Serial.begin(9600);
  Serial.write("AT Command: \n\n");
  BtDongle.begin(38400);
}

void loop() {
  while(BtDongle.available()) {
    unsigned char data = BtDongle.read();
    Serial.println(data, HEX);
  }

  while(Serial.available()) {
    char data = Serial.read();
    Serial.print(data);
    BtDongle.print(data);
  }
}

It looks like a configuration problem of the serial interface: try to play withe number of stop bits and the parity; there's probably one combination that will work.

I tried various combinations with Putty instead of the Arduino IDE's built in Serial Monitor. Here the output won't stop!
CFA78685CFA78685CFA78685CFA78685CFA78685CFA78685CFA78685...

In the built-in Serial Monitor
HEX:
AT
CFA78685
AT+NAME?
ABA6A0A629275469D62482C6C1B5416D5A60B18585CFA78685

AT+Version?
C5AAA9A7A94D4A4C4A23E1

CHAR:
AT
Ï§†…
AT+NAME?
«¦ ¦Q'UiÖ$‚ÆÁµÁmZ`±……Ï§†…

AT+VERSION?
«ª¢©*ÕÊ¦’ºÁµIab`°š˜˜CáÏ§†…

Well I faced a similar kind of problem with Wi-Fi module RN 171. Following are some tips that I would like you to check for.

Please share tips that I can check for?

It seems some bits are getting lost. Please add a buffer to both input and output and only start to transmit back to PC when you have received everything from BT.

I also got the same problem, and after a few researches, I found that it was related with a bug inside the library SoftwareSerial. Here is how to fix it :

Download the two files of the new version of the library on github
Rename them into mySoftwareSerial.cpp and mySoftwareSerial.h and put them in the working folder
Replace in the working file and in the file mySoftwareSerial.h the line #include <SoftwareSerial.h> into
#include "mySoftwareSerial.h"
Compile and send it to the arduino. It should work ! (Tested in AT mode at a baud rate of 38400, and in classical mode (+AT mode) with a baud rate of 57600 on a arduino nano)

You can find the file I used at the and of the post.
By the way, I also mention another problem I got which is not related but could help : in some models of HC-05 you have a pin EN instead of KEY. Here, instead of connecting the VCC to the KEY pin, you need to press the button on the top of the HC-05 board before starting the HC-05 module : this button will connect VCC to the pin 34 for you. But note that if you don't keep this button down, you will be able to do only a subset of the commands (for example, AT+NAME? won't work, while AT+NAME=... and AT will). You can find lot's of additional information here.
The files I used
This file is the "project file" used to forward the classical serial connection (Ctrl+Shift+M on arduino software) to the bluetooth device. Type AT commands here.
#include "mySoftwareSerial.h"
SoftwareSerial BTserial(7, 8); // RX | TX
// Connect the HC-05 TX to Arduino pin 2 RX.
// Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.
//

char c = ' ';

void setup()
{
    Serial.begin(9600);
    Serial.println("Arduino is ready");
    Serial.println("Remember to select Both NL & CR in the serial monitor");

    // HC-05 default serial speed for AT mode is 38400
    BTserial.begin(38400);
}

void loop()
{

    // Keep reading from HC-05 and send to Arduino Serial Monitor
    if (BTserial.available())
    {
        c = BTserial.read();
        Serial.write(c);
    }

    // Keep reading from Arduino Serial Monitor and send to HC-05
    if (Serial.available())
    {
        c =  Serial.read();
        BTserial.write(c);
    }

}

The file mySoftwareSerial.h, taken from the github page :
/*
SoftwareSerial.h (formerly NewSoftSerial.h) -
Multi-instance software serial library for Arduino/Wiring
-- Interrupt-driven receive and other improvements by ladyada
   (http://ladyada.net)
-- Tuning, circular buffer, derivation from class Print/Stream,
   multi-instance support, porting to 8MHz processors,
   various optimizations, PROGMEM delay tables, inverse logic and
   direct port writing by Mikal Hart (http://www.arduiniana.org)
-- Pin change interrupt macros by Paul Stoffregen (http://www.pjrc.com)
-- 20MHz processor support by Garrett Mace (http://www.macetech.com)
-- ATmega1280/2560 support by Brett Hagman (http://www.roguerobotics.com/)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
The latest version of this library can always be found at
http://arduiniana.org.
*/

#ifndef SoftwareSerial_h
#define SoftwareSerial_h

#include <inttypes.h>
#include <Stream.h>

/******************************************************************************
* Definitions
******************************************************************************/

#ifndef _SS_MAX_RX_BUFF
#define _SS_MAX_RX_BUFF 64 // RX buffer size
#endif

#ifndef GCC_VERSION
#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif

class SoftwareSerial : public Stream
{
private:
  // per object data
  uint8_t _receivePin;
  uint8_t _receiveBitMask;
  volatile uint8_t *_receivePortRegister;
  uint8_t _transmitBitMask;
  volatile uint8_t *_transmitPortRegister;
  volatile uint8_t *_pcint_maskreg;
  uint8_t _pcint_maskvalue;

  // Expressed as 4-cycle delays (must never be 0!)
  uint16_t _rx_delay_centering;
  uint16_t _rx_delay_intrabit;
  uint16_t _rx_delay_stopbit;
  uint16_t _tx_delay;

  uint16_t _buffer_overflow:1;
  uint16_t _inverse_logic:1;

  // static data
  static uint8_t _receive_buffer[_SS_MAX_RX_BUFF];
  static volatile uint8_t _receive_buffer_tail;
  static volatile uint8_t _receive_buffer_head;
  static SoftwareSerial *active_object;

  // private methods
  inline void recv() __attribute__((__always_inline__));
  uint8_t rx_pin_read();
  void setTX(uint8_t transmitPin);
  void setRX(uint8_t receivePin);
  inline void setRxIntMsk(bool enable) __attribute__((__always_inline__));

  // Return num - sub, or 1 if the result would be < 1
  static uint16_t subtract_cap(uint16_t num, uint16_t sub);

  // private static method for timing
  static inline void tunedDelay(uint16_t delay);

public:
  // public methods
  SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);
  ~SoftwareSerial();
  void begin(long speed);
  bool listen();
  void end();
  bool isListening() { return this == active_object; }
  bool stopListening();
  bool overflow() { bool ret = _buffer_overflow; if (ret) _buffer_overflow = false; return ret; }
  int peek();

  virtual size_t write(uint8_t byte);
  virtual int read();
  virtual int available();
  virtual void flush();
  operator bool() { return true; }

  using Print::write;

  // public only for easy access by interrupt handlers
  static inline void handle_interrupt() __attribute__((__always_inline__));
};

// Arduino 0012 workaround
#undef int
#undef char
#undef long
#undef byte
#undef float
#undef abs
#undef round

#endif

The file mySoftwareSerial.cpp, also taken from the github page:
/*
SoftwareSerial.cpp (formerly NewSoftSerial.cpp) -
Multi-instance software serial library for Arduino/Wiring
-- Interrupt-driven receive and other improvements by ladyada
   (http://ladyada.net)
-- Tuning, circular buffer, derivation from class Print/Stream,
   multi-instance support, porting to 8MHz processors,
   various optimizations, PROGMEM delay tables, inverse logic and
   direct port writing by Mikal Hart (http://www.arduiniana.org)
-- Pin change interrupt macros by Paul Stoffregen (http://www.pjrc.com)
-- 20MHz processor support by Garrett Mace (http://www.macetech.com)
-- ATmega1280/2560 support by Brett Hagman (http://www.roguerobotics.com/)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
The latest version of this library can always be found at
http://arduiniana.org.
*/

// When set, _DEBUG co-opts pins 11 and 13 for debugging with an
// oscilloscope or logic analyzer.  Beware: it also slightly modifies
// the bit times, so don't rely on it too much at high baud rates
#define _DEBUG 0
#define _DEBUG_PIN1 11
#define _DEBUG_PIN2 13
//
// Includes
//
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <Arduino.h>
#include "mySoftwareSerial.h"
#include <util/delay_basic.h>

//
// Statics
//
SoftwareSerial *SoftwareSerial::active_object = 0;
uint8_t SoftwareSerial::_receive_buffer[_SS_MAX_RX_BUFF];
volatile uint8_t SoftwareSerial::_receive_buffer_tail = 0;
volatile uint8_t SoftwareSerial::_receive_buffer_head = 0;

//
// Debugging
//
// This function generates a brief pulse
// for debugging or measuring on an oscilloscope.
#if _DEBUG
inline void DebugPulse(uint8_t pin, uint8_t count)
{
  volatile uint8_t *pport = portOutputRegister(digitalPinToPort(pin));

  uint8_t val = *pport;
  while (count--)
  {
    *pport = val | digitalPinToBitMask(pin);
    *pport = val;
  }
}
#else
inline void DebugPulse(uint8_t, uint8_t) {}
#endif

//
// Private methods
//

/* static */
inline void SoftwareSerial::tunedDelay(uint16_t delay) {
  _delay_loop_2(delay);
}

// This function sets the current object as the "listening"
// one and returns true if it replaces another
bool SoftwareSerial::listen()
{
  if (!_rx_delay_stopbit)
    return false;

  if (active_object != this)
  {
    if (active_object)
      active_object->stopListening();

    _buffer_overflow = false;
    _receive_buffer_head = _receive_buffer_tail = 0;
    active_object = this;

    setRxIntMsk(true);
    return true;
  }

  return false;
}

// Stop listening. Returns true if we were actually listening.
bool SoftwareSerial::stopListening()
{
  if (active_object == this)
  {
    setRxIntMsk(false);
    active_object = NULL;
    return true;
  }
  return false;
}

//
// The receive routine called by the interrupt handler
//
void SoftwareSerial::recv()
{

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Preserve the registers that the compiler misses
// (courtesy of Arduino forum user *etracer*)
  asm volatile(
    "push r18 \n\t"
    "push r19 \n\t"
    "push r20 \n\t"
    "push r21 \n\t"
    "push r22 \n\t"
    "push r23 \n\t"
    "push r26 \n\t"
    "push r27 \n\t"
    ::);
#endif

  uint8_t d = 0;

  // If RX line is high, then we don't see any start bit
  // so interrupt is probably not for us
  if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
  {
    // Disable further interrupts during reception, this prevents
    // triggering another interrupt directly after we return, which can
    // cause problems at higher baudrates.
    setRxIntMsk(false);

    // Wait approximately 1/2 of a bit width to "center" the sample
    tunedDelay(_rx_delay_centering);
    DebugPulse(_DEBUG_PIN2, 1);

    // Read each of the 8 bits
    for (uint8_t i=8; i > 0; --i)
    {
      tunedDelay(_rx_delay_intrabit);
      d >>= 1;
      DebugPulse(_DEBUG_PIN2, 1);
      if (rx_pin_read())
        d |= 0x80;
    }

    if (_inverse_logic)
      d = ~d;

    // if buffer full, set the overflow flag and return
    uint8_t next = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF;
    if (next != _receive_buffer_head)
    {
      // save new data in buffer: tail points to where byte goes
      _receive_buffer[_receive_buffer_tail] = d; // save new byte
      _receive_buffer_tail = next;
    }
    else
    {
      DebugPulse(_DEBUG_PIN1, 1);
      _buffer_overflow = true;
    }

    // skip the stop bit
    tunedDelay(_rx_delay_stopbit);
    DebugPulse(_DEBUG_PIN1, 1);

    // Re-enable interrupts when we're sure to be inside the stop bit
    setRxIntMsk(true);

  }

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Restore the registers that the compiler misses
  asm volatile(
    "pop r27 \n\t"
    "pop r26 \n\t"
    "pop r23 \n\t"
    "pop r22 \n\t"
    "pop r21 \n\t"
    "pop r20 \n\t"
    "pop r19 \n\t"
    "pop r18 \n\t"
    ::);
#endif
}

uint8_t SoftwareSerial::rx_pin_read()
{
  return *_receivePortRegister & _receiveBitMask;
}

//
// Interrupt handling
//

/* static */
inline void SoftwareSerial::handle_interrupt()
{
  if (active_object)
  {
    active_object->recv();
  }
}

#if defined(PCINT0_vect)
ISR(PCINT0_vect)
{
  SoftwareSerial::handle_interrupt();
}
#endif

#if defined(PCINT1_vect)
ISR(PCINT1_vect, ISR_ALIASOF(PCINT0_vect));
#endif

#if defined(PCINT2_vect)
ISR(PCINT2_vect, ISR_ALIASOF(PCINT0_vect));
#endif

#if defined(PCINT3_vect)
ISR(PCINT3_vect, ISR_ALIASOF(PCINT0_vect));
#endif

//
// Constructor
//
SoftwareSerial::SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic /* = false */) :
  _rx_delay_centering(0),
  _rx_delay_intrabit(0),
  _rx_delay_stopbit(0),
  _tx_delay(0),
  _buffer_overflow(false),
  _inverse_logic(inverse_logic)
{
  setTX(transmitPin);
  setRX(receivePin);
}

//
// Destructor
//
SoftwareSerial::~SoftwareSerial()
{
  end();
}

void SoftwareSerial::setTX(uint8_t tx)
{
  // First write, then set output. If we do this the other way around,
  // the pin would be output low for a short while before switching to
  // output high. Now, it is input with pullup for a short while, which
  // is fine. With inverse logic, either order is fine.
  digitalWrite(tx, _inverse_logic ? LOW : HIGH);
  pinMode(tx, OUTPUT);
  _transmitBitMask = digitalPinToBitMask(tx);
  uint8_t port = digitalPinToPort(tx);
  _transmitPortRegister = portOutputRegister(port);
}

void SoftwareSerial::setRX(uint8_t rx)
{
  pinMode(rx, INPUT);
  if (!_inverse_logic)
    digitalWrite(rx, HIGH);  // pullup for normal logic!
  _receivePin = rx;
  _receiveBitMask = digitalPinToBitMask(rx);
  uint8_t port = digitalPinToPort(rx);
  _receivePortRegister = portInputRegister(port);
}

uint16_t SoftwareSerial::subtract_cap(uint16_t num, uint16_t sub) {
  if (num > sub)
    return num - sub;
  else
    return 1;
}

//
// Public methods
//

void SoftwareSerial::begin(long speed)
{
  _rx_delay_centering = _rx_delay_intrabit = _rx_delay_stopbit = _tx_delay = 0;

  // Precalculate the various delays, in number of 4-cycle delays
  uint16_t bit_delay = (F_CPU / speed) / 4;

  // 12 (gcc 4.8.2) or 13 (gcc 4.3.2) cycles from start bit to first bit,
  // 15 (gcc 4.8.2) or 16 (gcc 4.3.2) cycles between bits,
  // 12 (gcc 4.8.2) or 14 (gcc 4.3.2) cycles from last bit to stop bit
  // These are all close enough to just use 15 cycles, since the inter-bit
  // timings are the most critical (deviations stack 8 times)
  _tx_delay = subtract_cap(bit_delay, 15 / 4);

  // Only setup rx when we have a valid PCINT for this pin
  if (digitalPinToPCICR(_receivePin)) {
    #if GCC_VERSION > 40800
    // Timings counted from gcc 4.8.2 output. This works up to 115200 on
    // 16Mhz and 57600 on 8Mhz.
    //
    // When the start bit occurs, there are 3 or 4 cycles before the
    // interrupt flag is set, 4 cycles before the PC is set to the right
    // interrupt vector address and the old PC is pushed on the stack,
    // and then 75 cycles of instructions (including the RJMP in the
    // ISR vector table) until the first delay. After the delay, there
    // are 17 more cycles until the pin value is read (excluding the
    // delay in the loop).
    // We want to have a total delay of 1.5 bit time. Inside the loop,
    // we already wait for 1 bit time - 23 cycles, so here we wait for
    // 0.5 bit time - (71 + 18 - 22) cycles.
    _rx_delay_centering = subtract_cap(bit_delay / 2, (4 + 4 + 75 + 17 - 23) / 4);

    // There are 23 cycles in each loop iteration (excluding the delay)
    _rx_delay_intrabit = subtract_cap(bit_delay, 23 / 4);

    // There are 37 cycles from the last bit read to the start of
    // stopbit delay and 11 cycles from the delay until the interrupt
    // mask is enabled again (which _must_ happen during the stopbit).
    // This delay aims at 3/4 of a bit time, meaning the end of the
    // delay will be at 1/4th of the stopbit. This allows some extra
    // time for ISR cleanup, which makes 115200 baud at 16Mhz work more
    // reliably
    _rx_delay_stopbit = subtract_cap(bit_delay * 3 / 4, (37 + 11) / 4);
    #else // Timings counted from gcc 4.3.2 output
    // Note that this code is a _lot_ slower, mostly due to bad register
    // allocation choices of gcc. This works up to 57600 on 16Mhz and
    // 38400 on 8Mhz.
    _rx_delay_centering = subtract_cap(bit_delay / 2, (4 + 4 + 97 + 29 - 11) / 4);
    _rx_delay_intrabit = subtract_cap(bit_delay, 11 / 4);
    _rx_delay_stopbit = subtract_cap(bit_delay * 3 / 4, (44 + 17) / 4);
    #endif

    // Enable the PCINT for the entire port here, but never disable it
    // (others might also need it, so we disable the interrupt by using
    // the per-pin PCMSK register).
    *digitalPinToPCICR(_receivePin) |= _BV(digitalPinToPCICRbit(_receivePin));
    // Precalculate the pcint mask register and value, so setRxIntMask
    // can be used inside the ISR without costing too much time.
    _pcint_maskreg = digitalPinToPCMSK(_receivePin);
    _pcint_maskvalue = _BV(digitalPinToPCMSKbit(_receivePin));

    tunedDelay(_tx_delay); // if we were low this establishes the end
  }

#if _DEBUG
  pinMode(_DEBUG_PIN1, OUTPUT);
  pinMode(_DEBUG_PIN2, OUTPUT);
#endif

  listen();
}

void SoftwareSerial::setRxIntMsk(bool enable)
{
    if (enable)
      *_pcint_maskreg |= _pcint_maskvalue;
    else
      *_pcint_maskreg &= ~_pcint_maskvalue;
}

void SoftwareSerial::end()
{
  stopListening();
}

// Read data from buffer
int SoftwareSerial::read()
{
  if (!isListening())
    return -1;

  // Empty buffer?
  if (_receive_buffer_head == _receive_buffer_tail)
    return -1;

  // Read from "head"
  uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
  _receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
  return d;
}

int SoftwareSerial::available()
{
  if (!isListening())
    return 0;

  return (_receive_buffer_tail + _SS_MAX_RX_BUFF - _receive_buffer_head) % _SS_MAX_RX_BUFF;
}

size_t SoftwareSerial::write(uint8_t b)
{
  if (_tx_delay == 0) {
    setWriteError();
    return 0;
  }

  // By declaring these as local variables, the compiler will put them
  // in registers _before_ disabling interrupts and entering the
  // critical timing sections below, which makes it a lot easier to
  // verify the cycle timings
  volatile uint8_t *reg = _transmitPortRegister;
  uint8_t reg_mask = _transmitBitMask;
  uint8_t inv_mask = ~_transmitBitMask;
  uint8_t oldSREG = SREG;
  bool inv = _inverse_logic;
  uint16_t delay = _tx_delay;

  if (inv)
    b = ~b;

  cli();  // turn off interrupts for a clean txmit

  // Write the start bit
  if (inv)
    *reg |= reg_mask;
  else
    *reg &= inv_mask;

  tunedDelay(delay);

  // Write each of the 8 bits
  for (uint8_t i = 8; i > 0; --i)
  {
    if (b & 1) // choose bit
      *reg |= reg_mask; // send 1
    else
      *reg &= inv_mask; // send 0

    tunedDelay(delay);
    b >>= 1;
  }

  // restore pin to natural state
  if (inv)
    *reg &= inv_mask;
  else
    *reg |= reg_mask;

  SREG = oldSREG; // turn interrupts back on
  tunedDelay(_tx_delay);

  return 1;
}

void SoftwareSerial::flush()
{
  // There is no tx buffering, simply return
}

int SoftwareSerial::peek()
{
  if (!isListening())
    return -1;

  // Empty buffer?
  if (_receive_buffer_head == _receive_buffer_tail)
    return -1;

  // Read from "head"
  return _receive_buffer[_receive_buffer_head];
}

Use a scope to check levels on the TX of the BT module. Some HC-xx modules come with 3.3V levels which can make problems.
I would suggest using the same speed for the serial port and for the bt dongle. You have a glitch here, which may make problems:
while(BtDongle.available()) {
  unsigned char data = BtDongle.read();
  Serial.println(data, HEX);
}

Eventually, the Bluetooth module sends you data at a high bit rate. You get the first letter, then send it out to the PC at a lower bit rate. Sending it out to the PC takes as long time as the BT dongle sends four more characters.
Although there are serial buffers in the Arduino, this problem will easily cause a loss of data, as @Avamander has pointed out.
Based on your comment telling that you were able to get an endless mess from Putty, this can escalate to losing the sync on the RX from the BT module, and then further bits will start a new byte, giving you a total mess. However, OK must work, so you likely have also level problems.

I once had problems comunicating a GPS serial cable with an arduino.
Conecting the gps to the PC serial port COM1 everything was ok.
but the arduino was receiving strange characters.
The solution was seting inverse_logic to true, the 3rd argument of SoftwareSerial.
SoftwareSerial mySerial(10,11,true);
maybe someone else can explain why some protocols are inverse


text:
Arduino Simon Says with Midi Controller
I altered code for the Simple Simon says to work with a Midi controller instead of push buttons. i am having trouble with the input of the song sequence with the Midi Controller. during the time where the code is waiting for input from the Midi controller waitForButton(int delay) the notes being inputted should sound but it dose not . i need help in figuring this out. any advice would be appreciated. Here's my code :https://pastebin.com/dV73eF9U
const int PLAY = 1;
const int TRYAGIN = 2;
long currentMillis = 0;
long previousMillis = 0;
int state;
void songlearn(int tune);
void showsequence();
void readsequnce();
void incorrect();
int tune;

void loop() {
  if (state == PLAY) {
    showsequence();
    readsequnce();
  }
  else if (state == TRYAGIN) {
    incorrect();
    state = PLAY;
  }
}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
  data1 = MIDI.getData1();
  if (data1 == 48) { //C3
    Status[0][0] = 1;
    noteOn(0, data1, 100);
    input[0] = data1;
  }
  if (data1 == 49) { //C3#
    Status[0][1] = 1;
    noteOn(0, data1, 100);
    input[1] = data1;
  }
  if (data1 == 50) { //D3
    Status[0][2] = 1;
    noteOn(0, data1, 100);
    input[2] = data1;
  }
  if (data1 == 51) { //D3#
    Status[0][3] = 1;
    noteOn(0, data1, 100);
    input[3] = data1;
  }
  if (data1 == 52) { //E3
    Status[0][4] = 1;
    noteOn(0, data1, 100);
    input[4] = data1;
  }
  if (data1 == 53) { //F3
    Status[1][0] = 1;
    noteOn(0, data1, 100);
    input[5] = data1;
  }
  if (data1 == 54) { //F3#
    Status[1][1] = 1;
    noteOn(0, data1, 100);
    input[6] = data1;
  }
  if (data1 == 55) { //G3
    Status[1][2] = 1;
    noteOn(0, data1, 100);
    input[7] = data1;
  }
  if (data1 == 56) { //G3#
    Status[1][3] = 1;
    noteOn(0, data1, 100);
    input[8] = data1;
  }
  if (data1 == 57) { //A3
    Status[1][4] = 1;
    noteOn(0, data1, 100);
    input[9] = data1;
  }
  if (data1 == 58) { //A3#
    Status[2][0] = 1;
    noteOn(0, data1, 100);
    input[10] = data1;
  }
  if (data1 == 59) { //B3
    Status[2][1] = 1;
    noteOn(0, data1, 100);
    input[11] = data1;
  }
  if (data1 == 60) { //C4
    Status[2][2] = 1;
    noteOn(0, data1, 100);
    input[12] = data1;
  }
  if (data1 == 61) { //C4#
    Status[2][3] = 1;
    noteOn(0, data1, 100);
    input[13] = data1;
  }
  if (data1 == 62) { //D4
    Status[2][4] = 1;
    noteOn(0, data1, 100);
    input[14] = data1;
  }
  if (data1 == 63) { //D4#
    Status[3][0] = 1;
    noteOn(0, data1, 100);
    input[15] = data1;
  }
  if (data1 == 64) { //E4
    Status[3][1] = 1;
    noteOn(0, data1, 100);
    input[16] = data1;
  }
  if (data1 == 65) { //F4
    Status[3][2] = 1;
    noteOn(0, data1, 100);
    input[17] = data1;
  }
  if (data1 == 66) { //F4#
    Status[3][3] = 1;
    noteOn(0, data1, 100);
    input[18] = data1;
  }
  if (data1 == 67) { //G4
    Status[3][4] = 1;
    noteOn(0, data1, 100);
    input[19] = data1;
  }
  if (data1 == 68) { //G4#
    Status[4][0] = 1;
    noteOn(0, data1, 100);
    input[20] = data1;
  }
  if (data1 == 69) { //A4
    Status[4][1] = 1;
    noteOn(0, data1, 100);
    input[21] = data1;
  }
  if (data1 == 70) { //A4#
    Status[4][2] = 1;
    noteOn(0, data1, 100);
    input[22] = data1;
  }
  if (data1 == 71) { //B4
    Status[4][3] = 1;
    noteOn(0, data1, 100);
    input[23] = data1;
  }
  if (data1 == 72) { //C5
    Status[4][4] = 1;
    noteOn(0, data1, 100);
    input[24] = data1;
  }
}

void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {
  data1 = MIDI.getData1();
  if (data1 == 48) { //C3
    Status[0][0] = 0;
    noteOff(0, data1, 100);
    input[0] = 0;
  }
  if (data1 == 49) { //C3#
    Status[0][1] = 0;
    noteOff(0, data1, 100);
    input[1] = 0;
  }
  if (data1 == 50) { //D3
    Status[0][2] = 0;
    noteOff(0, data1, 100);
    input[2] = 0;
  }
  if (data1 == 51) { //D3#
    Status[0][3] = 0;
    noteOff(0, data1, 100);
    input[3] = 0;
  }
  if (data1 == 52) { //E3
    Status[0][4] = 0;
    noteOff(0, data1, 100);
    input[4] = 0;
  }
  if (data1 == 53) { //F3
    Status[1][0] = 0;
    noteOff(0, data1, 100);
    input[5] = 0;
  }
  if (data1 == 54) { //F3#
    Status[1][1] = 0;
    noteOff(0, data1, 100);
    input[6] = 0;
  }
  if (data1 == 55) { //G3
    Status[1][2] = 0;
    noteOff(0, data1, 100);
    input[7] = 0;
  }
  if (data1 == 56) { //G3#
    Status[1][3] = 0;
    noteOff(0, data1, 100);
    input[8] = 0;
  }
  if (data1 == 57) { //A3
    Status[1][4] = 0;
    noteOff(0, data1, 100);
    input[9] = 0;
  }
  if (data1 == 58) { //A3#
    Status[2][0] = 0;
    noteOff(0, data1, 100);
    input[10] = 0;
  }
  if (data1 == 59) { //B3
    Status[2][1] = 0;
    noteOff(0, data1, 100);
    input[11] = 0;
  }
  if (data1 == 60) { //C4
    Status[2][2] = 0;
    noteOff(0, data1, 100);
    input[12] = 0;
  }
  if (data1 == 61) { //C4#
    Status[2][3] = 0;
    noteOff(0, data1, 100);
    input[13] = 0;
  }
  if (data1 == 62) { //D4
    Status[2][4] = 0;
    noteOff(0, data1, 100);
    input[14] = 0;
  }
  if (data1 == 63) { //D4#
    Status[3][0] = 0;
    noteOff(0, data1, 100);
    input[15] = 0;
  }
  if (data1 == 64) { //E4
    Status[3][1] = 0;
    noteOff(0, data1, 100);
    input[16] = 0;
  }
  if (data1 == 65) { //F4
    Status[3][2] = 0;
    noteOff(0, data1, 100);
    input[17] = 0;
  }
  if (data1 == 66) { //F4#
    Status[3][3] = 0;
    noteOff(0, data1, 100);
    input[18] = 0;
  }
  if (data1 == 67) { //G4
    Status[3][4] = 0;
    noteOff(0, data1, 100);
    input[19] = 0;
  }
  if (data1 == 68) { //G4#
    Status[4][0] = 0;
    noteOff(0, data1, 100);
    input[20] = 0;
  }
  if (data1 == 69) { //A4
    Status[4][1] = 0;
    noteOff(0, data1, 100);
    input[21] = 0;
  }
  if (data1 == 70) { //A4#
    Status[4][2] = 0;
    noteOff(0, data1, 100);
    input[22] = 0;
  }
  if (data1 == 71) { //B4
    Status[4][3] = 0;
    noteOff(0, data1, 100);
    input[23] = 0;
  }
  if (data1 == 72) { //C5
    Status[4][4] = 0;
    noteOff(0, data1, 100);
    input[24] = 0;
  }
}

//Send a MIDI note-on message.  Like Pressing a piano key
void noteOn(byte channel, byte note, byte attack_velocity) {
  talkMIDI( (0x90 | channel), note, attack_velocity);
}

//Send a MIDI note-off message.  Like releasing a piano key
void noteOff(byte channel, byte note, byte release_velocity) {
  talkMIDI( (0x80 | channel), note, release_velocity);
}

//Plays a MIDI note. Doesn't check to see that cmd is greater than 127, or that data values are less than 127
void talkMIDI(byte cmd, byte data1, byte data2) {
  mySerial.write(cmd);
  mySerial.write(data1);
  //Some commands only have one data byte. All cmds less than 0xBn have 2 data bytes
  //(sort of: http://253.ccarh.org/handout/midiprotocol/)
  if ( (cmd & 0xF0) <= 0xB0)
    mySerial.write(data2);
}

void playNote(int midi, int row, int col, int len, bool short_led = false)
{
  int len1, len2;
  if (short_led) {
    len1 = len * 3 / 4;
    len2 = len * 1 / 4;
  } else {
    len1 = len;
    len2 = 0;
  }
  noteOn(0x90, midi, 100);
  digitalWrite(LedR[row], HIGH);
  digitalWrite(LedC[col], LOW);
  delay(len1);
  digitalWrite(LedR[row], LOW);
  digitalWrite(LedC[col], HIGH);
  delay(len2);
  noteOff(0x90, midi, 0);
}

void songlearn (int tune) {
  if (tune == 1) {

    lcd.clear();
    lcd.setCursor(4, 0);
    lcd.print("Learning Song :");// Print a message to the LCD.
    lcd.setCursor(1, 1);
    lcd.print(menuP1);

    //Plays Mary Had a Little Lamb on a loop at 145 BPM

    //Bar 1
    note[0] = 0x40;
    note[1] = 0x3e;
    note[2] = 0x3c;
    note[3] = 0x3e;
    //Bar 2
    note[4] = 0x40;
    note[5] = 0x40;
    note[6] = 0x40;
    //Bar 3
    note[7] = 0x3e;
    note[8] = 0x3e;
    note[9] = 0x3e;
    //Bar 4
    note[10] = 0x40;
    note[11] = 0x43;
    note[12] = 0x43;
    //Bar 5
    note[13] = 0x40;
    note[14] = 0x3e;
    note[15] = 0x3c;
    note[16] = 0x3e;
    //Bar 6
    note[17] = 0x40;
    note[18] = 0x40;
    note[19] = 0x40;
    note[20] = 0x40;
    //Bar 7
    note[21] = 0x3e;
    note[22] = 0x3e;
    note[23] = 0x40;
    note[24] = 0x3e;
    //Bar 8
    note[25] = 0x3c;
    //End song
  }
}

void (*SongSeq[x])() =
{ //Bar 1
  [] { playNote(0x40, 3, 1, 414); } ,//Quarter note: E
  [] { playNote(0x3e, 2, 4, 414); } ,//Quarter note: D
  [] { playNote(0x3c, 2, 2, 414); } ,//Quarter note: C
  [] { playNote(0x3e, 2, 4, 414); } ,//Quarter note: D
  //Bar 2
  [] {playNote(0x40, 3, 1, 414, 1);} , //Quarter note: E
  [] {playNote(0x40, 3, 1, 414, 1); }, //Quarter note: E
  [] {playNote(0x40, 3, 1, 828, 1); }, //Half note: E
  //Bar 3
  []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
  []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
  []{playNote(0x3e, 2, 4, 828, 1);}, //Half note: D
  //Bar 4
  []{playNote(0x40, 3, 1, 414);}, //Quarter note: E
  []{playNote(0x43, 3, 4, 414, 1);}, //Quarter note: G
  []{playNote(0x43, 3, 4, 828, 1);}, //Half note: G
  //Bar 5
  []{playNote(0x40, 3, 1, 414);}, //Quarter note: E
  []{playNote(0x3e, 2, 4, 414);}, //Quarter note: D
  []{playNote(0x3c, 2, 2, 414);}, //Quarter note: C
  []{playNote(0x3e, 2, 4, 414);}, //Quarter note: D
  //Bar 6
  []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
  []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
  []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
  []{playNote(0x40, 3, 1, 414, 1);}, //Quarter note: E
  //Bar 7
  []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
  []{playNote(0x3e, 2, 4, 414, 1);}, //Quarter note: D
  []{playNote(0x40, 3, 1, 414);}, //Quarter note: E
  []{playNote(0x3e, 2, 4, 414);}, //Quarter note: D
  //Bar 8
  []{playNote(0x3c, 2, 2, 1656);}, //Whole note: C
  //End song

};

void showsequence() {
  //Add a new index to the end of the songseq
  SongSeq[largestindex];
  largestindex++;
  //loop through the songseq
  for (int index = 0; index < largestindex; index++) {
    SongSeq[index]();
  }
}

void readsequnce() {
  bool mademistake = false;
  int key;
  for (int index = 0; index < largestindex & mademistake == false; index++) {
    key = waitForButton(5000);
    if (key == -1 | key != note[index]) {
      mademistake = true;
      SongSeq[index]();
      SongSeq[index]();
      state = 2;
    }
  }
}

int waitForButton(int delay)
{
  int keyPressed = -1;
  int check;
  boolean keyBackUp = false;

  currentMillis = millis();      // The number of ms since the program started running
  previousMillis = currentMillis;   // Records the point when we start spinning the loop.

  // Keep spinning the loop until "delay" seconds have passed.
  while (currentMillis - previousMillis < delay & keyBackUp == false)
  {
    // Read the button and record when it has been pushed down.
    for (int i = 0; i < 25 & keyBackUp == false; i++)
    {
      if (input[i] != 0)
      {
        keyPressed = input[i];

        // Show the LED pushed.
        noteOn(0, keyPressed, 100);
        //  digitalWrite(leds[pin], HIGH);

        // It is possible the button is still being pushed.
        // This loop spins until the button is let up.
        while (currentMillis - previousMillis < delay & keyBackUp == false)
        {
          check = input[i];
          if (check == 0)
          {
            keyBackUp = true;
          }
          currentMillis = millis();
        }

        // Turn the LED pushed off.
        noteOff(0, keyPressed, 0);
        // digitalWrite(leds[pin], LOW);

        // See if they took to long.
        if (currentMillis - previousMillis > delay)
        {
          keyPressed = -1; // They took to long to let the button up so they lose.
        }
      }
    }

    currentMillis = millis();

  }

  return keyPressed;
}

Include the properly formatted code into the question. And your incomplete code is missing two }.

the proper code has been added

Please run your code through the formatter in the Arduino IDE. It's very difficult to read right now due to poor formatting, that discourages people from reading enough of it to answer your question. (It certainly discouraged me! I gave up trying to read it.) It's worth spending time on making your posts easy to read if you want people to take the time to answer.

@CurtJ.Sampson thanks for letting me know i set the auto format in the arduino IDE. i hope its easier to read now.

It's considerably better, but there are still some things you should do manually, such as adding blank lines between functions. (I've submitted an edit for that.) Now that I can read it, I can see that the code is incomplete: for example you have no init() function, no definitions of state or Status, PLAY, TRYAGIN, etc. You really need to cut down the program to much smaller size (e.g., by removing most of the keys) and post the complete smaller version. Also, you say you altered some code; where is the original code?

@CurtJ.Sampson the Original code : https://gist.github.com/anonymous/58f817ed9b9b8b155d51a49c015370b9

I notice that nothing in the code you posted calls the MyHandleNoteOn() function, which is the only thing that reads MIDI data in the code you posted.
The waitForButton() function where you say you're having the problem never does any input or output, it simply checks to see if something else has changed the input array. MyHandleNoteOn() above does change it.
This leads me to believe that code you haven't posted sets up an interrupt handler that calls MyHandleNoteOn() (and probably MyHandleNodeOff()). If that doesn't mean anything to you, the main problem here is that the program is a bit beyond your abilities and you need to start learning on something simpler. If it does mean something to you, the problem here is that the program is rather badly written and you need to write something simpler to practice using interrupts and shared memory communication.
Have you written simpler programs before that read MIDI events, do a bit of processing, and play back things based on that? Building a Simon Says game on top of that would be a good learning project.

yes i have written simpler programs for midi. the MyHandleNoteOn() &  MyHandleNodeOff() both are functions from the midi library  and are called when the keys on the midi controller are pressed.

Did your MIDI code use in-memory communication between interrupt handlers and your main loop? If not, you want to write some simpler programs that do that first, if you're going to use that technique. Alternatively, you could write a Simon Says game on top of non-interrupt-driven code that uses wait-loops (which would look quite different from the above). Either way, if you have further questions, pare your code down to the bare minimum that demonstrates the problem so that others can load it up and run it.

maybe my approach is off  how would you go about it ?

Start as small and as basic as I could, and then expand from there.

source: Stack Exchange

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

authors: Сергей Измалков

sort: votes


text:
waiting for a set number of inputs in an array to be reached
How do i have code wait for an x number of inputs be reached in an array before doing anything else?
int largestindex = 0;
int learnindex=0;

    void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
    learn[learnindex]=pitch;
     learnindex++;
    }

    while(learn[largestindex]==0){
          MIDI.read();
          if (learn[largestindex]!=0){
           break;
              }

Can you provide some example code of what you have so far?

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.  Also link to whatever MIDI library you use.  Does MIDI.read(); affect any of the variables mentioned in the snippet?

If the call to MIDI.read() is a blocking call (it stays in there until it has a value) then you are pretty close:
const int NumberOfInputs (42);
for (int index = 0; index < NumberOfInputs; ++index)
{
    MIDI.read();
}

You can simplify you handler by post incrementing the learnindex counter as you use it.  (Post increment will happen after the value has been 'used')
void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
{
    learn[learnindex++] = pitch;
}

When you increment a variable on its own line its usually better to pre increment it, because you aren't using the value and it might result in quicker execution.  However remember you are increasing the value before using it, so if you use it as above you end up accessing the array element one higher than you intended to!
int learnIndex = 0;
++learnindex;            // Pre-increment it to 1
learn[learnIndex++] = 1; // Set element 1 to 1.
learn[++learnIndex] = 3; // Set element 3 to 3.

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


text:
comparing the entries of two arrays
i am trying to compare the elements of two arrays before the code goes on to the next sequence. The elements of note[x] are filled with the note values of a song. and i want to be able to input values from a midi controller into learn[x]. how can i compare array learn[ ]  to array note[ ] before the showsequence(); is incremented?
 const int x = 100;
    int note[x];
    int learn[x];
    int largestindex = 0;
    int learnindex=0;
    void showsequence();
    void readsequnce();
    const int PLAY = 1;
    const int TRYAGIN = 2;
    int state=0;

 void loop() {
     if (state == PLAY) {
        showsequence();
        readsequnce();
      }
      else if (state == TRYAGIN) {
        incorrect();
       }
     MIDI.read();
    }
    void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
    learn[learnindex]=pitch;
     learnindex++;
    }

 void showsequence() {
      //Add a new index to the end of the songseq
      SongSeq[largestindex];
      largestindex++;
      //loop through the songseq
      for (int index = 0; index < largestindex; index++) {
        SongSeq[index]();
      }
    }

      void readsequnce() {
      static uint16_t nextkey;
      bool mademistake = false;
       nextkey=0;
       learnindex=0;

       if (array_cmp(learn, note, largestindex, largestindex) == true){
               // do this if they are equal
               lcd.setCursor(16, 2);
        lcd.print("True");
         }else{
               // do this if they are different
               lcd.setCursor(16, 2);
        lcd.print("False");
         }
    }

 boolean array_cmp(int *a, int *b, int len_a, int len_b){
         int n;

         // if their lengths are different, return false
         if (len_a != len_b) return false;

         // test each element to be the same. if not, return false
         for (n=0;n<len_a;n++) if (a[n]!=b[n]) return false;

         //ok, if we have not returned yet, they are equal :)
         return true;
    }

It depends what sort of comparison you want to do.  If you want to see if note[x] == learn[x] then that's what you do.
If you want to see if all the notes match all of learn then you'll need to put the comparison in a loop.
for (int n = 0; n < MAX_NOTE && note[n] == learn[n]; ++n)
{
    // Empty loop
}

If you want to see if the first n notes match the current note and the proceeding n notes then its a bit more complex, but its just a loop.
int n = 0;
for (int l = currentPos;
(l > (currentPos - 10)) && (note[n] == learn[l]);
 l--, n++)
{
    // Empty loop
}

If it is something else you want, please can you try and describe it in idiot proof terms so I can understand it.

i want to compare note[x] == learn[x] but then once the compare is matches to compare note[x] == learn[x] (x going from 0->1) increasing  by 1 every time the match is correct

Then use the bottom example, but int n = x, int l = x and l++.  You will have to be careful about n and l exceeding the maximum index of the array/data, so add two extra conditions into the third line && n < maxData && l < maxData  (Need to set maxData to something sensible.

Start by assuming they match. Loop over each element pair, compare them, and set a flag when you find a pair that don't match.
bool they_match = true; // assume they match
for ( int i = 0; i < x; i++ ) { // for each note/learn element
  if ( note[i] != learn[i] ) { // check if they don't match
    they_match = false; // they don't mach, so set flag
    break; // stop looping
  }
}

At the end they_match will be true if note[] and learn[] match, or false if they don't.
I would suggest you learn how control structures work.
https://www.cs.fsu.edu/~myers/c++/notes/control1.html
https://www.cs.fsu.edu/~myers/c++/notes/control2.html

authors: สุนธร ขําอนันต์


text:
Data logging speed with arduino
I am trying to make some data logging conserining physiological data coming from a bitalino.
My problem is that I would like to collect samples at something like 1 kHz, that is the rate that the bitalino can read the sensors, but I think that the time needed
to write this data to the SD card can't keep up with the speed, and here is why i think that:
I put in the script some timers to check what was consuming the time causing to low sample rate, resulting:
Bitalino: 0, SD: 27
Bitalino: 0, SD: 28
Bitalino: 2, SD: 26
Bitalino: 0, SD: 29

Being that the time in miliseconds.
void loop() {
    time = millis();
    readBIT();
    time2 = millis();
    printDataSD();
    time3 = millis();
    printData();
}

void printData() //Send the data acquired to the pc through the serial port
{
  Serial.print("Bitalino: ");
  Serial.print(time2-time);
  Serial.print(", SD: ");
  Serial.println(time3-time2);
}

void printDataSD() //Send the data acquired to the SD Card
{
    if (myFile) {
    //Bitalino
    myFile.print(_ECG);
    myFile.print(",");
    myFile.print(_EMG);
    myFile.print(",");
    myFile.print(_EEG);
    myFile.print(",");
    myFile.print(_EDA);
    myFile.print(",");
    //Time
    myFile.println(time);
    myFile.flush();

    } else {
    Serial.print("error opening file, ");
    SD.begin(10);
    delay(1000);
  }
}

I would like to know if there is a way to improve my sample rate.
Thank you!
Here is the readBit() like asked:
void readBIT() //Read IMU data
 {
  _ECG = analogRead(ECG);
  _ECG = ((_ECG/1024) - 0.5)*Vcc*1000/gECG; //mV

 _EMG = analogRead(EMG);
 _EMG = ((_EMG/1024) - 0.5)*Vcc*1000/gEMG; //mV

 _EEG = analogRead(EEG);
 _EEG = ((_EEG/1024) - 0.5)*Vcc*1000000/gEEG; //uV

 _EDA = analogRead(EDA);
 _EDA = (_EDA/1024*Vcc-0.259388)/gEDA; // revolution
 }

The serial prints were just for debuging purpose, i intened to remove them before using the device. What do you mean by "write unncecessary data? _EEG is the name of the variable, being printed it is only the value read. How can I know when i need to flush? could i do it every 2,3,4,5 cicles?

You should consider buffering the sensor data. Basically set up a timer to read the sensor every millisecond and place the data in a buffer. Then you write to the SD card when the buffer's full. Your readBIT() function has to satisfy a few conditions for this to be possible though. We need to see it.

I added the readBit() function, but how can I know that the buffer is full?

The OP has likely solved this problem by now, but I know that others will be in the same position, so I am answering for them.
I routinely record ten channels of biological sensors including one of 16-bit sound at 8 kHz (plus the associated FFT data) to an SD card using arduino-compatible systems, so I doubt very much that the SD card writing per se is the problem.
Throughput to an SD card is a function of several variables.

To maximize write throughput you need to write full blocks of data at
the correct block size, since partial blocks take the same amount of
time as full blocks.
You also need to be ready with more data as soon as the SD card is
ready to take more, otherwise precious cycles slip away from you.
You need to ensure that your writes are non-blocking (don't try to
write more than the buffer can receive) so your loop can process and
queue up new data while the SD card is doing its thing.
You need to read any timing-sensitive sensors using interrupt service
routines that write their data either to a circular buffer or to one
of a group of two or three buffers that are cycled between being
filled and being emptied.

Printing debug statements to the serial port can take many tens of milliseconds in a loop that otherwise may take only a few microseconds. If you write more than the serial port buffer can hold, the call will be blocking and you will be at the mercy of the PC that's reading the serial port. This will always be bad enough to mess up the program you're trying to debug... I've encountered situations where this introduced delays of up to 10 seconds (the PC was misbehaving, but still...).
A quick improvement to printing debug statements is to maintain a loop counter and only print a debug statement every N loops.
The program in the original question uses a naive strategy in the sense that it acquires some amount of data and then immediately tries to write it to the SD card, waiting until the write is complete before trying to acquire new data. This will never work at high data rates for the reasons given above. If you use this approach, you are likely wasting 90% of your program cycles in waiting for the SD write and the Serial port write. If either one takes too long, you will miss the next data acquisition window.
My advice: your first step is to research and find or write a circular buffer library.
Then set a timer to call an interrupt service routine that acquires data and puts it into the circular buffer.
Write a loop routine that checks to see whether the SD card is available for writing, and then takes just enough data out of the circular buffer to fit in a single block write for your SD card (look at the documentation for the card adaptor and the card).
At that point you will know whether your system can keep up with your needs.
It's possible that your SD card writing itself is OK but your Arduino is having trouble keeping up either because it's too slow or because you don't have enough room for a sufficiently large circular buffer. I doubt this because I've recorded and played back audio at 8 KHz on the Uno, but then I don't know what else you need to accomplish in your program.
If you do determine that the Arduino itself is too slow or has insufficient memory, take a look at the Teensy series of boards [https://www.pjrc.com/teensy/index.html]. They are entirely compatible with Arduino libraries and IDE but they run hundreds of times faster than the Uno at a larger data width, plus they have oodles of RAM and a gazillion pins. They're also much smaller than the Arduino form factor and the community that uses them is very knowledgeable.
If it turns out that SD card write throughput is OK but that it requires more buffering than you have on-board, you can add an SPI ram breakout board for more fast buffering space.
Finally, if the amount of data you need to collect is so large and so continuous that you simply can't buffer it long enough to get it written out to SD, or if the SD card truly can't keep up, or if the data is larger than any available SD card, you may consider sending your data off the board in near-real-time. I send 10 hours of nightly data from a Teensy over a USB virtual serial port to the PC at about 3Mbps, and others have done better. Ethernet output is also available and can be at least an order of magnitude greater.
glhf!

Why not write a simple program and try to write values like 1, 2, 3 ... 100 to the SD card with a 1 second delay between writes. Then read the values back and send them via serial link to your PC screen.
This way you can make sure that you are writing and reading values in the correct way.
Once this works, you can reduce the delay and see what is the minimum delay between writes that the SD card will support.
It might be advisable to also write a program to fill the SD card with 100 values = 0 to clear it before the next test.

I played a bit with SD cards and on Teensy 3.5 it was 8ms Open/write/close


text:
Connection issues with TI CC3000 & Arduino Uno
I bought a CC3000 Wifi Shield from Sparkfun and attached it to Arduino Uno board.
As first thing I tested the board with the board test example:

SparkFun CC3000 - Board Test
CC3000 initialization complete
Firmware version: 1.24
MAC address: 70:FF:76:01:30:1E
Finished board test

Then I scanned the networks:

SparkFun CC3000 - Scan Test
CC3000 initialization complete
Scanning APs. Waiting for scan to complete.
Access Points found:
SSID: dnhm MAC address: 20:AA:4B:08:AA:CC RSSI: 58 Security: WPA2
SSID: dnhm-guest MAC address: 20:AA:4B:08:AA:CE RSSI: 58 Security: Unsecured
Finished scan test

I set the SSID and the password and tried to connect:

SparkFun CC3000 - Connection Test
CC3000 initialization complete
Connecting to: dnhm
Error: Could not connect to AP
Error: Could not obtain connection details
Error: Could not disconnect from network Finished connection test

SparkFun CC3000 - Connection Test
CC3000 initialization complete Connecting to: dnhm-guest
Error: Could not connect to AP
Error: Could not obtain connection details
Error: Could not disconnect from network
Finished connection test

It did not connect none of the available connections, I reserved an IP address on the router for the mac address, but nothing changed.
I turned on logs on the router (Linksys e2500) and nothing appeared in logs as if the device never tried to connect. (I can see relevant logs when I re-connect with my notebook)
I use wpa2 so I kept the security setting as it is. I also have a 5ghz SSID and it does not show up in the scan. So I did not try to connect to it.
I also tried the smart config example with my ipad and it did not work either, the output:

SparkFun CC3000 - SmartConfig
CC3000 initialization complete
Starting SmartConfig
Send connection details from app now!
Waiting to connect…
Error: Could not connect with SmartConfig
Error: Could not obtain connection details
Looking up IP address of: www.sparkfun.com
Error: Could not lookup host by name
Pinging 0.0.0.0 3 times…
Error: no ping response
Error: Could not disconnect from network
Finished SmartConfig test

Obviously the board works (It can scan/find the networks), but cant connect them. What should I do as next step to troubleshoot the issue?
Here is the sample I used for connection testing: (I double checked the protocol from router's wifi settings to make sure I'm using the correct one)
    /****************************************************************
ConnectionTest.ino
CC3000 Connection Test
Shawn Hymel @ SparkFun Electronics
January 30, 2014
https://github.com/sparkfun/SFE_CC3000_Library

Connects to the access point given by the SSID and password and
waits for a DHCP-assigned IP address. To use a static IP
address, change the #define USE_DHCP from 1 to 0 and assign an
IP address to static_ip_addr in the Constants section.

NOTE: Static IP is not working at this time.

The security mode is defined by one of the following:
WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA, WLAN_SEC_WPA2

Hardware Connections:

 Uno Pin    CC3000 Board    Function

 +5V        VCC or +5V      5V
 GND        GND             GND
 2          INT             Interrupt
 7          EN              WiFi Enable
 10         CS              SPI Chip Select
 11         MOSI            SPI MOSI
 12         MISO            SPI MISO
 13         SCK             SPI Clock

Resources:
Include SPI.h and SFE_CC3000.h

Development environment specifics:
Written in Arduino 1.0.5
Tested with Arduino UNO R3

This code is beerware; if you see me (or any other SparkFun
employee) at the local, and you've found our code helpful, please
buy us a round!

Distributed as-is; no warranty is given.
****************************************************************/

#include <SPI.h>
#include <SFE_CC3000.h>

// Pins
#define CC3000_INT      2   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       7   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno

// IP address assignment method
#define USE_DHCP        1   // 0 = static IP, 1 = DHCP

// Connection info data lengths
#define IP_ADDR_LEN     4   // Length of IP address in bytes
#define MAC_ADDR_LEN    6   // Length of MAC address in bytes

// Constants
char ap_ssid[] = "SSID";                  // SSID of network
char ap_password[] = "PASSWORD";          // Password of network
unsigned int ap_security = WLAN_SEC_WPA2; // Security of network
unsigned int timeout = 30000;             // Milliseconds
//const char static_ip_addr[] = "0.0.0.0";

// Global Variables
SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);

void setup() {

    ConnectionInfo connection_info;
    int i;

    // Initialize Serial port
    Serial.begin(115200);
    Serial.println();
    Serial.println("---------------------------------");
    Serial.println("SparkFun CC3000 - Connection Test");
    Serial.println("---------------------------------");

    // Initialize CC3000 (configure SPI communications)
    if ( wifi.init() ) {
        Serial.println("CC3000 initialization complete");
    } else {
        Serial.println("Something went wrong during CC3000 init!");
    }

#if (USE_DHCP == 1)
    // Connect using DHCP
    Serial.print("Connecting to: ");
    Serial.println(ap_ssid);
    if(!wifi.connect(ap_ssid, ap_security, ap_password, timeout)) {
        Serial.println("Error: Could not connect to AP");
    }
#elif (USE_DHCP == 0)
    // Connect using static IP
    // ***TODO: Connect using static IP
#endif

    // Print out connection details
    if( !wifi.getConnectionInfo(connection_info) ) {
        Serial.println("Error: Could not obtain connection details");
    } else {
        Serial.println("Connected!");
        Serial.println();

        // Print MAC address
        Serial.print("CC3000 MAC Address: ");
        for ( i = 0; i < MAC_ADDR_LEN; i++ ) {
            if ( connection_info.mac_address[i] < 0x10 ) {
                Serial.print("0");
            }
            Serial.print(connection_info.mac_address[i], HEX);
            if ( i < MAC_ADDR_LEN - 1 ) {
                Serial.print(":");
            }
        }
        Serial.println();

        // Print IP Address
        Serial.print("IP Address: ");
        printIPAddr(connection_info.ip_address);
        Serial.println();

        // Print subnet mask
        Serial.print("Subnet Mask: ");
        printIPAddr(connection_info.subnet_mask);
        Serial.println();

        // Print default gateway
        Serial.print("Default Gateway: ");
        printIPAddr(connection_info.default_gateway);
        Serial.println();

        // Print DHCP server address
        Serial.print("DHCP Server: ");
        printIPAddr(connection_info.dhcp_server);
        Serial.println();

        // Print DNS server address
        Serial.print("DNS Server: ");
        printIPAddr(connection_info.dns_server);
        Serial.println();

        // Print SSID
        Serial.print("SSID: ");
        Serial.println(connection_info.ssid);
        Serial.println();
    }

    // Disconnect
    if ( wifi.disconnect() ) {
        Serial.println("Disconnected");
    } else {
        Serial.println("Error: Could not disconnect from network");
    }

    // Done!
    Serial.println("Finished connection test");

}

void loop() {

    // Do nothing
    delay(1000);

}

// Print out an IP Address in human-readable format
void printIPAddr(unsigned char ip_addr[]) {
    int i;

    for (i = 0; i < IP_ADDR_LEN; i++) {
        Serial.print(ip_addr[i]);
        if ( i < IP_ADDR_LEN - 1 ) {
            Serial.print(".");
        }
    }
}

Could you share your sketch code? Also, are you setting the proper security mode, for the Connection Test Examples?

I added the source code into the question, it s the sample that comes with the library. I just replaced SSID and the password. I also checked & verified the security mode from router settings.


text:
Arduino Remote controlled RGB LED strip, having issues with brightness/dimming
I have this sketch:
#include <TimerOne.h>
#include <IRremote.h>
#include <RGBMood.h>

int RECV_PIN = 2;  // IR-Receiver PIN
int led = 13;       // Satus-LED PIN
int modus;          // Modus for Interrupt-Querry
int ledr = 11;       // RGB LED red PIN
int ledg = 12;       // RGB LED green PIN
int ledb = 13;       // RGB LED blue PIN
int SerialBuffer = 0;

RGBMood m(ledr, ledg, ledb);

int timerwert = 20;   // Timer time for Interrupt in ms

String readString;

// Color arrays
int black[3]  = { 0, 0, 0 };
int white[3]  = { 100, 100, 100 };
int red[3]    = { 100, 0, 0 };
int green[3]  = { 0, 100, 0 };
int blue[3]   = { 0, 0, 100 };
int yellow[3] = { 40, 95, 0 };
int dimWhite[3] = { 30, 30, 30 };

int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by
// etc.

// Set initial color
int redVal = black[0];
int grnVal = black[1];
int bluVal = black[2];

int wait = 10;      // 10ms internal crossFade delay; increase for slower fades
int hold = 0;       // Optional hold when a color is complete, before the next crossFade
int DEBUG = 1;      // DEBUG counter; if set to 1, will write values back via serial
int loopCount = 60; // How often should DEBUG report?
int repeat = 3;     // How many times should we loop before stopping? (0 for no stop)
int j = 0;          // Loop counter for repeat

// Initialize color variables
int prevR = redVal;
int prevG = grnVal;
int prevB = bluVal;

#define ON                0xF4F37A66
#define OFF               0x1363ADB4
#define BRIGHTNESS_UP     0xE6721691
#define BRIGHTNESS_DOWN   0xE9721B48
#define FLASH             0xFFF00F
#define STROBE            0xFFE817
#define FADE              0x39ED1255
#define SMOOTH            0xFFC837

#define RED               0x9D561314
#define GREEN             0XCB8E93A5
#define BLUE              0xC88E8EEC
#define WHITE             0x16DBBEE3

#define ORANGE            0xFFB04F
#define YELLOW_DARK       0xFFA857
#define YELLOW_MEDIUM     0xFF9867
#define YELLOW_LIGHT      0xFF8877

#define GREEN_LIGHT       0XFF30CF
#define GREEN_BLUE1       0XFF28D7
#define GREEN_BLUE2       0XFF18E7
#define GREEN_BLUE3       0XFF08F7

#define BLUE_RED          0XFF708F
#define PURPLE_DARK       0XFF6897
#define PURPLE_LIGHT      0XFF58A7
#define PINK              0XFF48B7

IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
  pinMode(ledr, OUTPUT); // Set RGB LED Pins as Output
  pinMode(ledg, OUTPUT); // Set RGB LED Pins as Output
  pinMode(ledb, OUTPUT); // Set RGB LED Pins as Output
  pinMode(led, OUTPUT); // set Status-LED as Output
  m.setMode(RGBMood::RANDOM_HUE_MODE);  // Automatic random fade.
  m.setHoldingTime(4000);  // Keep the same color for 4 seconds before fading again.
  m.setFadingSteps(150);   // Fade with 150 steps.
  m.setFadingSpeed(50);    // Each step last 50ms. A complete fade takes 50*150 = 7.5 seconds
  m.setHSB(random(359), 255, 255);

Serial.begin(9600);

  irrecv.enableIRIn(); // Start of IR-Recive

  Timer1.initialize(timerwert); // Initialisation of Timer-Interrupts
  Timer1.attachInterrupt(leseIR); // IR-Read from Interrupt
}

void leseIR(){
  if (irrecv.decode(&results)){
     irrecv.resume();  // Receive the next value
    switch (results.value)  {

      case FADE: // Modus Fade (DIY 4)
        modus = 1;
      break;

      case 0xFF906F: // Modus pcambi (DIY 5)
        modus = 2;
      break;

      case ON:  //Power
       modus = 0;
        crossFade(white);         // RGB LEDs Off
      break;
            case OFF:  //Power
       modus = 0;
        crossFade(black);         // RGB LEDs Off
      break;

      case BLUE:  //Blau 0,0,255
        modus = 0;
      crossFade(blue);
      break;

      case RED: //Rot
        modus = 0;
        crossFade(red);
      break;

      case GREEN://Grün
        modus = 0;
        crossFade(green);
      break;

      case WHITE: //Weiss
        modus = 0;
        crossFade(white);
      break;

      case BRIGHTNESS_UP: //DIMMING
        modus = 0;
        // fade in from min to max in increments of 5 points:
  for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
    // sets the value (range from 0 to 255):
    analogWrite(ledg, fadeValue);

  }

      break;

       case BRIGHTNESS_DOWN: //orange
        modus = 0;
      for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
    // sets the value (range from 0 to 255):
    analogWrite(ledg, fadeValue);
      }

      break;

      case 0xFFAA55://Grün mitrtel
        modus = 0;

      break;

      case 0xFF926D: //blau mittel
        modus = 0;

      break;

      case 0xFF12ED: //rosa
        modus = 0;

      break;

     }             // Switch END

  }

}

void loop() {
if(modus==1){    // Querry pb Modus:1
m.tick();
}

      Serial.println(results.value, HEX);
      Serial.println(DEC);
      Serial.println(DEC);
      Serial.println(DEC);

  }

  int calculateStep(int prevValue, int endValue) {
  int step = endValue - prevValue; // What's the overall gap?
  if (step) {                      // If its non-zero,
    step = 1020/step;              //   divide by 1020
  }
  return step;
}

/* The next function is calculateVal. When the loop value, i,
*  reaches the step size appropriate for one of the
*  colors, it increases or decreases the value of that color by 1.
*  (R, G, and B are each calculated separately.)
*/

int calculateVal(int step, int val, int i) {

  if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
    if (step > 0) {              //   increment the value if step is positive...
      val += 1;
    }
    else if (step < 0) {         //   ...or decrement it if step is negative
      val -= 1;
    }
  }
  // Defensive driving: make sure val stays in the range 0-255
  if (val > 255) {
    val = 255;
  }
  else if (val < 0) {
    val = 0;
  }
  return val;
}

/* crossFade() converts the percentage colors to a
*  0-255 range, then loops 1020 times, checking to see if
*  the value needs to be updated each time, then writing
*  the color values to the correct pins.
*/

void crossFade(int color[3]) {
  // Convert to 0-255
  int R = (color[0] * 255) / 100;
  int G = (color[1] * 255) / 100;
  int B = (color[2] * 255) / 100;

  int stepR = calculateStep(prevR, R);
  int stepG = calculateStep(prevG, G);
  int stepB = calculateStep(prevB, B);

  for (int i = 0; i <= 1020; i++) {
    redVal = calculateVal(stepR, redVal, i);
    grnVal = calculateVal(stepG, grnVal, i);
    bluVal = calculateVal(stepB, bluVal, i);

    analogWrite(ledr, redVal);   // Write current values to LED pins
    analogWrite(ledg, grnVal);
    analogWrite(ledb, bluVal);

    delay(wait); // Pause for 'wait' milliseconds before resuming the loop

  }
  // Update current values for next loop
  prevR = redVal;
  prevG = grnVal;
  prevB = bluVal;
  delay(hold); // Pause for optional 'wait' milliseconds before resuming the loop
}

It's working like a charm, the fade operates smoothly using timer1, the colors appear correct on led, but I can't fix the brightness part. Can  someone provide sample code to do this?
If anyone else wants to use the code, I'm using an Arduino Mega 2560, please use the same PINs as mine since timers works only on 11,12,13 on this Arduino. (link with pin info regarding several Arduino boards)

RGB mood library
TimerOne library
IR Library

I'm using a small Xbox 360 IR control (no numbers keypad), some HEX codes are left intact from the original sketch found on internet.
original topic

Whats wrong with the brightness part?

i cannot set the brightness of the leds. Maybe i should use the expression "dim" instead of brightness to make it more clear. If i set the color RED, i cannot dim it up or down, same aplies for GREEN and BLUE.

No 'brightness' was clear, I just couldn't tell what wasn't working from your question. :P

You don't have a delay in the fade loop, this goes from 0 to 255 almost instantly:
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
    // sets the value (range from 0 to 255):
    analogWrite(ledg, fadeValue);
}

But I'm not sure you want to fade from off to on in one go. If you want to just increment and decrement the brightness:
First notice that prevR, prevG, prevB hold the current led values. So we shall use them.
Change the switch case to:
case BRIGHTNESS_UP:
    modus = 0;
    int c[3];
    // decrease by 0.9*value but also take off 2 so we get to zero
    c[0] = (prevR-2) * 90 / 100;
    c[1] = (prevG-2) * 90 / 100;
    c[2] = (prevB-2) * 90 / 100;
    for( int j = 0; j < 3; j++ ) {
        if (c[j] < 0) c[j] = 0;
    }
    crossFade(c);
    break;

case BRIGHTNESS_DOWN:
    modus = 0;
    int c[3];
    // increase value by 1/0.9 but also add 2 so we get off zero
    c[0] = (prevR+2) * 100 / 90 + 2;
    c[1] = (prevG+2) * 100 / 90 + 2;
    c[2] = (prevB+2) * 100 / 90 + 2;
    for( int j = 0; j < 3; j++ ) {
        if (c[j] > 100) c[j] = 100;
    }
    crossFade(c);
    break;

I can't check this to see if it works see please test and see.
Edit
Different approach:
Global variable for brightness:
int brightness = 100;
int c[3];

Change this value each time:
case BRIGHTNESS_UP:
    modus = 0;
    brightness += 5;
    if (brightness > 255) brightness = 255;
    c[0] = prevR; c[1] = prevG; c[2] = prevB;
    crossFade(c);
    break;

case BRIGHTNESS_DOWN:
    modus = 0;
    brightness -= 5;
    if (brightness < 0) brightness = 0;
    c[0] = prevR; c[1] = prevG; c[2] = prevB;
    crossFade(c);
    break;

Then in crossFade we change the last few lines:
analogWrite(ledr, redVal * brightness / 255);   // Write current values to LED pins
analogWrite(ledg, grnVal * brightness / 255);
analogWrite(ledb, bluVal * brightness / 255);

Edit 2:
I think that what might be happening is that the color is reduced by brightness, then that reduced value is saved in prevR/G/B when actually it should just be the full brightness value. Try changing last bit of crossFade to :
prevR = color[0];
prevG = color[1];
prevB = color[2];

IDE reports that there is redeclaration of 'int c [3]

Try move int c[3] outside leseIR() and make it global. Delete all instances in the switch statement.

you might want to muck around with the ratios too, say use 80 instead of 90 and 5 instead of 2 etc. I tried to use a ratio because our eyes perceive brightness on a log scale, so a small change in low brightness is like a large change in high brightness.

i removed it, code compiled, but, when i press the brighntess up button the color fades to black (switches off) and when i press the brightness down then the color brights up to white after several button presses.

oops, i got BRIGHTNESS_UP and BRIGHTNESS_DOWN round the wrong way

see this question for some people's approach to getting brightness changes correct  http://electronics.stackexchange.com/questions/1983/correcting-for-non-linear-brightness-in-leds-when-using-pwm

The brightness might actually have to be made a separate variable and applied in crossFade

Hi, i've tried the edited approach, all colors dim to 0, with a single button press, no matter if press the up or down brightness. So, if i've chosen the GREEN color, it dims to 0, the same applies to all. Crossfade class do the following: When the selected color is RED and press the GREEN button, then RED dims down to 0 and GREEN dims up to 100. So my guess is that we must not use the Crossfade class to control brightness.

Hey could you make crossFade print out the colour and the R G B values and just check they look ok? e.g. Serial.println(colour[0],DEC); and so on.

RED button pressed results crossfade : 100,0,0 and color : 255,0,0 .  GREEN crossfade : 0,100,0 and color : 0,255,0 . BLUE crossfade : 0,0,100 and color : 0,0,255 . WHITE crossfade : 100,100,100 and color 255,255,255 . So everything seems ok.

Oh sorry, I meant for the brightness up / down with the code I posted. :)

I've moved the analogWrite part of the code inside the switch case BRIGHTNESS_UP & BRIGHTNESS_DOWN and it's working. I also removed the crossFade(c); line.
Here's the working code:
#include <TimerOne.h>
#include <IRremote.h>
#include <RGBMood.h>

int RECV_PIN = 2;  // IR-Receiver PIN
int led = 13;       // Satus-LED PIN
int modus;          // Modus for Interrupt-Querry
int ledr = 11;       // RGB LED red PIN
int ledg = 12;       // RGB LED green PIN
int ledb = 13;       // RGB LED blue PIN
int SerialBuffer = 0;
int c[3];

//RGB Pins Array
int CH[3] = {11, 12, 13};
int val[3] = {0, 0, 0}; // led brightness 0-255

RGBMood m(ledr, ledg, ledb);

int timerwert = 20;   // Timer time for Interrupt in ms

String readString;

// Color arrays
int black[3]  = { 0, 0, 0 };
int white[3]  = { 100, 100, 100 };
int red[3]    = { 100, 0, 0 };
int green[3]  = { 0, 100, 0 };
int blue[3]   = { 0, 0, 100 };
int yellow[3] = { 40, 95, 0 };
int dimWhite[3] = { 30, 30, 30 };

int brightness = 100;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by
// etc.

// Set initial color
int redVal = black[0];
int grnVal = black[1];
int bluVal = black[2];

int wait = 10;      // 10ms internal crossFade delay; increase for slower fades
int hold = 0;       // Optional hold when a color is complete, before the next crossFade
int DEBUG = 1;      // DEBUG counter; if set to 1, will write values back via serial
int loopCount = 60; // How often should DEBUG report?
int repeat = 3;     // How many times should we loop before stopping? (0 for no stop)
int j = 0;          // Loop counter for repeat

// Initialize color variables
int prevR = redVal;
int prevG = grnVal;
int prevB = bluVal;

#define ON                0xF4F37A66
#define OFF               0x1363ADB4
#define BRIGHTNESS_UP     0xE6721691
#define BRIGHTNESS_DOWN   0xE9721B48
#define FLASH             0xFFF00F
#define STROBE            0xFFE817
#define FADE              0x39ED1255
#define SMOOTH            0xFFC837

#define RED               0x9D561314
#define GREEN             0XCB8E93A5
#define BLUE              0xC88E8EEC
#define WHITE             0x16DBBEE3

#define ORANGE            0xFFB04F
#define YELLOW_DARK       0xFFA857
#define YELLOW_MEDIUM     0xFF9867
#define YELLOW_LIGHT      0xFF8877

#define GREEN_LIGHT       0XFF30CF
#define GREEN_BLUE1       0XFF28D7
#define GREEN_BLUE2       0XFF18E7
#define GREEN_BLUE3       0XFF08F7

#define BLUE_RED          0XFF708F
#define PURPLE_DARK       0XFF6897
#define PURPLE_LIGHT      0XFF58A7
#define PINK              0XFF48B7
#define MAX 255

IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
  pinMode(ledr, OUTPUT); // Set RGB LED Pins as Output
  pinMode(ledg, OUTPUT); // Set RGB LED Pins as Output
  pinMode(ledb, OUTPUT); // Set RGB LED Pins as Output
  pinMode(led, OUTPUT); // set Status-LED as Output
 //initiate rgb pins output
    for (int i=0; i<3; i++)
  {
    pinMode(CH[i], OUTPUT);
  }

  m.setMode(RGBMood::RANDOM_HUE_MODE);  // Automatic random fade.
  m.setHoldingTime(4000);  // Keep the same color for 4 seconds before fading again.
  m.setFadingSteps(150);   // Fade with 150 steps.
  m.setFadingSpeed(50);    // Each step last 50ms. A complete fade takes 50*150 = 7.5 seconds
  m.setHSB(random(359), 255, 255);

Serial.begin(9600);

  irrecv.enableIRIn(); // Start of IR-Recive

  Timer1.initialize(timerwert); // Initialisation of Timer-Interrupts
  Timer1.attachInterrupt(leseIR); // IR-Read from Interrupt
}

void leseIR(){
  if (irrecv.decode(&results)){
     irrecv.resume();  // Receive the next value
    switch (results.value)  {

      case FADE: // Modus Fade (DIY 4)
        modus = 1;
      break;

      case 0xFF906F: // Modus pcambi (DIY 5)
        modus = 2;
      break;

      case ON:  //Power
       modus = 0;
        crossFade(white);         // RGB LEDs Off
      break;
            case OFF:  //Power
       modus = 0;
        crossFade(black);         // RGB LEDs Off
      break;

      case BLUE:  //Blau 0,0,255
        modus = 0;
      crossFade(blue);
      break;

      case RED: //Rot
        modus = 0;
        crossFade(red);
      break;

      case GREEN://Grün
        modus = 0;
        crossFade(green);
      break;

      case WHITE: //Weiss
        modus = 0;
        crossFade(white);
      break;

      case BRIGHTNESS_UP: //DIMMING UP
        modus = 0;
    brightness += 5;
    if (brightness > 255) brightness = 255;
    c[0] = prevR; c[1] = prevG; c[2] = prevB;
    analogWrite(ledr, redVal * brightness / 255);   // Write current values to LED pins
    analogWrite(ledg, grnVal * brightness / 255);
    analogWrite(ledb, bluVal * brightness / 255);

      break;

       case BRIGHTNESS_DOWN: //DIMMING DOWN
         modus = 0;
    brightness -= 5;
    if (brightness < 0) brightness = 0;
    c[0] = prevR; c[1] = prevG; c[2] = prevB;
    analogWrite(ledr, redVal * brightness / 255);   // Write current values to LED pins
    analogWrite(ledg, grnVal * brightness / 255);
    analogWrite(ledb, bluVal * brightness / 255);

      break;

      case 0xFFAA55://Grün mitrtel
        modus = 0;
      break;

      case 0xFF926D: //blau mittel
        modus = 0;

      break;

      case 0xFF12ED: //rosa
        modus = 0;

      break;

     }             // Switch END

  }
}

void loop() {
if(modus==1){    // Querry pb Modus:1
m.tick();
}
if(modus==2){    // Querry pb Modus:1

}
        Serial.println(prevR);
        Serial.println(prevG);
        Serial.println(prevB);
//      Serial.println(results.value, HEX);
//      Serial.println(DEC);
//      Serial.println(DEC);
//      Serial.println(DEC);
//      Serial.print("channel 1,2,3 values:");              // sends  brightness values to the serial monitor
    //  for(int i=0; i<3; i++){                             // every time the remote is pressed
    //  Serial.print(CH[i]);
//      Serial.print("   ");
    // }
  }

  int calculateStep(int prevValue, int endValue) {
  int step = endValue - prevValue; // What's the overall gap?
  if (step) {                      // If its non-zero,
    step = 1020/step;              //   divide by 1020
  }
  return step;
}

/* The next function is calculateVal. When the loop value, i,
*  reaches the step size appropriate for one of the
*  colors, it increases or decreases the value of that color by 1.
*  (R, G, and B are each calculated separately.)
*/

int calculateVal(int step, int val, int i) {

  if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
    if (step > 0) {              //   increment the value if step is positive...
      val += 1;
    }
    else if (step < 0) {         //   ...or decrement it if step is negative
      val -= 1;
    }
  }
  // Defensive driving: make sure val stays in the range 0-255
  if (val > 255) {
    val = 255;
  }
  else if (val < 0) {
    val = 0;
  }
  return val;
}

/* crossFade() converts the percentage colors to a
*  0-255 range, then loops 1020 times, checking to see if
*  the value needs to be updated each time, then writing
*  the color values to the correct pins.
*/

void crossFade(int color[3]) {
  // Convert to 0-255
  int R = (color[0] * 255) / 100;
  int G = (color[1] * 255) / 100;
  int B = (color[2] * 255) / 100;

  int stepR = calculateStep(prevR, R);
  int stepG = calculateStep(prevG, G);
  int stepB = calculateStep(prevB, B);

  for (int i = 0; i <= 1020; i++) {
    redVal = calculateVal(stepR, redVal, i);
    grnVal = calculateVal(stepG, grnVal, i);
    bluVal = calculateVal(stepB, bluVal, i);

    analogWrite(ledr, redVal);   // Write current values to LED pins
    analogWrite(ledg, grnVal);
    analogWrite(ledb, bluVal);

    delay(wait); // Pause for 'wait' milliseconds before resuming the loop

  }
  // Update current values for next loop
  prevR = redVal;
  prevG = grnVal;
  prevB = bluVal;
  delay(hold); // Pause for optional 'wait' milliseconds before resuming the loop
}

thanks geometrikal for your support! You believe it's possible to manipulate the dimming of the fade effect too? It's using the RGBMood class to create a HSB color mix.


text:
Curious Collision between OneWire and RadioHead
The code below runs on an Arduino Pro Mini (8MHz 328p) sending temperature readings using an inexpensive ASK transmitter. I use OneWire to read the DS18B20s, and RadioHead to manage the radio.
The original problem was the send() calls at the top of the loop always worked, but the send() call in the temperature-reading loop never did.
The fix was to insert a call to setModeTx() ahead of the send() call. I'm pleased it works, but it's a hollow victory because I can't figure out why it works.
OneWire uses no timers and no interrupts. I wait for the temperature conversion using _delay_ms() which is a spin delay.
I've read and re-read the OneWire and RH_ASK code and am still puzzled. Can anyone explain?
Many thanks
Here's the gist of the code…
RH_ASK radio(1024, 0, 10, 0, false);
OneWire ow(2);

void loop()
{
    radio.send(/* build info */);     // always works
    radio.send(/* battery health */); // always works
    ow.reset_search();
    while (ow.search(addr))
    {
        read_thermometer(addr);

        // the following send() works ONLY
        // when preceded by setModeTx()
        // It *never* works without it
        radio.setModeTx();
        radio.send(/* one temp reading */);
    }
}

UPDATE
@timemage was correct in that there are also calls to Serial (which resolve to HardwareSerial) interspersed. I'm no closer to solving it; however, by rearranging calls I can get the failure to happen more- or less often.
In a way this highlights the distinction between diagnosis and repair. I may in the end discover an ordering of the calls that makes the failure exceedingly rare, and in this case the problem will have been repaired; though not diagnosed.

I would expect RH_ASK radio(1024, 0, 10, 0, false); to interfere with Serial, but I have no way of testing that. But, you don't appear to be using Serial, but then you indicate it's not the complete code. But then... I don't know why .setModeTx() would have the effect it's having. In any case, it's not clear to me that 0 can mean "unused" there and is maybe something to fix regardless.

@timemage you're on to something. I had earlier dismissed interaction with Serial, which as you surmise I am using. Still looking…

I'm not even sure I'd go that far. I've seen some libraries use -1 as an indicator of "not used" or "not applicable". What I did was look the RadioHead library to see how it would interpret it. For the benefit of anyone that thinks this is an "answer" I feel the need to spell this out: No it's not. At it's an observation of something that should probably be fixed regardless and may or may not have any bearing at all on the actual problem as stated in the question. I'm not going to write it an an answer because there's no particularly good reason to think it is the answer or even an answer.

If you find out that it helps and why, you can write your own answer, because you'll actually know that it's the answer and ideally why.

I could imagine two thngs that might happen (or not ;-)). First there is a code line somewhere in your code that configures the ASk driver for RX. Second the first two sends fill the write buffer and the third send does not work, because there is not enough place in the buffer to add the new data. The setModeTx might clean the buffer or simply needs some time the ASK driver needs to send the remaining data. Isn't there a waitPacketSent() method to wait before new data can be written? Perhaps worth I try???

I think @PeterPaulKiefer is onto something. The setModeTx() does clear _txIndex, _txBit, _txSample. And the transmitTimer() has a check if (_txIndex >= _txBufLen). Of course I am spitballing. But worth an investigation there.

If I am not mistaken, radiohead will use manchester encoding. This ensures there is always a transition. 0 is low to high and 1 is high to low. An unlucky series of 1's or 0's will not create a "flat" zone. Your signal trace looks like a proper Manchester encoded signal. Sorry I dont know the root cause of your problem. Is this packet longer than the other two that are usually successful? Sometimes the radio receivers are temperature sensitive. Try to put them in the freezer or near an oven and see if they get better or worse.
But it doesnt answer why a call to setModeTx() would fix the issue.

What if you do a similar trace again but this time with the call to setModeTx() before the actual send.

Finally had time to get back to this. I connected the data-out line from the sender to the data-in line of the receiver, and discovered it always works. So it's not any sort of collision between OneWire and RadioHead, curious or otherwise. There's something amiss with the radio link… but what?
Have a look at the following oscilloscope traces. The magenta line is the input to the transmitter. Cyan is the output from the receiver (an SYN480R if you're curious). Yellow is just there to trigger the scope (a digitalWrite() just before sending the problem message).
The packet from the transmitter begins with a series of training pulses for the receiver to establish things like gain and threshold for the demodulator. Thereafter, the data is encoded in a series of long and short pulses.
Note how the receiver (cyan line) syncs up with the training pulses, and is in lock-step with the transmitter... until ... IT GETS LOST and thinks everything is a zero for awhile. It eventually re-syncs with the transmitter, but by this point the packet is corrupt, gets rejected by the decoder, and that is why I'm losing the packet at the receiver.

But, one wonders, why this particular packet and not any of the others? The answer to that question is pretty much out of band for a software forum, but here goes. Let's add a trace to the scope display.
The following image includes the demodulator threshold in blue. That's an analog value that the demodulator uses to decide if it's looking at a one or a zero. For the SYN480R chip, it's the output of a low pass filter, which produces an average over the recent bits.
In this case, notice how the threshold rises during the early part of the packet, then settles down. My conjecture is there are too many ones in the packet encoding thus far (i.e. many more ones than zeroes), and this shifts the threshold high enough that the demodulator thinks everything it sees is a zero. This is confirmed in the previous image. Seeing all zeroes, the threshold settles down and the demodulator can sync up again.
Interestingly, just touching the scope probe to the threshold capacitor (to get the blue trace) disturbs the threshold enough to slow the rise and keep the packets working.
Thus, OneWire is definitely off the hook, as is any interaction with RadioHead. Moving on, I either need to make some tweaks to the RadioHead RH_ASK driver packet encoder, or change out the threshold capacitor in the receiver. That in itself is a balance, because you want it to be able to track changes in the received signal, yet not be so sensitive to packet encoding.
Hope you found this interesting. Many thanks to everyone who took a look and offered your insight.

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


text:
I2C seems to stop working when I attach an AF motor shield
I have a cheap MPU 6050 chip that communicates over 3.3V I2C. I can talk to it just fine on my Leonardo. If I add an additional Adafruit Motor shield (the old one), my MPU 6050 demo sketch hangs somewhere, and I get nothing back.
As far as I see, the pins I use for the I2C communication are not used at all by the motor shield.
What could be wrong here?
I have the MPU6050 connected to SCL, SDA, GND and 3.3V, the motor shield uses almost all other pins.
Additional Info:
I am using this sketch currently: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050
Update:
Lots of "Serial.println"s later, I've narrowed it down a bit. The example sketch above hangs on the statement "Wire.endTransmission();" on line 279 of the I2CDev library.
Update:
Connecting the motor shield to external power seems to fix my problem. Weird =) I am still interested in the reason for this behavior.

Did you modify the code at all? Can you isolate the problem to a small section of the sketch and include that? Does the 'blink' sketch work? Thanks!

With both the motor shield and the mpu 6050 connected, the blink sketch works fine. I can even talk via Serial.

So, it is something with your code. Can you post the minimum code required to reproduce this issue?

I'll try... this will take a while, since I don't understand one bit of what the MPU 6050 library linked above really does =)

Wait... didn't see your edit. Which example are you using?

The "raw" one. https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/Examples/MPU6050_raw/MPU6050_raw.ino

How are you powering the Arduino? Sounds like the motor shield is drawing too much power and thus the 3.3V output from the Arduino is dropping too low and stuffing up I2C. You can confirm with a multimeter

Motors draw large amounts of current, and will either cause your power supply voltage to sag if you draw more current than your power supply can support, or cause blips in the power supply that will cause you all sorts of problems.
You need to take steps to isolate the power from the motor shield from the power for the Arduino.
How are you powering the motor shield? How are you powering the Arduino?
If your power supply has enough current to support both your Arduino and your motors then you can probably solve the problem by adding an isolation capacitor between the Vin port on your Arduino and ground.
What that does is to filter out temporary variations in the input voltage that's being fed to the Arduino. Without it, the Vin voltage to the Arduino is probably dropping as your motor draws large pulses of current, and that causes the output from the voltage regulator to droop as well.
I don't know how to pick the rating of the cap. A trip to the Electrical Engineering stack exchange is probably in order.


text:
Connecting wires and coding in GPS Module GY-NEO6MV2 with ESP8266-01

Here is the link : https://www.circuito.io/app?components=10167,11021,12083,13678,13959,975601
I'm just a beginner I don't have the idea on how GPS module wires should be connected
#include "DHT.h"
#include "NewPing.h"
#include <SoftwareSerial.h>
#define DEBUG true
 SoftwareSerial esp8266(11,10);
  //SoftwareSerial gps(8,9);
 #define DHTPIN 2       // DHT-11 Output Pin connection
 #define DHTTYPE DHT11   // DHT Type is DHT 11 (AM2302)
 #define TRIGGER_PIN 4
 #define ECHO_PIN 3
 #define MAX_DISTANCE 400

 NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

 float hum;
 float temp;

 DHT dht(DHTPIN, DHTTYPE);

 void setup() {
 Serial.begin (9600);
 Serial.println("START");
 esp8266.listen();
 esp8266.begin(9600);
 gps.begin(9600);
 dht.begin();

  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  sendData("AT+RST\r\n",2000,DEBUG);            // command to reset the
  module
     sendData("AT+CWMODE=2\r\n",1000,DEBUG);       // This will configure
     the mode
     as access point
   sendData("AT+CIFSR\r\n",1000,DEBUG);          // This command will get
   the ip
   address
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG);       // This will configure the
  esp
for multiple connections
sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // This command will turn on
the
server on port 80
}

void loop()
{

 delay(2000);  // Delay so DHT-11 sensor can stabalize

 hum = dht.readHumidity();  // Get Humidity value
 temp= dht.readTemperature();  // Get Temperature value

  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);

long duration,distance;
duration= pulseIn(ECHO_PIN,HIGH);

distance = duration/58.2;

Serial.print("Humid: ");
Serial.print(hum);
Serial.print(" %, Temp: ");
Serial.print(temp);
Serial.print(" C, ");
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(50);

gps.listen();
while (gps.available())
Serial.write(gps.read());

esp8266.listen();
if(esp8266.available())         // This command will that check if the esp
    is sending a message
    {
    if(esp8266.find("+IPD,"))
    {
    delay(1000);

    int connectionId = esp8266.read()-48; /* We are subtracting 48 from the
    output because the read() function returns
                                        the ASCII decimal value and the
    first decimal number which is 0 starts at 48*/
     String webpage = "<meta http-equiv=\"refresh\" content=\"5;
     url=192.168.4.1/\">";
     webpage += "
Mabalacat City College Garbage Monitoring System
";
    webpage += "

";
    if (distance<=5)
    {
    webpage+= " Trash can is Red";
    }
    if (distance == 20)
    {
      webpage+= " Trash can is Orange";
      }
      if (distance == 35)
    {
      webpage+= " Trash can is Light Orange";
      }
      if (distance == 50)
    {
      webpage+= " Trash can is Yellow";
      }
      if (distance == 70)
    {
      webpage+= " Trash can is 2st Light Yellow";
      }
      if (distance == 85)
    {
      webpage+= " Trash can is 1st Light Yellow";
      }
      if (distance == 95)
    {
      webpage+= " Trash can is Green";
      }
      if (distance >= 100)
    {
      webpage+= " Trash can is Empty";
      }
      webpage+= "
";
      webpage+="Distance: ";
      webpage+=distance;
      webpage+=" cm";
      webpage+= "
";
      webpage+="Temperature: ";
      webpage+= temp;
      webpage+=" celsius";
      webpage+= "
";
      webpage+= "Humidity: ";
      webpage+= hum;
      webpage+= " %";

 webpage += "

";
 String cipSend = "AT+CIPSEND=";
 cipSend += connectionId;
 cipSend += ",";
 cipSend +=webpage.length();
 cipSend +="\r\n";
 sendData(cipSend,1000,DEBUG);
 sendData(webpage,1000,DEBUG);
 String closeCommand = "AT+CIPCLOSE=";
 closeCommand+=connectionId;
 closeCommand+="\r\n";
 sendData(closeCommand,3000,DEBUG);
}
   }
  }

  String sendData(String command, const int timeout, boolean debug)
{
esp8266.listen();
String response = "";
esp8266.print(command);
long int time = millis();
while( (time+timeout) > millis())
{
  while(esp8266.available())
  {
    char c = esp8266.read();
    response+=c;
  }
}
if(debug)
{
  Serial.print(command);
  Serial.print("> ");
  Serial.print(response);
}
gps.listen();
return response;
}

Comments are not for extended discussion; this conversation has been moved to chat.

GPS - Arduino
---------------
GND -  GND
TX  -  pin of SoftwareSerial RX
RX  -  pin of SoftwareSerial TX
Vcc -  3.3 V

Only one instance of SoftwareSerial can listen. Method listen() determines which one. So you must add esp8266.listen(); before talking to esp8266 and gps.listen(); before talking to GPS module.

in setup() add esp8266.listen() before first sendData call
in loop() add gps.listen() before while (gps.available())
in loop() add esp8266.listen() before if (esp8266.available())

Comments are not for extended discussion; this conversation has been moved to chat.

@Majenko, the system didn't offer move to chat and I could not create a chat with OP, because OP doesn't have reputation points to use the chat

The message is an automated moderator thing. I'm just cleaning up.

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


text:
Alternative Rx/Tx Pins for Arduino Uno and Pro Mini
Do they have specific pins that is best to be use as Rx/Tx pins (aside from D0 and D1)? If so, what makes them special?
edit: What pin feature i should look out for when choosing the rx/tx pin? Is there any specific pins that will make it a better rx/tx pin?

https://arduino.stackexchange.com/questions/34126/whats-the-difference-between-all-the-software-serial-libraries-which-one-is-ar

Pins D0 and D1 are used for hardware serial, see Serial library reference.
You can use any other pins for virtual Rx/Tx lines employing a software serial mode, for example by using the SoftwareSerial library, see Software Serial example, or by implementing your own custom code, or custom library.

for Mega and Leonardo, there are other recommended pins for rx/tx. do they have it on uno?

The Arduino SoftwareSerial library can use any pair of pins.
AltSoftSerial uses special pins. AltSoftSerial uses a 16 bit hardware timer to generate the transmit output and measure the receive input waveforms. The timer works on pins 8 and 9 on Uno and Atmega 328p boards.

thanks. So this is alternative library to software serial is it. i will read about it first.


text:
Broken Arduino Uno, works over USB but cannot take DC in
My Arduino Uno (r3) board seems to be broken. It can still be powered over USB, and can store/run code properly, but the DC power in system appears to be crippled. I'm not entirely sure what happened, but I was most likely being careless with the power in and the vin pin. I'm not sure what component(s) are broken, but when I plug in 12v into the barrel connector, the uno doesn't power on. I can read about 0.6 volts from the 5 volt pin, and at some other locations on the board. Besides the 0.6, the only other voltage I read is the 12 volt, although it is slightly lower than the power supply, which outputs about 12.2 volts. How can I go about fixing this? Or is it even worth it?

Most certainly the voltage regulator is broken. Maybe you shorted the 5V pin intermediately or you tried to draw too much current from it. Do you have a specific question?

What is the voltage of the vin pin? If it is near 0v, then the diode is blown, if it is near 12v then the voltage regulator is broken. A broken voltage regulator can leak current of have a shortcut, if you remove a broken voltage regulator then you can use the board with usb power.

As you have noticed, measuring voltages is the first step. Here's some voltages for you and what they mean if they aren't there. These are all assuming precisely 12V in through the barrel jack. They are in order of "priority" - start at the top and work down, the first one that fails is your culpret (i.e., the barrel jack feeds VIN through the diode, VIN feeds 5V through the 5V regulator, and 5V feeds 3.3V through the 3.3V regulator).

Roughly 11.4V on VIN - if it's not there the input protection diode has blown
5V on the 5V pin - if it's not there the 5V regulator has blown
3.3V on the 3.3V pin - if it's not there the 3.3V regulator has blown

Fixing it may be as simple as replacing the faulty component identified above - although they are all surface mount and some are more tricky to replace than others.  That said, if it is (as it sounds) the 5V regulator that has gone, that is one of the larger components (SOT-223) so should be eaiser to replace. Also it's dirt cheap - I get them for a few cents each in bulk.

It would appear to be the 5v regulator, thank you! This was super helpful