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:
How to setup Arduino Wifi Shield with Red Bear Lab BLE Shield?
I'm new to Arduino shields.
I'm trying to stack these two shields on an arduino uno for a home automation project.
1 - Arduino Wifi Shield:
2 - Red Bear Lab BLE shield: http://redbearlab.com/bleshield/
I have pin contention, between the two shields:
The WiFi shield uses pins: 4, 7, 10, 11, 12, 13.
The BLE shield uses pins: 10, 11, 12, 13.
Is there a hardware or software way to allow the two shields to work together?
I saw in a similar thread, someone reccomended a go-between shield: https://www.sparkfun.com/products/11002, would this be something that I could use in this case?
If it's not possible, are there other shields that will work together?
Thanks

I'm trying to do the same thing.  Did you ever get this to work?

Not exactly...
I was able to switch around some pins in the library to compile and get past the setup for BLE and WIFI. It works running on the BLE shield doing all the normal stuff, but as soon as I tried to use the WIFI shield to send an email, it crashed.
Haven't had time to look into a proper fix yet.

Hey I just saw this: gonna wait to buy one once it's released: https://www.kickstarter.com/projects/1991736672/redbear-duo-a-small-and-powerful-wi-fi-ble-iot-boa?ref=category
I have their BLE board, really like it. Super excited for this.

The way the Arduino talks to each of the shields is by first telling the device that it wants to communicate with it, and then by exchanging information with that device. The Arduino uses 3 pins, 11, 12, and 13, to communicate to both the shields, and a 4th pin which it uses to select which of the devices it wants to use. This way the Arduino can use connect to two shields at once, by just selecting one at a time
I did some research, and found that the selection pin on the WiFi shield (which I believe is the same as yours: https://www.arduino.cc/en/Main/ArduinoWiFiShield) are pins 10 and 4; pin 4 for the SD card selection, and pin 10 for the WiFi selection. Now since pin 10 is used as a selection pin for both the WiFi shield and the BLE shield, you run into some problems: both the boards will be selected at the same time when pin 10 is used. In this case, you can use the Sparkfun go-between board you linked.
I've never used it myself, but it appears to be able to change what pin is attached where on the shield it's attached to. In this case, you want to put the WiFi shield on the bottom, then the Sparkfun go-between shield, then the BLE on the top. You want to set up the go-between shield to change pin numver 10 to another pin that's not being used (any pin but 11, 12, 13, 7, 4, or 10).
In the Arduino code you will at some point declare which pin is being used to select which board. In this case, set the WiFi selection to 10 (default), the SD card selection to 4 (default), and the BLE selection to whatever pin you changed pin 10 from with the go-between shield. This way, when you select the shield on pin 10, it will only select one shield, rather than two.

source: Stack Exchange

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

sort: votes


text:
MPU6050 or GY521/HMC5883 chips are burnt for no reason
I been trying to interface MPU6050 and HMC5883 with an Arduino Pro Mini/Nano. I²C scanner works just fine and identifies the device with no issues. I let the I²C scanner run like for 5 minutes and I see fumes coming out of the chips and sometimes the Arduino itself is burnt. I tried pull up resistors 2.2k, 7k without any luck. Has anyone got any inputs to this issue. Really frustrating to spend a weekend on this :(
To rule out the possibility of 5V supply causing the burn out I tried 3.3V from Nano and made promini 3.3V from 5V. Please see the pictures below.
Arduino Nano 3.3v was used to power up the I²C.
.
.
Pro Mini jumper was desoldered from 5V to 3.3V to see if the I²C chips are saved from being burnt. In both these setup voltage accross the I²C chip was measured and it was 3.3V.
Still no luck!
If you guys are to make the same circuit how would you do it and where would you get the components from? I must be doing something wrong and hope we together can figure it out.
Components are bought from eBay and the links are here.
GY521 = goo.gl/Y4aDph
HMC5883 = goo.gl/DfrC9l
Arduino Nano = goo.gl/CaAykI
PROMINI = goo.gl/79PVOM
This is some background of why this issue resolution is so important to me:
Just give you a backgroud of why I am doing this: I am building a quadcopter myself. Infact built one using GY80, but the module was expensive also it eventually got burnt out for the same reason mentioned above. Here is the first successful test flight of my first quadcopter goo.gl/rn6xWG (add https:// since I am rookie there is limitation on how many links I can post). If I can make the same thing work using GY521 and HMC5883 it would be awesome and cheaper.
Update on 08/11 @12:45 PM CST
I think it is because of the Pro Mini, I²C chips are getting fried. When using Nano, I think it is because of the voltage level difference between the SDA/SCL lines causing the problem. With Pro Mini tripped for 3.3V, I was not able to see any serial data from the chip too. To end all these I placed an order for 3.3V 8 MHz Pro Mini from amazon goo.gl/FjgTGj Let see how that goes.

Please post your wiring, or a photo of what you are doing, or both. Certainly the chips should not let out smoke.

burnt for no reason - chips don't burn for "no reason". There is a reason, you just haven't found it yet.

Arduino Nano/PROMINI, A4->SDA, A5->SCL, VCC to VCC, GND -> GND. Simple wiring on a bread board. I will send the picture later once i set up the circuit again.

The MPU6050 is a 3.3v device. Make sure you don't power it using 5v. Also make sure you don't connect the pull-ups to 5v, but to 3.3v. Also make sure there are no other breakouts on the I2C line that have pull-up resistors to 5v. Also disable the internal pull-ups inside the arduino

Here is the diagram db.tt/4ocbNOYW. Without pullup resistors and trying the GY521 or HMC5883 alone is burning the chip. GY521 or HMC5883 I am using is a 3-5V variant should have been working just fine. GY521 = goo.gl/Y4aDph HMC5883 = goo.gl/DfrC9l
Arduino Nano = goo.gl/CaAykI PROMINI = goo.gl/79PVOM –  Mohamed 2 mins ago   edit

Also @Gerben thanks for the info. I will try disabling the pullup resistors and see if it is working without any issues. Wonder how many more Arduinos/GY521 are left to try this out. Will Keep you posted.

That won't do much good if you are powering the devices with 5v like you show in the (tiny) diagram.

so If the promini is made 3.3v 8MHz from the 5V 16MHz, should it just work fine? or if I power the I2C devices from the 3.3v pin of the the Nano? I will try both ways and let you know. @Gerben I am reverting the pullup resistor changes from the wire library for now then.

It shouldn't be getting hot if you are only using 3.3 V. Can you please measure the Vcc into the HMC5883 and check it is 3.3 V?

I checked that it was 3.3V. No chip was getting hot like real hot but i can see fumes at times from the HMC5883 or GY521 for that matter. This last test i did no fumes happened but it fried the chips. If you masters are to make such a circuit how would you do it and where would you get the components from?

If I were in your shoes I would use my multimeter to measure the current going into the accelerometer. It should only be a few milliamps.

Now that the chip is burnt I need to solder up a new HMC5883 and see the current.  Will get back by tomorrow once I am back from work.  So if the current is higher what does it mean and what should be the conclusion.

Chips don't burn for no reason. Incorrect wiring could be one. Incorrect resistors. Voltage too high. And if the current was high I would be wondering why it is high.

Okay.  Let's think simple here.  5V Arduino powering the chip from 3.3v pin, why would you expect it to burn up.  I tried more than 10 Arduinos and i2c chips. Whole point of this open source chips is that it is plug and play.  May be because these are cheap knock off Arduinos and i2c chips one reason for this unpredictability.

Do the chips even tolerate 5V logic??

@Avamander Even used 3.3V power supply but it was still burning up the chips.

@Mohamed I did not ask about power supply. Do the I²C chips tolerate 5V I²C? Try dividing the voltage so that the chip gets 3.3V power and 3.3V logic.

@Avamander But how is it different from dedicated 3.3V for both Arduino and I²C?

@Mohamed I²C is a digital communication protocol. That means as digital data is 0 and 1s, 0 is 0V and 1 is the supply voltage, for 5V Arduino it is 5V. If you communicate with a chip that does not tolerate higher voltage logic, chips burn. That means 5V has to be turned into 3V in all places it could go in.

Fixed the issue with a dedicated 3.3V power supply.  I2C scanner is running for 30 minutes with no issues so far.

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


text:
Arduino Motor Shield

It seems that I can't get the DC Motor function to work while also having servos driven off the other ports :(
#include "Arduino.h"
#include <Servo.h>

int pinI1=8;//define I1 interface
int pinI2=11;//define I2 interface
int speedpinA=9;//enable motor A
int pinI3=12;//define I3 interface
int pinI4=13;//define I4 interface
int speedpinB=10;//enable motor
int spead =220;//define the spead of motor

Servo SteeringServo;  // create servo object to control a servo

void setup()
{
  // Steering servo pin setup
  SteeringServo.attach(5);  // attaches the servo on pin 9 to the servo object

  pinMode(pinI1,OUTPUT);
  pinMode(pinI2,OUTPUT);
  pinMode(speedpinA,OUTPUT);
  pinMode(pinI3,OUTPUT);
  pinMode(pinI4,OUTPUT);
  pinMode(speedpinB,OUTPUT);

  Serial.begin(9600);

}

void forward()
{
     analogWrite(speedpinA,spead);//input a simulation value to set the speed
     analogWrite(speedpinB,spead);
     digitalWrite(pinI4,HIGH);//turn DC Motor B move clockwise
     digitalWrite(pinI3,LOW);
     digitalWrite(pinI2,LOW);//turn DC Motor A move anticlockwise
     digitalWrite(pinI1,HIGH);
}
void backward()//
{
     analogWrite(speedpinA,spead);//input a simulation value to set the speed
     analogWrite(speedpinB,spead);
     digitalWrite(pinI4,LOW);//turn DC Motor B move anticlockwise
     digitalWrite(pinI3,HIGH);
     digitalWrite(pinI2,HIGH);//turn DC Motor A move clockwise
     digitalWrite(pinI1,LOW);
}
void left()//
{
     analogWrite(speedpinA,spead);//input a simulation value to set the speed
     analogWrite(speedpinB,spead);
     digitalWrite(pinI4,HIGH);//turn DC Motor B move clockwise
     digitalWrite(pinI3,LOW);
     digitalWrite(pinI2,HIGH);//turn DC Motor A move clockwise
     digitalWrite(pinI1,LOW);
}
void right()//
{
     analogWrite(speedpinA,spead);//input a simulation value to set the speed
     analogWrite(speedpinB,spead);
     digitalWrite(pinI4,LOW);//turn DC Motor B move anticlockwise
     digitalWrite(pinI3,HIGH);
     digitalWrite(pinI2,LOW);//turn DC Motor A move clockwise
     digitalWrite(pinI1,HIGH);
}
void stop()//
{
     digitalWrite(speedpinA,LOW);// Unenble the pin, to stop the motor. this should be done to avid damaging the motor.
     digitalWrite(speedpinB,LOW);
     delay(1000);

}

void loop()
{
  left();
  delay(15000);
  stop();
  right();
  delay(1000);
 stop();
 // delay(2000); Already commented out
  //forward();
 // delay(2000);
 // stop();
// backward();
  delay(12000);
  stop();
}

Your code:
int speedpinA=9;//enable motor A
...
int speedpinB=10;//enable motor
...
 analogWrite(speedpinA,spead);//input a simulation value to set the speed
 analogWrite(speedpinB,spead);

See https://www.arduino.cc/en/reference/servo

On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

(My emphasis).
So, you can't do that, exactly. Perhaps choose other pins for the analogWrite, pins that analogWrite supports, that are not 9 and 10.


text:
Run an Arduino without a PC
I would like to use an Arduino to make tasks in my life automatic - maybe to rotate every morning a motor, or to open a door.
So, can I run an Arduino as solo with no pc needed? Can i connect it to the Internet and can I setup software like PHP and Apache on it to control it over the internet? Has it any protocols like SSH like a normal server?
As an example: I will send over any protocol a signal to my Arduino with a certification and then the Arduino would run a function...
Is that possible?
thanks ahead

You can run the Arduino without a PC. use arduino to make tasks in my life automatic - what tasks do you have in mind?

i will send via putty to my arduino a command and the arduino open my garden door with electric

I will use arduino to make tasks in my life automatic maybe to let rotate every morning a motor or to open the door.

That's the kind of thing it's designed for.

So i will ask can i run arduino as solo so no pc needed,

Yes, you only need a PC to program it, once programmed it will run without the PC.

Can I connect it to the internet

Yes, there are Ethernet and WiFi shields available for connecting it to a network.

and can I setup PHP and Apache on it to control it over it; has it any protocols like SSH like an normal server ?

No.  The Arduino isn't powerful enough to run software like that.  You would normally connect it via the network / internet to a server to process data.  It would just receive simple instructions or send data to the server for processing.

as example: I will send over any protocol a signal to my Arduino with a certification and then the Arduino is running a function...

I assume by "a certification" you want to run SSL on the Arduino. That's not going to happen since it's way too underpowered for that.  As I mentioned earlier, the Arduino would connect to a server on the internet to receive its instructions, or you could interface to it directly within your local network (say from a smart phone) through a simple web server interface (very simplistic due to lack of memory - a few buttons and text, that sort of thing).

It is debatable if the Intel Edison can be called "Arduino", but it has an expansion board which allows to interfacing with Arduino shields and it can  run Apache/PHP/you-name-it.

I don't count the Edison as an Arduino. It's an embedded computer with an Arduino strapped on the side.  Personally I'd rather go for a Raspberry Pi 2 with a chipKIT Pi on top of it.

From that perspective, Edison is less of a cheat than Yun and Tre.
While both Yun and Tre make use of a separate microcontroller, to emulate the Arduino functionality, the Edison has only one Quark core for certain specific functionality. Last time I checked the PI2, it was still depending on a binary blob for booting, so I don't think it's the best choice. If I have to stay in the ARM filed, I think a BBB or an ODroid are much better choices.

Bbb is better than Pi certainly, but there is no chipKIT daughterboard available yet.


text:
Which wireless technology should I use for my outside "check-if-door-is-open" project?
I want to connect a magnetic door open/closed sensor to a device that can transmit (or be queried for, whichever) the state of the door to a hub inside (probably RaspberryPi). The outside unit should...

Operate on as little power as possible (outside unit will consist of board, open/closed sensor, power, and transmitter)
Be able to transmit from my back yard to inside my house (~15 meters to house & 1 or 2 walls).

I am new to this and pretty confused as to whether I should use BLE, Zig/xbee, or 2.4ghz rf (is that different? I am not even sure...).
Other considerations are cost (of course) and ease of use. I am a novice with hardware & want something easy to get up and running.

Had been looking at this when I asked the question: http://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24LU1P

NRF24L01+ would be more appropriate, unless you want to go program the 8051 processor that is inside the UL1P (which is not as easy as programming and arduino). Alternatively go with some 433mHz transmitter receiver pair. This frequency is used on most wireless doorbells, and wireless power outlets.

I agree with @Gerben - the nRF24L01+ would probably be the most suitable for your application.  It should have enough range to go 15m through a few walls, and the cost is about as cheap as you can get.
You can pick up cheap Chinese clone modules (not real nRF24L01+ but another chip that operates exactly the same) for around $2 each on eBay.  I by them by the bag full.
There are a few good libraries around for controlling them with an Arduino so programming really isn't much of a problem.
They even have the advantage that they can operate in a mesh network mode if you ever expand your system to incorporate other things.
The connection to the module is a simple 5-wire SPI interface - SDC, MOSI, MISO, Chip Enable and Command Select pins, so you don't even need to mess with lots of wires.
You can read more about using them here: http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01
The best library in existence is the RF24Network library: https://github.com/maniacbug/RF24Network
If you are looking for something more self-contained and stand-alone, you might look at the ESP8266 modules which are a programmable WiFi module.  They can either interface with an Arduino to be controlled through AT commands, which is quite nasty, or they can be programmed directly using an Arduino-like API which can be obtained here: https://github.com/esp8266/Arduino
These modules are a little more expensive, but that cost is offset by not then needing an Arduino in the mix as well.  The NodeMCU is probably the easiest to work with since it contains the USB serial interface on board like an Arduino.  It also has its own Lua based programming environment if you don't mind learning another new language, but you can use it with the Arduino API for ESP8266 above.
The ESP8266 is also supported by the beta version of UECIDE

So I could use this to a) read sensor state b) transmit directly to raspberrypi (or would it need to go thru router?) and c) run for days/weeks without needing recharge? It looks like there are only 8 pins and I assume a couple are for power? Sorry, I'm still pretty confused :(

Two are power and ground. Some are special purpose and need to be placed in a specific state to get it to run (or other states to enter the bootloader, etc), and others are digital IO to do with what you want.  It can connect to a WiFi access point (router) or it can be a WiFi access point for the Pi to connect to, or the Pi can be an access point for the ESP to connect to (hostapd). Can it run for weeks without recharge? That depends on a) how you program it (sleep modes etc) and b) what your power source is.

The smaller modules like that, though cheaper, are much harder to work with.  I'd seriously recommend working with the NodeMCU as your first foray into the ESP8266 since it is so much easier to work with.  Yes, it's a little more expensive, but is a great board to develop with.  You could then migrate to a little ESP-01 to build your finished device though.

Alright. Upvoted but upon further consideration this does not answer my question. There are two (plus) alternatives listed and no clear path with regards to power... I appreciate your help but I need "Use X because Y, it has the following API to sleep/wake your unit" etc.. I need a bit more specific guidance. :)

incidentally this unit will be dormant 99% of the time and only really need to transmit when the sensor's state changes. Is wifi as fast-to-connect/low-power as BLE here?

Pretty much every RF module has sleep or low-power facilities.  It doesn't really make that much difference which you choose from that perspective.  Yes, some are easier to sleep than others, but pretty much all can be slept.  WiFi takes seconds to connect.  The nRF24lL01+ doesn't need to connect so it takes no time at all - just the time it takes to come out of low power mode. From that perspective the nRF24L01+ would be a better option, but then you need an Arduino or something similar, again pretty much all options have a low-power or sleep option.  Some are better than others ...

... because of the power options on the board (linear regulators are power hungry and can't be slept) but there are specific arduinos available designed for battery operation.

BTW, see my previous answer for more technical detail about latency and range of the NRF24L01+.


text:
Sending A String from a Website to Arduino
I'm quite new to Arduino and have looked at many tutorials featuring an Arduino requesting data from a web server through a Wifi Shield, but haven't seen one featuring the sending of data from a website/server to an Arduino. I'm attempting to use a JavaScript then PHP script to send a string variable to the Arduino, which would then of course run its code at this point. Is this possible if I have a Wifi Shield and the Arduino's IP address?

Can you clarify if you want the Arduino to be a server or client?

send a string variable to the Arduino, which would then of course run its code - server

As @MattClark said, Arduino would be the server

However the question read: looked at many tutorials featuring an Arduino requesting data from a web server through a Wifi Shield - the Arduino requesting data from a web server makes it sound like a client to me.

On the yun, this functionality is built-in via the bridge. Here's an example.
Via the shield, you now end up writing your own webserver and responding appropriately.
I'm guessing it makes more sense to use the client (the web browser) to make the calls than the backend php, but in either case, once the webserver is up and going on the arduino, you're just using it like any other server.

If you really want the Arduino to be a web server (that is, you connect to it with your web browser) then I made a library a little while back to simplify processing the get/post/pathname/cookie arguments.
See Tiny web server for Arduino or similar.
Example code (that comes with the library) turns on various LEDs (presumably connected to pins on the Arduino) upon getting a "get" request like this:
http://10.0.0.241/?on=4&off=5

That would turn on pin 4 and turn off pin 5. Obviously you change the IP address to suit your network, and use a suitable MAC address.
// Tiny web server demo
// Author: Nick Gammon
// Date:  20 July 2015

#include <SPI.h>
#include <Ethernet.h>
#include <HTTPserver.h>

const int LOW_PIN = 3;
const int HIGH_PIN = 5;

// Enter a MAC address and IP address for your controller below.
byte mac[] = {  0x90, 0xA2, 0xDA, 0x00, 0x2D, 0xA1 };

// The IP address will be dependent on your local network:
byte ip[] = { 10, 0, 0, 241 };

// the router's gateway address:
byte gateway[] = { 10, 0, 0, 1 };

// the subnet mask
byte subnet[] = { 255, 255, 255, 0 };

// Initialize the Ethernet server library
EthernetServer server(80);

// derive an instance of the HTTPserver class with custom handlers
class myServerClass : public HTTPserver
  {
  virtual void processPostType        (const char * key, const byte flags);
  virtual void processGetArgument     (const char * key, const char * value, const byte flags);
  };  // end of myServerClass

myServerClass myServer;

// -----------------------------------------------
//  User handlers
// -----------------------------------------------

void myServerClass::processPostType (const char * key, const byte flags)
  {
  println(F("HTTP/1.1 200 OK"));
  println(F("Content-Type: text/html\n"
            "Connection: close\n"
            "Server: HTTPserver/1.0.0 (Arduino)"));
  println();   // end of headers
  println (F("<!DOCTYPE html>\n"
             "\n"
             "\n"
             "<title>Arduino test</title>\n"
             "\n"
             "\n"));

  } // end of processPostType

void myServerClass::processGetArgument (const char * key, const char * value, const byte flags)
  {

  int which = atoi (value);
  if (which >= LOW_PIN && which <= HIGH_PIN)
    {
    if (strcmp (key, "on") == 0)
      {
      digitalWrite (which, HIGH);
      print (F("
Turning on pin "));
      println (which);
      }
    else  if (strcmp (key, "off") == 0)
      {
      digitalWrite (which, LOW);
      print (F("
Turning OFF pin "));
      println (which);
      }
    else
      {
      print (F("
Bad action: "));
      fixHTML (value);
      println (F(""));
      }
    }
  else
    {
    print (F("
Bad pin number: "));
    fixHTML (value);
    println (F(""));
    }

  }  // end of processGetArgument

// -----------------------------------------------
//  End of user handlers
// -----------------------------------------------

void setup ()
  {
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip, gateway, subnet);

  for (int i = LOW_PIN; i <= HIGH_PIN; i++)
    pinMode (i, OUTPUT);
  }  // end of setup

void loop ()
  {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (!client)
    {
    // do other processing here
    return;
    }

  myServer.begin (&client);
  while (client.connected() && !myServer.done)
    {
    while (client.available () > 0 && !myServer.done)
      myServer.processIncomingByte (client.read ());

    // do other stuff here

    }  // end of while client connected

  client.println(F("
OK, done."));

  client.println (F("\n"
                    ""));

  // give the web browser time to receive the data
  delay(1);
  // close the connection:
  client.stop();

  }  // end of loop

Library source on GitHub at nickgammon/HTTPserver.
The library is designed to allow you to receive cookies, POST data, pathnames (on the URL) and GET parameters.


text:
Can a shift register be used to extend the Arduino pins when an ethernet shield is mounted on the Arduino?
I am currently working on a wireless home automation system. The system is connected to a wireless network in the home via the ethernet cable connected the ethernet shield and router. Hence, I need more pins on the Arduino to connect the appliances to be controlled in the home.

You can control a shift register with shiftOut or bit-banged SPI.
My page about SPI has a small library that does bit-banged SPI.
It is also possible to control a shift register using the same pins (MOSI/MISO/SCK) that the Ethernet interface uses, as long as you use a different SS (slave select) pin for your shift register. This may not be practical if the Ethernet card is active all the time. It is probably easier to do the bit-banged SPI or use shiftOut.

Yeah, if the Arduino has available pins to run a bit-banged SPI, it would likely be a bit safer overall.

Not all shift registers have an SS pin. But that doesn't matter as long as you don't latch the data sent to the Ethernet shield.


text:
Is parity check hardware only or can I read it? ( Arduino Mega )
Maybe a simple question, but I can't seem to find it.
Parity check is simple error detection.
But is in done in hardware on the arduino and is the data discarded before i can read it from software?
The reason I ask this quote from Thomas

1  Command bit, set on the first character of each datagram. Reflected in the parity bit of most UARTs. Not compatible with NMEA0183 but well suited for the multiprocessor communications mode of 8051-family microcontrollers (bit SM2 in SCON set).

From http://www.thomasknauf.de/rap/seatalk1.htm#Dat which might have confused me. So I guess this is not an option ... after the feedback from users.
So i need to read the 9 bit and since the hardware support it. The Arduino team won't implement it, since it has a bigger overhead and it's really not used anymore ... I agree ... but the SeaTalk bus uses it ... so I'm stuck here.
But after more seaching I found this GitHub repo: https://github.com/rob42/FreeboardPLC_v1_2 which have made changes to the HardwareSerial.h and HardwareSerial.cpp but only for version 1.5.7
Think I will go for this version unless someone have done the mods to 1.6.x ... have searched the web. Later I will try to see if I can get it to work with 1.6.x ... but since this is all new. I'm taking small steps.

I am not familiar with atMega, but on the chips I know (PIC, Cortex) when a parity error occurs, the parity error flag is set and the data byte is discarded, so you can't use it to fake 9 bit data. But Some UARTs doe have a 9-bit mode. You should check the data sheet of the chip (has nothing to do with arduino).

There are two partial queries here - one is asking about parity check on (I assume) the Atmega2560. The other is asking whether you can transmit 9-bit data on the same chip. Please help by clarifying which of the two is your actual question.

@wouter Thank ... I read more and got a bit more knowledge about the subject.

@stefan I have cleared up the question and also the part why I was looking into the Parity part ... which I guess is not the right way to go.

This came up a while back on the Arduino Forum - talking about Asynchronous SeaTalk.
I made a modified version of HardwareSerial which can be downloaded from http://gammon.com.au/Arduino/HardwareSerial9bit.zip
Changes are:

The internal buffers have been changed from 8-bit characters to 16-bit characters (to hold the 9th bit). Thus the buffers double in size.
There is a new argument to the Serial.begin() function, which is a boolean, whether or not you want 9-bit mode. It defaults to false.
There is a new function Serial.write9bit (). This takes an unsigned int argument, letting you supply a character with the 9th bit set. I didn't want to change the existing write function because it is used in the Print class.
The read function, which already returns an int, now will return the 9th bit where required.

Example code:
void setup ()
{
 Serial.begin (115200);  // debugging prints
 Serial1.begin (115200, true);  // 9 bit mode
 Serial2.begin (115200, true);  // 9 bit mode
 Serial.println ("--- starting ---");
}  // end of setup

int i;

void loop ()
{

 Serial1.write9bit (i++);  // send another byte

 // display incoming on Serial2
 if (Serial2.available ())
   Serial.println ((int) Serial2.read (), HEX);

 // check if we have sent all possible characters
 if (i >= 0x200)
   {
   delay (100);
   while (Serial2.available ())
     Serial.println ((int) Serial2.read (), HEX);
   delay (5000);
   i = 0;
   }  // end of sent 512 bytes
}  // end of loop

As Ignacio Vazquez-Abrams said, the hardware supports this 9-bit mode natively, it just takes a bit of fiddling around to make it work.
Because of the way that hardware serial is integrated into the IDE it is, unfortunately, necessary to find your existing files:

HardwareSerial.cpp
HardwareSerial.h

... and replace them with the ones in the download.

Note that this is for version 1.0.1 of the IDE. No guarantees are given that this will work with other versions. This was written a while back, I'm not sure what changes have been made to HardwareSerial in the meantime.
The actual changes are here: http://gammon.com.au/Arduino/hardwareSerial_diffs.txt
You could use those to guide your implementation on more recent versions, if the file download does not work "as is".

AVR devices with a hardware USART have a real 9-bit mode; there is no need to "fake" it.
But to answer your question, it is done in hardware; the appropriate USART Parity Error bit is set and while the datasheet is vague about it, it is implied that the data is stored in the receive buffer.

Thanks. That cleared up some of my confusion and also added more. Have updated the question with more information about my original issue since the parity check is not the way to go.


text:
Ethernet shield not have MAC address sticker
Hi everyone I recently bought an Arduino Mega and Arduino Ethernet Shield. There are lots of forum posts that say the shield should have a MAC address that is written on the back side of shield, but I don't have any sticker which has the MAC address. Does anyone know how I can get my MAC address or configure it with a new MAC address? Thanks

You can set the MAC address to whatever you want. See the above question that yeti mentions.

According to this documentation, you can just provide your own.

mac: the MAC (Media access control) address for the device (array of 6 bytes). this is the Ethernet hardware address of your shield. Newer Arduino Ethernet Shields include a sticker with the device's MAC address. For older shields, choose your own.

YES... you can define a MAC yourself. If you want to do it right, read a bit about MACs, especially the LAA-bit and how not to specify a broadcast address...


text:
Usefulness of measuring 0v using ADC
I'm looking at the datasheet of the ATMega328, and I see the different channels you can select for AD conversion. ADC0..7, ADC8 (temperature), 1.1V (VBG), and lastly 0V (GND).

What would be the use of measuring 0V?
Would it ever result in a reading other than 0? I find it very intriguing.

The datasheet doesn't seem to give any additional information about it.
AVR126 seems to give a hint:

configure 0V (GND) in ADC by setting Mux bitfield (MUX3:0) equal to 1111. This is done to discharge the capacitor of ADC.

Though I find the document rather strange (incomplete, lacking certain info, running the ADC at 500kHz while the datasheet says to not exceed 200kHz).
Is it to protect the ADC from to high a voltage in the ADC capacitor, when changing to a different (lower) reference voltage? Rather odd you need software to protect the IC, and it's not even mentioned in the datasheet. Also I've never seen anyone do this (e.g. when measuring the internal temperature of the ATMega).

That quote you mention says it all really.  It's purpose is to discharge the Sample And Hold capacitor.
That capacitor is used (as I'm sure you are aware) to store the incoming voltage while it's being sampled by the ADC.  The ADC operated in two main phases:

Acquisition
Sampling

During acquisition the capacitor is connected to the incoming voltage.  During sampling it is disconnected from the incoming voltage and the voltage it stores is read into the internal registers.
It takes a certain amount of time for the voltage in the capacitor to equal that of the incoming voltage.    If you try reading at higher speeds then what voltage was in the capacitor from the previous sample can affect the new reading.  However, if you do each sample always from a known voltage in the capacitor (0V) then you get much more stable results.
Another good use for it is when using the ADC as a Charge Time Measurement Unit.  This is the proper way of performing capacitative sensing.  You apply a constant (tiny) current to an external capacitor (the sensing plates) for a specific period of time.  When that time is up you disconnect the constant current source and measure the voltage that has developed across that capacitance.  The capacitances and currents are small, and if there is a charge in your S&H capacitor at the time you do the sampling that will be back-fed into the touch sensor capacitative plates changing the voltage.  By ensuring that the S&H capacitor is at 0V before you sample the plates you won't be adversely affecting the voltage on the plates with successive readings (well, you will, but it will be consistently in the same way every time so it won't affect your overall results).

About S&H: unless one is really desperate, shouldn't the acquisition phase be such that it allows the capacitor to charge to whatever is considered precise enough for the maximum variation? Iow, taking for example Ta=5RC, where R is the parasitic resistance and C the capacitance, don't they pretty much set the max frequency? I'd think that if one is really desperate to the point of forcing such constraint, it would be faster to not discharge the capacitor at all, assuming that there is somewhat a correlation between successive readings. Especially if performed at high frequency.

Forcing the initial voltage on the capacitor to be 0V means that one has to always allow enough time to reach Vmax. By limiting the maximum Voltage variation, it is possible to measure at increased speed, accepting that there might be a possibly large error, depending on how much the assumption on the max DeltaV is violated.

So consistency. That makes sense. Though with the speed example, you would lose half the rate, cause you do a 0v read between every regular read. Also, if the speed speeds are high, is the sample period long enough to fully discharge the cap?

Though I find the document rather strange (incomplete, lacking certain info, running the ADC at 500kHz while the datasheet says to not exceed 200kHz).

The document actually says:

The ADC can prescale the system clock to  provide an ADC clock that is between 50kHz and 200kHz to get maximum resolution.

(My emphasis)
It goes on to say:

If ADC resolution of less than 10 bits required, then the ADC clock frequency can be higher than 200kHz. At 1MHz it is possible to achieve eight bits of resolution maximum.

I did some testing on this page with different prescalers. The results showed that reasonable results could be obtained even with a 1 MHz ADC clock:
Prescaler 2

Analog port = 0, average result = 1023
Analog port = 1, average result = 1023
Analog port = 2, average result = 1023
Analog port = 3, average result = 1022
Time taken = 26220

Prescaler 4

Analog port = 0, average result = 673
Analog port = 1, average result = 718
Analog port = 2, average result = 512
Analog port = 3, average result = 193
Time taken = 32780

Prescaler 8

Analog port = 0, average result = 842
Analog port = 1, average result = 677
Analog port = 2, average result = 509
Analog port = 3, average result = 34
Time taken = 46040

Prescaler 16

Analog port = 0, average result = 1022
Analog port = 1, average result = 672
Analog port = 2, average result = 509
Analog port = 3, average result = 0
Time taken = 73164

Prescaler 32

Analog port = 0, average result = 1022
Analog port = 1, average result = 672
Analog port = 2, average result = 508
Analog port = 3, average result = 0
Time taken = 128040

Prescaler 64

Analog port = 0, average result = 1022
Analog port = 1, average result = 672
Analog port = 2, average result = 508
Analog port = 3, average result = 0
Time taken = 240972

Prescaler 128

Analog port = 0, average result = 1022
Analog port = 1, average result = 672
Analog port = 2, average result = 508
Analog port = 3, average result = 0
Time taken = 448108

The four test voltages were, and their results should have been:

5V (should return 1023)
3.3V (should return 674)
2.5V (should return 511)
0V (should return 0)

The tests were done in rapid succession, no allowing for the ADC to recharge or anything:
 unsigned long startTime = micros ();
  for (int i = 0; i < ITERATIONS; i++)
    {
    for (int whichPort = lowPort; whichPort <= highPort; whichPort++)
       {
       int result = analogRead (whichPort);
       totals [whichPort - lowPort] += result;
       }
    }
  unsigned long endTime = micros ();

Thank you. I guess I skipped that page when browsing your site. In the sample code belonging to the document, they use all the 10-bits. I just find it weird to give an example that's not as precise, and not even warn about this. Though your test seem to indicate there isn't any difference in the results. I guess I will 'overclock' my ADC to get a bit more battery life on my current project.


text:
CC3000 Wifi: Enable Debug
How do I enable debugging using Adafruit CC3000?
I am using the Adafruit_CC3000_Library.  I've followed the WebClient.ino example sketch.  I'm able to make 300 to 400 HTTP requests, but eventually the connection will hang.
I have looked at the CC3000 source and utilities and found that the Adafruit_CC3000_Library has a &Printer reference in a local variable called CC3KPrinter.  I can't figure out how to enable or activate CC3KPrinter, as it is in a code block contingent on CHECK_PRINTER.  I thought that #define-ing some variables in my sketch would help:
// None of these flags seem to enable debug within the CC3000 code.
#define _CC3000_DEBUG  1
#define DEBUG_MODE     1
#define ENABLE_CC3K_PRINTER 1

An example code snippet within the CC3000 library that I'm trying to enable is at line 916:
  CHECK_PRINTER {
    CC3KPrinter->println(F("Timed out waiting to connect"));
  }

Have you tested that the board actually connects to your wifi with more basic code? Did you put any print statement debugging into your code to see where it hangs? You're referring to this Printer section, but I feel that it is probably a red herring without knowing more about why you've picked it out. The other options look like the debugging, but if they aren't producing results then I'd just go through the library and put in print statements to see where you get to. They might not be returning anything if for some reason it doesn't get that far. Make sure your changes are correct.

@bladepanthera: I've edited the question to show that the connection works for 300-400 cycles; typically about 40 minutes.  I've confirmed via print statements that the hang happens within the CC3000 code.  This question pertains solely to enabling the CC3000 debugging code blocks.

From what I've been looking at the CC3KPrinter will print to serial when debugging is enabled, which is what you want. I'm not sure why it's not when you seem to have it enabled. I can only think of the obvious things like make sure #include "utility/debug.h isn't commented out and are you using the library you think you're using (I have two versions of Arduino on my laptop). If still no luck, then debug the library yourself with prints to find out exactly where the hang is. Make sure the buffer is clearing properly etc. Sorry can't help more.

@bladepanthera: I did re-confirm that I have the utility/debug included.  I think "debug the library yourself" is a great idea, but I'm not sure where to start.  In my Arduino IDE (v1.6.5) I can only open *.ino sketches.  The libraries are written in C++.  Are you suggesting I modify the *.cpp library files (i.e., Adafruit_CC3000.cpp)?

Yup. Literally put print statements in the cpp file.

Do you use a single TCP connection for the 400 HTTP requests or made and close a TCP connection for each HTTP request?

@LookAlterno IIRC I made a new TCP connection for each request.

To enable debugging, you need to

uncomment ENABLE_CC3K_PRINTER in Adafruit_CC3000.h
If you want to pass in some debug stream other than the default Serial, you should pass a pointer to the object (which should inherit from Print, such as SD or Client) as the last argument to the constructor in your sketch:
Adafruit_CC3000(uint8_t csPin, uint8_t irqPin, uint8_t vbatPin, uint8_t spispeed = SPI_CLOCK_DIVIDER, Print* cc3kPrinter = CC3K_DEFAULT_PRINTER);

In utility/debug.h, change the value of DEBUG_MODE to 1 (or any non-zero value)

I don't know what caused your issue but you shouldn't put this in your code:
#define _CC3000_DEBUG  1

Because most of utility/debug.h is wrapped in the usual:
#ifndef _CC3000_DEBUG
.
.
.
#endif

Your #define, depending on where it's placed, could cause most of the file to be skipped by the compiler and result in compilation errors. To be on the safe side, get rid of it and simply include utility/debug.h as needed.

Poor workaround: since I was trying to solve a connection hang, I opted to use a watchdog timer solution, leveraging the lightly documented <avr/wdt.h> library.

authors: جمعان الزاهرني


text:
Yum as eth->wlan adaptor
Is there a way to make a yun an Ethernet-wifi bridge? Applications include giving wifi to raspberry pi and other Ethernet only devices and vice versa.

You know you can get a real high-performance Wifi access point for much cheaper...

@MattiVirkkunen Already got one of those...in the other room. And no, I can't move it or the wired only device.

I'm sure any shop will be happy to sell you another one. Or three! Probably should've said "Wifi client" since some devices only support AP mode. And for an RPi, just get a USB Wifi adapter...

@MattiVirkkunen I don't have a lot of money. Besides, i have a spare yun (haven't found something to do with it yet besides hosting a kittens game server)

Yes, you can.  I use one to connect my Sky box (Ethernet only) to my WiFi network,
It's not an easy task though and you have to have a good understanding of networking and routing.
Basically you have to set the Yun up as a router to route packets between the Ethernet and the WiFi interfaces.  You set the Ethernet interface up on a separate subnet to your existing WiFi network, and set a static route on your main router to send traffic destined to your new Ethernet subnet to the Yun's WiFi IP address.
Your Ethernet devices can then be allocated an IP address on the Ethernet subnet (turn on DCHP for that interface on the Yun) and will use the Yun as the default gateway.
There are probably ways you can enable bridging on the Yun to tie the Ethernet and WiFi interfaces together so it becomes transparent but I haven't investigated that yet.


text:
'AttachPinChangeInterrupt' was not declared in this scope
I am a beginner trying to upload the SimpleExample328.ino sketch on my Arduino Uno. When I verify my sketch however, I run into the error:

'AttachPinChangeInterrupt' was not declared in this scope.

I would assume the header file PinChangeInt.h is not in the correct location; currently the PinChangeInt folder (that contains PinChangeInt.h) is placed in the Arduino IDE libraries folder, which I believe is the correct location.
Did I place the header file in the wrong location or does this error result from another cause? Thanks :)

Please edit your question, and post the sketch you are attempting to compile (or, if it is long, post a link to where you found it). Please copy and paste the error messages. Use Ctrl+K on both blocks to indent them so they appear as "code" in the post.

Do you mean this sketch: SimpleExample328.ino? I think that library is made for Arduino 1.0, and not the latest 1.6.

Oh, yes I do! Where would I find the latest library for PinChangeInt and examples for me to try? Thank you :)

Did you take a look at the README? “This library is deprecated [...] users are encouraged to migrate to the EnableInterrupt library [...]”.

You don't have the library installed. To install:

Go to https://github.com/GreyGnome/PinChangeInt
Click the green Clone or Download button
Select Download ZIP

The .ZIP file will download to your computer. Take note of the location.

Open up the Arduino IDE
Go to Sketch > Include Library > Add .ZIP library...
Browse to the download location
Select the PinChangeInt ZIP file

Its done! Compile your program and all should work!

@sa_leinand, what do you do? the library was already deprecated in the time the question was asked in 2015

Agreed that the library is depreciated. That doesn't mean it doesn't work. The sketch that the OP is trying to run is actually one of the examples from that library. To get that sketch to run you need to install the library.

The library was deprecated and completely rewritten as the EnableInterupt library. The main reason was so that the library is "for all versions of the Arduino", not just the few that PinChangeInt worked for. The OP has tagged the Arduino Uno, which works fine with PinChangeInt.


text:
LCD Display Flicker When Arduino Main Board Supply Voltage to GSM Shield Board
I have a 16x2 LCD display that is connected to an Arduino microcontroller.
It is working fine but the LCD display flickers when I connect the Vin and GND of the main board to its slave GSM Shield.
I used main board Vin and GND to power up the GSM Shield so I only have one power supply. I was able to power up GSM Shield by adding jumper to Vin and GSM +Vin.
In additional question, is there any other way to power up Arduino GSM Shield without connecting it to another power source to still keep having only one plug for power?

What Arduino model?  What's the supply you attached to Vin, what's it's nominal voltage, and what voltage do you measure when it's attached?  What model GSM board?  Why hook GSM to Vin instead of +5?

GSM is notorious for very high pulse power demand when transmitting, which can easily cause a supply brownout.  Capacitor solutions are possible, but some have resorted to using a battery to power the radio.

This sounds like either your GSM Shield is drawing to much power (from time to time) and thus your Vin drops resulting in flickering or your GSM Shield induces ripple on top of your Vin.
To debug this I would recommed to have a look at Vin with an oscilloscope and see how stable Vin is. Additionally some capacitors between Vin and GND (100nF and 10-100µF) and a ferrit between Vin and the GSM Shields Vin might help.


text:
How to make C++ code compatible with Arduino IDE?
I wrote some code in C++ (Used libraries like fstream, vectors etc.) Now when I transferred the code to Arduino it wouldn't compile so I added the following library: https://github.com/maniacbug/StandardCplusplus I downloaded the IDE from here: https://www.arduino.cc/en/main/software
Now almost all my code works: All the libraries I've used work except for fstream which I've used to read a specific file.
Now is there a certain problem with the 'StandardCplusplus' library and how can I counter this problem.
Plus can someone give me an alternative for fstream that works with Arduino. Was reading a bmp image using C++. Now fstream works in a certain way (reads the file in a certain way). Is there some alternative to fstream.

Work with Atmel Studio and their compiler?

When you run that library on the Arduino and ask it to open a file, where do you imagine it would read the file from? Your Arduino has no hard disk or other file system.
One way to solve this is to include a library that emulates a read-only file system in the Arduino's flash. I dunno whether this exists (such libs do exist for for some other targets, for instance for the Nintendo DS), but it would be a bit of overkill IMO.
Another way is to include the data that is in the file in your program, as a const (expr) array of bytes, and read from that array instead of from the file. But if you have a library that is coded to use file read calls this would require some rewriting.
A third approach would be to do the reading and interpreting of the file on your host PC, output the interpreted content to a const (expr) byte array, and include that in your application. This frees you from having to include the bmp-read code in your image.

seem a lot easier to use atmel studio and their compiler that let you use Macros...

How would that solve the problem of not having a file system?

AVR GCC can compile c++, but Arduino IDE isn't the most suitable tool to do that all. With a tool like Atmel studio, he could create a "memory partition" in the internal memory, i see project were dev kit where transform into fat32 USB stick,therefore he would have a "file system".

Well you can add a filesystem if you add an SD Card reader. You'd just have to replace part of the code with the SD library... However this better be done on a Mega 256 or better.

If you want to write C++ for an Arduino, I'd recommend you cease using the Arduino IDE and instead use Atmel Studio. The microcontroller on board is an Atmel AVR, and you can write for that using the gcc-avr toolchain that comes with Atmel studio.
You'll lose the spiffy libraries that come with the arduino platform that abstract away a lot of the intricacies of the hardware, and you'll instead be looking at the AVR datasheet and the schematic of the arduino, but you'll learn quite a bit in the process and have direct control over the hardware.
With all that said though, the AVR does not have a file system so using fstream doesn't make any sense to begin with.

The Arduino IDE does compile your code using the avr-g++ compiler. In other words, it is C++.

Was reading a bmp image using C++.

This isn't practical on the smaller Arduinos, at least, because they have so little RAM. They also don't have a file system. There is a streaming library for output, which is very handy for streaming out things to Serial, LCDs, etc.
One of the replies here mentioned that if you switch to Atmel Studio you can look at the datasheet and get down to the intricacies of the hardware. Well, you can certainly do that as well with the IDE. All the hardware registers are available for use. I often use the "bare" registers for timers, watchdog, interrupts etc.
Also Atmel Studio only runs on Windows. You are out of luck if you use a Mac or Linux.
There is also a port of the Standard Template Library for the Arduino, if you want to use vectors, lists, maps etc.
There is also another port of the STL which may work better and be easier to install.

Are you using Arduino UNO? Look at the datasheet and see how much RAM the Arduino has. Assuming you are using Arduino Uno, it should be around 2kilobyte or less. So it is highly likely not to have enough memory to read the BMP file. Even if you are trying to read very small BMP file, the code reading the file would vary depending where you are reading the BMP file from (SD Card, SPI Flash memory, etc.) It cannot read files directly from your computer using just fstream.

To answer your compile problem.. Are you using c++11? The issue could be that Arduino Compiler may not support entire C++11 features.
So if you cant find an alternative for fstream (I dont know any) then you have to find a different way compile the C++11 code and upload it. You can do this with a Makefile, avr-gcc. Its plenty of generators out there.

While C++ version features can be an issue, in this case it is far overshadowed by the fact that the library is trying to perform tasks that aren't possible on the Arduino.


text:
How do I compile the Marlin firmware?
I have a folder of mostly .h and .cpp files for the Marlin firmware (3D Printing) from here.
How do I compile that so I can upload it to my Arduino Mega with Ramps?

Your question is very broad. What have you tried?. In what way did it not work? Does the linked site not have a tutorial? In what way did the tutorial not help?

You need to open the .ino file. that is the project file for the Marlin Firmware. then upload that. Also do some research about the settings for Marlin. It isn't just plug and play, you have to enter some information about your individual stepper motors.
http://solidutopia.com/marlin-firmware-user-guide-basic/ - heres a guide for Marlin.
the cpp and h files are c++ files that are apart of the project. the Arduino IDE cannot open these individually. the .ino file is the project file that will allow you to open up the entire project and not just one portion of it.


text:
Is it possible to accept multiple web requests at once?
I have an Arduino with ethernet shield and there are 8 different URLs that can be called to perform different actions.
The program loads and runs as expected for the most part, but, if it is busy doing an action, it won't accept the next one until the current action has finished.
Basically, the code's main loop listens for a client connection, then has a bunch of ifs that look in the URL that was called (for a query string) and then process the command.
I have looked at a few answers on here, but none deal with listening to HTTP requests. One recommended a library, but, I couldn't quickly get it to compile, and the other answer recommended a state machine - I do like this approach, however, I haven't had time to implement and it doesn't "feel" right as the listening for a HTTP request works on a if(client) basis.
I was wondering if anyone has done this before and/or has any advice?

What sort of action would it be busy doing? Generally I would expect the server to decode the HTTP request almost instantly, and then do the action (eg. return some data). Is your setup such that this might take some time?

@NickGammon - it needs to operate a solenoid for ~2 seconds which doing inline in the http request code means that it stops listening for new requests.

Then you need to start with the basics.  Look at the BlinkWithoutDelay example to see how to write non-blocking code. I'll bet your sketch is littered with delay() calls.  There is no place for delay() in a proper program, except for tiny (a millisecond or so) delays for timing purposes.  Also, get to grips with the concept of the Finite State Machine (there are many resources and tutorials online).

Not sure if it will work for your case, but you can try using interrupt to quickly jump to some signal and back to your main loop. This is similar to concurrency in a web server, since Arduino cannot run things in parallel.

it needs to operate a solenoid for ~2 seconds which ... means that it stops listening for new requests - as the other comments point out you just need to restructure. Turn the solenoid on, remember when you did that, and check in the loop which is listening for new requests if the time is up to turn it off again.

The official Ethernet Shield advertises ability to run 4 simultaneous sockets...

It can be done. The Arduino is a single tasking environment so you have to make sure your code is non-blocking.
BlinkWithoutDelay is a good starting point (thanks @Majenko) but you should also look at the Timer1 library.
Basically your programs needs to do all the steps it can right away and whenever it does something that could block, it must do it asynchronously and during a later loop() run check if it's finished and continue with the next task. The alternative (if you know how long your task will take) is to use the timer interrupt with the library mentioned above.


text:
Arduino for delivering a WoL signal over ethernet, when receiving a specific command over WiFi
I'd like to assemble a device that could accomplish the following:

Connect to my home wifi (WPA2-Personal)
Connect to my home PC with via Ethernet cable
Able to send WoL signal to the PC when getting a signal over wireless connection
The whole set up needs to be less than 45USD, desirably much less, otherwise I'd just buy a wireless bridge.

The goal is both to have a useful device (that will allow me to wake up my pc remotely) but also have fun learning something new (arduino).
I have no background in Arduino or Electronics in general. I program well though and learn fast.
Do you think Adruino is adequate for the above? Is soldering required (I'd rather not, or at least not a lot)?

Raspberry Pi sounds like the more appropriate option for you, as said by Mr Kim below. A useful thing about the Raspberry Pi is that you can put a lite operating system on it which makes it a lot easier to do networking stuff and run by itself. It's not that Arduino can't do it in theory, but in practice it isn't designed for that purpose. The latest Rasp Pi (2B+ or something) also has a decent amount of ram, and in general you use an SD card for memory so is more flexible in that sense.

Why do you need both wifi and ethernet. Just connect the arduino via ethernet to your router. You can send WoL packet from anywhere inside the network. You don't need a direct connection to the PC.

@Gerben the PC is connected to the router wirelessly. So will be the device. But the device will be also connected to the PC physically via ethernet, so it will be able to send WoL. Make sense?

Why not send the WOL via wireless as well. That way you don't need an ethernet shield. Also, why does the device need to be near the PC?

@Gerben To receive WoL on wireless, PC need to be powered up. It's the PC that does WPA, not the wireless network card. If PC is shutdown there is nothing that can actually receive and decrypt the wireless signal. Even if you take decryption out of equation (which in any practical set up you really can't) it's still not workable, because unlike Ethernet card a WiFi card need actively "scan" for wireless signals to receive them, and as a rule they do not do this when PC is powered off.

That makes sense. I didn't think of that. Alternatively you could connect the power button to an arduino pin and wake the PC that way. Just an idea.

@Gerben, yep, that would work too, still need WiFi though.

The Arduino might not be a choice for you. The reason why microcontroller boards(like Arduino) become popular is the simplicity and the easiness of control peripherals through GPIO pins, like output PWM signal to control motors, reading sensors through SPI or I2C, reading analog voltage, and etc. Most microcontrollers on Arduino boards itself, however, is not designed for networking features and does not have even enough performance for it. This means that it would cost you much more money on additional networking devices like WIFI shield, Ethernet shield and microprocessor for networking (Arduino Yun).
So, if you are looking for just a pure networking device like what you have in mind, I would highly recommend you Raspberry Pi(2 Model B for $39 and 1 Model B+ for $30), which has enough capability of networking itself. All you need is a USB WIFI dongle($9) with the Raspberry Pi, I guess. I am pretty sure you won't have a cheaper option using Arduino.
You can use the raspberry Pi as a web server, a NAS, a media server along with the features you mentioned.

The Raspberry Pi is definitely the easiest way to do this, however it will use more power.
You can do it within your budget by using Arduino clone hardware from places like AliExpress.
If you don't mind the extra effort, it certainly can be done using the Arduino and a wireless and ethernet shield.
A WiFi shield is around $17, an ethernet shield is less than $6 and an Arduino Uno clone is around $3. Make sure you can combine these shields (I haven't checked). There's also a combined Linux, Ethernet + Wifi Yun shield for around $30.

I doubt if you will do it in that price range. Buying genuine products (as opposed to clones from eBay) you would be paying something like:

Arduino Uno: $US 25
WiFi shield: $US 40
Ethernet shield: $US 45

Prices from Adafruit - other suppliers would have the same or similar for similar prices.
I see there is a Arduino Ethernet which combines the Uno and the Ethernet shield for $US 65.

The whole set up needs to be less than 45USD, desirably much less ...

Maybe someone else can suggest a cheaper option, but I think you will be pushing it here.


text:
Is the Arduino library so slow?
I have a plan to operate 5MP camera module with the arduino Due. But I wonder if I can use the arduino libraries that include digitalRead, digitalWrite and so on. But some people said that it is a bad idea. Especially I found that people wrote values on registers instead of using the library, when they control ov7670 with Uno.
Contrary to this, ArduCam uses the libraries, even for OV5642!. Here is the link
https://github.com/ArduCAM/Arduino/blob/master/ArduCAM/examples/mini/ArduCAM_Mini_OV5642_Video_Streaming/ArduCAM_Mini_OV5642_Video_Streaming.ino
So could anyone please let me know, if it is okay to use such library and never to use register directly? With 'register' I mean arduino's register, not camera's.
I guess the system clock and existence of FIFO would affect the answer. But still I don't know how to evaluate their effect analytically.

I don't see any digitalWrite call in that that library.

Unless you have a really large number of read/write operations and very tight time constraints, I doubt you are going to have any significant advantage in terms of speed.
Accessing the bits in a port together, rather than individually is certainly more efficient, both in terms of time and space, but it might cost in readability, depending on how comfortable you are with leaving the Arduino libraries behind.
You can have also a look at this thread.
Notice that the maximum gain happens only when all the pins you have to read or write belong to the same register.

You can use ANY and ALL libraries (if their LICENCies allows it) you want, or none library at all.
More important is, if the result does what you need.
For some kinds of problems even very slow library is fast enought. For some kinds only highly optimized library can do. Some problems are so complex, that any Arduino cannot do it even with the best effort and total optimization of code and HW resources. (Well, for some problems even todays best supercomputers are not good enough)
Lot depends on what exactly you plan to do with such camera - if you need some simple controls (like START, STOT, change sesitivity ...) maybe anything is good. If you want to make some autonomous system navigated by vison system which would learn from experience and will recognize all your face expression, than there is no Arduino with needed computing power at all.
Just try find any project vaguelly similar to yours, look, what they are using and what they say about it (excelent, barely usable, we found it impossible) and try library/approach based on that. If it works somehow, make it better and be celebrity too :) If it does not work at all and does not yeld any usable results, maybe try something different.
A lot can be done, if you enhance Arduinos capabilities with external modules (commercial or home made) be it in form of shield or in form of totally different platform.

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


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

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

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

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

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

Link

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

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

what about this issue now @PeterR.Bloomfield

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

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

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

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

Have you tried with a new trimmer?

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

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

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

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

link this is the wiring @Majenko

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

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

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

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

@evolutionizer check the photo

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

Also if possible please upload a higher resolution picture

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


text:
Arduino digitalWrite 1 or 0 instead of HIGH or LOW
Is it ok to use
digitalWrite(pin, 1) instead of digitalWrite(pin, HIGH)

or
digitalWrite(pin, 0) instead of digitalWrite(pin, LOW)

I want it that way to make the coding lesser because I save values on EEPROM with 1's and 0's. So if I want to use EEPROM value, I can call it this way
digitalWrite(pin, EEPROM.read(1))

I have no arduino to test now, but my bet is it's possible. HIGH and LOW are just constants for 1 and 0.

As a continuation to all the answers, the result of HIGH and LOW being #defined is that there is no change in compiled binary size -- only more descriptive names in source files (which is why they are recommended). The preprocessor converts HIGH into 0x1 and LOW into 0x0 for you.

Yes, that is fine.  LOW is 0 and HIGH is 1.  digitalWrite() sets the output to off if it receives a 0 and on if it receives anything of 1 or more.
That means that these are all equivalent:
digitalWrite(pin, HIGH);
digitalWrite(pin, 1);
digitalWrite(pin, 69);

It's especially useful when you are examining a variable for, say, a certain bit being set:
digitalWrite(pin, bytevar & 0x80);

That will set the pin to high on any value from 128 to 255 in the byte variable, and low for anything below 128.

From the arduino source code:
#define HIGH 0x1
#define LOW  0x0

So HIGH is exactly the same as 1. And LOW exactly the same as 0.

Exactly, and since HIGH == 1, then you could save HIGH to the EEPROM.

Also HIGH - HIGH == LOW (-;

This misses the point. The question is: is LOW guaranteed to always be 0 and is HIGH guaranteed to always be 1? Looking at the current source code provides no answer to that question.

@AnT HIGH and LOW are Arduino specific. Arduino doesn't have a specification like for example C, C++, or Forth. So looking at the Arduino source code is currently the best way to determine this. Can they change their code tomorrow? yes. Is this likely? Not in the slightest.

it doesn't have a type? As in if I want to declare a variable state and assign it a value HIGH or LOW later on, should i declare state as an int or something else?

@rfii #define is a macro. So the preprocessor replaces all the occurrences of HIGH and LOW with 1 and 0, before the result goes to the compiler. So, to the compiler, it looks as if you would have written 1 and 0. Or did a find&replace yourself. So it doesn't have a type, but can be seen as a string.

When you look at the source code of Arduino, HIGH is defined as 1 and LOW is defined as 0 using #define.
You may heard about Preprocessor, Compiler, and Linker. When you build the project, preprocessor do its job before the code is compiled. What the preprocessor does is basically converting defined words into corresponding value.
For example when you write a syntax like:
digitalWrite(1, HIGH);

When you build your project, the preprocessor converts the above like into this:
digitalWrite(1, 1);

Then the code is compiled. Therefore, there is no difference between HIGH and 1.
So, if the result of EEPROM.read(1) is either 0 or 1, there should be no problem.