text:
Interfacing an ATtiny85 with MIDI via Software Serial
In order to finish a synth project that I'm working on I built a MIDI interface. To test it, I drew up some code which (is supposed to) light up an LED when any key is pressed. The light turns off again when the key is released. This will later be merged with another branch of code here to tell me which note is playing. This sounds simple enough but the devil's in the details. Due to my project's size constraints I am using ATMEL's ATtiny85 chip instead of my Arduino Uno. The ATtiny doesn't support the Arduino Serial library and by extension the standard MIDI library. As I can't make use of simple functions like MIDI.read() I've opted to work with an alternative Software Serial technique I adapted from an Instructable. Unfortunately, the results have been less than exemplary. Simply put, the LED almost never lights up. I have conducted two test only 1 of which somewhat succeeded:
1)
if(velocityByte > 0 ){digitalWrite(LED, HIGH);}
if(velocityByte == 0 ){digitalWrite(LED, LOW);}

Initially, I had figured that would be the most successful of my options. My keyboard* is binary about its ouput velocity. There are no pressure sensors so "on" is on and "off" is off. Unfortunately, however, the code seems to think otherwise.
2)
if(commandByte == noteOn ){digitalWrite(LED, HIGH);}
if(commandByte != noteOff ){digitalWrite(LED, LOW);}

Though originally less sure of this one, I've found it to be better than the other at catching notes. noteOn is the integer 144. While it does in fact trigger it does so only very rarely - once every 10 presses or so.
I believe I have however, whittled down the possible number of problems to 2:
1) Something is up with one or more of my calls to Serial. I've never really felt super confident with the author's method of obtaining data from Serial. For one, I have no confidence that I can insure I have collected the correct byte. If the code were to somehow "miss" counting a byte would it not assign, say, a commandByte to a noteByte? Is a better method available?
2) My keyboard's MIDI protocol is incompatible with my if-statement cases.
At first I was under the assumption that my keyboard never sends a true "note off" message of any kind but instead a velocity = 0 message. But my test casts much doubt on this being the case and because of this, I don't really know how the keyboard handles note off messages. Does anyone else know?
*A Yamaha YPT-230
//MIDI INPUT LED TEST
//Adapted from code written
//by Instructables user Amanda Ghassaei

#include <SoftwareSerial.h>

SoftwareSerial mySerial(0, 1);  //RX, TX

#define LED 2

byte commandByte;
byte noteByte;
byte velocityByte;

byte noteOn = 144;
byte noteOff = 128;

void setup(){
  mySerial.begin(31250);
  digitalWrite(LED, LOW);
  delay(1000);
}

void checkMIDI(){
  do{
    commandByte = mySerial.read();//read first byte
    noteByte = mySerial.read();//read next byte
    velocityByte = mySerial.read();//read final byte

    if (commandByte == noteOn){
      digitalWrite(LED, HIGH);
    }
    if(commandByte != noteOn){
      digitalWrite(LED, LOW);
    }

  }
  while (mySerial.available() > 2);//when at least three bytes available
}

void loop(){
  checkMIDI();
}
/*
void gotNoteOn(commandByte, noteByte, velocityByte){
  digitalWrite(LED,HIGH);
}

void gotNoteOff(commandByte, noteByte, velocityByte){
  digitalWrite(LED,LOW);
}
*/

UPDATE Following a suggesting, I have replaced the do .. while loop with an ordinary while loop. Relevant changes below:
void checkMIDI(){
  while(mySerial.available() > 2){
    commandByte = mySerial.read();
    if (velocityByte > 0x00){//if note on message
      digitalWrite(LED, HIGH);
    }
    if(velocityByte == 0x00){
      digitalWrite(LED, LOW);
    }
  }
}

I'd like to think it's an improvement but if so only a slight one. Curiously, it almost works backwards - The default state of the LED is on while pressing a key produces no change pressing and holding causes the light to briefly shut off. But even this is sporadic. It may also be worth noting that I elected to use hex '0x00' as opposed to decimal '0'.
UPDATE II / NOTE Having slept on the problem I think I now understand why I am encountering this issue in the first place. The author of the Instructables code I adapted used an Arduino for both MIDI In as well as MIDI Out. Had they simply hooked one Arduino Uno to the other in an in/out configuration they could have perfectly ensured there were no running status issues by just never sending any running status messages. This would explain the lack of conformity to the actual realities of MIDI on the input side. If you can control exactly what data you are sending on one end (MIDI Out) it becomes fairly trivial to receive that data on the other end (MIDI In). Generalizing, the author may have assumed that a true keyboard behave the same thing and failed to actually verify this. Thoughts?
UPDATE III Following the lead of CL but deviating somewhat because I didn't fully understand what CL was doing, I have written up a highly derivative, new code. It is based around what I now know to be the highly fluid nature of MIDI messages and seeks to intelligently discriminate important messages from non-important messages based on content. It does not work (except for LED test at the beginning) but seems like a promising step nonetheless.
//MIDI Input LED Test

#include <SoftwareSerial.h>

SoftwareSerial mySerial(0, 1);  //RX, TX

#define LED 2  //Test LED

void setup(){
  mySerial.begin(31250);
  digitalWrite(LED, HIGH); //Test
  delay(1000);
  digitalWrite(LED, LOW);
  delay(1000);
}

void loop(){
  checkMIDI();
}

void checkMIDI(){
/*Two of the three independent types of bytes are always
distinct and can be identified simply by their values.
A Status byte (on channel 1 at least) is always either
0x80 (off) or 0x90 (on). No other type of message
(Note, Velocity) can ever take this value and so if
this is the value of the byte received I can be
assured it is a Status byte.

The Note and Velocity bytes are a bit (haha) dicier.
They have overlapping ranges with both taking values of
anywhere between 0x00 to 0x7F. *Ordinarily*. A caveat
is that my Yamaha YPT-230 is binary as far as velocity
goes. A YPT-230 data is either 0x00 (full off) or 0x7F
(full on). As long as a Note byte is never 0 or 127 I can
use this to discriminate between these two types
in this manner.
*/

  if(mySerial.available() > 0){
    byte b = mySerial.read();

    if(b == 0x80 || 0x90){
      byte commandByte = b;
    }else if(b == 0x00 || 0x7F){
      if(b == 0x00){
        digitalWrite(LED, LOW);  //If vel = 0 turn LED off
      }else if(b == 0x7F){
        digitalWrite(LED, HIGH); //If vel = 127 turn LED on
      }
      //velocityByte = b;
    }else{
      byte noteByte = b;  //Do nothing with this for right now.
    }
  }
}

Have you tried using UsiSerial yet?

Never heard of it. I'll read up. Thanks.

Is your LED tied high or low?

If that is your amended code, then you are no longer reading the velocityByte.

I suggest you take a closer look at the code on my page about MIDI - for one thing some MIDI devices return a "running status" which means that instead of the command byte being sent every time, it assumes that if you get a byte with the high-order bit clear, it is the same command as last time. If you just blindly read 3 bytes every time you will be interpreting all sorts of things as something they are not.

Yes, I've heard about running status but wasn't sure if it would be applicable. I'll look at your code. I downloaded your MIDI decoding code but ran into an unknown issue trying to run it on my Uno. I'll take another crack at that as well.

@IgnacioVazquez-Abrams It's simply connected to the output via a resistor. In the setup() part of my code I ensure that at least at the very beginning of operation the LED is off. Interestingly, in some tests, after the initial second even the simple act of connecting the MIDI cable to the keyboard resulted in the LED turning on.

And the other end is tied... where?

I elected to use hex '0x00' as opposed to decimal '0'. In C, the number 0 and 0x00 are the same thing. They are, however, different from '0' (inside the quotes).

but ran into an unknown issue trying to run it on my Uno - an unknown issue, eh? It compiled OK for me under 1.6.4, so I'm not sure what this issue is.

@IgnacioVazquez-Abrams It goes Pin -- > 330 Ohm Resistor --> LED -- > GND. Nick, thanks for clearing up the 0x00 vs 0 thing. I really wasn't sure. For consistency sake I'll try to stick with hex whenever I'm defining byte variables. I'll see if I can give your code another shot.

See my amended post. I made a version for the ATtiny85. Tested on my electric piano, works fine.

I suggest you first find what your Yamaha is sending you. I have a sketch that decodes MIDI for the Uno (assuming you have a Uno lying around). Run that, and see if you got note on with velocity zero, or note off. Then you are a little closer to solving the problem.

This part is quite wrong:
  do{
    commandByte = mySerial.read();//read first byte
    noteByte = mySerial.read();//read next byte
    velocityByte = mySerial.read();//read final byte

  ...

  }
  while (mySerial.available() > 2);//when at least three bytes available

You are reading 3 bytes, even if none are available. At least change it to:
while (mySerial.available() > 2)
  {
        commandByte = mySerial.read();//read first byte
        noteByte = mySerial.read();//read next byte
        velocityByte = mySerial.read();//read final byte

      ...

  }

The do ... while construct tests at the end of the loop. You must ensure you have 3 bytes "available" before reading 3 of them, not after.

Example code for ATtiny85
The code below is an adaptation of the MIDI decoder in my link above. This one just reads the incoming MIDI and turns on the LED on a "note on" and turns it off on a "note off" (or note on with velocity zero). Tested, works perfectly.
//  MIDI_decoder for ATtiny85
//
// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

#include <SoftwareSerial.h>

const byte LED = 0;   // pin 5 on ATtiny85

// Plug MIDI into pin D2 (MIDI in serial) (pin 7 on ATtiny85)

SoftwareSerial midi (2, 3);  // Rx, Tx

const int noRunningStatus = -1;

int runningStatus;
unsigned long lastRead;
byte lastCommand;

void setup() {
  //  Set MIDI baud rate:
  midi.begin(31250);
  runningStatus = noRunningStatus;
  pinMode (LED, OUTPUT);
} // end of setup

void RealTimeMessage (const byte msg)
  {
    // ignore realtime messages
  } // end of RealTimeMessage

// get next byte from serial (blocks)
int getNext ()
  {

  if (runningStatus != noRunningStatus)
    {
    int c = runningStatus;
    // finished with look ahead
    runningStatus = noRunningStatus;
    return c;
    }

  while (true)
    {
    while (midi.available () == 0)
      {}
    byte c = midi.read ();
    if (c >= 0xF8)  // RealTime messages
      RealTimeMessage (c);
    else
      return c;
    }
  } // end of getNext

const char * notes [] = { "C ", "C#", "D ", "D#", "E ", "F ", "F#", "G ", "G#", "A ", "A#", "B " };

byte note;
byte octave;
byte velocity;

// interpret a note in terms of note name and octave
void getNote ()
  {
  note = getNext ();
  octave = note / 12;
  note %= 12;
  }  // end of getNote

void getVelocity ()
  {
  velocity = getNext ();
  }

// show a control message
void showControlMessage ()
  {
   byte message =  getNext () & 0x7F;
   byte param = getNext ();
  }  // end of showControlMessage

// read a system exclusive message
void showSystemExclusive ()
  {
  int count = 0;
  while (true)
    {
    while (midi.available () == 0)
      {}
    byte c = midi.read ();
    if (c >= 0x80)
      {
      runningStatus = c;
      return;
      }

    } // end of reading until all system exclusive done
  }  // end of showSystemExclusive

void loop()
{
  byte c = getNext ();
  unsigned int parameter;

  if (((c & 0x80) == 0) && (lastCommand & 0x80))
    {
    runningStatus = c;
    c = lastCommand;
    }

  // channel is in low order bits
  int channel = (c & 0x0F) + 1;

  // messages start with high-order bit set
  if (c & 0x80)
    {
    lastCommand = c;
    switch ((c >> 4) & 0x07)
      {
      case 0:   // Note off
        getNote ();
        getVelocity ();
        digitalWrite (LED, LOW);
        break;

      case 1:   // Note on
        getNote ();
        getVelocity ();
        if (velocity == 0)
          digitalWrite (LED, LOW);
        else
          digitalWrite (LED, HIGH);
        break;

      case 2:  // Polyphonic pressure
        getNote ();
        parameter = getNext ();  // pressure
        break;

      case 3: // Control change
        showControlMessage ();
        break;

      case 4:  // Program change
        parameter = getNext ();  // program
        break;

      case 5: // After-touch pressure
        parameter = getNext (); // value
        break;

      case 6: // Pitch wheel change
        parameter = getNext () |  getNext () << 7;
        break;

      case 7:  // system message
        {
        lastCommand = 0;           // these won't repeat I don't think
        switch (c & 0x0F)
          {
          case 0: // Exclusive
            parameter = getNext (); // vendor ID
            showSystemExclusive ();
            break;

          case 1: // Time code
            parameter = getNext () ;
            break;

          case 2:  // Song position
            parameter = getNext () |  getNext () << 7;
            break;

          case 3: // Song select
            parameter = getNext () ;  // song
            break;

          case 4:    // reserved
          case 5:    // reserved
          case 6:    // tune request
          case 7:    // end of exclusive
          case 8:    // timing clock
          case 9:    // reserved
          case 10:   // start
          case 11:   // continue
          case 12:   // stop
          case 13:   // reserved
          case 14:   // active sensing
          case 15:   // reset
             break;

          }  // end of switch on system message

        }  // end system message
        break;
      }  // end of switch
    }  // end of if
  else
    {
    // unexpected, ignore
    }

}  // end of loop

Suggested schematic

From a comment:

the 4N35 is too slow to work reliably with MIDI signals

Below is an updated schematic that uses a faster opto-coupler.

Admittedly the 4N35 is below spec for its rise time (it is supposed to be  less than 2 μs rise time, however the 4N35 is slower at between 3 µs and 7 µs). However during my testing it worked OK. It sounds like the faster rise time is specified to allow for multiple devices to be connected in series, a slow rise time will introduce distortion.

Thanks for the point on the do ... while loop. I had no idea it worked like that. I'll correct the code right now and respond with my results.

Hmm, I'll get back with full results but so far it's not measurably any better...

I've looked at and uploaded your code - it's great stuff! Two quick questions as I look through it thoroughly: Why is it so much longer than CL's suggested code? Are all the case statements strictly necessary?

His code is not a complete sketch, it demonstrates decoding the MIDI only. He also ignores a lot of things (other than note on and note off) for simplicity. I think you possibly do this at your peril, because some commands are followed by different numbers of bytes, so you won't be certain what each byte means unless you decode the command. And if you don't have the running status (byte with the high-order bit on) you won't know for sure when you are starting a new command. My code above isn't particularly long.

That seems very plausible. I've been doing a lot of reading these past few days and it's become quite apparent that MIDI is much trickier than I was lead to believe!

This schematic is wrong: the receiver must not connect the shield directly to its own ground, and the 4N35 is too slow to work reliably with MIDI signals.

@CL are you suggesting just omitting the ground connection on pin 2 of the MIDI socket?

@CL - I didn't have any problems during testing, but that doesn't necessarily prove much. I have added another schematic with a faster opto-coupler.

The ground connection must not be omitted at the transmitter; see the specification. (And the pullup would need to be as low as 350 Ω only to reach 10 Mbit/s, which is not necessary for MIDI; in practice, values between 1 kΩ and 4.7 kΩ are used.)

@CL - OK, I amended the second schematic.

May I ask: What is the role of the 0.1uF capacitor, is it just for smoothing the VCC? Does it matter if we use a larger capacitance?

Yes it would be for smoothing. A larger capacitor may work but would react more slowly so it might not be ideal (the larger the capacitance the longer it takes to charge).

This is not how the MIDI protocol works.
The incoming stream can contain other commands than note-on or note-off, and with running status, it is impossible to predict the length of any single command.
You need at least some kind of state machine to remember where in the command you are:
byte nr;

for (;;) {
    byte b = mySerial.read();
    if (b & 0x80) { // status byte
        if (b >= 0xf8) {
            // real-time command; ignore
        } else {
            commandByte = b;
            nr = 1;
        }
    } else { // data byte
        if ((commandByte & 0xf0) == 0x80 ||
            (commandByte & 0xf0) == 0x90) {
            if (nr == 1) {
                noteByte = b;
                nr = 2;
            } else if (nr == 2) {
                velocityByte = b;
                nr = 1;

                if ((commandByte & 0xf0) == 0x90 &&
                    velocityByte > 0) {
                    // note on
                } else {
                    // note off
                }
            }
        }
    }
}

You're right. I updated my question to include a note about this. I think the author completely neglected variable command lengths. Very quickly, could I ask you why you used the bitwise '&' in your code?

What else should I use?

No reason I can think of. It's just that I don't understand what it does. At first, I mistook it for the 'and' sign (&&) and figured you were  doing boolean logic but now I know that's not the case. Could you for instance explain if b & 0x80){}? Is this identical to if(b==0x80){}?

b & 0x80 checks if the 7th bit is set. b & 0xf0 extracts the upper nybble. My code is the minimum needed to pase MIDI note-on/-off messages correctly. To be able to program, you need to learn more about C.

Could you tell me how well my code stacks up to what you have in my most recent update (III)? I opted to check  if the incoming byte matched against a set of potential values (e.g. if(b == 0x80 || 0x90){commandByte = b;} ) given the nature of particular types of data. It doesn't work but would it be viable?

You cannot differentiate between note and velocity bytes by their value. And this is not how checking against multiple values works in C; you must learn more about C.

Let us continue this discussion in chat.

Got it! After doing the requisite amount of research... I've developed a much improved checking system which allows me to truly demarcate between messages during running status much like Nick Gammon's code. While the code seems to work perfectly now it was still a bit glitchy when I tried it the other day. Perhaps I accidentally fixed it, most likely it'll crop back up again. How does it look?
//MIDI_Input_0x01
#include <SoftwareSerial.h>

SoftwareSerial mySerial(0,1);

const int LED = 2;

int isStatus();
int isAftertouch();
int isRealTimeCategory();

int dataByte;
int velocityByte;
int result;

void setup()
{
  mySerial.begin(31250);
  pinMode(LED, OUTPUT);

  digitalWrite(LED, HIGH);
  delay(1000);
  digitalWrite(LED, LOW);
  delay(1000);
}

void loop()
{

  while(mySerial.available())
  {
    //This is the protocol for reading new stuff
    byte myByte = mySerial.read();
    if(isRealTimeCategory(myByte))
    {
      ;
    }
    else
    {
      if(isStatus(myByte))
      {

        result = (myByte | 0x80);       //0b10000000
        switch(result)
        {
          case 0b10000000:
            digitalWrite(LED, LOW);
            break;
          case 0b10010000:
            digitalWrite(LED, HIGH);
            break;
          case 0b10100000:
            break;
          case 0b10110000:
            break;
          case 0b11000000:
            break;
          case 0b11010000:
            break;
          case 0b11100000:
            break;
          case 0b11110000:
            break;
        }
      }
      else
      {
        byte myByte = mySerial.read();  //This is the protocol for reading new stuff
        if(isRealTimeCategory(myByte))
        {
          ;
        }
        else
        {
          if(myByte > 0)
      {
        digitalWrite(LED, HIGH);
      }
      else
      {
        digitalWrite(LED, LOW);
      }
        }
      }
    }
  }
}  //END

/**********************
//function declarations
**********************/

int isStatus(int b)
{
  if( (b & 0x80) == 0x80)
  {
    return 1;
  }
  else if( (b & 0x80) == 0)
  {
  return 0;
  }
}

int isAftertouch(int b)
{
  if( (b & 0xf0) == 0xa0)
  {
    return 1;
  }
  else //if( (b & 0xf0) != 0xa0)
  {
    return 0;
  }
}

int isRealTimeCategory(int b)
  {
    if(b >= 0xF8)
    {
      return 1;
    }
    else
    {
      return 0;
    }
}

On top of this, I managed to tweak the code to output particular values to a shift register as I had initially intended. The method I use to differentiate between note and velocity bytes is less than ideal but works on my keyboard. Because of certain limitations it only works over a range of 13 notes but that's fine for now. Code and flowchart below.
//              MIDI_Input_0x02

#include <SoftwareSerial.h>             //The Attiny does not natively support the Serial library so this
                        //is the work-around.
SoftwareSerial mySerial(0,1);

const int latchPin = 2;
const int clockPin = 3;
const int dataPin = 4;

const int gate = 1;             //Note that initially, this was the tx pin.
                                //In this configuration absolutely every Attiny85 pin is used.
int isStatus();
int isAftertouch();
int isRealTimeCategory();

int result;
int dataByte;
int velocityByte;

//int noteApprox[13] = {1,3,5,7,9,12,14,17,20,23,26,29,32};
int noteApprox[13] = {32, 29, 26, 23, 20, 17, 14, 12, 9, 7, 5, 3, 1};
    //The above numbers are approximately 100 cents
    //apart from one another. This corresponds to notes of a scale.
    //They descend here because their corresponding
    //voltages will later become inverted in the circuit.

void setup()
{
  mySerial.begin(31250);

  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(gate, OUTPUT);        //'Gate' controls the level of the
                    //envelope generators. The signal
                    //becomes inverted later.

  digitalWrite(gate, HIGH);     //A simple test to ensure the
  delay(1000);              //circuit is wired correctly
  digitalWrite(gate, LOW);
  delay(1000);

}

void loop()
{

  while(mySerial.available())
  {
    //This is the protocol for reading new stuff
    byte myByte = mySerial.read();      //Read the oldest byte in the buffer
    if(isRealTimeCategory(myByte))      //See Function Notes
    {
      ;
    }
    else
    {
      if(isStatus(myByte))               //See Function Notes
      {
        result = (myByte | 0x80);       //0b10000000
        switch(result)
        {
          case 0b10000000:
            digitalWrite(gate, LOW);            //0b10000000 is the note Off
            break;                      //message
          case 0b10010000:
            digitalWrite(gate, HIGH);           //10010000 is the note On
            break;                      //message
          case 0b10100000:          //Absolutely none of these are important.
            break;
          case 0b10110000:
            break;
          case 0b11000000:
            break;
          case 0b11010000:
            break;
          case 0b11100000:
            break;
          case 0b11110000:
            break;
        }
      }
      else                                     //This is the part where I assume it's a data byte.
      {                                        //this might be causing problems...
        if( (myByte > 48) && (myByte < 61) )         //<-- That's 13 notes. An octave and an extra
        {
          digitalWrite(latchPin, LOW);
          shiftOut(dataPin, clockPin, MSBFIRST, noteApprox[myByte - 48]);   //Write to the shift
          digitalWrite(latchPin, HIGH);                     //register.
        }
        else
        {
          digitalWrite(gate, LOW);
        }

        byte myByte = mySerial.read();
        if(isRealTimeCategory(myByte))
        {
          ;
        }
        else
        {
          if(myByte > 0)
      {
        digitalWrite(gate, HIGH);  //Velocity Byte
      }
      else
      {
        digitalWrite(gate, LOW);
          }
        }
      }
    }
  }
}  //END

/***************************
    function Declarations
***************************/

int isStatus(int b)         //Determines if the incoming byte is a Status Byte of some sort.
                    //Returns 1 if so and 0 if not.
{
  if( (b & 0x80) == 0x80)
  {
    return 1;
  }
  else if( (b & 0x80) == 0)
  {
  return 0;
  }
}

int isRealTimeCategory(int b)           //Determines if the incoming byte is a Real Time Category byte
  {                 //I'm not positive what these *are* but they are only 1 byte long
    if(b >= 0xF8)           //a piece and easily detected (they're all greater than 11111000).
    {
      return 1;
    }
    else
    {
      return 0;
    }
}

/*              Bit Math Notes

    if(b & 0x80) == 0x80)

b    =  10000000
0x80 =  10010000
      & ________
        10000000 =/= 10010000

        Not a Note On byte.
        Return 0.

b    =  10010000
0x80 =  10010000
      & ________
        10010000 == 10010000

        A Note On byte! Hooray!
        Return 1.
*/

Your code still has issues in many cases. For example, if you get an "other" with the 0x80 bit set, you go back to your main loop but for (say) polyphonic pressure (0x82) you ignore the next byte which is the amount of pressure. That means the pressure amount could be interpreted as a note value next time around the loop.

Good catch. I hadn't put much thought into it seeing as my keyboard doesn't have polyphonic pressure. I'll look into it, thanks.


text:
Writing MIDI Notes More Quickly to a Shift Register with Arduino
I'm working on an Arduino code which will interpret a given MIDI note message and output the corresponding note number to a string of LEDs as a binary integer. I have adapted it from existing code found on the site Notes & Volts which features a similar circuit designed to trigger an LED every time a key is pressed.
My circuit takes this further by telling the user exactly which note is being pressed. The note value byte is information is passed to a 74HC595 shift register which displays the note as a binary via a line of LEDs.
In a loose sense the code I have adapted "works". When a key is pressed a series of LEDs light up corresponding to the MIDI note designated to that key. The issue is that this only happens sporadically. Many times a key press won’t be followed by any LEDs but other times it will. Even quick, successive presses tend to result in only a handful of "read" notes.
Why does this happen? To my intuition it would seem that the Arduino is "missing" notes, that is, spending so many clock cycles writing bits to the shift register that it falls out of sync with incoming bytes from the keyboard. Notes & Volts describes almost this exact situation in one of their instructional videos (relevant part at around 6:57). The author cautions against including too many time consuming processes in the code but doesn't mention how many is too many. I can only assume that a ShiftOut command takes a good deal longer than a digitalWrite and that this explains why the example code works but my adaptation does not. Given this information, how long exactly does ShiftOut take and what could be done to speed up my program?
#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();

int latchPin = 8;
int clockPin = 12;
int dataPin = 11;  //The pins I am using

void note_On(byte channel, byte pitch, byte velocity) {  //Runs when note is pressed

  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, pitch);
  digitalWrite(latchPin, HIGH);  //Write 'pitch' to 74HC595. Standard fare
}

void note_Off(byte channel, byte pitch, byte velocity){ //Writes '0' when note is off (all LEDs off)
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, 0x00);
  digitalWrite(latchPin, HIGH);
}
void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

  MIDI.begin(MIDI_CHANNEL_OMNI);
  MIDI.setHandleNoteOn(note_On);
  MIDI.setHandleNoteOff(note_Off);
}

  void loop() {
  MIDI.read();  //This function which must be re-run in quick succession
}

UPDATE
@CL @Nick I wrote a code comparing the execution time difference between shiftOut and digitalWrite. While I am not perfectly confident in all of the numbers (1K digitalWrites takes a full 44mS??) one result did not surprise me - shiftOut is slower. By my numbers it is 3.75 times slower. That said, I welcome critiques on my methodology and I will address them as soon as I can. In the meantime I will make a point to research Arduino SPI and welcome any other alternatives to shiftOut.
int latchPin = 8;       //Declaration of serial register pins
int clockPin = 12;
int dataPin = 11;

int led = 13;          //On-board LED

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

  Serial.begin(9600);

  pinMode(led, OUTPUT);

}

void loop() {

  unsigned long startTime = millis();    //Writes to SR 1K times.
  for(int i = 0; i < 1000; i++){       //Prints difference between
    digitalWrite(latchPin, LOW);       //start and end times.
    shiftOut(dataPin, clockPin, MSBFIRST, 0xFF);
    digitalWrite(latchPin, HIGH);
  }

  Serial.print("\nsO:");
  Serial.print(millis() - startTime);

  delay(1000);

  startTime = millis();
  for(int i = 0; i < 8000; i++){    //Performs digitalWrite 8K times
    digitalWrite(led, HIGH);
  }

  Serial.print("\t\tdW:");          //
  Serial.print(millis() - startTime);

  delay(1000);
}

UPDATE
While working on a similar issue I discovered that a dramatic change to my code seems to perfectly clear up the issue. I'd still like to know why this particular example does not, however, so I'll keep poking around until I get somewhere.

Is your MIDI input circuit the same as in the link? (I.e., does it omit the decoupling capacitor?) If you're using a 6N138, can you try with a faster optocoupler, like the H11L1 or 6N137?

Can't you measure how fast shiftOut executes? (Execute it ten thousand times, and run millis() before and afterwards.)

I'll try your and other people's suggestions today but I'll chime in now just to say that I am already using an H11L1 so I think I have isolated the issue to the code itself. The input circuit I copied directly from the datasheet with the addition of a 220 Ohm resistor and a protection diode at the MIDI input. I got nice sharp pulses on the oscilloscope.

I still don't think that shiftOut is the issue, even if it is slower. My code did serial prints which are a lot slower again. Try the code I linked in my answer. The hardware should be the same, except move the MIDI input to pin D2 - leaving D0 and D1 for communicating with the Serial Monitor. You haven't answered my question about how you wired the LEDs. If you don't have a series resistor you may be overloading the 74HC595 output pins. Also the 74HC595 should have a decoupling capacitor.

Just to clarify, using SPI is a good idea. I don't argue with that. But I don't think it will fix this issue.

shiftOut is slow, yes.  It is basically "bit banging" a synchronous serial interface, which is a bit daft really when the Arduino has a hardware synchronous serial interface built in that can operate at much higher speeds.
That built in synchronous serial interface is called SPI.  I suggest you switch to SPI instead of shiftOut.
Also you should check what codes the MIDI keyboard is actually sending out.  I had a similar experience to you recently, but as far as I can tell it's down to the keyboard, not my software.  I built a system which reads in MIDI NoteOn codes through a serial port and plays a sample of a bass guitar at the right pitch.  The system worked perfectly when wired to the computer through a USB MIDI adapter, but as soon as I connected it to a keyboard (I don't have one, so I only had the one chance to test it recently with a real keyboard) it would only react to a key pressed after a long delay.  Almost as if the keyboard only sends a NoteOn if there is nothing happening for a while, and sends something else at other times.  I need to examine the keyboard's output data in more detail to see exactly what is being sent and why.
You might like to manually examine the MIDI codes being sent by the keyboard to be sure that it is actually sending a NoteOn when you think it should be and not something else (it'd be very interesting to see the results of your experiments too).

The keyboard problem sounds as if your code did not support running status.

@CL quite possibly, since I have never heard of that, and none of the references I read while writing it mentioned it. Do you have a link?

MIDI Specification: Running Status

That's interesting stuff. No, my code doesn't implement that and it explains perfectly why it failed on the keyboard. I wonder if the same is true for the MIDI class used by the OP?

The OP's problem sounds more random.

I can't believe it is the shiftOut that is the issue. There is more going on here than meets the eye. I wrote a MIDI decoder a while back. That reads from MIDI and outputs to serial. That would be a lot slower than doing one shiftOut. It runs perfectly, not just with you sitting there tapping notes, but with the synth generating its inbuilt music. See video of it in action.
Either the library is doing something weird, or your 74HC595 is wired strangely. Do you have current-limiting resistors for each LED? Please show your wiring.
Also add a Serial print to display when your note_On and note_Off are called, and with what values. In my test I was able to connect MIDI up to Software Serial (pins D2 and D3 in my case) which was fine for receiving MIDI.

source: Stack Exchange

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

sort: votes


text:
3.5" TFT LCD Display is not working with Arduino Mega 2560 R3
Even I can't do similarly with my 2.4" TFT LCD in here still: 2.4" TFT LCD Shield isn't working on Arduino Mega
Now, I have bought 3.5" TFT LCD display for my Arduino Mega 2560 R3 to try whether I could run the screen or not, and it is not working now! I am so depressed and angry for these two's misbehaviors. I have already checked website and a lot of Arduino IDE code examples and libraries such as UTFT.h, UTouch.h, UTFT_MEGA, UTFT_CTE, TFTLCD. I tried these and I can not run my 3.5" screen. Where am I faulty? There is something below the screen shield: www.mcufriend.com and 3.5" TFTLCD for Arduino 2560. Are there any basic code or have anyone tried to run Mcufriend's displays correctly?

possible duplicate of 2.4" TFT LCD Shield isn't working on Arduino Mega

I would recommend contacting the seller about example code/libraries, or at the least a datasheet.

I know how to make these work, but they are all a little different. Please post a link to the exact product you bought. A link to an online store or something will work fine. If it's like the one in my photo, I can make it work... https://www.flickr.com/photos/77816686@N02/11719888193/in/set-72157636192458205

Yes it is @Jasmine. Please do. Thank you in advance.

I still don't see a link to the product? I could write up a general approach, but it might be a waste of time.

http://www.henningkarlsen.com/electronics/library.php?id=51
Download hennings new UTFT library.
in myGLCD define R61581 as this is the driver chip for 3.5 display.
Regards!

Try this code:
https://www.dropbox.com/s/fce43rxofttl001/Librer%C3%ADas%20UTFT%20%2B%20UTouch%20para%203.5%20TFTLCD%20para%20Arduino%20Mega%202560%20%20-%20copia.rar
First delete the old UTFT library, then copy and paste the library inside de RAR file.

Can you please post the contents of the file?

I have the same lcd shield from mcufriend. It has ILI9327 in 8 bit mode.
This shield doesn't work with original UTFT library (it supports only 16-bit mode).
Try modified version from https://github.com/dgolda/UTFT and use:
myGLCD(NIC35WS,38,39,40,41); //3.5" TFTLCD for arduino 2560 from mcufriend.com

This might be a silly suggestion, but the mega2560 is 5v, and the display is 3.3v...and you need an interface board between.  I have successfully run a 3.2" display using this interface board
http://www.elecfreaks.com/store/lcd-tft01-arduino-shield-v20-shd09-p-213.html
Hope this helps

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


text:
LM35 and Character LCD
I have an arduino pro mini and I have attached a 16x2 character LCD and an LM35 analog temperature sensor. When I upload a sketch using only the sensor and send the readings to serial monitor, the readings are OK. When I upload a sketch that displays the readings to the LCD the readings are about 130°C in room temperature. Where is the problem and how can I solve it. Thanks in advance
Code with lcd:
#include <LiquidCrystal.h>
byte smiley[8] = {
  B00000,
  B01110,
  B01010,
  B01110,
  B00000,
  B00000,
  B00000,
};
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.createChar(0, smiley);
  lcd.begin(16, 2);
  analogReference(INTERNAL);
  // Print a message to the LCD.
  lcd.print(analogRead(0)/1024.0 * 500);
  lcd.write(byte(0));
  lcd.print("C");
  lcd.setCursor(0, 2);
  lcd.print("21");
  lcd.write(byte(0));
  lcd.print("C");

}

void loop() {
  // Turn off the cursor:
  lcd.print((analogRead(0)/1024.0)*500);
  lcd.write(byte(0));
  lcd.print("C");
  lcd.setCursor(0, 2);
  delay(5000);
  lcd.clear();
}

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

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(analogRead(0)/1024.0*500);
  delay(500);
}

Adding your code would be helpful.

I think adding code is essential...

I just added it sorry for the delay.

Firstly you do not keep your code consistent between you temperature test and your LCD test code. The problem lies in your use of the internal analog reference, that reference is 1.1V and that is giving you 130°C.
Temp = 260*0.5= 130
The 260 is the ADC reading worked back from the 130°C you gave
To use Internal reference-
Internal ref = 1.1÷1024=0.001074219
That multiplied by one hundred to account for the mV reading of the lm35 gives 0.107 that will give you the correct temp when using the internal reference
Analog reference from the arduino site.
If you want to use the analog reading *0.5 comment out the analogReference()


text:
Pressing button stops listening on nrf24l01
I have been tinkering for 2 days to manage send and receive between 2 arduinos. My code is bellow:
Arduino 1:
#include <SPI.h>
#include <RF24.h>
#include "printf.h"
#define LED 2
#define RF_CS 8
#define RF_CSN 9
RF24 radio(8,9);
String datargb = "rgb: 000000005";
char chartosend;
char inchar;
String inradio;
int endchar = '~';
void check_radio(void);
void setup() {
  // put your setup code here, to run once:
Serial.begin(115200);
  printf_begin();
  radio.begin();
  radio.setRetries(15,15);
  radio.openWritingPipe(0x080C600C01LL);
  radio.openReadingPipe(1,0x080C600C71LL);
  radio.setPALevel(RF24_PA_MAX);
  radio.setAutoAck(true);
  radio.printDetails();
  attachInterrupt(0, check_radio, FALLING);
  radio.stopListening();
}

void loop() {
  // put your main code here, to run repeatedly:
int lnth = datargb.length();
  for(int i=0; i<lnth; i++){
      chartosend=datargb.charAt(i);

      while(!radio.write( &chartosend, sizeof(chartosend) )){}

      Serial.println("sent");
  }
  radio.write(&endchar,1);
}
void check_radio(void){

  bool tx,fail,rx;
  radio.whatHappened(tx,fail,rx);

  if(rx){
    Serial.println("interrupt!!");
radio.startListening();
    radio.read( &inchar, sizeof(inchar) );
    inradio+=inchar;
    Serial.println(inchar);
    if(inradio.endsWith("~")){
      Serial.println(inradio);

      if(inradio.startsWith("rgb: ")){
        analogWrite(6,inradio.substring(5,8).toInt());
        analogWrite(9,inradio.substring(8,11).toInt());
        analogWrite(5,inradio.substring(11,14).toInt());
      }
      inradio = "";
      radio.stopListening();
    }
  }
}

Arduino 2:
#include <SPI.h>
//#include <nRF24L01.h>
#include <RF24.h>
#include "printf.h"
//#include <RF24_config.h>
RF24 radio(8,10);
char data;
char chartosend;
char endchar = '~';
String inradio;
void check_radio(void);
String datargb = "To mounti tis manas tou nrf24";
void setup() {
  // put your setup code here, to run once:
  pinMode(9, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, INPUT);
  attachInterrupt(1, check_radio, FALLING);
  Serial.begin(115200);
  printf_begin();
  radio.begin();
   //radio.setRetries(2,15);
    // open pipe for writing
    radio.openReadingPipe(1,0x080C600C01LL);
    radio.openWritingPipe(0x080C600C71LL);
    radio.setPALevel(RF24_PA_MAX);
    radio.startListening();
    radio.printDetails();
    radio.setAutoAck(true);
}

void loop() {
  // put your main code here, to run repeatedly:
if(digitalRead(7)==HIGH){
  radio.stopListening();
  for(int i=0; i<28; i++){
      chartosend=datargb.charAt(i);
      while(!radio.write( &chartosend, sizeof(chartosend) )){}
      //Serial.println("sent");
  }
  radio.write(&endchar,1);

  while(digitalRead(7)==HIGH){}
  radio.startListening();
}
}
void check_radio(void){

  bool tx,fail,rx;
  radio.whatHappened(tx,fail,rx);

  if(rx){
    Serial.println("interrupt!!");
//radio.startListening();
    radio.read( &data, sizeof(data) );
    inradio+=data;
    Serial.println(data);
    if(inradio.endsWith("~")){
      Serial.println(inradio);

      if(inradio.startsWith("rgb: ")){
        analogWrite(6,inradio.substring(5,8).toInt());
        analogWrite(9,inradio.substring(8,11).toInt());
        analogWrite(5,inradio.substring(11,14).toInt());
      }
      inradio = "";
      //radio.stopListening();
    }
  }
}

Arduino 2 receives all data from ar1 but when I press the button attached to the pin 7 arduino 2 stops listening and only sends the first character of the string.

There is probably a death-lock situation where both arduino's are trying to send data the the other, while both aren't listening. So both are waiting for the other to ack. Like I said at your previous question. Why not send all rgb data in one packet. Also, there is no need to call radio.stopListening.

I tried to send a string and on the other side i did not receive these characters but some others. Besides that I have to call stopListening because in the loop I write. Another question: If receiver receives ack package does it cause an interrupt?

The receiver doesn't receive an ACK. Only the sender does. You can send data while you are still listening. No need to call stopListening before calling radio.write().

I said that because when i press the button the receiver turns into sender and sends a string. Then it waits for an ack. So if it receives an ack it breaks the for loop and mabe it is the reason that it sends only one char

You send one char, and wait for and ACK. Then you send the next char and wait for an ACK. If the other unit doesn't process the message, the buffer will will up after 3 messages, and it will no longer send an ACK (because the buffer is full), and you while loop will hang.

So what should i do to make it work?

I already told you twice.

Yes but when i send string it doesnt arrive as it is it shows some random chars

And all tutorials on the internet use the char by char method

Use RF24 library's examples. tmrh20.github.io/RF24 is the webpage you can find them.


text:
Burning arduino generate hex file to blank atmel chip
Is it possible to burn the hex file to a blank chip, generated by Arduino to burn using USBASP to that particular chip without using Arduino board ? Will the program work ?

My main goal is to use Atmega328P for low power. Should I select Arduino pro mini in the arduino IDE ?
Ater successful testing I will just burn the hex file to another 50 chips. thats why I dont want to use arduino board.

I wan to burn the hex file which is generated by arduino ide. But dont want to use arduino board. Instead I want to burn by USBASP like regular avr program hex file burning.

Note that the Arduino IDE supports several programmers directly, including the USBasp.

Yes. The binary generated by the Arduino IDE in no way requires the presence of the Arduino bootloader in order to operate. Note that certain characteristics such as the MCU and clock rate are set at build time and cannot be changed in the final binary.

Do I have to do anything with fuse settings while burning ?

The clock settings should match those expected by the code. The other fuses are up to whatever is required for the application.

Yes that's no problem as long as you check your fuse bytes. And the connections to the 6pin ISP header.
Make sure you study the avrdude command line and the manual for the particular Atmel chip.
I'm assuming the programmer you are using must use avrdude to be able to work.
I often use a nice GUI called "avrdudess" which is freeware. Great for avr beginners, and takes some of the effort out of writing directly into the command prompt.

I will check avrdudess

What will be the fuse settings if I use Arduino UNO as platform in IDE ?


text:
DFRobot Bluno + Relay Shield
I'm a new to all things electronics and I'm having trouble using a DFRobot Bluno V2 with a DFRobot Relay Shield for Arduino V2.1. For testing purposes I've done the exact same circuit as represented in this diagram:

http://www.dfrobot.com/wiki/index.php/Relay_Shield_for_Arduino_V2.1_(SKU:DFR0144)#Connection_Diagram
But it is not working. If I send HIGH signal to D10 or press the S4 button on the shield, the circuit does not close and the LED doesn't turn on (even though the LED4 next to the relay on the shield lights up). If I do same circuit connecting the LED to D10 directly (ie., without using the relay) it works fine. I've also tested this with the other relays on the shield and the results were the same.
Does anyone know what might be the issue? What am I doing wrong?
Thanks in advance.


text:
Arduino with ESP8266
I have completed the circuit and code to interface ESP8266 module with Arduino UNO.
When i send AT,AT+RST from serial monitor the reply is correct .
But when i send AT commands to search WIFI networks (AT+CWLAP) & connect to WIFI (AT+CWJAP="SSID","password") the reply is ERROR.
But the IP address (may be default) is obtained as 192.168.4.1
 when i send AT+CIFSR .
Here is my code
#include <SoftwareSerial.h>
SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3

void setup()
{
    Serial.begin(9600);
    esp8266.begin(9600); // your esp's baud rate might be different
}

void loop()
{
    if(esp8266.available()) // check if the esp is sending a message
    {
        while(esp8266.available())
        {
            // The esp has data so display its output to the serial window
            char c = esp8266.read(); // read the next character.
            Serial.write(c);
        }
    }
    if(Serial.available())
    {
        // the following delay is required because otherwise the arduino will read the first letter of the command but not the rest
        // In other words without the delay if you use AT+RST, for example, the Arduino will read the letter A send it, then read the rest and send it
        // but we want to send everything at the same time.
        delay(1000);
        String command="";
        while(Serial.available()) // read the command character by character
        {
            // read one character
            command+=(char)Serial.read();
        }
        esp8266.println(command); // send the read character to the esp8266
    }
}

Your serial reading code, with that really horrible delay, is not good.  You should read and digest this: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

You want to use  AT+CWSAP="SSID","password",1,0

Finally i found the solution .
Send AT+CWMODE=1 first , then all other commands working fine.


text:
Different questions regarding Arduino C++ library coding style
I'm reading the two wire library in Arduino libraries and in the C++ source  code I found different methods which I don't know what they mean, in the following:
// Initialize Class Variables //////////////////////////////////////////////////

uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
uint8_t TwoWire::rxBufferIndex = 0;
uint8_t TwoWire::rxBufferLength = 0;

uint8_t TwoWire::txAddress = 0;
uint8_t TwoWire::txBuffer[BUFFER_LENGTH];
uint8_t TwoWire::txBufferIndex = 0;
uint8_t TwoWire::txBufferLength = 0;

uint8_t TwoWire::transmitting = 0;
void (*TwoWire::user_onRequest)(void);
void (*TwoWire::user_onReceive)(int);

// Public Methods //////////////////////////////////////////////////////////////
void TwoWire::begin(void)
{
  rxBufferIndex = 0;
  rxBufferLength = 0;

  txBufferIndex = 0;
  txBufferLength = 0;

  twi_init();
}

void TwoWire::begin(uint8_t address)
{
  twi_setAddress(address);
  twi_attachSlaveTxEvent(onRequestService);
  twi_attachSlaveRxEvent(onReceiveService);
  begin();
}

void TwoWire::begin(int address)
{
  begin((uint8_t)address);
}

My first question, regarding to class variables:

Why has the author connected the variables to the class with scope-resolution operator "::"?
I want to understand the last two lines of class variables, I know they are function pointers, but I want to know more details and benefits of function pointers?

My second question, regarding to public methods:

There are three versions of the "begin" function, can someone explain why?
Why is begin(); called inside the second function declaration?

Why they connect the variables to the class with scope-resolution operator "::"?

Those are static variables. They don't exist within an instantiated class instance since they are common to all class instances - so they have to be defined elsewhere, and for that you need the full "class path" for them to associate them with the class itself.

I want to understand the last two lines of class variables, I know they are function pointers, but I want to know more details and benefits of function pointers?

Yes, they are function pointers. They are used to store the address of functions the user supplies at runtime. Without them it is very hard for the user to tell the class which of his own functions should be called for various events.

There are three versions of the "begin" function, can someone explain why?

This is called function overloading. It allows you to have the same function but provide different combinations of parameters. In this case one with no functions (in master mode) and two with different numeric parameters (for slave mode) with those numeric parameters in different storage formats.

Why begin(); is called inside the second function declaration?

It saves having to duplicate all the code from the other begin() function within that function. You call the function with a numeric parameter, it does a little bit of "extra" work, then it calls the "common" begin code from the other begin() function. Code duplication is generally a bad thing since any changes you make have to be made in multiple places. This keeps the common code in one location, and the most convenient place for that is the begin() function that takes no parameters.

Guys, first of all thank you very much for Mr Code Gorilla for correcting my English it's really a honor for me that a friend in the technical field is interested to help me with my English skills :), and secondly, thanks to Mr Majenko for answering my questions. I'm really thrilled that one help me with my English and the other one helped me with my technical topic. I understood some answers and others not so quite, so I need more time to understand and comment again for the answers.

There are some complex things there you are looking at. May help: http://www.learncpp.com/cpp-tutorial/811-static-member-variables/ - https://www.tutorialspoint.com/cplusplus/cpp_overloading.htm

For the fisrt answer, I understood half of your answer as static variables are shared and that's it but I didn't understand the second half, "so they have to be defined elsewhere, and for that you need the full "class path" for them to associate them with the class itself." Do you mean by full path is to define their type and connect them with the class name? I think yes, and also I understood in the library that the author is defining them at the beginning and before class definition with the class name. OK this point is now obvious to me :)

@PerchEagle With a static variable the type is defined in the class, but the storage space for that variable has to be manually defined, and that is what those entries are. A normal variable has the storage space allocated in a class instance when it is created (e.g., Servo myServo; allocates the space for the variables within the Servo class). Static variables can't do that since the storage space isn't specific to any one object, but to all objects - so you have to manually create that storage space. And you do that by defining the variables in a source file. The variable's name is ...

... <ClassName>::<VariableName>. You need the <ClassName>:: bit so that the compiler knows you mean the variable in that class, not some other unrelated variable.

The second answer is not obvious because I didn't implement it practically in my AVR C coding yet so I don't know the benefits of function pointers. 3. The third answer is obvious which is function overloading and now I see an example for function overloading but I don't know why the author implemented this function overloading. 4. The fourth answer is not clear.

Re 2: It is not a question of "benefit" - it's a question of how do you implement storing a function passed to you as a parameter, and function pointers are the answer. Re 3: Because he wanted to. It's a clean way of doing it, and you only have to remember "begin", not "beginMaster" and "beginSlaveInt" and "beginSlaveUint8" functions. Re 4: Which would you prefer: to write the same code 3 times or write it once and just call the function with it in?

OK, I understood your reply and the Servo example, but why would I need static variables anyway if its storage is shared with all instances?

Because static storage happens to be the correct solution to a specific problem.

Thank you very much for helping me Re 2, 3, 4 are OK to me because I have to implement these techniques to see the results for C++ applications.

Absolutely thank you for your answers I'm really thankful for your cooperation I've been away of coding because I was busy with my marriage and honeymoon it's been 1 month for my marriage :) I just started off reviewing coding these days :)

I got another question today :) Why the author put two functions to se the frequency or the clock? Regards, void TwoWire::setClock(uint32_t clock)
{
twi_setFrequency(clock);
}

@PerchEagle The bulk of the Wire library code is actually a third party (probably written by Atmel) C library of routines. The TwoWire class is merely a C++ wrapper to those C functions to give an easy user interface. TwoWire::setClock merely calls the relevant function in that library (which is all in the utility directory) to do the actual setting of the clock.

Oh yeah, so clear thank you very much, I'm really happy with your answers :) Please see my new post at avrfreaks, but didn't find a quite clear answer. http://www.avrfreaks.net/forum/twen-twint, or I should post it in this website in a new topic? Regards,


text:
Powering relay module with 5v external supply
The relay module consists of two sets of pins:
Set1: GND, VCC, Int1, Int2
Set2: JDVcc, VCC, GND
In set 2, VCC and JDVcc are jumpered together normally, which is removed to power the relay coil with external supply.
However, can I supply 5v directly from external source to the VCC pin of Set 1 and connect the GND pin to common ground, leaving the VCC and JDVcc pin jumpered together as they are? It's because I am running out of pins in my Uno.
Will that work?

if you leave it jumpered, you will re-use the control's VCC to drive the relay. If that supply has enough current, that's a fine way of doing it. Don't mess with the grounds; they have continuity already...

@dandavis it s a arduino module so i guess its designed to take in low current bcoz arduino ports can supply only 20mA.

check the datasheet for the holding current of what i'm guessing is a common 5v songle relay. probably ok.

I'm voting to close this question as off-topic because it is about relays and has nothing to do with Arduino, and provides insufficient detail to be answerable anyway.

can I supply 5v directly from external source to the VCC pin of Set 1
  and connect the GND pin to common ground, leaving the VCC and JDVcc
  pin jumpered together as they are?

Probably you're using this relay module, which is fairly common:

If that's the case, then the answer is YES as long as you keep all grounds tied together and the 5V external supply deliveries a voltage reasonably close to the Arduino 5V.
Why?

When IN is high and VCC is close to 5V, there isn't enough voltage difference for forward biasing the diodes. They won't conduct and no current will flow from or into your Arduino data pin.
When IN is low, the diodes are forward biased and current will sink into the Arduino data pin. As long as VCC is close to 5V, the current limiting resistor will keep current within specification of what the Arduino data pin can tolerate.


text:
Middle school Student stuck and needs help
I have a middle school student who is having problems getting her pollution sensor to work when asked to. I have attached her document to this post. Can anyone help her fix the issue?
int conductivitySensorValue; //initialize an integer variable to hold the sensor reading

void setup() {
Serial.begin(9600); //start serial communications so we can print the reading out

}

void loop() {
  conductivitySensorValue = analogRead(A0); //gat the integer representation of the sensor reading

  float voltage = conductivitySensorValue*(5.0/1023.0); //put the data in terms of our voltage (5 volts)

  Serial.println("The Conductivity is" + voltage); //print the current reading to the serial port
}

Arduino: 1.8.2 (Windows 7), Board: "Arduino/Genuino Uno"

C:\Users\sushmit\Documents\Arduino\sketch_apr19a\sketch_apr19a.ino: In function 'void loop()':

sketch_apr19a:13: error: invalid operands of types 'const char [20]' and 'float' to binary 'operator+'

   Serial.println("The Conductivity is" + voltage); //print the current reading to the serial port

                                          ^

exit status 1
invalid operands of types 'const char [20]' and 'float' to binary 'operator+'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

End copy.......

Please edit your question (click "edit") and mark the code as code. In the editing box, highlight the code and press ctrl-k. Or highlight the code and click the {} icon in the toolbar at the top of the editing box. To highlight text click-drag across it or use the arrow keys while holding the shift key. ¶ Add a few blank lines between the end of the code and the beginning of the error messages.

Try Serial.println(String("The Conductivity is ") + voltage); or simply Serial.print(F("The Conductivity is ")); Serial.println(voltage);

Welcome to Arduino SE.  Please take a minute to view the tour:  https://arduino.stackexchange.com/Tour - there are tips in there about how to format your questions.

Your post reads as if you are a teacher.  I would have expected a teacher to understand this issue, maybe you ought to do some revision.  If you are the student why hide?

Serial.println("The Conductivity is" + String(voltage)); works and is readable, though there's more efficient ways with lower level code.

You can't add a string literal and a number together.
Instead you either have to convert one or both into a format that can be joined, or just treat them as separate entities. The simplest way is:
Serial.print(F("The Conductivity Is: "));
Serial.println(voltage).

Note the use of F(...) around the string literal - that forces it to stay in Flash so it doesn't waste RAM. Maybe not an issue with this project, but a good habit to get into nonetheless.

This is how I do it (although I didn't know about the F part) - Serial.print will do the conversion implicitly.  No need to do any conversions in your code.


text:
Sending file from SD card to android using ESP8266
I came across this post
https://stackoverflow.com/questions/10327506/android-arduino-bluetooth-data-transfer
where the author sends files from the arduino to android platform over bluetooth.
I am wondering, is this possible to achieve with the ESP8266 SoC?
I have no experience with it, but i am willing to buy and experiment, if it hads that functionality.

Will you be using an Arduino to transfer the data from the SD card to the ESP8266?  If so it should be possible.  If not it gets trickier - it might still be possible, but also ceases to be on topic here.

yeah, using the arduino of course


text:
How to put 2 variables in a macro?
In a previous question (Append Text to Variable Names: Please Help Me Shorten This Code) I learned that in order to shorten this code:
fanSpeed = readEEPROM(AT24C32_ADDRESS, 1, fanSpeedPos);

I could define a macro at the top of the script like this:
#define readEE(VAR) VAR = readEEPROM(AT24C32_ADDRESS, 1, VAR ## Pos)

And then just use the following shorter code:
readEE(foo);

Which would be expanded out to:
foo = readEEPROM(AT24C32_ADDRESS, 1, fooPos);

My current question is: How can I write a macro that accepts 2 arguments instead of just 1? I couldn't find much information about this concerning Arduinos, so I studied about how to do it in C++ (like from here: http://en.cppreference.com/w/cpp/preprocessor/replace) but it was too complicated for me to understand.
In particular, I would like to learn if it's possible to shorten the following code:
void writeToEE(byte location, bool value, bool &var) {
  writeEE(loc, value); var = value;
}

(Sidenote: the writeEE function looks like this: void writeEE(uint8_t entry, uint8_t data) { writeEEPROM(AT24C32_ADDRESS, 1, entry, data); }. Since the first 2 arguments are almost always constants, that's why I shortened it with another function).
Since whenever I'm using writeToEE, the "entry" variable name is always the "data" variable name with "Pos" appended, I would ideally like to do this (pseudo-code):
#define wrEE(VAR, VAL) VAR = writeToEE(VAR ## Pos, VAL, VAR)

so that when I write this:
wrEE(fanSpeed, 3);

it will be expanded out to:
writeToEE(fanspeedPos, 3, fanspeed);

I just don't know how to pass the 2nd argument ("VAL") into the macro, which is the value being stored in the "fanSpeed" variable, in the "fanSpeedPos" location in the EEPROM. When I try to compile my pseudo code example (was hoping to get lucky!), I get the following error message: "void value not ignored as it ought to be"

... Did you mean to put "VAR = " in front of it?

I really don't know what I'm doing, and I took the "VAR = " part from the first link in the first sentence of the post.

But the return type is void. Which means it doesn't return anything.

Thanks for the guidance! Now I understand that in the first example (from the other thread), the readEEPROM was returning a variable, which is why VAR = was needed. I removed it so that the macro then became: #define wrEE(VAR, VAL) writeToEE(VAR ## Pos, VAL, VAR), and it seems to work! It seems like it's storing my variable correctly. Is it really that simple? Does it look like that's the correct way to do it?

Small side question: since the writeToEE function is calling the writeEE function, would the code run faster if I skipped the writeToEE function and just had the macro expand out to the writeEE function? (Sorry for the confusing similar names). Or does it all end up to be the same after it goes through the compiler?

In the parameter list of the #define for the macro, separate the second argument from the first with only a comma.  For example:
#define wrEE(speed,var) writeToEE((etc))

The "void value not ignored as it ought to be" error message is a consequence of trying to store the void result of writeToEE.  The solution is to not try to store it.
In C, variable, parameter, and constant names are case-sensitive.


text:
Issue with leOS2 for one-time tasks
I'm trying to use the last version of leOS2 scheduler from Leonardo Miliani ( https://github.com/leomil72/leOS2 ) but I have a strange behavior with a very simplistic ONETIME task.
Platform : Arduino Uno clone, so Atmel Atmega 328P CPU.
My code is very straightforward :
#include "leOS2.h"
leOS2 myOS; //create a new istance of the class leOS

bool test = true;

void setup()
{
    myOS.begin(); //initialize the scheduler
}
void loop()
{
    // Do some stuff ...

    if(test)
    {
       DoAndUndo(3000);
       test = false;
    }
}

void DoAndUndo(unsigned long duration)
{
    doSomething();

    myOS.addTask(cancelTheThing, myOS.convertMs(duration), ONETIME);
}

void doSomething()
{
    Serial.println("thing on");
}

void cancelTheThing()
{
    Serial.println("thing is off");
}

In case it can be some kind of conflict, my code also relies on the following :
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <IRremote.h>

The problem is :
        myOS.addTask(cancelTheThing, myOS.convertMs(duration), ONETIME);
is supposed to call asynchronously the "cancelTheThing" method 3 seconds later, and for only one time, and then forget it.
But for an unknown reason, it's called after the expected delay, but it loops infinitely on this method ! In the example case above, my serial stream is filled with a lot of "thing is off" messages, and the µc is unresponsive to anything apart a reset.
The call to DoAndUndo() will produce a such like output :
 thing on

And 3s later, in a very fast infinite loop :
 thing is off
 thing is off
 thing is off
 thing is off

If I remove the "ONETIME" flag, the task is called every three seconds (exactly as it's suppose to do, so the scheduler works, but it's not what I want in my use case).
note : As a try of workaround, I've tried some tricks like calling haltScheduler() inside my cancelTheThing() and reenable it with restartScheduler() in DoAndUndo(), and also tried to call removeTask once it has ran, but it didn't help.
Thank you for your help

There appears to be a fault with the library whereby if the only registered task is a one-shot task it doesn't get cancelled when it has executed.
Adding another periodic task in setup() (say to blink an LED every 500ms) so there are now 2 tasks instead of one works around the problem.
The way the system is written it will always try an execute task number 0 even when there are 0 tasks registered because they erroneously used a "do {...} while" construct instead of a "while { ...}" construct.

I  have filed a bug report, corrected the error, and raised a pull request with the fix in it.  Until it gets accepted you can obtain the fixed version here: https://github.com/majenkotech/leOS2

Hello, thanks to have answered but it's not the solution. The above sample was not accurate (I've edited it, sorry for the lack of precision). The "infinite loop" issue I encounter effectively comes from the scheduler as I explained, not a such trivial issue as you thought. If it was a so simple mistake, my "doSomething" method would have loop too...

@AFract If you want our help you will have to provide a piece of code that compiles and executes exactly as shown and demonstrates the problem. An approximation is of no use at all.

And the one in first post should be ok. The original code was only slightly different, i just add an "if" to show that the true one doesn't do what you thought. And even without it, the explanation below it were already enoughly clear to make you figure your answer cannot help to fix the issue.

@AFract What you write below your code describes precisely what I would expect from the original code you posted. Now you have changed the code so it doesn't compile it is of no use at all.  What is "test"?

It's an EXAMPLE. What you need to focus on is : When i call "DoAndUndo(3000);" ONE time it continuously executes cancelTheThing() instead of just calling it once, as the ONETIME flag passed to the scheduler should do. Exactly like explained in the post content.

With your ORIGINAL code I would expect that to happen since the way it was written you were CONSTANTLY creating the task over and over again.  Now with this code it's not the case because you added something that hasn't been defined.  WITHOUT KNOWING WHAT THAT IS WE CANNOT HELP YOU!!!

The question was clear, the code sample is here to illustrate the use I do of leOS. Maybe if you had read it instead of posting ironical-useless answers like "Here's a hint... What do you think the name of this function signifies...?", you'd have notice it. To be kind with you, I changed the sample to make it build and behave "as you want" till the part with the scheduler. To be clear : the problem does not look to be in the algorithm, it's in the behavior of the scheduling lib.

It's NOT "to keep me happy"!  It is to make it physically possible for us (NOT JUST ME) to HELP you!  Quite frankly, to be brutally honest, I really don't know if I can be bothered now.  You probably won't listen to the answer because apparently you already know everything!

@AFract Incidentally, you clearly haven't even tried running the code you have posted, since it still CAN NOT work.

I can't upload it right now to the Arduino (I don't have it here) but it builds well for me. But the point is really simple :     "myOS.addTask(cancelTheThing, myOS.convertMs(duration), ONETIME);" doesn't do what its documentation suggests : instead of calling cancelTheThing one time, it locks up in infinite loop. If the original author of the lib or somebody who knows it well read my msg, he could probably have an hint about the problem.

@AFract Now that I have re-written your program so that it actually works, I can replicate your results - something that I couldn't have done before.  Now I can actually analyse the problem and find the cause.

I didn't "rewrite" it and I didn't change the example since 20 minutes. But nevermind, thanks for your help and your efforts. I'm glad to see you meet the same issue than me, even on a so simple example.

No, I had to re-write it.  I have traced the problem and found a workaround for it - I have also corrected the underlying problem and raised a bug report and pull request with the repository.  More info in my answer.

Wow ! great work of debugging. I'll try it ASAP, I hope your pull request will be accepted. I'll tell you if it's effectively ok with your little change.


text:
Alternative to patching core library source and header files
I am following a DIY guide that requires me to patch two arduino core library files: HID.cpp and USBAPI.h. This is not really practical for many reasons. I am not a native C programmer, but I am sure there are better ways to achieve the same without messing directly with system files. How can I override system library files without modifying the originals?

That all depends on what the modifications are you need to do...

@Majenko principally it adds a third device description (HID Remote) to the two devices that are described in those two files (Keyboard and Mouse). I can upload a diff.

Can't you just place a copy in the sketches folder and alter this local copy?

Unfortunately there really isn't any way of doing that other than modifying those files. The good news is that it is perfectly viable to make the modifications under a different "core" and then amend boards.txt with the core containing the modifications.


text:
Controlling amplifier using remote control jack
Many older amplifiers support wired remote control through connector jacks or ports. My 10-year old Marantz also supports this function, using a simple RCA connector.
Originally these were used with external IR receivers when the unit was not kept in plain sight.
I wonder if there is a way to control the amplifier using an Arduino, which probably means by generating the required signal over the connector instead of receiving it from an IR receiver. Any pointer to a similar project is appreciated as well.

Sounds like the sort of thing which might be possible. Unless someone happens to know specifics of how they work, a spec for the connection, and/or a circuit diagram of either/both the amp or/and a suitable controller would help a lot.

it's probably just the same pulses as the IR, but you'd need an oscilloscope or a service manual to be sure. you can always improvise

You'd have to know the protocol, which is probably proprietary. I'd just use IR, by connecting an IR led to the Arduino.

@dandavis That's exactly what I think. But given that Marantz IR protocol is well-known, do I really need to check the pulses manually? Note, I wouldn't need to do that even if I wanted to emulate a Marantz remote controller with actual IR output.

That's what I was assuming - that you would stand a good chance of guessing the protocol with some trial-and-error, but it would be really helpful to have some idea of how it works electrically to get you started, otherwise you've got two degrees of freedom (and you might possibly damage the device). Two connections (as on an RCA) isn't enough for an IR receiver (you need three) so it's not immediately obvious (to me, anyway) how it would work. Even a working example IR receiver circuit would get you started.

i seem to recall an article 20 years ago that said marantz gear could interact with sony using those control signals. if that's true, or maybe just for an overview look into sony's...

According to this thread on remotecentral the signal on the RCA connector is just the inverted signal that the IR-LED receives. So if you load an RC5 library and invert the output (0=1 and 1=0), you should be able to send codes to that connector with an arduino. Or even better, use an ESP8266 and control it over wifi ;)
The RC5 codes and their functions are in this  nice excel sheet or use this information if you want to send raw hex

Someone blogged how to do it using a Raspberry PI and LIRC. The excel shet link is broken, found a copy here. Another useful dicsussion here.

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


text:
Sustainable power source for outdoor arduino weather station
I have been running a simple weather station composed of a Sparkfun Pro Micro (8kHz/3.3V), a DHT22 and a NRF24L01+ transceiver during the last couple of months, and I can tell you up here in Canada weather stations save lives...
The board checks the temperature and the humidity once every second and transmits the new measurements back to my home server over RF if the changes are above some threshold. As such, the board sleeps most of the time, and the transmissions happen rarely (about once to thrice per minute).
The system has been running off an iPhone charger up to now, but I am now thinking of weaning it off the mains. The maximum power consumption of the whole circuit when DHT22 is on and RF chip is transmitting remains below 200mA and many articles suggest that with some optimization one can reduce the power draw by levels of magnitude. Actually, from what I read I gather that the average consumption of the circuit can be pushed below 1mA.
So, I was thinking of adding a solar panel, a charging circuit and a Li-ion battery to my setup, when I discovered these low-cost solar-powered USB power banks on several vendor websites. They make outrageous claims about their charge capacity, that in my experience one has to divide at least by two (20,000 ~= 10,000), but they are pretty rugged and seem appropriate for outdoor installation. The units seem to use a 6V/0.6W (100mA) solar cell that should theoretically be sufficient for charging the battery even if some days are less sunny or shorter.
I wonder if anyone has used one of these as a continuous power supply for an arduino kit, or can inform me about the possible limitations. The idea is not to deal with the power apparatus myself each time I want to assemble a kit.

Can the Power Bank (solar battery charger) be used out-doors? That would require some extra sealing. Otherwise that is plenty of power. I have a project where I hacked a Garden Solar Light; removed the LEDs and added an ATtiny84, sensors and NRF24L01 (alt. RX433) transmitter. The Garden Light has two rechargeable batteries (less than 600 mA) but with low power software tricks you can reduce power to under 100 uA in standby.

Good to know! Yes, it seems this second one is pretty sturdy and resistant.


text:
How to send data from cc3000 to herokuapp server
I tried this code:
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include "utility/debug.h"
#include "DHT.h"
#include<stdlib.h>

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER); // you can change this clock speed

// WLAN parameters
#define WLAN_SSID       "ID"
#define WLAN_PASS       "PASS"
#define WLAN_SECURITY   WLAN_SEC_WPA

#define IDLE_TIMEOUT_MS  3000      // Amount of time to wait (in milliseconds) with no data
                                   // received before closing the connection.  If you know the server
                                   // you're accessing is quick to respond, you can reduce this value.
#define DHTPIN 7
#define DHTTYPE DHT11

// What page to grab!
#define WEBSITE      "myapp.herokuapp.com" //your website

uint32_t ip;
DHT dht(DHTPIN, DHTTYPE);

const unsigned long connectTimeout  = 15L * 1000L;
void setup(void)
{
    Serial.begin(115200);
    //Serial.begin(9600);
    Serial.println(F("\nInitializing..."));
    if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }
    Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID);
    if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }
    Serial.println(F("Connected!"));

    Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }
  ///if he login and he can show info/ mean he login and only then continue
    while (! displayConnectionDetails()) {
    delay(1000);
  }
}

void loop(void)
{
 float h = dht.readHumidity();
  float t = dht.readTemperature();

  int temperature = (int) t;
  int humidity = (int) h;

  String temperatures=String(temperature);
  String humiditys=String(humidity);

  Serial.print("Temperature: ");
  Serial.print(temperatures);
  Serial.print(" F /");
  Serial.print("Humidity: ");
  Serial.print(humiditys);
  Serial.print("%");
  Serial.println("");

   // Create the request.
  String request = "GET /plants/0003/create_measurement?capsules=1&humidity=" + humiditys + "&soil_moisture=40&temperature=" + temperatures + " &water_tank=10&light=20&battery=4 HTTP/1.1\r\n";
  // Print and Send the request
  Serial.println("About to send: ");
  Serial.print(request);
  Serial.print(F("Host: "));
  Serial.print(WEBSITE);
  Serial.print(F("\r\n"));
  Serial.print(F("User-Agent: Compost Monitor/1.0\r\n"));
  Serial.println();
  send_request(request);

}

void send_request (String request)
{
  Serial.println("Enter Request");
  ip = 0;
  // Try looking up the website's IP address
  Serial.print(WEBSITE); Serial.print(F(" -> "));
  while (ip == 0) {
    if (cc3000.getHostByName(WEBSITE, &ip)<0) {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }

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

  Adafruit_CC3000_Client www ;
   unsigned long t = millis();

do {
    Serial.println("Into do");
   www = cc3000.connectTCP(ip, 80);
} while((!www.connected()) &&
    ((millis() - t) < connectTimeout));

  String b="0";
  if(www.connected())
  {
  b="1";
  }
  Serial.println("! Out Do" + b);
  if (www.connected()) {
    www.print(request);
    www.print(F("Host: "));
    www.print(WEBSITE);
    www.print(F("\r\n"));
    www.print(F("User-Agent: Compost Monitor/1.0\r\n"));
    www.print(F("\r\n"));
    www.println();
  } else {
    Serial.println(F("Connection failed"));
    return;
  }

  Serial.println(F("-------------------------------------"));
Serial.println("time to reed");
  /* Read data until either the connection is closed, or the idle timeout is reached. */
  unsigned long lastRead = millis();
  while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
    while (www.available()) {
      char c = www.read();
      Serial.print(c);
      lastRead = millis();
    }
  }
  www.close();
  Serial.println(F("-------------------------------------"));
Serial.println("no time to reed");

}

bool displayConnectionDetails(void)
{
  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

  if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
  {
    Serial.println(F("Unable to retrieve the IP Address!\r\n"));
    return false;
  }
  else
  {
    Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
    Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
    Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
    Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
    Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
    Serial.println();
    return true;
  }
}

This sends data to my server. However, no entries are appearing on my server.

Welcome to Arduino.SE. Please can you explain your problem? What exactly are you trying to do, and what's not working?

hii Peter R. Bloomfield.
i try to send the Temperture and Humidity to my server by send them with cc3000
i did like i post  (that the full// only without the name of app) and it all work it get to the end but it not adding a record on my server
that program should to add to id ="0003" a new record with all the Info such as:
capsules=true
humidity=37 // as example
untill the end
but still it not add the record

Welcome to Arduino SE! This seems more like a server issue than an Arduino issue... is there any way to verify the server is working and this code isn't? Also, what have you tried? Can you narrow it down to a small section of the code?

use http://requestmaker.com to send a properly formatted GET request to your heroku app. If it works, it is your Arduino code, if not, it is your app.


text:
Arduino Custom Function Problem
I am experiencing problems when I put parts of my code into custom functions and then have Arduino Mega 2560 run it. The code works fine when I put it all in the void loop() function, but when I create new functions then call those functions in the loop() function, it doesn't do what I want it to.
Here is the code where I put everything in the loop function
/*
Location.txt: Date/Time , Latitude (deg decimal), Longitude, Altitude (m)
Speed.txt: Date/Time, Speed (m/s), Heading (deg)
*/

#include<TinyGPS.h>
#include<SD.h>
#include<SPI.h>

int CS = 53;

long lat,lon;
unsigned long time, date;
int year,tinseconds;
byte month, day, hour, minute, second, hundredths;
unsigned long age;
char dataString[20];
TinyGPS GPS;

struct GPSstruct {
  String dateTime;
  int timeseconds;
  float C_lat;
  float C_lon;
  float C_alt;
  float heading;
  float speedmps;
};

void setup()
{
  Serial.begin(115200);
  Serial1.begin(38400);
  pinMode(CS, OUTPUT);
  if(!SD.begin(CS))
  {
    Serial.println(F("Card Failure"));
  }
}

void loop()
{
if(Serial1.available()){ // check for gps data
   if(GPS.encode(Serial1.read())){ // encode gps data
    GPS.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
    GPS.get_position(&lat,&lon); // get latitude and longitude in degree decimals multiplied by 10^5
    sprintf(dataString, "%02d/%02d/%02d %02d:%02d:%02d",month,day,year,hour,minute,second);
    tinseconds = second + minute*60 + hour*3600;
    float C_lat = ((float)lat)/1000000; //to get degree decimals
    float C_lon = ((float)lon)/1000000;
    float C_alt = GPS.f_altitude();
    float heading = GPS.f_course();
    float speedmps = GPS.f_speed_mps();
    GPSstruct A = {dataString,tinseconds,C_lat,C_lon,C_alt,heading,speedmps};

//DEBUG
    Serial.println();
    Serial.print(F("Date/Time: "));Serial.println(dataString);
    Serial.print(F("Time (sec): "));Serial.println(tinseconds);
    Serial.print(F("Lat: "));Serial.println(C_lat,5);
    Serial.print(F("Lon: "));Serial.println(C_lon,5);
    Serial.print(F("Alt: "));Serial.println(C_alt);
    Serial.print(F("Heading: "));Serial.println(heading);
    Serial.print(F("Speed: "));Serial.println(speedmps);
//END of DEBUG

//add the code below makes alt = 1000000 for a long time then it fixes at some ?wierd? number
//------//
  File dataFile = SD.open("Location.txt", FILE_WRITE); //Records date/time, lat, lon, alt
    if (dataFile)
    {
      dataFile.print(A.dateTime);dataFile.print(" , ");dataFile.print(A.C_lat,5);dataFile.print(" , ");dataFile.print(A.C_lon,5);dataFile.print(" , ");dataFile.println(A.C_alt);
      dataFile.close();
    }
    else
    {
       Serial.println(F("Location.txt cannot be opened!"));
    }

   File dataFile2 = SD.open("Speed.txt",FILE_WRITE); //Records date/time, speed, heading
   if (dataFile2)
   {
     dataFile2.print(A.dateTime);dataFile2.print(" , ");dataFile2.print(A.speedmps);dataFile2.print(" , ");dataFile2.println(A.heading);
     dataFile2.close();
   }
   else
   {
     Serial.println(F("Speed.txt cannot be opened!"));
   }
//------//
   }
}
}

Here is the code where I put them into two custom functions and call them in loop()
#include<TinyGPS.h>
#include<SD.h>
#include<SPI.h>

int CS = 53;
long lat,lon;
unsigned long time, date;
int year,tinseconds;
byte month, day, hour, minute, second, hundredths;
unsigned long age;
char dataString[20];
TinyGPS GPS;

struct GPSstruct {
  char dateTime[20];
  int timeseconds;
  float C_lat;
  float C_lon;
  float C_alt;
  float heading;
  float speedmps;
};

//Function Prototypes
struct GPSstruct GPSdata(void);
void SDlogger(struct GPSstruct);

void setup()
{
  Serial.begin(115200);
  Serial1.begin(38400);
  pinMode(CS, OUTPUT);
  SD.begin(CS);
}

//GPS data function:
struct GPSstruct GPSdata(void) {
static GPSstruct A;

 if(Serial1.available()){ // check for gps data
   if(GPS.encode(Serial1.read())){ // encode gps data
    GPS.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
    GPS.get_position(&lat,&lon); // get latitude and longitude in degree decimals multiplied by 10^5
    sprintf(dataString, "%02d/%02d/%02d %02d:%02d:%02d",month,day,year,hour,minute,second);
    tinseconds = second;
    float C_lat = ((float)lat)/1000000; //to get degree decimals
    float C_lon = ((float)lon)/1000000;
    float C_alt = GPS.f_altitude();
    float heading = GPS.f_course();
    float speedmps = GPS.f_speed_mps();
    strcpy(A.dateTime, dataString);
    A.C_lat = C_lat;
    A.C_lon = C_lon;
    A.C_alt = C_alt;
    A.heading = heading;
    A.speedmps = speedmps;

//DEBUG
    Serial.print(F("Date/Time: "));Serial.println(dataString);
    Serial.print(F("Time (sec): "));Serial.println(tinseconds);
    Serial.print(F("Lat: "));Serial.println(C_lat);
    Serial.print(F("Lon: "));Serial.println(C_lon);
    Serial.print(F("Alt: "));Serial.println(C_alt);
    Serial.print(F("Heading: "));Serial.println(heading);
    Serial.print(F("Speed: "));Serial.println(speedmps);
    Serial.println();
//END of DEBUG
  }
 }
 return A;
}

//SD data logging funct:
void SDlogger(struct GPSstruct A)
{
   File dataFile = SD.open("Location.txt", FILE_WRITE); //Records date/time, lat, lon, alt
    if (dataFile)
    {
      dataFile.print(A.dateTime);dataFile.print(" , ");dataFile.print(A.C_lat);dataFile.print(" , ");dataFile.print(A.C_lon);dataFile.print(" , ");dataFile.println(A.C_alt);
      dataFile.close();
    }
    else
    {
       Serial.println(F("Location.txt cannot be opened!"));
    }
   File dataFile2 = SD.open("Speed.txt",FILE_WRITE); //Records date/time, speed, heading
   if (dataFile2)
   {
     dataFile2.print(A.dateTime);dataFile2.print(" , ");dataFile2.print(A.speedmps);dataFile2.print(" , ");dataFile2.println(A.heading);
     dataFile2.close();
   }
   else
   {
     Serial.println(F("Speed.txt cannot be opened!"));
   }
}
void loop()
{
  struct GPSstruct Gdata = GPSdata();
  SDlogger(Gdata);
}

The one with all the code in the loop function prints all the serial.println commands and writes data into the micro SD card, but the one with custom functions DOESN'T print serial.println commands in GPSdata function and only prints that "Location.txt/Speed.txt cannot be opened!" and have writes 0 into the mirco SD card.
Why is this happening? Is it memory problems? (But the other one works fine)
The code here is meant to be a part of a bigger main code that uses these GPS data, so I would prefer it if I can keep the main script clean using custom functions.
Thank you.

The code in both appears to be perfectly satisfactory - stock - normal - stream file writing. Do you have an "errno" global variable available? If you do, that might shed some light on the errors you're getting. There's nothing inherent to custom functions that would make your code not work. You're absolutely sure that the SD card was plugged in & functional when you used the custom function and it failed?

Admittedly, your code is somewhat hard to read without an actual editor (not your fault), but I think the issue is that in the first code (everything in one loop), the matching bracket from the initial if-statement (if(Serial1.available()) {) is located after the SD logging functions.
In the second code (decomposing the code), you have the SD logging done outside the if-statement. My guess is that Serial1.available() = false initially, so in the first piece of code, it skips everything else and loop until Serial1.available() == true. That probably doesn't take long, so you just see everything working. In the second code, you return static GPSstruct A (I'm not sure you want this to be static, but I could be wrong) which has been initialized but contains no useful data (it's uninitialized). The void loop() then takes that empty struct and passes it over to SDlogger(struct GPSstruct). That function doesn't do any error-checking to make sure that A has useful information.
An easy workaround would be to add a field to the GPSstruct for whether or not it contains data. It's a simple boolean value. The code might look something like this:
struct GPSstruct {
  boolean containsData;
  String dateTime;
  int timeseconds;
  float C_lat;
  float C_lon;
  float C_alt;
  float heading;
  float speedmps;
};

...

if(Serial1.available()){
  A.containsData = true;
  ...
} else {
  A.containsData = false;
}

...

void SDlogger(struct GPSstruct A) {
  if(A.containsData) {
    ...
  } else {
    return;
  }

Also, as I was typing this, it got migrated...

Personally, I'd put the check for available data in loop(), and if available, call the GPSdata and SDlogger functions based on that check.

That would work too. You can do it however you like; I just tried to come up with a quick example. Putting it in the loop would definitely be simpler.

Was that the problem? I don't actually see a way to mark the answer, but if you can mark a post as answering your question, you should to close it.
Glad we could help!