text:
Is i2C more or less robust than GPIO?
Currently using i2C to connect a RPi with an arduino. It seems i2C is quite finicky and, drops the bus immediately if there are any IO errors. Since what i am building is meant to be semi permanent, I am worried that i2C may not be the best choice.
Has anyone done any real world testing of i2C vs GPIO for RPi to arduino communication?

GPIO is too generic to compare to without being more specific; for example, you can (with some difficulty) implement I2C using GPIOs.  I2C reliability/recovery problems are likely more about drivers than peripheral blocks themselves.

Here are a few things to remember:

You should have a ground connection between the RPi and Arduino
I2C was meant for really short distances on a printed circuit board
Arduino runs at 5 Volt logic levels and RPi at 3.3 Volt logic levels - you need a level translator between them to make that work.

If the RPi and the Arduino are not far apart, I would say less than 1 foot (30 cm) and you have the grounds connected between the boards, then it is a software issue. I2C is meant for short distances any anything longer than a foot puts too much capaitance on the wires and starts causing unreliable communication. I would not even use it for more than a few inches unless it was on a circuit board where you control the capacitance.
I am assuming your using the Wire library on the Arduino side. On the RPi side I would use the the Adafruit I2C library for the RPi as I have had success using the library to communicate with I2C sensors listed on their site. Here is the link:
Adafruit RPi I2C Tutorial

Not sure there is such a thing as the 'Adafruit' i2c library. The instructions on the adafruit site are quite good, but really no different than those on half a dozen other blogs. Also I believe you are incorrect about needing a level translator if connecting just one device.

Sorry, I2C is not the library, I was thinking the smbus Python library they tell you to apt-get. That is what I installed for my RPi. As for the level translator - you should not put 5 Volt signals to the RPi pins as it will burn them out. It might take a little while, though in my experience I burn out a few GPIO with 5 Volt signals as soon as I turned power on. Take a look at this from the Raspberry Pi website: http://www.raspberrypi.org/documentation/hardware/raspberrypi/gpio/README.md

@tiger19tony72 is right. If its 5V, use 5V, if 3.3V use 3.3V. Specifications exsit for a reason :)


text:
Modifying serial message for Adafruit NFC/RFID card
Using an Uno configured with an Adafruit RFID-NFC shield to send the UID values to a desktop game I am building.
Works fine. However, in addition to just the UID, I need to send 1 additional value, lets call it 'game choice'. This can be one of 3 values. This is just the relevant code. Can any experts suggest how I might modify the following to send this additional value?
/**************************************************************************/
#include <Wire.h>
#include <Adafruit_NFCShield_I2C.h>

#define IRQ   (2)
#define RESET (3)  // Not connected by default on the NFC Shield

Adafruit_NFCShield_I2C nfc(IRQ, RESET);

void setup(void) {
  Serial.begin(115200);
  Serial.println("Hello!");

  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print("Didn't find PN53x board");
    while (1); // halt
  }
  // Got ok data, print it out!
  Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

  // configure board to read RFID tags
  nfc.SAMConfig();

  Serial.println("init");
}
void loop(void) {
  uint8_t success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
  int nfcDEC;
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

  if (success) {

   nfc.PrintHex(uid, uidLength );
}
}

Could you elaborate on what you want to send, from where and to whom? Its not entirely clear.

The message is sent obviously whenever a user scans their tag over 1 of 3 possible scan targets(game choices). This 'game choice' value would be hardcoded. The receiving end is a desktop Adobe AIR application. Using the ArduinoConnector native Extension https://code.google.com/p/as3-arduino-connector/

so 3 arduinos+3 shields, 1 used for each choice and COM port

had to simply modify PrintHex in
Adafruit_NFCShield_I2C.h
to accept an additional argument

Could you explain a bit more on what you changed (show relevant code)? The answer in its current form isn't very useful to others having the same issue.

source: Stack Exchange

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

sort: votes


text:
Problem with Xbee or Arduino?
I am sending three analog signals through the xbees to be written to analog pins on the receiving side so they can be read in Simulink. I connected both of the arduino megas to my laptop and uploaded the sketches. I have a shield and a series one xbee connected to each arduino. I pulled up the serial monitor for each sketch. I connected a 1 volt DC power supply to all three analog pins. On the transmitting serial monitor I got numbers close to 200 which I believe is correct but on the receiving side I was not getting anything. I believe the problem is with the arduino. After I uploaded the code on the transmitting side the TX led was green but the RX led on the receiving side was not lit up at all. The power LED on the transmitting arduino is red but it is green on the receiving side. The 'L' led on the transmitting side is red on the transmitting side is read and yellow on the receiving side. On both of the xbee shield the power led's are red and the DIO5 led blinks green. On the receiving xbee shield the DOUT LED is red and the DI LED is green. If more information is needed let me know.
Here is my configuration for the xbees: (series 1. firmware version: 10ed)
Transmitting Xbee:
PAN ID: 1234
MY:10
DL:11
Receiving Xbee:
PAN ID: 1234
MY: 11
DL: 10
Transmitting arduino program:
int val1 = 0;
int val2 = 0;
int val3 = 0;
int analogPin1 = 0; //these are you analog in pins
int analogPin2 = 1;
int analogPin3 = 2;
void setup()  {
  Serial.begin(9600);  //start serial
}
void loop()                               // run over and over again
{
        Serial.print("<");                // This character signifies the begining of our data cycle
            val1 = analogRead(analogPin1);    // read the input pin
        Serial.println(val1);             // output the signal
        Serial.print("\t");               // Signifies end of 1st piece of data
            val2 = analogRead(analogPin2);    // read the input pin
        Serial.println(val2);             // output the signal
        Serial.print("\t");               // Signifies end of 2nd piece of data
            val3 = analogRead(analogPin3);    // read the input pin
        Serial.println(val3);             // output the signal
        Serial.print(">");                // This character signifies the end of our data cycle
        delay(100);
}

Receiving Arduino program:
#include <SoftwareSerial.h>
// software serial #1: TX = digital pin 0, RX = digital pin 1
SoftwareSerial portOne(0,1);
int Apin1 = 0; // These variables hold the current incoming value
int Apin2 = 0;
int Apin3 = 0;
int AnalogOut1 = 0;  //Set our analog pins
int AnalogOut2 = 1;
int AnalogOut3 = 2;
int Digits = 0; // Helps watch for comma
int Mode = 0; // This designates which section of reading we are doing - begin = 0, Apin1 = 1, Apin2 = 2, APin3 = 3, end = 4
void setup()
{
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
  // Start each software serial port
  portOne.begin(9600);
}
void loop()
{
  portOne.listen();
  while (portOne.available() > 0) {
  // read the incoming byte:
    char inByte = portOne.read();

    if (isdigit(inByte) && Mode == 1) {
    int temp = inByte - '0';
    Apin1 = (Apin1 * 10) + temp;
    Serial.print('\n'); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
    Serial.print(temp);
    Serial.print('\n');
    Serial.print(Apin1);
    Serial.print('\n');
    }
   if (isdigit(inByte) && Mode == 2) {
    int temp = inByte - '0';
    Apin2 = (Apin2 * 10) + temp;
    Serial.print(temp); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
    Serial.print('\n');
    Serial.print(Apin2);
    Serial.print('\n');
    }
  if (isdigit(inByte) && Mode == 3) {
    int temp = inByte - '0';
    Apin3 = (Apin3 * 10) + temp;
    Serial.print(temp); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
    Serial.print('\n');
    Serial.print(Apin3);
    Serial.print('\n');
    }
    if (inByte == ',') {
    Mode++;
    }
    if (inByte == '<') {
    Mode = 1;
    }
    if (inByte == '>') {
    Mode = 4;
    if (Apin1 > 0 && Apin2 > 0 && Apin3 > 0) {
    analogWrite(AnalogOut1, Apin1);
    analogWrite(AnalogOut2, Apin2);
    analogWrite(AnalogOut3, Apin3);
    }
    Serial.print('\n'); // This is just some debugging stuff, if you plug in your programmer this will output the data to a serial monitor
    Serial.print(Apin1);
    Serial.print('\n');
    Serial.print(Apin2);
    Serial.print('\n');
    Serial.print(Apin3);
    Serial.print('\n');
    Apin1 = 0; // These variables hold the current incoming value
    Apin2 = 0;
    Apin3 = 0;
          }
    }
}

also, maybe you should talk to @user734 and work on your posts together

The problem is the same as last time (XBee+Arduino communication problem)
You are sending the data via:
Serial.println(val1);

which outputs an ASCII representation of the number.
But in your reading, you are reading in a byte value. Actually, I just realised you are reading in a char which is a signed (-128 to 127) value:
char inByte = portOne.read();

first, change that to:
byte inByte = portOne.read();

Now, you have three options:

If (as you say) the numbers you expect are around 200 and will always be below 256 (and positive) then you could send a byte value instead. That way, when you read the byte in, you get the same value. You would do this using Serial.write(val1); instead of print.
If you need to send larger than a byte value, eg int, then send as two bytes, HIGH and LOW. Then on the receiving end, take in two bytes when reading that data.
Send as plain text but read in as plain text. Since you have delimiters, keep reading in the serial until you have all the data you need and then break it down. (You could adapt the code I posted in the answer above to do that).

edit: a couple of other points with your code:

You're doing an analogWrite to digital pins 0, 1, and 2. Was that your intention? analogWrite is reserved for sending out PWM signals on only those pins that are capable (see: http://arduino.cc/en/Reference/analogWrite )
analogRead will read a value of 0-1023 and if your intention is to just use PWM at the other end, then step it down to a value of 0-255. In that case you can get away with writing byte values to Serial.write.
You're never setting the pinMode of the outputs in the receiver.
You're sending val1, val2, and val3 out via Serial.println which will send your value out (as ASCII), followed by a newline, so the bytes sent from that one line will be 32 30 30 0D 0A. You have to interpret that at the other end.
You're also using software serial on the hardware serial port (you're assigning digital pins 0 and 1. These are the hardware serial pins). BUT you're also initialising it via hardware serial. I'm guessing that it really wouldn't matter (if the pins are aligned), but you can't expect to receive data via software serial and send data via hardware serial if they're all using the same pins.

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


text:
What does the 'arduino' avrdude programmer do?
The command line that my toolchain (CLion + PlatformIO) uses to program my Arduino (Uno) includes includes
avrdude ... -c arduino ...

but the documentation for this programmer simply reads

-c programmer-id
           ...
          arduino           Arduino
           ...

What does the arduino programmer do. Does it just correspond to using the bootloader?

Yes, the -c option specifies the methods of interacting with the device's loader.
The source code of the arduino programmer is http://svn.savannah.nongnu.org/viewvc/trunk/avrdude/arduino.c?root=avrdude&view=markup
Specifically, '-c arduino' chooses the client side code tailored to the bootloader in the Arduino Uno.  Looking at the code in the above link, it tweaks the DTR and RTS lines to get the Ardunino into an stk500 compatible mode, and then invokes the stk500 protocol.

Yes, I know the -c option generally specifies "methods of interacting". The question is:  What does choosing -c arduino do? Specifically, is it using the bootloader, when I'm connected to the Uno using the serial port?

'-c arduino' chooses the client side code tailored to the bootloader in the Arduino Uno.  Looking at the code, it tweaks the DTR and RTS lines to get the Ardunino into an stk500 compatibple mode, and then invokes that.

Can you elaborate a bit (in noob terms)?

I don't know much, but I'd look in the code and "Trust the source, Luke".  The avrdude has '-c ??????' options for a large number of embedded systems, and from a cursory browse, it seems like each one may have  different initialization and protocol schemes.  The '-c arduino' has its own that apparently works with whatever is normally loaded into the arduino's bootloader.  You can look at the avrdude code to see how one side interacts with the other.  I don't know what's in the chip's bootloader, but maybe https://www.arduino.cc/en/Hacking/Bootloader/ would help you.


text:
How to parse array to x,y positions?
I have 16x16 LED matrix and I want to show some custom characters on it. I saw font made with array like this.
const byte zero[16] = { // Create byte array number 0
        B0111110,
        B1111111,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1100011,
        B1111111,
        B0111110
    };

But I dont know how to parse it to x, y positions. Can someone help me? Do you know better way to store characters that is easily readable by human? Thanks

To get the value at a particular location, use this code:
boolean val = zero[y] & ((B1 << maxX) >> x);

where y is the y position from 0 to zero.length, maxX is the length of the binary constants minus one (in this case, it would be 6), and x is the x position from 0 to maxX.
For more information, see BitMask.

That code looks promising. I will try it :)

Is it possible to get that maximum x and maximum y from array? I want to make it functional with any size of array(character).

@Antoan See my edit. I would suggest that you make all the byte arrays have the same width, e.g. seven.

Nice thanks. But is it posssible to get maxX from my array? Like it will check zero[0] and by that it knows its 7 bits long. Is it possible?

I tried this code:
for(int x = 0; x < 7; x++){     for(int y = 0; y < 16; y++){        boolean val = zero[y] & (B1000000 >> x);        if(val == 1){         Pixel(x,y,1);       }     }   }
but it only shows 7th bit. Where I made mistake?

@Antoan Once the code is compiled, there is no difference between B0000000000000001 and B1. Because of that, the only way to find maxX would be to loop through every element in the array and find the max value, then extrapolate the minimum possible value for maxX from that. It's far easier to standardize the arrays.

Thanks for help :) I tried bolean array, but every bit is stored as byte so it takes a lot of memory. I will stick with byte array:)

Th example looks like the character '0', 8 bits wide and 16 bits high, though it could be the 16x8 due to '0's symmetry. Find the '2' array, for instance and plot the 1-bits on a piece of graph paper (even a hand-drawn grid will do). Once you should see the character shape you'll know how the bits/dots are arranged in the array.
If your LED array has a square pitch (same spacing vertically and horizontally), 16-bit high characters may appear rather tall and skinny. If so, you could re-plot the characters to suit yourself. If you do decide to hand code them, look at your display hardware. It probably (but not necessarily) accepts 8 horizontally-adjacent bits at a time. But regardless, you can simplify your display code if one array-byte contains 8 bits that will be output at once.
--------- Update:
There's a lot missing from your question but I'll pick some assumptions to base an answer on.
Y = array_index;
X = (6-bit_position) + (is_right_hand_character ? 8 : 0);

based on assumptions that:

you want the display coordinates of a given bit in the array;
the origin (0,0) of your display is the upper left hand corner LED;
the first character starts in column 0; the second in column 8; The
leftmost bit to display is in bit-6 of each byte and bit 7 (MSb) is
not used;
you'll use zero-based coordinates.

The 'Y' coordinate is pretty straight-forward - byte-0 is the first byte.
The 'X' coordinate is found by subtracting the position of the bit of interest from 6, and maybe adding 8, since bit-6 goes into column-0 or column-8 for the left or right character, respectively.

That 0 is my character I want to display on matrix. I want to display 2 numbers on it so thats why I use 7x16 size. I just want to know how to get x,y positions from array like that.


text:
Can I set the Arduino board type in code
When I've come back to Arduino programming after a spell doing other things, I keep forgetting that I last experimented with a different type of board and get a "avrdude: stk500_getsync(): not in sync: resp=0x00" error.
I have one sketch which will always be compiled and uploaded against a specific piece of hardware. Therefore, I would like to specify the board type and preferably COM port as well, in my sketch.
Can it be done?

You can do this by customizing one of the Makefile-based build/upload paths that have been offered by the community as alternatives to the IDE - even if you choose to use the IDE as your normal tool (just be sure to close the serial monitor before trying to flash from the command line).

No, it cannot. Neither the compiler invocation nor the subsequent upload examine the code for the hardware in use, so there is no way of doing what you are asking.
What you can do is to create entries in a new boards.txt and programmers.txt using an existing core that specify all the parameters, and all you would have to do is select them in the IDE for everything to be set at once. See Google Code/Arduino/Platforms for more information.

It seems an obvious compiler directive to have, but if it doesn't exist, that's fine. I just needed to be sure.

The compilers involved are fairly target specific, so by the time a directive is read it is "too late" to choose between say Due (ARM) and Uno (ATmega).  But you could put in traps so that the build will fail with an informative custom error if the wrong one is selected.

I suppose then it's not a compiler directive I'm talking about, more of a directive to the IDE, but that then doesn't make the code very portable. Nicer fail is a good compromise though.

Yes you could do this, but you won't get much support from the Arduino libraries. From what I have used, the board type is evaluated at library compile time.
But if you are willing to delve through the datasheets for all the boards you want to support, then writing a board-agnostic driver should not be impossible.

No, that is way too much work. I was just looking for shortcut, not more work! :)


text:
How would I establish a serial connection with python without using the serial monitor?
How would I establish a serial connection with python without using the serial monitor?
What I want to do is give my python script some input and have the arduino do something (blink for example)
I also want to be able to read in data with the arduino to give it to my python script.
What modules for python would be useful? I'm just starting out and don't have much of an idea for this one.
I am using a windows7 machine with python 2.7.6 and have an UNO board and a Leonardo board that I want to be able to use.

This question is about python not arduino

@Martynas - Technically you're right, and thanks for your vigilance here. However, we'll often allow questions like this which involve an Arduino even if the main issue is about something else. That policy is mainly for the sake of newcomers to the platform who perhaps don't know exactly where/what to ask.

@PeterR.Bloomfield yes i read about something like this in meta and i said my opinion to Twitchykid. There are better places with more experienced ppl to ask.

This question is about Python not Arduino... Before asking here please ask GOOGLE
Anyway...
This is the answer Arduino and Python
Python code:
## import the serial library
import serial

## Boolean variable that will represent
## whether or not the arduino is connected
connected = False

## open the serial port that your ardiono
## is connected to.
ser = serial.Serial("COM11", 9600)

## loop until the arduino tells us it is ready
while not connected:
    serin = ser.read()
    connected = True

## Tell the arduino to blink!
ser.write("1")

## Wait until the arduino tells us it
## is finished blinking
while ser.read() == '1':
    ser.read()

## close the port and end the program
ser.close()

Arduino code:
// Open a serial connection and flash LED when input is received

void setup(){
  // Open serial connection.
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  Serial.write('1');
}

void loop(){
  if(Serial.available() > 0){      // if data present, blink
    digitalWrite(13, HIGH);
    delay(500);
    digitalWrite(13, LOW);
    delay(500);
    digitalWrite(13, HIGH);
    delay(500);
    digitalWrite(13, LOW);
    Serial.write('0');
  }
}


text:
Connect multiple I2C to an Uno
Is it possible to use more than 1 device that needs to use SDA for I2C with a mini?
Would you use a different analogue pin with a 10k pull up resistor and tie all of the devices to the SCL?

Is it possible to use more than 1 device that needs to use SDA for I2C with a mini?

Yes, provided they have unique I2C addresses.

Would you use a different analogue pin with a 10k pull up resistor and tie all of the devices to the SCL?

No. All of the devices must be tied to both SDA and SCL. You may need a smaller resistor depending on how many devices there are; see NXP document UM10204 for details.


text:
Lily Pad mp3, nested loops with timing and play randomly choosen mp3, coding problem
The best way to explain my problem is in form of code...
    const int ringerPin = A0;
    const int offhook = A4;
    const int onhook = A5;

    void setup(){
    pinMode(ringerPin, OUTPUT);
    pinMode(offhook, INPUT);
    pinMode(onhook, INPUT);
    randomSeed(analogRead(0));

  }

  int randCall = random(60000, 3600000); // generate a random number between 1 min and 60 min

//ring every 1 to 60 minutes if the phone is down (hookon) and dont ring if the phone is picked up (no hookon)
void loop()
{
  if (digitalRead(hookon) == HIGH)

void loop(){
delay(randCall);

      //i dont know how to let this loop below here run for 30 seconds.
 void loop()
    {
      //turn audio off - i dont know how to.
    for(int x = 0; x < 15; x++){
      digitalWrite(ringerPin, HIGH);
      delay(50);
      digitalWrite(ringerPin, LOW);
      delay(80);
    }
    delay(2500);
    }
  else
    //play one randomly choosen audiofile out of 10 - i dont know how to
}
}

Maybe you can give me some suggestions to my coding problems.?
I wrote them inside the code descriptions.

WHy do you have 3 definitions of loop() in your code, is it a copy/paste issue?

Halo, thank you for ansering anything.. I got the loop loop loop thing now runin..
So its about playing an Audiofile if hookon == LOW ........ check it out :-)
The code now looks like this.
const int ringerPin = A0;
const int offhook = A4;
const int onhook = A5;
double beginRing = -40000;

void setup(){
    pinMode(ringerPin, OUTPUT);
    pinMode(offhook, INPUT);
    pinMode(onhook, INPUT);
    randomSeed(analogRead(0)); // this starts Arduino's random number generator
}

int randCall = random(60000, 3600000); // generate a random number between 1 min and 60 min

//ring every 1 to 60 minutes if the phone is down (hookon) and dont ring if the phone is picked up (no hookon)
void loop()
{
  if (digitalRead(hookon) == HIGH){
    delay (randCall);
    beginRing = Time.elapsedTime;
    while(Time.elapsedTime - beginRing <= 30000 && digitalRead(hookon) == HIGH){
      //turn any audio off???
      for(int x = 0; x < 15; x++){
        digitalWrite(ringerPin, HIGH);   // turn the solenoid on (HIGH is the voltage level)
        delay(50);                           // wait for 50 msec
        digitalWrite(ringerPin, LOW);    // turn the solenoid off by making the voltage LOW
        delay(80);                          // wait for 50 msec
      }
      delay(2500);
    }
  }
  if(Time.elapsedTime - beginRing <= 30000){
    //play one randomly choosen audiofile out of 10
  }
}

So, now its about to stop any sound if the hookon is HIGH and to play the randomly choosen file 1 out of 10 if the hookon is LOW (its in the code as description...there i need the right comands)


text:
Sending variable in url
Working on a arduino code, but its C code. Having the problem that I want a variable with int to increase in a loop to run with the url:
student.cs.hioa.no/~s180343/updatedb.php?verdi=%d

The updatedb.php files takes the parameter and saves it to the database.
#include <Process.h>
char buffer[50];
int val=1200;

void setup() {
  // Initialize Bridge
  Bridge.begin();

  // Initialize Serial
  Serial.begin(9600);

  // Wait until a Serial Monitor is connected.
  while (!Serial);

  // run various example processes
  //runCurl(val);
  //runCpuInfo();
}

void loop() {
  Serial.println("Starting");
  sprintf (buffer, "student.cs.hioa.no/~s180343/updatedb.php?verdi=%d", val);
   val++;
   Serial.println(buffer);
   runCurl();
   delay(5000);
  // Do nothing here.
}

void runCurl() {

  // curl is command line program for transferring data using different internet protocols
  Process p;        // Create a process and call it "p"
  p.begin("curl");  // Process that launch the "curl" command
  p.addParameter(buffer); // Add the URL parameter to "curl"

  p.run();      // Run the process and wait for its termination

  // A process output can be read with the stream methods
  while (p.available()>0) {
    char c = p.read();
    Serial.print(c);
  }
  // Ensure the last bit of data is sent.
  Serial.flush();
}


text:
How can I indicate that I am using ATmega2560 so that Arduino libraries understand it?
I am developing AVR microcontollers in Atmle Studio and sometimes I am using Arduino libraries(such as LiquidCrystal).
When I initialize LiquidCrystal lcd(12, 11, 5, 4, 3, 2); I don't think Arduino Libraries use registers and ports of ATmega2560, although I am building my code with the device selection ATmega2560 option of Atmel Studio. Atmel Studio works in order to program 2560 but how can I tell Arduino libraries that I am using 2560?

Take a look here http://arduino.stackexchange.com/questions/4169/arduino-ide-ifdef I think this will work in Atmel Studio

There are two things that have to be considered here.
One is telling the code what board you are using, so it can compile in the right optional parts, and the other is getting the right pin mappings.
The first can be covered simply with a compilation flag:
-DARDUINO_MEGA2560

That defines the macro ARDUINO_MEGA2560 which is used in some places to know which board you are using.
Second is the pin mappings.  These are stored in the file pins_arduino.h and each board variant has its own copy.  You need to ensure that this file (and be sure to get the right one) is included in your code in the right places to ensure that the pins can be mapped right.  If you are including the whole Arduino core (which it sounds like you must be in order for things to even have a hope of working) then you just need to ensure that you have the compiler set up to include the right copy of the pins_arduino.h file.
That means making sure you have an include path in your compile command line which points to where the pins_arduino.h file is before anything else Arduino core related.
-IC:\Path\to\arduino\mega2560\variant

or
-I/path/to/arduino/mega2560/variant


text:
Arduino Mega's 4 Serial Ports?
I have been using only Arduino Uno. Now I am about to buy Mega. But a question rises. Are those 4 Serial Ports of Mega controlled still through one usb cable?

Don't overlook the ChipKIT uC32. It roughly compares to the Mega at a glance, but has 2x the RAM and 10x the clock speed. Plus tons of I/O.

No. If Arduino ATmega microcontroller supports more than a single UART, then only the first one is available through the standard USB connection. Other UARTs use their own pins that you have to connect to on the board. Mind you these pins are TTL logic serial and need a converter for RS232 or similar. It is possible to use a second (third, ...) TTL-serial to USB cable to access the port on your PC.


text:
Driving power MOSFET from 3.3v or lower Arduino Pro Mini
I want to control a low voltage (hobby class) motor with a 8Mhz/3.3v Arduino Pro Micro.  I'd like to power both from 2 alkaline cells.  The motor draws approximately 1 A @ 3V with new batteries.  I would be doing PWM of a couple of channels at the normal Arduino rates.
My thought is to connect the batteries to the Vcc pin (not Vraw) and run the Arduino unregulated at about 3V, but somewhat less when the motor is running.  I'm willing to reprogram the fuses for a lower brownout voltage (or none) if needed.
I'm feeling my way on the rest of this - I'll lay out my (perhaps naive) approach and get some feedback about whether I'm understanding it, and how to proceed.
With such a low battery voltage, a TIP120 darlington seems to drop too much voltage and substantially reduce the motor speed/power.  So I'm thinking that I need to use a power N channel MOSFET, and it appears that I need to be fairly selective to get one which can sufficiently turn on with a <3V gate to source voltage.
I'm considering something like the

FQP30N06L http://www.mouser.com/ds/2/149/FQP30N06L-244344.pdf

If I read the datasheet correctly, Vgs of 3V and a load Ids of 1A would result in less than 100mV drop Vds.  But this transistor may be overkill, and the TO220 package is larger than I'd prefer.
If I'm willing to deal with SOT-23-3 surface mount packaging, there are some options like:

Toshiba SSM3K324RLF http://www.semicon.toshiba.co.jp/info/docget.jsp?type=datasheet&lang=en&pid=SSM3K324R
Infineon BSS806NE  http://www.mouser.com/ds/2/196/BSS806NE_Rev2%2001-359816.pdf

If I'm reading it right, with 2x1.5v (nominal) batteries directly powering an Arduino Pro Micro, I can sufficiently drive Vgs to handle 1A Ids at a small Vds and a low enough power dissipation, with any of these three.
I would put a reverse diode and a cap across the motor.  I've seen devices with a small electrolytic across the motor terminals, and I've seen a smaller value ceramic cap - what's the best practices?
Is this a feasible and reasonable approach?  What are the gotcha's that I need to take into consideration?  Any advice about choosing among these (or other) transistors?
My concerns are: not understanding MOSFETs enough, and the unregulated power supply being too noisy for the ATMega328p when it's also powering the motor.  Can I handle the latter by adding another cap or two across the Arduino Pro Micro's Vcc/Ground?
Backup option: run 3x1.5v alkalines and power the Arduino Pro Micro through its regulated Vraw input.

The FET seems to work, tho using PWM creates a lot of audio noise unless I use the highest PWM frequency.
My current concern is motor noise on the power supply.  As it turns out, I also want to operate a radio transceiver like the nRF24L01+, which is somewhat finicky about its power supply.  This issue of a noisy battery power supply and how to mitigate it is part of the original question (other than adding the nRF) - should I pursue that aspect here or start another Q?

I don't think the mosfets will be an issue. Looking at the last one (BSS806NE); in figure 5 in the datasheet you see that for 1A and 1.4v (Vgs) you'd get a Vds of only .1v.
I think a bigger problem might be the voltage of the batteries dropping under load. You'd have to measure that with a multimeter while the motor is running. A simple cap might help with a little noise, but not with the voltage dropping while the motor is running. Not sure how much the AVR would mind having its supply voltage dropping all of a sudden.
Of the top of my head the minimal voltage of the Atmega328 @8mhz is 1.8v, while default fuse settings use 2.7v, so I'd probably change to fuses to make BOD at 1.8v. Other fuses don't need to change.
Backup option sound good, though you might have to go with 4 x 1.5v depending on the voltage drop under load. Another alternative might be to have two sets of 1.5v batteries in parallel, halving the current load on each battery.


text:
It is possible to revive my Arduino Leonardo (mini beetle) board?
I have this board:

It has the atmega32u4 chip.
I have updated its code several times, and used it without issues for several months. Today, while updating (using Arduino IDE) it started to throw some errors. At the end it said that the checksum didn't match, so I repeated again few more times with the same behavior until it reported "Uploaded" without errors. I used for few minutes and it was working as expected. Then, I had to do another update and the same happened (checksum didn't match). However this time I got to the point in which it was no longer detected by the OS (Ubuntu), and no LED is turning on.
Whenever I connect it to the USB port, I can only see in the logs:
usb 1-9.4: new full-speed USB device number 9 using xhci_hcd
However /dev/ttyACM0 is not longer created.
I'm trying to use avrdude to reset it, but it is reporting:
avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory
which make sense as /dev/ttyACM0 doesn't exists. So, what are my options? Is there anything I can do to make it work again?
UPDATE
I didn't realize that this board has a reset marked as "RES". Following Juraj recommendation I bridged RES and GND. The LED marked as "SDA" turns ON after I release the contact and I can read in the logs:
[1212051.679205] usb 1-9.4: USB disconnect, device number 22
[1212058.532030] usb 1-9.4: new full-speed USB device number 23 using xhci_hcd
[1212058.621972] usb 1-9.4: New USB device found, idVendor=2341, idProduct=0036
[1212058.621982] usb 1-9.4: New USB device strings: Mfr=2, Product=1, SerialNumber=0
[1212058.621988] usb 1-9.4: Product: Arduino Leonardo
[1212058.621994] usb 1-9.4: Manufacturer: Arduino LLC
[1212058.622933] cdc_acm 1-9.4:1.0: ttyACM0: USB ACM device

Which I think its good news. However, it seems ttyACM0 becomes available for few seconds. I was able to upload the Blink example into the chip and I can confirm its working because its blinking. Still the ttyACM0 disappears after few seconds.
Output of avrdude -c avr109 -p atmega32u4 -P /dev/ttyACM0 :
Connecting to programmer: .
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.00s
avrdude: Device signature = 0x1e9587 (probably m32u4)
avrdude: safemode: Fuses OK (E:FB, H:D8, L:FF)
avrdude done.  Thank you.

did you try double reset to activate the bootloader? did you try other USB port? try to clean the USB contacts.

I tried other USB ports and other computers as well. How do I double reset it?

wire a button between reset pin and ground and push it twice. the bootloader will handle the USB for a moment. then try to upload a small working sketch (Blink for example)

ok I will do that. I updated my question and as you can see, it seems to be working

Added blink, its working. Thanks, but ttyACM0 its being removed after few seconds... is that normal?

Its working now, after following the recommendations by chris101 in: https://discuss.littlebits.cc/t/solved-thanks-everyone-did-i-brick-my-arduino/22581/13. The trick is to use littleBits Arduino Module. @Juraj: Thank you. You point me in the right direction.

Probably you have overwritten your Bootloader.
Connect MOSI, MISO, SCK and RESET to an ISP-Programmer and flash the file
Caterina-LilyPadUSB.hex
to it.
There are lots of tutorials on the net how to use a spare arduino as an ISP-Programmer.

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


text:
How do I use RFID-RC522 with an Arduino?
I am working on a project for my local Makerspace, we have limited budget so I was hoping to use the RFID-RC522 el'cheap'o RFID/NFC readers on eBay, I received a couple of SPI based boards, they work, however the code examples for them are limited.
I have found several different libraries and settled on this one: https://github.com/ljos/MFRC522
The trouble is that all the code available online seem to spawn from some Chinese guys Python code that people have translated, and hacked into an Arduino library.
The code works, but Mifare cards are meant to have 4, 7 or 10 byte UIDs and the example/library is returning a 5 byte serial number.
There is no documentation and the NXP datasheet is incomprehensible... Additionally it seems to work with most cards, but it doesn't work with Mastercard PayWave cards which conform to the ISO 14443 standard. The more expensive RDM880 reader which is based on the MFRC500 works fine and has a nice library but the cost makes the implementation impossible.
So, can someone help me to get this NXP MFRC522 based unit reading the UID from all ISO 14443 cards.
#include <SPI.h>
#include <MFRC522.h>

#define RFID_SS  10
#define RFID_RST 5

MFRC522 rfid( RFID_SS, RFID_RST );

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

void loop() {
  byte data[MAX_LEN];
  byte uid[5];

  if ( rfid.requestTag( MF1_REQIDL, data ) == MI_OK ) {
    if ( rfid.antiCollision( data ) == MI_OK ) {
      memcpy( uid, data, 5 );
      for ( int i = 0; i < 5; i++ ) {
        Serial.print( uid[i], HEX );
        Serial.print( ' ' );
      }
      Serial.println();
    }
  }
}

This is probably not the problem, but your uid array is of length 5. Did you try using a larger array since you want a 10 byte result?

Yes, I did but it didn't help, in fact the other reader seems to only return 4 byte numbers and it's a different make with decent example code, very confused.

Sorry, but I must disagree with your 'NXP datasheet is incomprehensible'. From the FIRST PAGE of the MFRC522 datasheet:
'Remark: The MFRC522 supports all variants of the MIFARE Mini, MIFARE 1K,
MIFARE 4K, MIFARE Ultralight, MIFARE DESFire EV1 and MIFARE Plus RF
identification protocols'
Here it says the MFRC522 covers just a part of ISO/IEC 14443. The following are missing fron the NXP RC522:
*MIFARE DESFire EV1 (includes AES encryption)
MIFARE DESFire EV2 (includes MIsmartApp, Transaction MAC, Unlimited Applications
MIFARE Plus drop-in replacement for MIFARE Classic with certified security level (AES 128 based))
MIFARE SAM AV2 (secure access module that provides the secure storage of cryptographic keys and cryptographic functions)*
These are probably the ones used in bank cards. Again, from the FIRST PAGE of the MFRC500 datasheet:
'All protocol layers of the ISO/IEC 14443 A are supported.'
You'll have to plow through all the different MIFARE / ISO/IEC 14443 specs to find out how many ID bytes there are for the different types (I suspect diferent types return a different quantity of bytes).
So, basically, you're screwed. Spring for the expensive MFRC500-based reader. I assume that with the higher cost you also get a high-class API, documentation and examples or even (gasp!) tech support.
Cheers

You are right that the MFRC522 doesn't support this, but you are wrong that the MFRC500 is the solution, that device only supports MIFARE Classic, MIFARE 1K (S50) and MIFARE 4K (S70) cards.

Also the MFRC522 module is <£3 and the MFRC500 is £30.

The MFRC522::requestTag() returns the card type in the first two bytes of the 2nd parameter (data in your example above).  You will need to look at this value to determine which sort of card it is.  Use this information to print out the required N bytes of ID.
At a pinch, you could dump out the full 16 bytes (MAX_LEN), and test them with your various card types to see which bytes are changing in a deterministic manner, thus allowing you to determine the correct length of the ID.
And in case it saves you some time, if you call that library's self-test functions - getFirmwareVersion() and digitalSelfTestPass(); it's necessary to call MFRC522::begin() again, otherwise it's not possible to read RFID IDs (at the time of writing of course.)

Try using the most popular one.
https://github.com/miguelbalboa/rfid
This is working for me. It returns the uID as what you desire. Just remove the other functions just the getting of the uid from its example.

The fifth byte from the RC522 is just a checksum.
For instance, a possible return value (taken from https://github.com/miguelbalboa/rfid/issues/604#issuecomment-1885042556 ) is:
8B 65 66 B9 31
and if you do the binary xor of the first four numbers, you get precisely the fifth:
In [1]: hex(int("8B", 16)^int("65", 16)^int("66", 16)^int("B9", 16))[2:]
Out[1]: '31'

(Indeed, if you compare the first four bytes from the RC522 with the four bytes from the other reader, they should coincide)

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


text:
how does serial port communication work under the hood?
im just looking for how to send/ write date to pc over serial port from arduino..vice versa.
I have few Question to ask after taking so much time and couldn't figure it out myself. I hope you guys can guid me please.
First, i found i can use Serial.println() function to send some data then, on the pc side, it just checks and reads the port (/dev/tty..). But, how does this process actually work under the hood? So, if you use serial.println() it knows about where to write?
Second i also found it's something to do with UART communication.. But, inside Hardware.cpp file, i couldn't find any function call to the one for UART.
Third there is the code like extern HardwareSerial Serial; Then where is the definition of this Serial?
Fourth There seem to have ring buffer for serial buffer. So, when data is being sent then, what and who fill the data into this buffer inside Hardware.cpp?
please, forgive my silly question.. i'm just so curious about this..

See chapter 19 of the datasheet.

Stackexchange sites are for specific, individual questions.  Please edit your post to ask a single question which can have a specific answer - preferably one you are left with after reading the documentation.

You might find this interesting about buffers on both sides of a Nano connected to a Raspian system running a Python data logger, using just a regular USB programming cable between the two:
https://arduino.stackexchange.com/questions/11710/does-data-came-on-serial-port-store-for-some-time

Serial.println knows where to write because Serial is an object. On boards with more than one port there will also be a Serial1,Serial2,etc. Each object corresponds to a port.
The ring buffers are filled from interrupts. When a new byte comes in, it triggers an interrupt that puts the byte in the buffer. When a byte is finished sending it triggers another interrupt that reads the next byte from the buffer and sends it.
Somewhere there is a source file that sets up the UART. It's full of writing special values to registers and low level things like that. I'm not sure what files things are defined in, but if you use the search feature on github there is tons of interesting stuff.

Thank you for reply. now that i know serial is an object then when does it get initialised ? And, when the interrupts happens, then somehow the code for that interrupt knows about Serial object so that i can play with that ring buffer ?

While there is an interrupt for "transmit complete," that's not the one most libraries would be using to fill the ring buffer. Instead they'd use the "USART Data Register Empty" interrupt to indicate that you can load a new values in the transmit register, which holds the next byte that will be sent after the USART has finished sending the current byte in the shift register. In other words, the interrupt happens when the MCU starts sending a byte, which may be important in some applications. (Section 24.7.3 of the datasheet.)

The first question already got a perfectly good answer. I am answering the other ones.

i couldn't find any function call to the one for UART.

There are no "UART functions" in the MCU. The UART is controlled by reading and writing into special registers. These come by names like UCSR0A, UCSR0B, UCSR0C (USART 0 Control and Status Registers A, B and C), UBRR0L, UBRR0H (Low and High bytes of the USART 0 Baud Rate Register) and UDR0 (USART 0 Data Register). These registers are all referenced in HardwareSerial.cpp. You can check the datasheet for their meaning.

where is the definition of this Serial?

In HardwareSerial.cpp, by the end of the file, right after the comment "Preinstantiate Objects".

There seem to have ring buffer for serial buffer. So, when data is being sent then, what and who fill the data into this buffer inside Hardware.cpp?

There are actually two ring buffers: the receive buffer (_rx_buffer) is filled by an interrupt service routine and is emptied by you calling Serial.read(). The transmit buffer (_tx_buffer) is filled by you calling Serial.write(), Serial.print() or Serial.println() (the line _tx_buffer->buffer[_tx_buffer->head] = c; in HardwareSerial::write()), and is emptied by an interrupt service routine.
These interrupt service routines are defined in HardwareSerial.cpp. They start with lines like ISR(SOMETHING_vect). They are triggered by the hardware UART. The transmit ISR is triggered when the UART is ready to accept a new byte to transmit (when it is done transmitting byte n, it starts transmitting byte n+1 and is ready to accept byte n+2 in its TX buffer). The receive ISR is triggered when a new byte has been received.

when does it get initialised?

When you call Serial.begin().

Note that if the IDE is on a Raspbian, HardwareSerial.cp is located at /usr/share/arduino/hardware/arduino/cores/arduino - go into HardwareSerial.cpp and look at where it detects it has more than 1000 bytes of memory (The Rpi has 2048) and that is where the ring buffer setting is 64.  I haven't found any need to expand it, but it can be done.


text:
Can I use this replacement motor without modifying the circuit?
I have a demo that spins a motor, but the leads on my motor broke. I happen to have another motor lying around that I'd like to swap in, but it's of a different type. Here's my circuit:

This is the old (broken) motor: https://www.sparkfun.com/products/11696. It has an operating voltage range of 1.0 to 3.0V DC and a no load speed of 6600±10% RPM (@1.0V DC, 110mA).
The new motor that I'd like to use is part of this kit: https://www.sparkfun.com/products/12866. It's a 6VDC motor with a No Load Speed of 90±10rpm and a No Load Current of 190mA(max.250mA).
I'm running this off a Sparkfun Redboard, which is UNO R3 compatible.
Can I swap in the new motor without any circuit changes? Will I have to add additional power for the new motor? Or should I change the circuit with a larger resistor or something else?

The board runs off USB, so 5v, I think.

You really shouldn't be running motors off the Arduino's power supply to begin with.  The new motor's higher voltage rating suggests that at the same voltage it may actually draw less current than the low voltage motor did - but it may also fail to spin.

Regarding voltage, I think there should be no problem as the datasheet for your replacement motor specifies a "suggested voltage 4.5V DC".
However, be careful that there is another important value in motor datasheets: the stall current.
Simply stated, this is the current consumed by the motor when it tries to rotate but is unable to, due to its too low torque in comparison with the effort needed for rotation, e.g. if it tries to rotate the wheel of a robot that is too heavy.
The original motor has a stall current of 0.8A according to its datasheet (you can get it from the link you provided).
Your replacement motor has 1A according to the link you provided.
These 200mA can make a big difference for the transistor used in your circuit, a P2N2222A.
Indeed, that transistor is specified to switch a maximum of 600mA current at the collector.
So in the best case, the motor will run correctly without load, but if you provide some load that makes it stall, then the transistor will raise temperature (you could sense that by approaching your finger) and ultimately would get toasted.
Please also note that some poorly designed motors may consume a current near the stall current, due to internal friction (I have already almost grilled a transistor this way...)
So my answer is:

you can do it for a simple experiment with no load on the motor
if you really want to do something with the motor, take another transistor with a higher Ic current

Great answer! This motor does work in a pinch so I can get my demo done; it's a little wimpy but does spin. Thanks for explaining the robustness / torque factor!


text:
What's the deal with Uno's pin 13 LED?
(I have a Sparkfun RedBoard, but this question seems to apply to R3 Unos and Uno-compatible boards.) As I was building the first circuit in my SIK guidebook (add a resistor, LED, hook it up and make it blink from code), I noticed a blue LED on the board itself did everything that the circuit's LED did - blinking according to the programming.
Why is this LED here? What use cases is it for?
What kind of circuits will I have to adjust to account for this LED?
Is pin 13 traditionally a debug or a troubleshooting pin? Where did this convention come from?

Why is there a scroll wheel on a mouse? It's convenient, but not needed.

The LED on pin 13 is used by the optiboot loader (the one used on UNO):

at Arduino boot time (the LED blinks a few times)
when uploading a sketch to Arduino

I haven't checked other bootloaders, they may provide the same behavior as the optiboot.
For optiboot, there are optional defines (at compile time) to modify this behavior:

LED_START_FLASHES defines the number of flashes of pin 13 LED at boot time (can be set to 0)
LED_DATA_FLASH will use pin 13 LED during sketch upload if defined at compile-time

These defines are explained in hardware/arduino/bootloaders/optiboot/optiboot.c from within your Arduino IDE install directory.
If you want to change these, you will have to recompile the optiboot loader first and then burn it to your Arduino through an ISP programmer.
I guess one other reason for the LED on pin 13 was to simplify the demonstration of the "Hello World" sketch for Arduino, namely the Blink sketch, without the need for any extra component.

What kind of circuits will I have to adjust to account for this LED?

You'll need to take it into account if you're using that pin as a digital input.

NOTE: Digital pin 13 is harder to use as a digital input than the
  other digital pins because it has an LED and resistor attached to it
  that's soldered to the board on most boards. If you enable its
  internal 20k pull-up resistor, it will hang at around 1.7V instead of
  the expected 5V because the onboard LED and series resistor pull the
  voltage level down, meaning it always returns LOW. If you must use pin
  13 as a digital input, set its pinMode() to INPUT and use an external
  pull down resistor. Arduino - DigitalPins

I just ran into this problem while using a 1wire temperature sensor.  I couldn't enumerate the bus due to that LED interfering.  I noticed some odd spikes on my oscilloscope when using that pin. I moved to another pin and all was good.

What everyone else said, plus: if you find the digital-13 LED gives you a problem, you can always remove it from the circuit, either by removing the LED, or the series resistor.
This might be useful if you are running out of digital I/Os, or you want several contiguous I/O bits and don't want one of them to behave differently from the others.

Yes, pin 13 is traditionally an output pin that drives an LED. But the blue LED should not be blinking as it is the "power on" indicator - do you have a grunty power supply to your board?
You can experiment with PWM to the pin13 LED, which will control its apparent brightness. There are plenty of example sketches on the web.

I don't know what a grunty power supply is; power was supplied via USB.
It looks like RedBoards are pre-programmed with the Blink sketch, which uses pin 13.

"Grunty". LOL. I think he means a very high current power supply. I use the term "stiff", meaning it resists voltage droop at higher loads.


text:
Is the Sparkfun RedBoard pre-loaded with a blink sketch?
As soon as I plugged my brand new RedBoard (Sparkfun's Uno) into my computer, I saw the onboard LED (for pin 13) blink on and off every 1 second. This was before I even sent the first demo sketch to blink the LED. After I uploaded a sketch to change the blink time, the LED's blink cycle changed as I expected.
But why was the LED blinking before I sent my very first sketch? Is the RedBoard pre-loaded with a sketch?

If it's not behaving like you expected it to without a sketch, then I'd say that the answer is yes.

What is the standard behavior for a brand new OOB Uno or RedBoard when it's first connected to power? Does it differ if that power is from the wall or USB?

@KatieK wall or USB should not make a difference.

Yes, the RedBoard is preloaded with the blink sketch (or at least the two that I've purchased have been).


text:
YUN. How to reset the micro controller from linux?
As the title, I'd like to reset the Arduino sketch from the linux machine. Is it possible? how?
One solution could be to save the hex file inside the sd card and then upload it via the lua sketch but I think there is a smarter solution.

Use command reset-mcu: it's a linux script that resets the 32u4 via GPIO

According to the Yun schematic, GPIO18 of the SoC is connected to the MCU reset circuitry. Toggling it should allow you to reset the MCU.

I lightly understand what are you saying. Any ideas on how practically do it?

Depends on where you are when you want to reset it. C? Python? Shell?

python or shell.. c is only the last resource (I'm not good at C)

http://linino.org/doku.php?id=wiki:gpio


text:
Arduino DUE and a ledmatrix with issues
I am trying to code something for fun using an Arduino Due and a LED matrix. The led matrix has a backpack controller. This device is using SPI. So I connect MOSI and SCLK to their respective pins and SS to pin 10 on the Due. So far so good.
The problem I have is that when i run my rudimentary code nothing happens.
this is the current code I am using. I thought this should be enough, but it clearly isn't.
#include <SPI.h>
void setup() {
  SPI.begin(10);
  SPI.transfer(10, 0x26, SPI_CONTINUE); //setup the matrix
  for (int i = 0; i<64; i++){
    SPI.transfer(10, 0x00, SPI_CONTINUE); //set all pixels to black...
  }
}

Output:
 Erase flash
 Write 10444 bytes to flash
 [                              ] 0% (0/41 pages)
 [=======                       ] 24% (10/41 pages)
 [==============                ] 48% (20/41 pages)
 [=====================         ] 73% (30/41 pages)
 [============================= ] 97% (40/41 pages)
 [==============================] 100% (41/41 pages)
 Verify 10444 bytes of flash
 [                              ] 0% (0/41 pages)
 [=======                       ] 24% (10/41 pages)
 [==============                ] 48% (20/41 pages)
 [=====================         ] 73% (30/41 pages)
 [============================= ] 97% (40/41 pages)
 [==============================] 100% (41/41 pages)
 Verify successful
 Set boot flash true
 CPU reset.

So my question is: am I doing something wrong? what?
Or is the Led matrix broken?
Hoping for good answers.
regs
KB


text:
What to with reset pin when laying out Arduino PCB?
I'm designing a PCB with a standard arduino ATMEGA328 DIP IC. Do I need to make a connection to the reset pin?

You absolutely need one! What if you have to reset your processor but you can't detach from the power supply?

"Atmel AVR042: AVR Hardware Design Considerations"

+1 for the ref. “The reset line has an internal pull-up resistor, but if the environment is noisy it can be insufficient and reset can therefore occur sporadically.” So it seems one could possibly live without in “quiet” environments...

Certainly. None of my prototypes use the above circuit, but my final products do.

I don't get the diode however, if you only connect a button. Can noise really cause it to enter high-voltage-programming-mode?

Yes, you do.  The pin needs to be pulled up to Vcc via a pullup resistor - typically 10KΩ.  Also, if you are using the Arduino bootloader and want to program via serial then this pin should be connected to your serial interface's DTR pin through a 100nF (typically) capacitor.  It is also often desirable to provide a reset button which switches this pin to ground.
You should examine the Arduino Uno's schematics and use them as a reference.


text:
Send one bit out per clock pulse received using direct port manipulation?
I want to send one bit of a byte out per 'rising edge' received to an Arduino digital input. I am addressing the outputs using direct port manipulation (to achieve maximum speed), and I would like to do the same for input.
So I'm calling a function called bitBang in my main loop, sending the ready line high before moving into the function:
//Send control
PORTB |= _BV(PORTB2);
bitBang(controlByte);
PORTB &= ~_BV(PORTB2);

What I would like to do upon entering the function is listen for a rising edge to appear on the digital input port using the direct port syntax and iterate through the byte setting the data line high or low depending on the bit's value.
How can I achieve this in the most efficient way possible?

Use the SPI facility.

You could do a while loop on the bit state, or an inline asm version thereof.  Consider declaring your function inline too.  But are you sure you can't accomplish your need using the hardware of the ATmega's SPI engine?

@Chris Stratton I need to send a ready line high to the peripheral device which will send clock pulses in to the arduino which will send data out. Is this achievable with SPI?

Possibly... Depends on the details and if you can use the SPI pins, but generally clocking out data in response to a clock input is what a slave mode SPI engine does.  The ready output could be a GPIO controlled in software after the SPI is armed.

Search for bit bang SPI since this is essentially what you're doing.

Example bit-banged SPI using port manipulation:

bitBangedSPIfast.h :
#include <Arduino.h>

class bitBangedSPIfast
  {
  // addresses of output ports - NULL if not applicable
  volatile byte * const mosiPort_;
  volatile byte * const misoPin_;
  volatile byte * const sckPort_;

  // bit masks for above
  const byte mosiBit_;
  const byte misoBit_;
  const byte sckBit_;

  // addresses of data direction register ports
  volatile byte * const mosiDDR_;
  volatile byte * const misoDDR_;
  volatile byte * const sckDDR_;

  // bit masks for above
  const byte mosiDDRBit_;
  const byte misoDDRBit_;
  const byte sckDDRBit_;

  // delay for clock being high
  unsigned long delayUs_;

  public:
    // constructor
    bitBangedSPIfast (
          // output ports
          volatile byte & mosiPort,
          const    byte mosiBit,
          volatile byte & misoPin,
          const    byte misoBit,
          volatile byte & sckPort,
          const    byte sckBit,

          // data direction register ports
          volatile byte & mosiDDR,
          const    byte mosiDDRBit,
          volatile byte & misoDDR,
          const    byte misoDDRBit,
          volatile byte & sckDDR,
          const    byte sckDDRBit,

          const unsigned long delayUs = 1)
       :
         mosiPort_ (&mosiPort),
         mosiBit_  (1 << mosiBit),
         misoPin_  (&misoPin),
         misoBit_  (1 << misoBit),
         sckPort_  (&sckPort),
         sckBit_   (1 << sckBit),

         mosiDDR_     (&mosiDDR),
         mosiDDRBit_  (1 << mosiDDRBit),
         misoDDR_     (&misoDDR),
         misoDDRBit_  (1 << misoDDRBit),
         sckDDR_      (&sckDDR),
         sckDDRBit_   (1 << sckDDRBit),

        delayUs_ (delayUs) { }

    void begin ();
    byte transfer (byte input);

  };  // end of bitBangedSPIfast

bitBangedSPIfast.cpp :
#include <bitBangedSPIfast.h>

void bitBangedSPIfast::begin ()
  {
  if (mosiPort_)
    *mosiDDR_ |= mosiDDRBit_;    // output
  if (misoPin_)
    *misoDDR_ &= ~misoDDRBit_;   // input
  *sckDDR_ |= sckDDRBit_;        // output
  }   // end of bitBangedSPIfast::begin

// Bit Banged SPI transfer
byte bitBangedSPIfast::transfer (byte c)
{
  // loop for each bit
  for (byte bit = 0; bit < 8; bit++)
    {
    // set up MOSI on falling edge of previous SCK (sampled on rising edge)
    if (mosiPort_)
      {
      if (c & 0x80)
        *mosiPort_ |= mosiBit_;
      else
        *mosiPort_ &= ~mosiBit_;
      }

    // finished with MS bit, get read to receive next bit
    c <<= 1;

    // read MISO
    if (misoPin_)
      c |= (*misoPin_ & misoBit_) != 0;

    // clock high
    *sckPort_ |= sckBit_;

    // delay between rise and fall of clock
    delayMicroseconds (delayUs_);

    // clock low
    *sckPort_ &= ~sckBit_;

    // delay between rise and fall of clock
    delayMicroseconds (delayUs_);
    }  // end of for loop, for each bit

  return c;
  }  // end of bitBangedSPIfast::transfer

Example usage:
#include <bitBangedSPIfast.h>

bitBangedSPIfast bbSPI (PORTD,  5, PIND,  6, PORTD, 7,    // MOSI port (D5), MISO pin (D6), SCK port (D7)
                        DDRD,   5, DDRD,  6, DDRD,  7);   // MOSI ddr  (D5), MISO ddr (D6), SCK ddr  (D7)
const byte mySS =  8;  // slave select

void setup (void)
  {
  bbSPI.begin ();
  pinMode (mySS, OUTPUT);
  }  // end of setup

void loop (void)
  {
  char c;

  // enable Slave Select
  digitalWrite(mySS, LOW);

  // send test string
  for (const char * p = "Hello, world!" ; c = *p; p++)
    bbSPI.transfer (c);

  // disable Slave Select
  digitalWrite(mySS, HIGH);

  delay (100);
  }  // end of loop

Reference
SPI - Serial Peripheral Interface - for Arduino


text:
How to cast float into four bytes?
I'm trying to save GPS coordinates to an EEPROM.
In this example I feed it the latitude of 56060066 as the argument float x
void writeFloat(unsigned int addr, float x)
{
  byte seriesOfBytes[3];
  *((float *)seriesOfBytes) = x;
  // Write all four bytes.
  for(int i = 0; i < 4; i++)
  {
    i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM
    Serial.println(seriesOfBytes[i],BIN);  // Debug line
  }
}

I'm expecting to receive the following four bytes from the serial print:
00000011
01010111
01101000
10100010

Instead I'm getting these:
00101000
11011010
01010101
01001100

I've tried changing all sorts of parameters, but can't seem to find the problem. Can anyone spot the issue?

If you were to enable the display of warnings you would most likely see it complain about "dereferencing type-punned pointer will break strict-aliasing rules" which is what you are doing here.
Basically you are trying to cast an array of four 8-bit values which can have any alignment they like (byte alignment) to a 32-bit float value which needs 4-byte alignment.  And the two just don't mesh.
Instead you need to work the other way around - cast a type that has smaller alignment requirements over the type that has larger requirements.
So instead of getting 4 bytes and trying to fill them as a float you get a float and read it as 4 bytes:
byte *b = (byte *)&floatVal;

Then you can access b[0] to b[3] quite happily.
Another way to do it is with a union:
union {
    float fval;
    byte bval[4];
} floatAsBytes;

floatAsBytes.fval = floatVal;
EEPROM.write(0, floatAsBytes.bval[0]);
EEPROM.write(1, floatAsBytes.bval[1]);
EEPROM.write(2, floatAsBytes.bval[2]);
EEPROM.write(3, floatAsBytes.bval[3]);

Also, in your code, you only allocated enough room for 3 bytes, not 4...

Thanks. I just tried the union you suggested, but it's showing the same result! Compiler is not showing any warnings. Would you expect the serial print with BIN parameter to show the correct result?

@blarg Have you considered that maybe you are expecting the wrong values? Where did you get those values from?

You are getting exactly what you said you want. 4 bytes representing the number in float format.
What you are expecting to get, is 4 bytes representing the number in big-endian integer format.
Using Majenkos solution for casting, you need to change the types and reverse the for loop for big-endinaness.
I also used int32_t because the size of the int is 16-bit (2-byte) on the Arduino Uno (and other ATMega based boards) and on the Arduino Due it's 32-bit (4-byte). Its better to define the exact int in this case.
union {
    int32_t ival;
    byte bval[4];
} int32AsBytes;

void writeInt32(unsigned int addr, int32_t x)
{
    int32AsBytes.ival = x;
    for(int i = 3; i >= 0; i--) // reverse for big-endian
    {
        i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM
        Serial.println(int32AsBytes.bval[i], BIN);  // Debug line
    }
}

This mucking around with casts and arrays is far too complex.
See: Reading and Writing Data Structures to EEPROM
The library EEPROMAnything.h will accomplish this.

EEPROMAnything.h
The library just consists of this file. Save into your "libraries" folder under the folder name EEPROMAnything.
#include <Arduino.h>  // for type definitions
#include <EEPROM.h>

template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
{
    const byte* p = (const byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        EEPROM.write(ee++, *p++);
    return i;
}

template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
{
    byte* p = (byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        *p++ = EEPROM.read(ee++);
    return i;
}

Example code
#include <EEPROM.h>
#include <EEPROMAnything.h>

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  float foo = 56060066;
  EEPROM_writeAnything (0, foo);

  float bar;
  EEPROM_readAnything (0, bar);

  Serial.println (bar);
  }  // end of setup

void loop ()
  {
  }  // end of loop

Output from above
56060064.00

Note you don't get exactly the same number back. This is because of the precision of 4-bytes floats.

After re-reading the question I see you are using I2C EEPROM. That changes the answer a bit, but you can see an adaptation of that library for I2C here. The general idea is the same though.

i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM

Your code seems to be writing all of the bytes to the same address, I don't know how that could work.

union Float {
    float    m_float;
    uint8_t  m_bytes[sizeof(float)];
};

float        pi,pi1;
uint8_t      bytes[sizeof(float)];
uint8_t      bytes1[sizeof(float)];
Float        myFloat;

#include <Wire.h>
#define disk1 0x50    //Address of 24LC256 eeprom chip
void setup(void)
{
  unsigned int address = 0;
  Serial.begin(9600);
  Wire.begin();
  pi = 300.78;
  Serial.println("*******************************************");
  Serial.println("pi = "+ String(pi));
  Serial.println("***** Conversion by using type casting *****");
  *(float*)(bytes) = pi;
  for(int i=0;i<4;i++) Serial.println( bytes[i]);
  Serial.println("*******************************************");
  for( int i=0;i<4;i++){
      writeEEPROM(disk1, address, bytes[i]);
      address=address+sizeof(bytes[i]);
  }
   address=0;
   for( int i=0;i<4;i++){
      bytes1[i]=(readEEPROM(disk1, address));
      address++;
      Serial.println(bytes1[i]);
   }
   Serial.println("************Conver Byte to Float*************************");
 pi1 = *(float*)(bytes1);
 Serial.println("pi = "+String( pi1));
 Serial.println("********* Conversion by using union *********");
 myFloat.m_float = pi1;   // assign a float to union
 Serial.println("myFloat.m_Float = "+String( myFloat.m_float));
 Serial.println("myFloat.m_Bytes = "+String(myFloat.m_bytes[0])+String(myFloat.m_bytes[1])+String(myFloat.m_bytes[2])+String(myFloat.m_bytes[3]));  // get the bytes
}
void loop(){}
void writeEEPROM(int deviceaddress, unsigned int eeaddress, byte data )
{
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8));   // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB  Wire.send(data);
  Wire.write(data);
  Wire.endTransmission();
  delay(5);
}

byte readEEPROM(int deviceaddress, unsigned int eeaddress )
{

Hope This could help. Just done a fews min ago. good luck

Please add a few sentences to accompany the code.  It may help those who are trying to understand it.


text:
How do you write to a free location on an external EEPROM?
I want to log GPS positions to an external EEPROM over I2C.
For example:
Latitude: 51.0000
Longitude: 4.0000
If I remove the decimal place then each of these addresses would consume up to two bytes each.
My question is: How can I log each new set of GPS data to a new memory address on the EEPROM each time?
Bearing in mind that the Arduino might be switched off between entries.

The trick you are looking to implement here is the ability to look through the EEPROM and say "This is the last place I wrote to - I will write to the next place now."
There's two ways of doing it, the easy way and the right way.
The easy way is to maintain a single address in the EEPROM that says where you wrote to last.  If you are trying to implement some form of wear levelling to extend the life of your EEPROM then this would basically negate it, since that one cell in the EEPROM will wear out before the rest of it and become useless.  So it's really not a good idea although it may sound like it at first.
The right way to do it is to store more information in the EEPROM every time.  Not only do you need to store the data, but also some kind of identifying sequence number.
Say you have 4 bytes of data to write each time.  Add a fifth byte to it.  That fifth byte increases by one each time you write.  Before you write you scan through the EEPROM looking at every fifth byte looking for the "end" of the sequence.
For instance, you may end up with (xx is your data bytes) in hexadecimal:
00: 00 xx xx xx xx
05: 01 xx xx xx xx
0A: 02 xx xx xx xx
0F: 03 xx xx xx xx
14: FF FF FF FF FF

You see that at address 0x14 the nice sequence of numbers breaks.  Therefore your next write must be at that point.  Now, if you then loop through the EEPROM many times after a while, you may end up with something that looks like this:
00: FE xx xx xx xx
05: FF xx xx xx xx
0A: 00 xx xx xx xx
0F: 01 xx xx xx xx
14: 58 xx xx xx xx

You can see a clear sequence here of 0xFE 0xFF 0x01 where they increase by 1 each time (0xFF + 1 = 0x00) so you can see that you have looped through your sequence numbers. You don't care though because it's still just plus one.  Only when you get the jump from 0x01 to 0x58 does the sequence break, so you know where the last write would have been.
There are only a couple of small gotchas here:

You can only use 5*n cells in the EEPROM since the last 5-byte packet of data may not fit within the last bit of EEPROM (say it's a 1024 byte EEPROM you would have room for 204.8 packets - so 204 packets and 4 bytes left over).
You must ensure that you don't end up with exactly 256 packets fitting in the EEPROM before you loop the address - otherwise the sequence won't "break" so you will never know where the last write was after the first loop.

You can divide EEPROM space into entries and provide each entry with a single "used" bit. You could use a separate byte to store it, or reuse a bit from a byte which is not completely used by your data.
Suppose you start with EEPROM willed with zeroes, and you decide that the first byte of each entry holds the "used" bit in the LSb. When you log coordinates the first time, you'll have:
 /---"used"
01 51 00 00 04 00 00
00 00 00 00 00 00 00
 \---"free"
...
00 00 00 00 00 00 00

(of course, you don't have to store GPS coordinates as BCD, it's just an illustration).
Note that as you add entries, it's trivial to keep track of the last one: just check the entries in sequence until you find a "free" one and go back one step. Also note that the first entry is always "used".
This will go on until all your entries are "used":
01 51 00 00 04 00 00
01 52 00 00 05 00 00
...
01 53 00 00 06 00 00

At this point (when you have to write new data but there are no "free" entries), you start writing from the first entry again, inverting the value of the "used" bit:
 /---"used"
00 54 00 00 07 00 00
01 02 00 00 05 00 00
 \---"free"
...
01 53 00 00 06 00 00

(remember that the first entry is always "used"? Thanks to this, it's possible to simply swap the values representing "used" and "free" entries without actually erasing anything).
To sum up, the algorithm is:

read the "used" bit from the first entry
scan entries until the value of the "used" bit changes, or until you reach the end.
to read the last logged data, use the last "used" entry
to write new data, use the first "free" entry. If there are no "free" entries, start from the beginning, inverting the "used" bit.

This seems like the best answer here.  "Dirty" might not be the best word for the currently valid data, though.

@endolith Thanks, I replaced "dirty" with "used" and "clean" with "free".

You could assign the first byte(s) of the EEPROM as the address of the next free location in which to store GPS coordinates, and update it before the Arduino sleeps. At wake-up, retrieve the address.
You could keep the pointer in RAM, too; RAM keeps its contents across a sleep. But using EEPROM would even let you power off the Arduino, and still pick up where you left off after the power-up reset. (Of course, other parts of your program would have to be restart-tolerant as well; I'm just looking at the coordinate storage here).
As an aside, two bytes isn't sufficient to store a GPS coordinate to four decimals unless their range is limited such that you can scale them into [0 - 65535].

Using the same bytes and writing into the same location often will render those bytes soon broken. They have a limited write amount.

The question asks specifically about EEPROM (E2) and many of the answers point out or attempt to address E2's main limitation: limited # of write operations. Not mentioned is E2's slow speed. Its is best suited for storing infrequently modified data such as-built- or setup parameters such device calibration data and features of a device's external operating environment. Its only real advantage over other solutions is that it may already exist on your MCU - Atmega 328, for instance.
The new(er) kid on the block for non-volatile data storage is Ferroelectric RAM - FRAM. Write times are on the order of 30 times faster, at 150ns, and endurance is claimed to be 10^12 writes, or 10 million TIMES the endurance of E2. I've built a data logger that uses a ring-buffer in FRAM to store periodic data samples and write them on request.
The same techniques proposed in the answers for E2 will work equally well in FRAM with the additional advantage that you can ignore the complications meant to work around E2's limited write-endurance.
And by way of disclaimer: I don't sell this this stuff or have any other interest in it. But I do use it and it works like it says on the box.
Adafruit makes these on a breakout board in a couple of variations - size and serial-bus type - that are sold by them and other retailers. The link is for an 8K-byte, SPI-bus board.


text:
AVCC and AREF when using a reference voltage lower than 5V?
I'm designing a circuit that will use a 2.5v reference for the AREF. Should AVCC be powered from 5V or 2.5V?

AVCC is the supply voltage pin for the A/D Converter, PC3:0, and ADC7:6. It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter. Note that PC6...4 use digital supply voltage, VCC.

So it should be connected to 5V.


text:
What's the simplest way to get arduino functionality?
I want to control a servo with the least amount of components. But generally, what is the simplest way to do this without actually using a fullblown arduino board?

You can control a servo with just a basic 555 chip

If you what you're looking for is the cheapest option with the fewer components possible, then you can use a regular ATMega328p chip, with a few passive components attached to it.
You just need to program it with an Arduino Bootloader once, in order to be able to program it easily, but you can use any existing Arduino to do that. After doing this once, you can program it with any FTDI-type USB to Serial converter.
Here's an Instructable that explains the whole process.

Since you need some sort of programmer in order to write the bootloader out, you're usually better off bypassing the bootloader altogether and sticking with the programmer. This will also free up any flash that may have been used by the bootloader as well.

This is useful if you don't need all the I/O of the Atmega.
If you want a simple board just to run a servo or two and still have some I/O you could use a ATTiny85 chip and use this software servo library that works with the attiny. It also works best with the High-Low tech cores.
I used this with a project and it works flawlessly without stalling.
This would give you small setup as you can use the internal clock 8MHz and minimal external components, i.e. regulator and Capacitors.

Please, take a look at this guide by Nick Gammon, which explains in detail how to build a breadboard Arduino.
You'll need also an Arduino board without the chip (a good UNO will do the job) because you need to program it some way. It is needed absolutely in the case that you buy an ATMEGA328 that hasn't the bootloader, as you'll have to write it on the blank chip.
To speak directly via serial with the standalone Arduino (and to program it), I suggest you to buy a FT232RL board (just be careful to buy a real one, as there are fakes that FTDI blocked and bricked with drivers)
Then, for the servo you just have to plug it correctly: two cables for power, one for the control.


text:
Reset fuses on atmega328p using Arduino
I bought a few atmega328p chips but unfortunately they came with the Arduino bootloader and they are set to use the external clock. I want to reset their fuses using avrdude so I can use the internal 8mhz clock but it's not working. How can I (if even possible) reset their fuses using the Arduino? I have no other programmer and here are the arguments I use for avrdude as well as the response:
avrdude -C .\avrdude.conf -p m328p -c arduino -P \\.\COM12 -b 115200 -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m

Response:
avrdude.exe: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude.exe: Device signature = 0x1e950f
avrdude.exe: reading input file "0x62"
avrdude.exe: writing lfuse (1 bytes):

Writing |  ***failed;
################################################## | 100% 0.06s

avrdude.exe: 1 bytes of lfuse written
avrdude.exe: verifying lfuse memory against 0x62:
avrdude.exe: load data lfuse data from input file 0x62:
avrdude.exe: input file 0x62 contains 1 bytes
avrdude.exe: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.00s

avrdude.exe: verifying ...
avrdude.exe: verification error, first mismatch at byte 0x0000
             0x62 != 0x00
avrdude.exe: verification error; content mismatch

avrdude.exe: safemode: lfuse changed! Was 62, and is now 0
Would you like this fuse to be changed back? [y/n]

You cannot set the fuses using the Arduino bootloader, since they cannot be self-programmed. You must use either serial or parallel programming via ArduinoISP or an external programmer to set them. Since the chip is configured to use an external crystal you must either connect a crystal up to the chip appropriately (see sections 9.3 or 9.4 of the datasheet) or use parallel programming. You will then be able to use the lfuse, hfuse, and efuse memory types to read and write the fuse bytes.

If your answer includes information that mine doesn't then you should consider leaving it so that others can learn from it.

It's pretty much the same answer haha


text:
How to continuously calibrate sensor
I have a problem in calibration an LDR sensor. I want to let the sensor goes all day long and I'm using the LDR sensor as a presence sensor. The calibration values (min and max) changes all the day, and I need to detect only the peaks, or continuously change the min and the max values. Are there some defined pattern or algorithms to use?

In this situation, it may be useful to look at the differential of the signal.
One way to do this is to store the value, wait some time and read another value. You can then do:
dv = current_value - last_value
Or if you have some time metric (Perhaps clock ticks, or a rtc):
dv = (current_value - last_value) / (current_time - last_time)
You would then want to only count significantly large changes in dv. As the day progresses the light value will only change at a small rate but if someone were to block the light then there will be a large difference between current_value and last_value, causing dv to be largely negative (Indicating a loss of a lot of light) and when they no longer block the light you will get the opposite, indicating there is no longer an obstruction. (Or rather, less of an obstruction.)

yes I came at this solution too

Anyway, cool. Where to find some more documentation and algorithm about this kind of simple signal processing things in C?


text:
Best multiplexer for a led cube
I had fun making a 3x3x3 led cube. Now I want to build a bigger one. I'd like to find out the best IC for it. I've seen that some projects uses multiplexer like 4051 or 74HC595.
I'd like to make it at least 8x8x8 (so the multiplexer has to easily be spotted in cascade), possibly supporting also the pwm (to fade the leds).
And I'm a little bit scared by the real time with a lot of LED.. do I have to solve the problem in hardware (with a "faster" multiplexer) o via software?

Those aren't multiplexing chips. Those are just chips to give you more outputs than your arduino has.
The multiplexing is just done on the microcontroller. But it depends on how you are wiring the leds. You can wire the cube to use less digital outputs, but you'll end up with a less bright leds.
You could use no multiplexing. That way the leds are lid with a 100% duty cycle. But for that you'd need 512 outputs.
You can choose to light up only one level at a time. That way you only need 72 outputs (64 for the leds, and 8 for selecting the level). This is a form of multiplexing. Since only one level is lid at a time, the leds have a duty cycle of 12.5%. Please note that because of the way humans perceive light, it will look more like 1/3rd the brightness, instead of 1/8th (so that's great). Also note that since you only need one level to be on at a time, some people prefer to use a decade counter IC for that.
You could also choose to only light one row at a time. That way you only need 24 outputs (8 for the leds, 8 to select which row, 8 to select which level). But you'd need some additional circuitry to combine row- and level-selection.
There are specialized multiplexing IC, but those only support rows and colums (not level). So you need 1 chip for each level, and more problematically you need to run 8-row and 8-culumn wires for each level to the bottom. That's quite a bit of wire, which might ruin the aesthetics of the cube.
In short. There are quite a few ways of making a 8x8x8 cube. I'd suggest finding a well documented build from someone else that you like and follow that.
Quite a bit of information. I hope it's of help. If you have any more question feel free to ask.

You could use a few TLC 5940 PWM Drivers (http://www.ti.com/product/tlc5940).
Each one has 16 channels which would mean to power an 8*8*8 cube would need 32 Drivers.
However, you can use multiplexing to reduce the number of 5940's you would need.
For example, you could use 4 X 5940's which would give you 64 channels and use 8 X time multiplexing to give you 512 channels.
There are 4096 PWM steps giving you lots of control over brightness and can take up to 17v which should be more than enough for any LED.
One of the added features for the 5940 is because it is a current sink, you dont need a resistor on every LED.
I am currently working on a project with TLC5940's that requires control over 512 RGB LED's meaning I have  1536 individual channels to control


text:
Digital Potentiometer not fading LED
So I am trying to test what will eventually be a Arduino controlling 3 110V motors that are currently controlled by an analog pot. But more on that later.
I am trying to test out using a digital pot (never have before) and am running into some issues with tutorials I have found online. For now, I want to control a LED with the digital pot (Spec Sheet) so that the LED fades in and fades out in a continuos loop.
Here is the tutorial I followed. It uses a different chip model but it seems from the pot I am using that the pins are the same. (I could be wrong?)
I double and triple checked the wiring and it matches below.

Here is the code I am running (slightly modified from the tutorial, also tried the tutorial code)
#include <SPI.h>
byte address = 0x11;
int CS= 10;
int i=0;

void setup()
{
  pinMode (CS, OUTPUT);
  SPI.begin();
}

void loop()
{
    for (i = 0; i <= 128; i++)
    {
      digitalPotWrite(i);
      delay(10);
    }
    delay(500);
    for (i = 128; i >= 0; i--)
    {
      digitalPotWrite(i);
      delay(10);
    }
}

int digitalPotWrite(int value)
{
  digitalWrite(CS, LOW);
  SPI.transfer(address);
  SPI.transfer(value);
  digitalWrite(CS, HIGH);
}

As a result of the two above, I have an LED that stays lit (at about 50% it seems) and does not fade in/out at all.
Being relatively new to wiring and EE in general, is there a better way to replicate an analog pot without using a digital pot? Can I just use PWM to control it? Why would the LED be just staying lit?
Thanks!

The spec sheet you provide is very general and covers very different models of digital pots. What is the exact reference of yours?

Sorry @jfpoilpret, I am using the MCP41X1 reference as the chip is a MCP4131 via Amazon

Yes, you can just use Arduino PWM to control an LED. See http://arduino.cc/en/Tutorial/Fade .

After studying the datasheet differences between MCP41100 (digital pot used in the tutorial) and MCP4131 (the one you get), I found two major differences between both:

Difference in resolution:

MCP41100 has 257 steps resolution (8 bits + 1): you can see that at the beginning of its datasheet
MCP4131 has only 129 steps resolution (7 bits + 1): you can get this information on page 2 of its datasheet

Difference in commands formats sent through SPI; both use one "command byte" followed by a "data byte", but have a diffrent format for their command byte:

MCP41100 command byte is X X C1 C0 X X P1 P0 where X is unused, C1 C0 is one of 4 possible commands,  only 2 being valid commands actually: 01 (Write data), 10 (Shutdown), finally P1 P0 should be always 01 for an MCP41100
MCP4131 command byte is AD3 AD2 AD1 AD0 C1 C0 D9 D8, where AD3-AD0 is the address of the "register" on which to perfom a command. For the MCP4131, the most important address is 00 which means "volatile wiper 0" (this is what allows you to change the resistance value of the pot), C1 C0 is one of 4 possible commands (read data, write data, increment, decrement), in your example the command should be 00 (write data); finally D9 D8 are the high order bits of the value to write to the register, but D9 is unused and should always be 0. For 257-steps pots, D8is used to have the full resistance scale, otherwise it should be 0

Now that we know aht your MCP4131 expects as commands passed through SPI, we can take a look at what the tutorial program passes:
00010001 value

The first byte can be broken down as such:

0001 address of the pot wiper register 1 (not 0): this wiper does not exist on MCP4131 hecne writing to it will have no impact...
00 command bits meaning "Write to register specified in previous address"
01 high order bits (D9-D8) of the value to write to the wiper register.

Although I don't have an MCP4131 at hand, I think you should adapt the program as follows:
byte address = 0x00;

And that should be fine! Indeed, now your program passes:
00000000 value

Which means "write value (between 0 and 128 which matches exactly the 129 steps resolution) to the wiper register 0 of the port".
Note that the MCP4131 has more features than the MCP41100 in terms of commands, for instance you could use the special commands "increment" and "decrement", with the advantage they need only one byte (the command byte), e.g.
void loop()
{
    for (i = 0; i <= 128; i++)
    {
      digitalPotIncrement();
      delay(10);
    }
    delay(500);
    for (i = 128; i >= 0; i--)
    {
      digitalPotDecrement();
      delay(10);
    }
}

void digitalPotIncrement()
{
  digitalWrite(CS, LOW);
  SPI.transfer(0x04);
  digitalWrite(CS, HIGH);
}

void digitalPotDecrement()
{
  digitalWrite(CS, LOW);
  SPI.transfer(0x08);
  digitalWrite(CS, HIGH);
}