text:
How to do run time calibration for MPU9250?
Does anyone know how to do the run time calibration for MPU9250 ?

By that you mean finding the calibration matrix for each sensor? Like offsets, gains, hard iron corrections?

I used this script to calibrate the MPU6050, which is the same as the MPU9250 minus the digital compass. This guide explains how to calibrate the MPU9250's magnetometer.


text:
Arduino Due interrupt is taken but not executed completely
I tried to build a simple l-meter with my arduino due. I programmed a simple frequency meter with one timer and one counter. The timer takes an interrupt each 10s, 100ms, 10ms and 1ms. But ones the interrupt is taken it is stopped and even a short Serial.println("Hello World"); does not appear in the serial monitor of the arduino IDE. I don't know what I forgot.
Here is my code:
#define voltage 26

volatile uint32_t current_range = 10000;               //starts with highest range and decrements. longer measurements produce more precise results. measurements for small l values require 11.111ms
volatile const double c_1 = 2533029590000000.0;        //constant value for l value calculation
volatile double correction_value = 0;
volatile boolean calib = true;
volatile uint32_t counter_value = 0;

void initCounter(){
    pmc_enable_periph_clk(ID_TC0);              //enable peripheral clock for TC0

    REG_TC0_CMR0 = TC_CMR_TCCLKS_XC0;           //External clock 0 connected to PB26 (Digital Pin 22)
    REG_TC0_CCR0 = TC_CCR_CLKEN;                //Enable clock
}

void initTimer(){
    pmc_enable_periph_clk(ID_TC1);              //enable peripheral clock for TC1

    REG_TC0_CMR1 = TC_CMR_TCCLKS_TIMER_CLOCK1;  //42MHz clock
    REG_TC0_IER1 = TC_IER_CPCS;                 //Enable compare RC interrupt
    REG_TC0_IDR1 = ~TC_IDR_CPCS;                //Enable compare RC interrupt (disbale interrupt = 0)
    REG_TC0_CCR1 = TC_CCR_CLKEN;                //Enable clock

    NVIC_EnableIRQ(TC1_IRQn);                   //Enable interrupt in nested vectored interrupt controller NVIC (IRQN number = TC number * channels + channel number)
}

double calc_l(uint32_t CV){
    double freq = (double)CV / ((double)current_range / 1000.0);
    freq = freq * freq;

    return c_1 / freq;
}

void calibrate(){
    Serial.println("---Calibrating... shorten inputs then press enter---");
    while(!(Serial.available() == '\n'));
    Serial.print("Start calibration\n");
    initCounter();                              //initialize counter
    initTimer();                                //initialize timer

    REG_TC0_RC1  = 0x1908B100;                  //RC = 420.000.000 to run 10.000ms

    REG_TC0_BCR = TC_BCR_SYNC;                  //reset and start timer and counter simultaneously
}

void measure(){
    calib = false;

    //Serial.println("---Measure... connect inductivity then press any key---");
    //while(!(Serial.available() > 0));
    initCounter();                              //initialize counter
    initTimer();                                //initialize timer
    REG_TC0_RC1  = 0x1908B100;                  //RC = 420.000.000 to run 10.000ms

    REG_TC0_BCR = TC_BCR_SYNC;                  //reset and start timer and counter simultaneously
}

void setup() {
    Serial.begin(250000);

    pmc_set_writeprotect(false);                //disable writeprotect for pmc
    pinMode(13, OUTPUT);
    pinMode(voltage, OUTPUT);                   //set digital pin 26 as output
    digitalWrite(voltage, HIGH);                //set digital pin 26 HIGH
    delay(1000);                                //wait 1 second to get circuit working

    calibrate();
}

void loop() {
    analogWrite(13, 25);
    delay(100);
    Serial.print(REG_TC0_SR1);
    Serial.print(";");
    Serial.print(REG_TC0_CMR1);
    Serial.print(";");
    Serial.print(REG_TC0_IER1);
    Serial.print(";");
    Serial.print(REG_TC0_IDR1);
    Serial.print(";");
    Serial.print(REG_TC0_CCR1);
    Serial.print("\n");
}

void TC1_Handler(){

    uint32_t SR = REG_TC0_SR0;                    //save status register
    uint32_t CV = REG_TC0_CV0;                    //save counter value

    if((SR & TC_SR_CLKSTA) == TC_SR_CLKSTA){      //check whether counter clock is enabled
        if((SR & TC_SR_COVFS) == TC_SR_COVFS){      //check whether counter overflow accured
            switch(current_range){                    //check current range. decrement until smallest range is reached. then print error
                case 10000: REG_TC0_RC1  = 0x280DE80;                   //RC = 42.000.000 to run 1.000ms
                            current_range = 1000;
                            REG_TC0_BCR  = TC_BCR_SYNC;
                            break;
                case 1000:  REG_TC0_RC1  = 0x401640;                    //RC = 4.200.000 to run 100ms
                            current_range = 100;
                            REG_TC0_BCR  = TC_BCR_SYNC;
                            break;
                case 100:   REG_TC0_RC1  = 0x668A0;                     //RC = 420.000 to run 10ms
                            current_range = 10;
                            REG_TC0_BCR  = TC_BCR_SYNC;
                            break;
                case 10:    REG_TC0_RC1  = 0xA410;                      //RC = 42.000 to run 1ms
                            current_range = 1;
                            REG_TC0_BCR  = TC_BCR_SYNC;
                            break;
                case 1:     //Serial.println("Error: l value out of range!");
                            REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                            REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                            break;
            }
        } else {
            if(calib){
                if(CV < 10){
                    //Serial.println("Error: wrong calibration value!");
                    REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                    REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                } else {
                    //correction_value = calc_l(CV);
                    measure();
                }
            } else {
                if(CV < 10){                           //check if counter value is below 10. then l value is to high to get accurate results
                    //Serial.println("Error: l value out of range!");
                    REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                    REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                } else {                               //l value in nH;
                    counter_value = CV;
                    //Serial.print(calc_l(CV) - correction_value);
                    //Serial.print(" nH; ");
                    //Serial.print(CV);
                    //Serial.print(" ticks in ");
                    //Serial.print(current_range);
                    //Serial.println("ms.");
                    REG_TC0_CCR0 = ~TC_CCR_CLKEN;
                    REG_TC0_CCR1 = ~TC_CCR_CLKEN;
                }
            }
        }
    } else {
        REG_TC0_CCR0 = TC_CCR_CLKEN;
        REG_TC0_BCR  = TC_BCR_SYNC;
    }
}

It would be very nice if someone could help me with this.

Calling Serial from an ISR is not a very good idea. Have you tested removing that?

Yes but after removing these lines the µc still hangs in the ISR. The only thing that changes is that I don't know how far the TC1_Handler is executed.

But the ISR may call measure() and that waits for data on Serial, "while(!(Serial.available() > 0));". You need to rethink the control flow between the ISR and the measurement.

I removed these lines too for testing so that it does not wait for any serial data. I only printed the value of the counter via Serial.println(REG_TC0_CV0) but after some time this output stops and nothing is done. Without any serial communication the measure() function only initializes the timer and the counter and restarts them.

Now check the behavior by reading the timer registers in loop().

REG_TC0_CMR1, REG_TC0_IER1, REG_TC0_IDR1 & REG_TC0_CCR1 are all 0. Is it possible that i have to enable the IER each time the interrupt is taken?

Please update the code above. I think we are out of sync with your changes and tests.

Code is now updated. I read that all variables that are manipulated in an ISR have to be volatile so I changed them too.

Do you need to the the floating point inside the ISR?  Or would it be sufficient to put it outside in the 100ms loop()  Same with the range-setting, calibration, and enabling-- Can they be moved into setup? Maybe set up a one-shot measurement (or report) before the 100ms delay in the reporting loop(), and conditionally report the results afterwards?

I don't know if I understand what you mean. Which floiting point and how should I move range settings to the loop() function?

I meant the calc_1() call.  Does it need to be within the ISR?  And do you need to update current_range more often than 100ms?  If an overflow occurs, set a flag for recalculating the range stuff out in the loop.

I need this current_range to specify how much time it take to get in the next interrupt. In the end in 10 ms so updating it iun the isr is needed but the calc_l function is not  required. I removed this but it does not work either.

Maybe I'm dense, but I don't understand why most of the config code is in the ISR.  If the system is getting bound up there, I'd move much of it out and try to simplify it as much as possible, maybe saving only the counter value and the fact that the timer triggered on interrupt, and saving the overflow value if it overflowed.  Then, outside the ISR, on the reporting timescale, I'd check that there was valid data and report or reconfigure as needed.
int validReading = 0;
uint32_t measuredCount;
int overflowed =0;

void TC1_Handler(){
    measuredCount = REG_TC0_CV0;
    if((SR & TC_SR_COVFS) == TC_SR_COVFS){  //counter overflow occurred
       validMeasurement=0;
       overflow=1;
    else {
       validMeasurement = 1;
       // either reset counter and clock or stop handling interrupts
    }
 }

 loop(){
   ...
   if (validReading) { // report
      ...
   } else {
   if (overflowed ) { // shorten sampling time, calibrate, and initialize
      ...
   }
   if ( measuredCount < 10 ) { // lengthen sampling time?
      ...
   }
   // calibrate and reinitialize
 }

Looks like it could work. Did not thought about putting data handling in the loop function. I will try this version tomorrow. Thanks for your help.

source: Stack Exchange

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

authors: Йорданка Запрянова

sort: votes


text:
Turn on a light when there is an input
I am using the pin 4 as an OUTPUT and pin 8 as an INPUT to turn on/off the light, but for some reason it is not working. Light is on all the time, but when I try to input something it gets brighter and doesn't turn off when I don't give anything to pin 8.
LED is connected to pin 4 with a 220 R, and the other side to GND. When pin 8 is connected to 5V pin then the light should come on, and off when I disconnect them.
Here is the code:
void setup()
{
  Serial.begin(9600);
  pinMode(4, OUTPUT);
  pinMode(8, INPUT);
}

void loop()
{
   bool on = digitalRead(8);
   if(on)
   {
     digitalWrite(4, HIGH);
   }
   else
   {
     digitalWrite(4, LOW);
   }
}

What am I doing wrong?

Use input with pullup on pin 8 and a button to ground (GND). See below:
const int ledPin = 4;
const int buttonPin = 8;

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
   digitalWrite(ledPin, digitalRead(buttonPin));
}

Using the pin as input and disconnecting is not the same as GND. The pin is floating. By using the internal pullup resistor the pin is HIGH when the button is not connected to GND.

Thank you for your reply. It worked. But I still don't understand why my solution didn't work. Will you be able to explain?

See updated answer.

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


text:
Problem with biased circuit for oxygen sensor (SGX EC410)
I have designed a circuit for an SGX EC410 oxygen sensor by using these application note -PAGE 4, FIGURE 4 - (http://www.sgxsensortech.com/content/uploads/2014/08/A1A-EC_SENSORS_AN2-Design-of-Electronics-for-EC-Sensors-V3.pdf). When I try to measure the biased voltage between working (SENS) and reference (REF) electrode, the value of -600 mV is held for about one second and goes down to few milli volts rapidly. The same happens when I connect the sensor without voltmeter. Am I doing something totally wrong, or the circuit is not quite right?

I'd try asking at electronics.stackexchange.com instead.


text:
Programming an ATtiny85
Recently I ordered some ATtiny85's from Jameco, and I've been trying to upload code to them through an Arduino Uno, following the instructions from this video on YouTube. I've been getting a lot of unexpected errors and I am now wondering if the chips I bought are the problem. Here are the specs from the Jameco website:

Flash (Kbytes): 8 Kbytes
Pin Count: 8
Max. Operating Frequency: 20 MHz
Power Supply: 2.7 - 5.5V
Operational Range: Industrial (A) (-40°C to 85°C)
CPU: 8-bit AVR
Number of Touch Channels: 3
Hardware QTouch Acquisition: No
Max I/O Pins: 6
Ext Interrupts: 6
USB Speed: No
USB Interface: No

Does the "USB Speed: No; USB Interface: No" mean these aren't programmable by my set up? Or is there is anything else I should know about these chips? Do I need to get new ones that are different?

Please post the error messages. There are a lot of warnings when programming ATtiny with these old tools.

Before you panic (try not to panic) and buy new chips, test the existing ones. See my page about detecting chip signatures which has links to code on Github for a sketch you can run on your Uno, to test the ATtiny85.

You can also upload code from a .hex file (which the IDE produces) by using a different sketch (same code link) from this page about a hex uploader and wiring like this (you also need an SD card adapter):

The first sketch and wiring should at least confirm your chips are OK. The second one is an alternative way of programming them.

I would suggest you to take a look at this video which explains step by step how to program the ATtiny85. https://www.youtube.com/watch?v=i9WOwDrpRKs
From my early days trying to program the ATtiny, i have watched this video.

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


text:
ATMega328P-PU not working
I bought some material on the net to start working with Arduino. I didn't want to buy an Arduino, since it costs a bit too much IMHO, so I bought an ATMega328P-PU, and made an Arduino on a breadboard. However, when I use my USBasp to program it it says that he can't set sck period (settings are: Arduino Uno as Board, USBasp as Programmer). It says that it has loaded the bootloader/program anyway, so I tried to go on and ignore it. The blink program can be loaded via programmer, but it doesn't blink (I'm using a small lamp, connecting it directly to 5V and ground works). Here I describe the circuit:

First Atmega Pin, Arduino Reset -> 10 kOhm Resistor (Brown, Black, Black, Red, Brown) -> Ground (not GND pin);
1st pin, Arduino Reset -> also to USBasp RST;
7th pin, Arduino VCC -> directly to 5V (and USBasp VCC);
8th, GND -> directly to Ground (and USBasp GND);
9th, XTAL -> to one pin of the 16MHz Crystal Oscillator, and to 22 pF capacitor, which connects to ground (not the pin);
10th, XTAL -> exactly as above, but it's connected to the other pin of the same crystal;
17th, digital 11 -> USBasp MOSI;
18th, dig 12 -> USBasp MISO;
19th, dig 13 -> USBasp SCK, and to the lamp whose other pin goes to ground (neither pin nor direct works), but the lamp needs to be disconnected while loading programs to prevent errors (target not responding);
20th, AVCC, and 21st, AREF -> directly to 5V;
22nd -> directly to ground (not pin).

The can't set sck period message has to do with the USBasp. I get the same message every time I upload. It will still upload just fine.

Pin 1 (reset) should have a pull-up to +5V, not to Gnd.

@NickGammon sorry, I misread the guide... Thanks!

With your help, now it works. it was probably the resistor. Now I'm waiting for Mikael Patel's answer, but probably that wasn't the problem. However, it may cause some in the future

First Atmega Pin, Arduino Reset -> 10 kOhm Resistor (Brown, Black, Black, Red, Brown) -> Ground (not GND pin);

So it's permanently in RESET mode then? How can it ever do anything if you're holding it in RESET all the time?
RESET should be pulled UP by the resistor, not DOWN.

That was a nice catch!

Yeah, I misread the guide... Thank you a lot!

The blink program can be loaded via programmer, but it doesn't blink (I'm using a small lamp, connecting it directly to 5V and ground works).
19th, dig 13 -> USBasp SCK, and to the lamp whose other pin goes to ground (neither pin nor direct works), but the lamp needs to be disconnected while loading programs to prevent errors (target not responding);

The lamp needs to be low power (< 20 mA) to work this way. If it uses more power you will burn the MCU pin.
Use a LED and a resistor instead. Or at least use a voltmeter.

21st, AREF -> directly to 5V;

This is not a good idea. Should be capacitor to ground. See for instance Uno schematics.
Cheers!

How many Farads? In the schematics I can't find it... By the way, thanks! I'll use my voltmeter.

Follow the AREF from the upper right connector and there it is 100nF. For more details http://www.avrfreaks.net/forum/capacitor-aref-atmega328

Ok, i need to buy those... I've only got 22 pF ones. Thanks a lot!


text:
Exit status 1 expected primary-expression before ']' Arduino
Here's the whole error:
 Arduino: 1.6.7 (Windows 7), Board: "Arduino/Genuino Uno"

 *\readMifare\readMifare.ino: In function 'void loop()':

 readMifare:113: error: expected primary-expression before ']' token

    if (uid[] == { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

            ^

 readMifare:113: error: expected primary-expression before '{' token

    if (uid[] == { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

                 ^

 readMifare:113: error: expected ')' before '{' token

 readMifare:121: error: expected '}' at end of input

    }

    ^

 exit status 1
 expected primary-expression before ']' token

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

Here's the code
 #include <Wire.h>
 #include <SPI.h>
 #include <Adafruit_PN532.h>

 // If using the breakout with SPI, define the pins for SPI communication.
 #define PN532_SCK  (2)
 #define PN532_MOSI (3)
 #define PN532_SS   (4)
 #define PN532_MISO (5)
 // If using the breakout or shield with I2C, define just the pins connected
 // to the IRQ and reset lines.  Use the values below (2, 3) for the shield!
 #define PN532_IRQ   (2)
 #define PN532_RESET (3)  // Not connected by default on the NFC Shield

 // Uncomment just _one_ line below depending on how your breakout or shield
 // is connected to the Arduino:

 // Use this line for a breakout with a software SPI connection (recommended):
 Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);

 // Use this line for a breakout with a hardware SPI connection.  Note that
 // the PN532 SCK, MOSI, and MISO pins need to be connected to the Arduino's
 // hardware SPI SCK, MOSI, and MISO pins.  On an Arduino Uno these are
 // SCK = 13, MOSI = 11, MISO = 12.  The SS line can be any digital IO pin.
 //Adafruit_PN532 nfc(PN532_SS);

 // Or use this line for a breakout or shield with an I2C connection:
 //Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

 #if defined(ARDUINO_ARCH_SAMD)
 // for Zero, output on USB Serial console, remove line below if using      programming port to program the Zero!
 // also change #define in Adafruit_PN532.cpp library file
 #define Serial SerialUSB
 #endif
 #include <Servo.h>

 Servo servo1;

 void setup(void) {
   #ifndef ESP8266
   while (!Serial); // for Leonardo/Micro/Zero
   #endif
   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("Waiting for an ISO14443A Card ...");
   servo1.attach(9);
 }

 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)

   // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
   // 'uid' will be populated with the UID, and uidLength will indicate
   // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
   success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

   if (uid[] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 }) {

      int position;
      for(position = 0; position < 180; position += 2){
       servo1.write(position);
       delay(20);
      }

   }

Please note that I'm using an example from the Adafruit official PN532 library examples and trying to edit it.

You probably do not want an '=' in the if statement.  What example had this?

This is what I added, still new though, so what should I input?

To compare you use ==. = is for assignment. Common mistake, even by the professionals.

I wouldn't use strncmp because the UID might have zeroes in it. This looks safer:
   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)

   const uint8_t wantedUid [] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 };

   // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
   // 'uid' will be populated with the UID, and uidLength will indicate
   // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
   success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

   if (success &&
      uidLength == sizeof (wantedUid) &&
      memcmp (uid, wantedUid, sizeof wantedUid) == 0) {
      ...

I threw in a test for the uidLength being the expected size, otherwise you might find a 4-byte card happens to match the first four bytes of the wanted UID.
memcmp compares a block of memory for the number of bytes you specify. It returns zero on a match.

You probably need something like:
uint8_t uidTarget[] = { 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 };

...
if (success && !strncmp((const char*) uidTarget,(const char*)uidSource,8)) {

Your '=' tries to do an assignment, and an '==' would check if the pointers to the arrays are identical, rather than the contents of the arrays.  strncmp() tests equality of strings of characters, and the (const char*) casts the uint8_t values as characters.
Nick Gammon's answer is better.

added what you told me to add, error:
readMifare:113: error: invalid conversion from 'uint8_t* {aka unsigned char*}' to 'const char*' [-fpermissive]
if (success && !strncmp(uid,{ 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 },8)) {
readMifare:113: error: cannot convert '' to 'const char*' for argument '2' to 'int strncmp(const char*, const char*, size_t)'
readMifare:121: error: expected '}' at end of input
}
exit status 1
invalid conversion from 'uint8_t* {aka unsigned char*}' to 'const char*' [-fpermissive]

@Dahacker305: remove the const.

"if (success && !strncmp(uid,{ 0x04, 0xEC, 0x89, 0x32, 0x55, 0x42, 0x80 },8))" - no you cannot do that. The ID must be an array variable.


text:
Arduino array length
So I have a programme that loads a text file from an sd card into a string array. Each line in the text file is stored in a different string in a string array. Well its supposed to be.
file = SD.open("/classes/basic.txt", FILE_READ);
Serial.print("Reading, Checking and Compiling \n\n\n");

for(int i = 0; i < sizeof(result)-1;i++){
 while(file.available()) {
  character23 = file.read();
  content.concat(character23);

}
if (content != "") {
  result[i] = content;
    Serial.println(content);

}

}
I want each line in the txt file to be stored in a different string in the array, in chronological order and each string has to be accessible individually. The problem with this code is that it stores the whole text file in one string. How can I fix this?
EDIT: here is what I have now
  file = SD.open("/classes/basic.txt", FILE_READ);
  Serial.print("Reading, Checking and Compiling \n\n\n");

 for(int i = 0; i < sizeof(result)-1;i++){
   while(file.available()) {
  character23 = file.read();
  if (character23 == '^') break;
  content.concat(character23);

}
if (content != "") {
  result[i] = content;
  Serial.println(content);

  delay(1000);
}

}
 Serial.println(result[3]);

To do that, you need to read the file until you reach a line break.
Replace this code:
while(file.available()) {
  character23 = file.read();
  content.concat(character23);
}

by this:
while(file.available()) {
   character23 = file.read();
   if (character23 == '\n') break;
   content.concat(character23);
}

I'm trying to debug and I'm trying to find what is stored in a certain string of the array is this correct: Serial.println(result[1]); because it keeps returning nothing

Can you show your complete code rather than a snippet?

ye ill edit the above code

where is the declaration of the array? Also, this line is wrong if (character23 == '^') break;. It should be \n not ^.

ye but all the lines in the txt file end in ^

The array is at the top of the class

string Array[4];

what if you print the first line? like this: Serial.println(result[0]);

it prints nothing

if I rpint content I get

println("sharkByte OS v1.1)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)
println("sharkByte OS v1.1)
delay(2000)

Let us continue this discussion in chat.


text:
Powering a stepper motor
I'm working on a project where I need a high torque stepper motor. The stepper motor being used is rated at 12 - 24 volts and when I used a 12 volt battery supply composed of 8 AA batteries it appeared to work fine.
Because I wanted higher torque I set the pot on the Easy Driver to 0.5 amps which is within what was recommended for the motor, and used a Lithium Ion battery originally being used for a power drill rated at 18V and 1.5Ah.
When I connected the battery to the easy driver the motor got very hot and would shake when I tried to turn it but not turn. Now the motor will not work with the 8 AA batteries either. Heres a link to the motor US Ship OSM 5:1 Planetary Gearbox Nema 8 Stepper Motor Samll Size High Torque.

What did I do wrong and how can I fix it?
P.S. I am using a photon as the micro controller and the motor is being controlled using the Blynk app I eliminated the chance of it having to do with the photon or Blynk App.
I found out that the battery I'm using is the Makita BL1815 and it is really composed of 2 batteries which are both rated at 15C. I am not sure if C-rating adds or stays the same when you are using two batteries. When I measure the Voltage on the test points I get 4.27V and when using a formula to find current for the Easy Driver I get 0.480A.

In what way is this related to the Arduino?

An rating of 1.5Ah says nothing about the maximal output current of the battery. 1.5Ah states that it could (theoretically) deliver 1.5A over the course of one hour. You might want to re-check your battery pack specs. Since some may have a maximal discharge current rated well below that 1.5A. It's noted by the E-value, 1E would be 1.5A maximal discharge current in this case.
(Probably not the problem here, but it's something)

@Paul I couldn't find an E-value but I think that you meant C-rating because this is all I could find and it seems to be the same thing as what you're saying an E-value is.

C is charge rating, E should be discharge rating. I'm not quite sure if it's documented as so, or that they are generally the same value.

The ratings of the battery are a longshot anyway. Probably not related to your problem, those accu-packs for makita are basically made for this.
And the engine is the one heating up.

How did you set the amps on the http://www.schmalzhaus.com/EasyDriver/ to 0.5A?   What was the voltage at the test point?  The EasyDriver v4.5 schematic says the formula for coil current is A = V/6.  So rearranging, V=A*6, and to get 0.5A, the voltage should be 0.5*6=3V at the motor driver's test point.
The linked motor spec is 0.6A max per coil, and if things went wrong, you could have overloaded a motor.  The 18V battery could have easily provided 1.8 amps to the 10ohm coil in the motor for a bit, before 3x the rated current of the coils would burn it out, or the easydriver went into thermal shutdown or something.
The easydriver looks like it would be capable of controlling the current adequately, but if misconfigured, could easily overcurrent the motor.

When I measure the voltage I get 4.27V. I used the potentiometer on the Easy Driver to adjust the current, and when using a formula I found online to find the current of the Easy Driver I get 0.480A

Try switching back to the situation that did work. To check if something got broken while trying to connect the other battery

The schematic for the easyDriver v4.5 ( https://github.com/sparkfun/Easy_Driver/raw/master/Hardware/EasyDriver_v45_sch.pdf ) says the formula is A=V/6 or 4.27/6=0.712A

Ahhh I see I think that I used a formula for a previous Easy Driver I'll try this out once a get a new stepper motor and see if this solves the issue. Thank you


text:
Don't know how to work IMU and NRF24 together
I'm having problem  on how can I use IMU and NRF24 together.
This is the code that i'm trying to use,
 /*
 Copyright (C) 2012 James Coliz, Jr. <maniacbug@ymail.com>
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 version 2 as published by the Free Software Foundation.

 Update 2014 - TMRh20
*/
/**
* Simplest possible example of using RF24Network
*
* TRANSMITTER NODE
* Every 2 seconds, send a payload to the receiver node.
*/
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>
#include <Wire.h>
#include "I2Cdev.h"
#include "RTIMUSettings.h"
#include "RTIMU.h"
#include "RTFusionRTQF.h"
#include "CalLib.h"

RTIMU *imu;                                           // the IMU object
RTFusionRTQF fusion;                                  // the fusion object
RTIMUSettings settings;                               // the settings object

//  DISPLAY_INTERVAL sets the rate at which results are displayed

#define DISPLAY_INTERVAL  300                         // interval between
pose displays

//  SERIAL_PORT_SPEED defines the speed to use for the debug serial port

#define  SERIAL_PORT_SPEED  11520
unsigned long lastDisplay1;
unsigned long lastRate1;
int sampleCount1;

 RF24 radio(7,8);                    // nRF24L01(+) radio attached using
 Getting Started board
 RF24Network network(radio);          // Network uses that radio
 const uint16_t this_node = 01;        // Address of our node in Octal
 format
 const uint16_t other_node = 00;       // Address of the other node in Octal
 format
 const unsigned long interval = 2000; //ms  // How often to send 'hello
 world to the other unit
 unsigned long last_sent;             // When did we last send?
 unsigned long packets_sent;          // How many have we sent already
 struct payload_t {                  // Structure of our payload
 unsigned long ms;
 unsigned long counter;
 };
 void setup(void)
 {
 int errcode;

 Serial.begin(SERIAL_PORT_SPEED);
 Wire.begin();
 imu = RTIMU::createIMU(&settings);                        // create the imu
 object

 Serial.print("ArduinoIMU starting using device "); Serial.println(imu-
 >IMUName());
 if ((errcode = imu->IMUInit()) < 0) {
 Serial.print("Failed to init IMU: "); Serial.println(errcode);
 }

 if (imu->getCalibrationValid())
    Serial.println("Using compass calibration");
 else
    Serial.println("No valid compass calibration data");

 lastDisplay = lastRate = millis();
 sampleCount = 0;

// Slerp power controls the fusion and can be between 0 and 1
// 0 means that only gyros are used, 1 means that only accels/compass are used
// In-between gives the fusion mix.

fusion.setSlerpPower(0.02);

// use of sensors in the fusion algorithm can be controlled here
// change any of these to false to disable that sensor

fusion.setGyroEnable(true);
fusion.setAccelEnable(true);
fusion.setCompassEnable(true);

Serial.println("RF24Network/examples/helloworld_tx/");

SPI.begin();
radio.begin();
network.begin(/*channel*/ 90, /*node address*/ this_node);
}
void loop() {

unsigned long now1 = millis();
unsigned long delta1;
int loopCount1 = 1;

while (imu->IMURead()) {                                // get the latest
data if ready yet
// this flushes remaining data in case we are falling behind
if (++loopCount1 >= 10)
        continue;
    fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(),
imu->getTimestamp());
    sampleCount++;
    if ((delta1 = now1 - lastRate1) >= 1000) {
        Serial.print("Sample rate: "); Serial.print(sampleCount);
        if (imu->IMUGyroBiasValid())
            Serial.println(", gyro bias valid");
        else
            Serial.println(", calculating gyro bias");

        sampleCount = 0;
        lastRate1 = now1;
    }
    if ((now1 - lastDisplay1) >= DISPLAY_INTERVAL) {
        lastDisplay1 = now1;
     RTMath::display("Gyro:", (RTVector3&)imu->getGyro());                // gyro data
      RTMath::display("Accel:", (RTVector3&)imu->getAccel());              // accel data
      RTMath::display("Mag:", (RTVector3&)imu->getCompass());              // compass data
        RTMath::displayRollPitchYaw("Pose:", (RTVector3&)fusion.getFusionPose()); // fused output
       Serial.println();
    }
}

   network.update();                          // Check the network regularly

  unsigned long now = millis();              // If it's time to send a
  message, send it!
  if ( now - last_sent >= interval  )
  {
  last_sent = now;
  Serial.print("Sending...");
  payload_t payload = { millis(), packets_sent++ };
   RF24NetworkHeader header(/*to node*/ other_node);
   bool ok = network.write(header,&payload,sizeof(payload));
  if (ok)
  Serial.println("ok.");
  else
  Serial.println("failed.");
  }
  }

My question is what  should I put in this part
   [code]struct payload_t {                  // Structure of our payload
    unsigned long ms;
    unsigned long counter;
    };

so that the output for
 RTMath::display("Gyro:", (RTVector3&)imu->getGyro());                //
 gyro data
      RTMath::display("Accel:", (RTVector3&)imu->getAccel());
 // accel data
      RTMath::display("Mag:", (RTVector3&)imu->getCompass());
 // compass data
      RTMath::displayRollPitchYaw("Pose:",
 (RTVector3&)fusion.getFusionPose()); // fused output[/code]

will Transmit to the RX ..
What will I put in this part :
   Serial.print("Sending...");
   payload_t payload = { millis(), packets_sent++ };
   RF24NetworkHeader header(/*to node*/ other_node);
   bool ok = network.write(header,&payload,sizeof(payload));
   if (ok)
   Serial.println("ok.");
   else
   Serial.println("failed.");

Please help me guys. Thanks :)

My question is what should I put in this part

You need to take the data from IMU sensor and put it into the payload. Remember that NRF24L01 allows max 32 byte payload and the library uses some of that.
The RTVector3 is a C++ class with 3 floating point numbers. With AVR float/double that is 12 bytes. This means that you will have to send several messages.
enum {
   GYRO_TYPE = 0,
   ACCEL_TYPE = 1,
   COMPASS_TYPE =2
};

struct payload_t {
  int8_t type;
  float data[3];
};

This assumes that the sender and receiver have the same data representation. The type field is for the value type (GYRO, ACCEL, COMPASS).
Cheers!

I tried it but there is an error, I don't know what will I put in the payload. , please see the edited code above. thank you :)


text:
SPI with a level converter in the other end of connection
I have an Arduino MEGA hooked up with a NRF24L01, and working nicely, talking with another Arduino Uno. It works as described, power supply to 3.3V, and SPI lines (MISO,MOSI,CLK) connected directly to the Arduino;
However, when I hook up a level converter in the end (5V to 3V, bidirectional) (making the NRF module in the middle, like in a T connection), the module stops working, and I don't know why. How does the level converter module is interfering in the connection? Is there any way I can prevent this and use it?
I intend in adding in the future, modules that talk in 3.3V SPI;
This is the level converter I'm using:

(source: at-the.space)
I suspect it is because of the pullups (5 think that these 10kΩ resistors are pull-ups, but I'm a noob in that part), but I really don't know if that is the problem, as the seller advertises it as being compatible with SPI, I2C, and UART. I have successfully used these for a UART.
I have checked Slaving multiple Arduinos via SPI and tried using an external 5V supply, and a 3.3V supply, but no dice.. However, the 3V side has no connections to it; But, being bi-directional, I don't think there is a problem with this...
I found that 74HCT245D works very well for this, but I'd like to know why with the level converter from JY-MCU this won't work.
Providing the library and connections just in case (the module works without the level converter):

Library & sketch comes from Optimized High Speed NRF24L01+ Driver Class Documenation.
Connection:

NRF2401 Pinout:
NRF24l01 http://ralphfox.at-the.space/imglink/nrf24l01.jpg
My connection:
Arduino with NRF24l01 and Level Converter  http://ralphfox.at-the.space/imglink/nrf_bb.png

making the NRF module in the middle, like in a T connection - what do you mean by that? Can you post a schematic of what you have done, exactly?

How is ground connected? Arduino, converter, module?

@NickGammon Sorry, i have added the connection for arduino, thanks.

@MikaelPatel Added the connection, please check it, thank you.

You have put the NRF24 on the wrong size of the converter.

@MikaelPatel Hmm, i'm mostly sure i tried both sides.. but anyway i thought in putting in the 5V side of the converter, because the arduino is sending and receiving the data through the 5v digital pins; I'll try to re-connect them to the 3v side, with the arduino on 5v side..

@MikaelPatel Yep, no dice :/ i just got home, putting the NRF24 on the 3.3v side gave me the same result as in the 5v.. I'm thinking the issue might be electrical, not logical; maybe it's better to have this topic moved over to electronics?

I don't realy see on presented circuit how your level-converter is connected with other components but I would suggest to check twice the 4-bit SPI signal directions. I guess that converter pins connected to one of MOSI/MISO   should be swapped.

@soerium there is none connected yet; I tried putting one side of the MISO/MOSI on the 3.3v, but that caused the same line to rise to 5v; an non 5v tolerant module on that line would suffer... Remember that the nRF24 is on the 5v side of the level shifter, together with the arduino (same 5v bus); Thanks for the reply thought!

More than probably your level shifter is not fast enough.
A level shifter uses a mosfet to copy signals from one voltage level to the other, but each mosfet has a latency or, if you prefer, a rise time.
Your board probably doesn't use a fast switching mosfet and so the SPI protocol (which is a quite fast one) is not copied correctly.
On top of that you actually don't need a level switcher for the nRF24 modules: the power pin must be limited to 3.3V, but the signal pins are 5V tolerant.
This means you only need a 3.3V voltage source and all the remaining connections can go directly (and safely) into your Arduino board.
UPDATE: the speed concept still applies, it doesn't matter which side of the connection you are using. A mosfet has a little capacitance which slows down the signal transmission: higher the capacitance, slower the maximum data rate.
The cheap chinese level shifter is not designed for high speed communication, while the Texas Instrument device is clearly designed for high speed.
If you look at the SN74HCT245 datasheet you'll notice the switching speed is reported for 50pF capacitance and ranges from 8ns to 16ns: that's the time needed to build enough charge in the switching circuit.

For other devices, you could increase the SPI clock divider to get slower SPI signals. Or voltage divider resistors (which might be faster).

@Paul voltage divider resistors are definitely slower than the level shifter, consider a generic mosfet as a voltage divider in the order of the milliohms: an equivalent voltage divider will be very close to a short. The SPi clock divider is definitely a good advice though, even if not always applicable.

Ah, I always consider resistors to be "instant". But that'd be my mistake (: lowering SPI clock should be applicable in almost every scenario though? But yeah, don't try to fix it in software. ...especially if it lowers your speed (:

@RobertoLoGiacco Sorry for the late reply, i'm on another timezone it seems;As stated in the question, i am not using the level switcher on the nRF24, i was going to use the level switcher to add non 5v tolerant modules(3.3v) to the same SPI line; Sorry if i was not clear enough. I fail to see how the slow level shifting is hitting the nRF24 as the wireless module is on the 5.5v; could you explain please? I solved by using a 74HCT245D; but the question still stands, "why i am not able to use the level shifter?" Thanks for your reply.

5 minute limit to edit... by 10 seconds, damm :/   ; the question would be "why i am not able to put the level shifter on the same bus the nRF24 is?"

@RalphFox I hope my update satisfied your comments, in which case... you know... ;-)

AVR's like all digital have their limits. In this case you're dealing with source resistances that need to charge multiple gate capacitances through series resistances (wires and metal contact connections. Specifically an Absolute MAX 40mA/pin, some milliohms in your copper wire and PCB traces, and pico to nano Farad capacitances, plus depending on how High Speed the SPI is (the spec does not list an upper limit), you will be also contending with frequency limiting parasitics. At MHz frequencies, your wire and PCB traces will have higher resistances due to "skin" effect, where the electrons migrate to the surface of the wire when transferring. Depending on frequency of the wire, adding just a single gate could degredate rise/fall times enough to corrupt data, as the SPI library (whichever you choose) and the SPI peripheral within the AVR probably won't be as sophisticated as a PC based one. The AVR & the SPI library lacks sophistication in that neither has provisions to detect and compensate for extra gate capacitance on the bus line, nor could they compensate for china jumper wires which are quite small (9x40ga) wiring.
There are many factors which could corrupt your SPI project that are coming into play to limit performance.
You should probably do some internet research on high speed bus anatomy if you intend on pushing the SPI bus on the arduino to it's limits.
I think the gate capacitances are combining with source resistance and skin effect and your 40mA/pin is not in fact 40mA per pin but more like 10-20mA is hitting all gate capacitances when skin effect is considered (it effectively raises the resistance of the wire sufficiently to then be a factor).
If connecting the JY-MCU converter AND running SPI at minimum speed corrects communication, then the extra gate capacitances are the factor you should change to higher performance versions. There's the 74AS series with gate times down to 1.7nS and fMAX up to 40MHz!
Hope this helps.

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


text:
Timer CTC Set and Clear modes -- How to un-Clear and un-Set?
Nick Gammon's cheatsheet for the Ardunino UNO's ATmega328P (below) shows some hints on the Clear Timer on Compare (CTC) modes of AVR chips.  Most of the examples for CTC mode I find use the COMxxx registers of 01 = toggle to control the OCxx pin, which would give a 50% duty cycle at 1/2 the frequency of the timer clearing.
My question is about using the non-toggling COMxxx modes of Clear and Set, which don't seem to provide an automatic way to reset into the opposite state, as in the PWM modes.
For example:

void setup() {
  // put your setup code here, to run once:

   // Timer 1 CTC mode Clearing OC1B at 0.25Hz using OCR1A to set frequency
   // Output on OC1B
   // Clear at OCR1B
   // WGM =15 0b0100

   DDRB |= bit(DDB5)| bit(DDB6);  // Teensy2.0 atmega32u OC1A and OC1B outputs
  // DDRB |= bit(DDB1)| bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)
   TCCR1A =  bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM12)  | bit(CS12);  // Set /1 prescaler
   TCCR1C = 0;  // Note that it is good to initialize the timer
                // into a known mode before trying to set interesting TOPs
   OCR1A  = 62500U ;    // Set TOP count to 16000000/(PreScaler *Ftimer)
   OCR1B  = OCR1A/2;    //  ~50% duty cycle
   TCCR1A =  bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM12)  | bit(CS12) | bit(CS10);  // Set /1024 prescaler
   TCNT1 = 0 ;
}

void loop() {
  // put your main code here, to run repeatedly:
  //OCR1B = 62500U/4-1; // 25% duty cycle.
}

If I try the above code, I get a 0.125Hz ( 8s period signal) on PB5 and a constant low on PB6.
What is the way to set OC1B high to be cleared by the timer match?  And similarly, vice versa: clearing OC1B to be set by the timer match?
Is there a direct way or do you fiddle with COM1Bx, trigger FOC1B, and then fiddle COM1B back?

This code uses the TCCR1C:FOC1B register to set the bit by messing with the TCCR1A:COM1Bx bits, but it seems awkward:
void setup() {
   // Timer 1 CTC mode Clearing OC1B at 0.25Hz using OCR1A to set frequency
   // Output on OC1B
   // Clear at OCR1B
   // WGM =15 0b0100

   DDRB |= bit(DDB5)| bit(DDB6);  // Teensy2.0 atmega32u OC1A and OC1B outputs
  // DDRB |= bit(DDB1)| bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)
   TCCR1A =  bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM12)  | bit(CS12);  // Set /1 prescaler
   TCCR1C = 0;  // Note that it is good to initialize the timer
                // into a known mode before trying to set interesting TOPs
   OCR1A  = 62500U ;    // Set TOP count to 16000000/(PreScaler *Ftimer)
   OCR1B  = OCR1A/2;    //  ~50% duty cycle
   TCCR1A =  bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM12)  | bit(CS12) | bit(CS10);  // Set /1024 prescaler
   TCNT1 = 0 ;
}

void loop() {
  int saveCOM;
  Serial.println(TCCR1A,BIN);
  delay(7000); // 7 seconds
  saveCOM = TCCR1A;
  TCCR1A |= bit(COM1B1) | bit(COM1B0) ; // config for set OC1B
  TCCR1C = bit(FOC1B); // force a compare to set bit
  TCCR1A = saveCOM ; // restore mode
}

This code has the 0.125Hz on OC1A, and a semi-random series of 1-4 second long pulses on OC1B.
I was interested in playing with the CTC modes for doing long cycle/low frequency PWM.  With the normal PWMs you could range from a 1-bit 50% PWM at 8MHz to a 16 bit PWM at a frequency of 0.119Hz (8.388s)  With the CTC modes, if you could manage the sets and clears in an TIMERx_OVF_vect with a couple 16 bit registers, you could extend it to 32 bits of PWM resolution with a period up to 152 hours.

If you don't set the WGM mode before you set the TOP/OCR1A/ICR1, it could be truncated to 8 (, 9, or 10?) bits from the Arduino default WGM=5=0b0101 modes.

You can set the output using digitalWrite(10, HIGH). On compare match it's cleared. If it was already cleared, nothing happens. This would be useful to create a single pulse of a precise length.

@Gerben Maybe it's my Teensy 2.0, but putting digitalWrite(PIN_B6,HIGH) or digitalWrite(15, HIGH) seems to stay high forever after the CTC config, or be cleared immediately if before the CTC setup. Checking TCCRA1, it seems that digitalWrite(PIN_B6,HIGH) unsets COM1B1 and COM1B0.

Sorry, stupid me. The digitalWrite implementation will disable PWM. Instead do something like PORTB |= _BV(PB2).

@Gerben.  Stiil nope.  it seems that the PORTB bit value is inhibited/overriden by the OC1B state.  "If one or both of the COMnB1:0 bits are written to one, the OCnB output overrides the normal port func- tionality of the I/O pin it is connected to. If one or both of the COMnC1:0 bits are written to one, the OCnC output overrides the normal port functionality of the I/O pin it is connected to." in the TCCR1A section of my datasheet.  If I toggle COM1Bxx on and off with an underlying high PORTB, it toggles the voltage off and on at the pin.

Teensy2.0 atmega32u - my cheat sheet was for the Atmega328P. Things are likely to be a bit different.

It is a bit different, e.g., the atmega32u has an OC1C, and they are on different bits, but the basic functionality appears to be much the same.

http://arduino.stackexchange.com/questions/30507/timer2-clear-oc2b-on-compare-match-not-working-as-expected-in-ctc-mode/30529#30529 is related


text:
Sending colours to vga monitor
I'm looking for a simple way to send a signal from my arduino to a vga monitor.
What would be the easiest method, and what components would be needed?
I don't need to display an image, just a solid colour.

See if this helps.

My page about Arduino Uno output to VGA monitor has a lot of theory on it, including a sketch that produces colour bars like this:

Code
To produce a single colour is slightly simpler, this sketch did it for me:
/*
 VGA colour video generation

 Author:   Nick Gammon
 Date:     22nd April 2012
 Version:  1.0

 Connections:

 D3 : Horizontal Sync (68 ohms in series) --> Pin 13 on DB15 socket
 D4 : Red pixel output (470 ohms in series) --> Pin 1 on DB15 socket
 D5 : Green pixel output (470 ohms in series) --> Pin 2 on DB15 socket
 D6 : Blue pixel output (470 ohms in series) --> Pin 3 on DB15 socket
 D10 : Vertical Sync (68 ohms in series) --> Pin 14 on DB15 socket

 Gnd : --> Pins 5, 6, 7, 8, 10 on DB15 socket

*/

#include <TimerHelpers.h>
#include <avr/pgmspace.h>
#include <avr/sleep.h>

const byte hSyncPin = 3;     // <------- HSYNC

const byte redPin = 4;       // <------- Red pixel data
const byte greenPin = 5;     // <------- Green pixel data
const byte bluePin = 6;      // <------- Blue pixel data

const byte vSyncPin = 10;    // <------- VSYNC

const int horizontalBytes = 60;  // 480 pixels wide
const int verticalPixels = 480;  // 480 pixels high

// Timer 1 - Vertical sync

// output    OC1B   pin 16  (D10) <------- VSYNC

//   Period: 16.64 ms (60 Hz)
//      1/60 * 1e6 = 16666.66 µs
//   Pulse for 64 µs  (2 x HSync width of 32 µs)
//    Sync pulse: 2 lines
//    Back porch: 33 lines
//    Active video: 480 lines
//    Front porch: 10 lines
//       Total: 525 lines

// Timer 2 - Horizontal sync

// output    OC2B   pin 5  (D3)   <------- HSYNC

//   Period: 32 µs (31.25 kHz)
//      (1/60) / 525 * 1e6 = 31.74 µs
//   Pulse for 4 µs (96 times 39.68 ns)
//    Sync pulse: 96 pixels
//    Back porch: 48 pixels
//    Active video: 640 pixels
//    Front porch: 16 pixels
//       Total: 800 pixels

// Pixel time =  ((1/60) / 525 * 1e9) / 800 = 39.68  ns
//  frequency =  1 / (((1/60) / 525 * 1e6) / 800) = 25.2 MHz

// However in practice, it we can only pump out pixels at 375 ns each because it
//  takes 6 clock cycles to read one in from RAM and send it out the port.

const byte verticalBackPorchLines = 35;  // includes sync pulse?
const int verticalFrontPorchLines = 525 - verticalBackPorchLines;

volatile int vLine;
volatile byte backPorchLinesToGo;

#define nop asm volatile ("nop\n\t")

// ISR: Vsync pulse
ISR (TIMER1_OVF_vect)
  {
  vLine = 0;
  backPorchLinesToGo = verticalBackPorchLines;
  } // end of TIMER1_OVF_vect

// ISR: Hsync pulse ... this interrupt merely wakes us up
EMPTY_INTERRUPT  (TIMER2_OVF_vect)

void setup()
  {

  // disable Timer 0
  TIMSK0 = 0;  // no interrupts on Timer 0
  OCR0A = 0;   // and turn it off
  OCR0B = 0;

  // Timer 1 - vertical sync pulses
  pinMode (vSyncPin, OUTPUT);
  Timer1::setMode (15, Timer1::PRESCALE_1024, Timer1::CLEAR_B_ON_COMPARE);
  OCR1A = 259;  // 16666 / 64 µs = 260 (less one)
  OCR1B = 0;    // 64 / 64 µs = 1 (less one)
  TIFR1 = bit (TOV1);   // clear overflow flag
  TIMSK1 = bit (TOIE1);  // interrupt on overflow on timer 1

  // Timer 2 - horizontal sync pulses
  pinMode (hSyncPin, OUTPUT);
  Timer2::setMode (7, Timer2::PRESCALE_8, Timer2::CLEAR_B_ON_COMPARE);
  OCR2A = 63;   // 32 / 0.5 µs = 64 (less one)
  OCR2B = 7;    // 4 / 0.5 µs = 8 (less one)
  TIFR2 = bit (TOV2);   // clear overflow flag
  TIMSK2 = bit (TOIE2);  // interrupt on overflow on timer 2

  // prepare to sleep between horizontal sync pulses
  set_sleep_mode (SLEEP_MODE_IDLE);

  // pins for outputting the colour information
  pinMode (redPin, OUTPUT);
  pinMode (greenPin, OUTPUT);
  pinMode (bluePin, OUTPUT);

}  // end of setup

// draw a single scan line
void doOneScanLine ()
  {

  // after vsync we do the back porch
  if (backPorchLinesToGo)
    {
    backPorchLinesToGo--;
    return;
    }  // end still doing back porch

  // if all lines done, do the front porch
  if (vLine >= verticalPixels)
    return;

  PORTD = bit (5) | bit (6);  // cyan (green + blue)
  delayMicroseconds (27);     // one scan line

  PORTD = 0;  // back to black
  // finished this line
  vLine++;

  }  // end of doOneScanLine

void loop()
  {
  // sleep to ensure we start up in a predictable way
  sleep_mode ();
  doOneScanLine ();
 }  // end of loop

As @ChrisStratton suggested, the hardware timers are a big help.

Wiring
I wired it up like this:

TimerHelpers library
The TimerHelpers.h library is described on my timers page, a copy is below:
/*
 Timer Helpers library.

Devised and written by Nick Gammon.
Date: 21 March 2012
Version: 1.0

Licence: Released for public use.

See: http://www.gammon.com.au/forum/?id=11504

 Example:

 // set up Timer 1
 TCNT1 = 0;         // reset counter
 OCR1A =  999;       // compare A register value (1000 * clock speed)

 // Mode 4: CTC, top = OCR1A
 Timer1::setMode (4, Timer1::PRESCALE_1, Timer1::CLEAR_A_ON_COMPARE);

 TIFR1 |= bit (OCF1A);    // clear interrupt flag
 TIMSK1 = bit (OCIE1A);   // interrupt on Compare A Match

*/

#ifndef _TimerHelpers_h
#define _TimerHelpers_h

#include <Arduino.h>

/* ---------------------------------------------------------------
 Timer 0 setup
 --------------------------------------------------------------- */

namespace Timer0
{
  // TCCR0A, TCCR0B
  const byte Modes [8] [2] =
  {

  { 0,                         0 },            // 0: Normal, top = 0xFF
  { bit (WGM00),               0 },            // 1: PWM, Phase-correct, top = 0xFF
  {               bit (WGM01), 0 },            // 2: CTC, top = OCR0A
  { bit (WGM00) | bit (WGM01), 0 },            // 3: Fast PWM, top = 0xFF
  { 0,                         bit (WGM02) },  // 4: Reserved
  { bit (WGM00),               bit (WGM02) },  // 5: PWM, Phase-correct, top = OCR0A
  {               bit (WGM01), bit (WGM02) },  // 6: Reserved
  { bit (WGM00) | bit (WGM01), bit (WGM02) },  // 7: Fast PWM, top = OCR0A

  };  // end of Timer0::Modes

  // Activation
  // Note: T0 is pin 6, Arduino port: D4
  enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_64, PRESCALE_256, PRESCALE_1024, T0_FALLING, T0_RISING };

  // what ports to toggle on timer fire
  enum { NO_PORT = 0,

    // pin 12, Arduino port: D6
    TOGGLE_A_ON_COMPARE  = bit (COM0A0),
    CLEAR_A_ON_COMPARE   = bit (COM0A1),
    SET_A_ON_COMPARE     = bit (COM0A0) | bit (COM0A1),

    // pin 11, Arduino port: D5
    TOGGLE_B_ON_COMPARE  = bit (COM0B0),
    CLEAR_B_ON_COMPARE   = bit (COM0B1),
    SET_B_ON_COMPARE     = bit (COM0B0) | bit (COM0B1),
  };

  // choose a timer mode, set which clock speed, and which port to toggle
  void setMode (const byte mode, const byte clock, const byte port)
  {
  if (mode < 0 || mode > 7)  // sanity check
    return;

  // reset existing flags
  TCCR0A = 0;
  TCCR0B = 0;

  TCCR0A |= (Modes [mode] [0]) | port;
  TCCR0B |= (Modes [mode] [1]) | clock;
  }  // end of Timer0::setMode

}  // end of namespace Timer0

/* ---------------------------------------------------------------
 Timer 1 setup
 --------------------------------------------------------------- */

namespace Timer1
{
  // TCCR1A, TCCR1B
  const byte Modes [16] [2] =
  {

  { 0,                         0 },            // 0: Normal, top = 0xFFFF
  { bit (WGM10),               0 },            // 1: PWM, Phase-correct, 8 bit, top = 0xFF
  {               bit (WGM11), 0 },            // 2: PWM, Phase-correct, 9 bit, top = 0x1FF
  { bit (WGM10) | bit (WGM11), 0 },            // 3: PWM, Phase-correct, 10 bit, top = 0x3FF
  { 0,                         bit (WGM12) },  // 4: CTC, top = OCR1A
  { bit (WGM10),               bit (WGM12) },  // 5: Fast PWM, 8 bit, top = 0xFF
  {               bit (WGM11), bit (WGM12) },  // 6: Fast PWM, 9 bit, top = 0x1FF
  { bit (WGM10) | bit (WGM11), bit (WGM12) },  // 7: Fast PWM, 10 bit, top = 0x3FF
  { 0,                                       bit (WGM13) },  // 8: PWM, phase and frequency correct, top = ICR1
  { bit (WGM10),                             bit (WGM13) },  // 9: PWM, phase and frequency correct, top = OCR1A
  {               bit (WGM11),               bit (WGM13) },  // 10: PWM, phase correct, top = ICR1A
  { bit (WGM10) | bit (WGM11),               bit (WGM13) },  // 11: PWM, phase correct, top = OCR1A
  { 0,                         bit (WGM12) | bit (WGM13) },  // 12: CTC, top = ICR1
  { bit (WGM10),               bit (WGM12) | bit (WGM13) },  // 13: reserved
  {               bit (WGM11), bit (WGM12) | bit (WGM13) },  // 14: Fast PWM, TOP = ICR1
  { bit (WGM10) | bit (WGM11), bit (WGM12) | bit (WGM13) },  // 15: Fast PWM, TOP = OCR1A

  };  // end of Timer1::Modes

  // Activation
  // Note: T1 is pin 11, Arduino port: D5
  enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_64, PRESCALE_256, PRESCALE_1024, T1_FALLING, T1_RISING };

  // what ports to toggle on timer fire
  enum { NO_PORT = 0,

    // pin 15, Arduino port: D9
    TOGGLE_A_ON_COMPARE  = bit (COM1A0),
    CLEAR_A_ON_COMPARE   = bit (COM1A1),
    SET_A_ON_COMPARE     = bit (COM1A0) | bit (COM1A1),

    // pin 16, Arduino port: D10
    TOGGLE_B_ON_COMPARE  = bit (COM1B0),
    CLEAR_B_ON_COMPARE   = bit (COM1B1),
    SET_B_ON_COMPARE     = bit (COM1B0) | bit (COM1B1),
  };

  // choose a timer mode, set which clock speed, and which port to toggle
  void setMode (const byte mode, const byte clock, const byte port)
  {
  if (mode < 0 || mode > 15)  // sanity check
    return;

  // reset existing flags
  TCCR1A = 0;
  TCCR1B = 0;

  TCCR1A |= (Modes [mode] [0]) | port;
  TCCR1B |= (Modes [mode] [1]) | clock;
  }  // end of Timer1::setMode

}  // end of namespace Timer1

/* ---------------------------------------------------------------
 Timer 2 setup
 --------------------------------------------------------------- */

namespace Timer2
{
  // TCCR2A, TCCR2B
  const byte Modes [8] [2] =
  {

  { 0,                         0 },            // 0: Normal, top = 0xFF
  { bit (WGM20),               0 },            // 1: PWM, Phase-correct, top = 0xFF
  {               bit (WGM21), 0 },            // 2: CTC, top = OCR2A
  { bit (WGM20) | bit (WGM21), 0 },            // 3: Fast PWM, top = 0xFF
  { 0,                         bit (WGM22) },  // 4: Reserved
  { bit (WGM20),               bit (WGM22) },  // 5: PWM, Phase-correct, top = OCR2A
  {               bit (WGM21), bit (WGM22) },  // 6: Reserved
  { bit (WGM20) | bit (WGM21), bit (WGM22) },  // 7: Fast PWM, top = OCR2A

  };  // end of Timer2::Modes

  // Activation
  enum { NO_CLOCK, PRESCALE_1, PRESCALE_8, PRESCALE_32, PRESCALE_64, PRESCALE_128, PRESCALE_256, PRESCALE_1024 };

  // what ports to toggle on timer fire
  enum { NO_PORT = 0,

    // pin 17, Arduino port: D11
    TOGGLE_A_ON_COMPARE  = bit (COM2A0),
    CLEAR_A_ON_COMPARE   = bit (COM2A1),
    SET_A_ON_COMPARE     = bit (COM2A0) | bit (COM2A1),

    // pin 5, Arduino port: D3
    TOGGLE_B_ON_COMPARE  = bit (COM2B0),
    CLEAR_B_ON_COMPARE   = bit (COM2B1),
    SET_B_ON_COMPARE     = bit (COM2B0) | bit (COM2B1),
  };

  // choose a timer mode, set which clock speed, and which port to toggle
  void setMode (const byte mode, const byte clock, const byte port)
  {
  if (mode < 0 || mode > 7)  // sanity check
    return;

  // reset existing flags
  TCCR2A = 0;
  TCCR2B = 0;
  TimerHelpers.h
  TCCR2A |= (Modes [mode] [0]) | port;
  TCCR2B |= (Modes [mode] [1]) | clock;
  }  // end of Timer2::setMode

}  // end of namespace Timer2

#endif

References

Timers
Interrupts
Arduino Uno output to VGA monitor

Just one quick follow on question. What do I have to search to obtain a connection for a vga cable?

@Terry "VGA female connector" (female connector means you plug a male connector in)

A quick Google search for "Arduino VGA" will give you a lot of information. There are a few variations on both circuits and programming, which also vary in resolution and color depth.
I was searching for this a few days ago, and these are my favorite (so far):

http://labdegaragem.com/profiles/blogs/gerando-sinal-vga-colorido-com-arduino-completo (it is in portuguese, but you can get a pretty good idea of what to do)
https://forum.arduino.cc/index.php?topic=320238.0 (read the whole discussion, pretty nice results)

If using a TV is also a plausible option, check the Arduino TV out library. It can be installed directly from the Arduino IDE and has a good demo.

Not needing to display an actual image simplifies things substantially, as an Arduino lacks the memory and (except in a crude sense) the bandwidth to do so.
However, you cannot simply apply a steady analog voltage to the R, G, and B lines.  Not only do you have to drive horizontal and vertical sync signals, you have to blank the RGB signals when not on the active portion of the screen, otherwise the monitor will assume their steady voltage means "black" and your colors will last only as a brief flash when your device is first connected or enabled.
Generating a large rectangular field of color from an Arduino is likely to be rather challenging, but probably not impossible.  You may be able to use hardware PWM channels for the horizontal and a "color enable", and tightly coded software counters for the vertical aspect.  You can then use the "color enable" to gate a network of potentially variable resistors to establish the single color of particular interest.


text:
Is it possible to infer the length of a neopixel string using 1-wire protocol?
I'have been looking at the AdaFruit NeoPixels recently and am trying to understand how the addressing scheme works.
All of the examples I've seen explicitly identify the length of the string (number of neopixel units) and are typically set using an array of 24-bit values to control the color of a particular neopixel.
My question is two fold:

How do the neopixels know where they are in a string to allow for addressing?
If the neopixels know where they are in the string, would it not be possible to potentially feed the output of the last neoxpixel back to a microcontroller to determine the number of neopixels in the string?

OP Note (this is my interpretation and may be suspect, but it is more or less my take away)
Thank you for all the answers on this - it has been very enlightening from ALL of the answers. General take away, the NeoPixel is not "directly" addressable in the sense that you can pick pixel "X" of "n" pixels. The string of NeoPixels acts essentially as a gigantic shift-register (as stated in one of the answers) so to "address" a particular pixel you have to update a buffer that represents the state of the entire string and then shift it down the wire. This is why micro-controllers, such as an Arduino, would have limitations on how many NeoPixels it could control. This is also why it is more practical to define the number of pixels in the string and allocate memory to represent that state.

Why do you want to do this? Don't you know how many NeoPixels you have?

I've seen people light every pixel in a row, and measure the slight voltage drop in the supply voltage. When you try to turn on an led that isn't there, the voltage drop disappears, and you know where the string ends.

As noted in Chris Stratton's answer, “Each pixel "peels off" the first data word before passing on the rest, so the payload gets shorter and shorter as you move down the chain”.
This behavior is spelled out clearly in WS2812.pdf and WS2812B.pdf datasheets from http://www.world-semi.com :

The data transfer protocol use single NZR communication mode. After the pixel power-on reset, the DIN port receive data from controller, the first pixel collect initial 24bit data then sent to the internal data latch, the other data which reshaping by the internal signal reshaping amplification circuit sent to the next cascade pixel through the DO port. After transmission for each pixel, the signal to reduce 24bit. pixel adopt auto resha-ping transmit technology, making the pixel cascade number is not limited the signal transmission, only depend  on the speed of signal transmission.

This means that each WS2812 unit in a chain picks off the first 24-bit data packet, latches that data into an internal register, and passes the rest of the data on out, through reshaping circuitry.  Hence, if you put m packets of data into a chain and k packets come out, the chain length is m-k or more.  (The chain length may be more than m-k when k is zero.)

Each pixel "peels off" the first data word before passing on the rest, so the payload gets shorter and shorter as you move down the chain.  Although the data wire may look continuous it isn't - the signal is electrically re-driven from each unit to the next.
For the RGB ones, they are logically three monochrome pixels of different colors, so they peel off three words rather than just one.
At any point in the chain you can determine how many logical pixels potentially remain to be updated, by counting the words you are passing on.  You can't of course tell if they are actually there, or if there are further pixels for which no data is being provided.  And you can't tell how many pixels preceded, other than to bound it by the amount of gap time from the previous update you received.

So that more or less answers my understanding in that each neopixel peels off the data it knows about (the "head" of the data set) and then passes the rest. But doesn't that mean I could feed the end of the last pixel back to the microcontroller and have a routine to "watch" for pulses to come back? If no pulses were received then we are either at or below the length of the chain. The first group of pulses that we receive after sending would indicate the number of pixels-1 yes?

Yes, if you have access to both ends of the chain and don't know how many elements you have, you can measure it that way.  It may get a little tricky in practice as the transition edges you get will probably be delayed from those you sent, at the least by electrical delay and probably by many register clock-to-out delays as well, and for a long enough chain could make receiving them in software a little challenging.  For some of these signalling schemes (would have to look again to see if this one) you can persuade a sufficiently flexible UART peripheral to help, for others you cannot.

I guess a simpler method than truly receiving the data could be to configure a pin change interrupt on the tail-of-chain return, and then send frames with increasing numbers of data words in each into the head end until you finally see something make it out that tail end, or do so in a pattern more like a binary search.

Looks like I finally arrived at the same conclusion you did, Chris. However the binary search idea may have a speed penalty. What number would you start with? Too small and you miss a long string, too large and it would take a long time to send all those pixels. Still this guy drove 1000+ pixels at 30 FPS, so maybe it is a pretty reasonable idea at that. Maybe start with 1000 pixels and work your way down. :)

Or maybe send in increments of 100 until you overshoot, then do a binary search on that last amount.

It is possible to do this by feeding the end of the strip back into the arduino.  bunnie Huang blogged about doing this a few years ago: http://www.bunniestudios.com/blog/?p=3345
He has schematics and firmware which uses a modified neopixel library that can measure the length of the strip.

As far as I can make out (eg. NeoPixels Revealed: How to (not need to) generate precisely timed signals) the NeoPixels are not in fact addressed, but are like a long shift register. Thus if you have 10 pixels, you have to send out 10 lots of RGB colours and then latch them. This is why you need to know how many pixels you have, so that you send out the right number of RGB bytes.
I don't think it would be particularly practical to try to detect how many pixels are in the chain, because the individual ones "reshape" the timing pulses.

What about feeding the far end of the data line back into an arduino input pin?

What would that tell you? Because of the reshaping done by individual pixels you don't know how long each bit will be, exactly. Thus whilst you might know how long it took for a bit to arrive at the other end, without knowing the length of each bit, you don't know what to divide that time by, to arrive at a count.

I suppose, since each pixel "peels off" one RGB colour, you might try sending increasing numbers of pixels out, and waiting until one arrives at the other end. That might work.

This is certainly possible as I have now confirmed.
The code below will detect the length of a string of NeoPixels up to 10000 long.
/*
 *
 * Find length of NeoPixel string.
 * Author: Nick Gammon
 * Date:   11 March 2016
 */

#include <SPI.h>

const unsigned long LIMIT = 10000;  // maximum pixels to test

// Note: Connect NeoPixels to MOSI (pin D11 on a Uno, pin D51 on a Mega)
//       Connect the other end of the NeoPixels to D2 (External Interrupt 0)

void sendByte (byte b)
  {
    // send one byte to the Neopixels - note that the "off" gap is partly handled by the loop overhead
    //   gaps measured empirically to be 1.7 µs to 2 µs, so we don't need to add any more of our own
    for (byte bit = 0; bit < 8; bit++)
      {
      if (b & 0x80) // is high-order bit set?
        SPI.transfer (0b11111100);  // 1 bit - 750 ns on + 250 ns off (acceptable "on" range 550 ns to 850 ns)
      else
        SPI.transfer (0b11100000);  // 0 bit - 375 ns on + 625 ns off (acceptable "on" range 200 ns to 500 ns)
      b <<= 1; // shift next bit into high-order position
    } // end of for each bit
} // end of sendByte

void ledsetup()
{
  SPI.begin ();
  SPI.setClockDivider (SPI_CLOCK_DIV2);
  SPI.setBitOrder (MSBFIRST);
  SPI.setDataMode (SPI_MODE1);   // MOSI normally low.
} // end of ledsetup

void sendPixel (const byte r, const byte g, const byte b)
  {
  sendByte (g);
  sendByte (r);
  sendByte (b);
  } // end of sendPixel

void show()
  {
  delayMicroseconds (7);
  } // end of show

volatile bool triggered;

void myISR ()
  {
  triggered = true;
  } // end of myISR

void setup()
  {
  ledsetup();
  Serial.begin (115200);
  Serial.println (F("Starting ..."));
  attachInterrupt (0, myISR, RISING);
  } // end of setup

unsigned int increment = 1000;
unsigned int counter = increment;

void loop()
  {
  noInterrupts ();
  triggered = false;
  EIFR = bit (INTF0);  // clear flag for interrupt 0

  for (unsigned int i = 0; i < counter; i++)
    sendPixel (5, 0, 0);
  TIMSK0 = bit (TOIE0);  // throw away timer overflow interrupt
  interrupts ();
  show ();  // latch the colours - handle the interrupt meantime

  if (triggered)
    {
    if (increment <= 1)
      {
      Serial.print (F("There are "));
      Serial.print (counter - 1);
      Serial.println (F(" NeoPixels in the string."));
      Serial.flush ();
      exit (0);
      }
    else
      {  // binary search
      counter -= increment;
      increment /= 2;
      } // end of if
    } // end of if triggered

  counter += increment;

  if (counter > LIMIT)
    {
    Serial.print (F("Could not find any NeoPixels after trying "));
    Serial.print (LIMIT);
    Serial.println (F(" pixels."));
    Serial.flush ();
    exit (0);
    }

  } // end of loop

It works by sending out increasingly long strings of 24 bits, and waiting for one to "shuffle off" the other end of the string.
Connect the Data In of the NeoPixels to MOSI (pin D11 on a Uno, pin D51 on a Mega) as this sketch uses SPI to generate the timed sequences. Connect the far end of the NeoPixels (Data Out) to pin D2 which is External Interrupt 0.
The sketch pumps out batches of pixels, and waits for an external interrupt. When that occurs it indicates that the last pixel in the chain was reached, and passed the pixel data out Data Out to the non-existent pixel past the end of the chain.
The number of pixels needed to do this is then noted.
The sketch does a "binary search" to speed things up for long strings of pixels. The worst-case scenario (where you have either 10000 pixels, or none at all) takes 6 seconds to execute. With less pixels it will be faster. I had under a second execution time for 3 pixels in my test string.
The sketch outputs a dull red (intensity 5) so you should see the pixels light up in red if all is well. If you wanted to do it unobtrusively, you could output black (as that still results in bits being sent down the string).
Example output:
Starting ...
There are 3 NeoPixels in the string.


text:
Can I use the TLC5940 LED Driver if I'm already using other SPI devices on my Arduino mega?
The way I understand SPI is that 3 wires are shared (MOSI, MISO, & SCHK). The slave select is pulled high when you want to write to a specific device. The 3 shared wires can be daisy chained. The TLC5940 LED Driver says that it uses SPI but I don't see any documentation about a slave select. Can I just include this in the standard daisy chaining and assign a new slave select? In some forums online some people seem to indicate you can't use the TLC5940 on the same SPI bus as other devices. I thought that was the whole point of SPI. Are there different forms of SPI? I'm quite confused, can I use the TLC5940 with other SPI devices?

Can I just include this in the standard daisy chaining and assign a new slave select?

SPI is normally used as a parallel bus and requires MISO to be tri-state (disconnected when not selected).

In some forums online some people seem to indicate you can't use the TLC5940 on the same SPI bus as other devices.

The device does not have a chip select which gives a challenge. No direct wiring is possible but can be solved.

Are there different forms of SPI? I'm quite confused, can I use the TLC5940 with other SPI devices?

It is possible to connect the TLC5940 but it requires some extra logic. You can for instance block the clock signal when it is not selected. This can be done with a MOSFET or 74HC125 and a pull-low resistor.
Cheers!


text:
A simple login page on Arduino Uno
I'm trying to setup home automation system controlled with webpage stored in SD card of Arduino, I was thinking if it was possible to set a login page, only combination of correct user id & password will be able to access the control page.

What have you already tried? In order for other people to help you, you need to show effort in doing so yourself.

That is easy to break. Have you considered checking the client MAC address?

I seen some tutorials, a simple webpage with buttons can control "things" connected to relay.

At Atmega based Arduino is the wrong choice to start with.

@Mikael, "Have you considered checking the client MAC address?" Eh, why? How's a MAC address more secure than a username and good password? Are you referring to lack of HTTPS in the question? Also, unless using IPv6 without privacy addressing, MAC addresses don't make it beyond the first network router, so would limit control. And when within that same network, a simple arp -a will show MAC addresses of other devices, and that can easily be spoofed... MAC filtering is not secure at all.

Arduino Uno based security is not security at all. Only something that keeps honest people honest is possible.

I have a page about a tiny web server for the Arduino Uno or similar boards. It simply isn't true that you can't make one, or that a much more powerful processor would be better. There are some limitations imposed by small amounts of RAM, but the library described there decodes incoming HTTP information "on the fly" so it can handle a reasonably large page.
You could put the data to be display into PROGMEM (more information here) or onto an SD card as someone suggested.
The login and password could be stored in EEPROM.

I would also suggest making your UI a "one page" Javascript application. This means all the UI is loaded into the browser up front and all further interactions with your Arduino can be made with simple GET/POST requests eg AJAX/RESTful requests. This approach also has the advantage of allowing you to pre-compress the JS/CSS application code with GZip (just add a Content-Encoding: gzip header) greatly reducing the amount of flash required and overhead of streaming content from flash to the browser.
The main point here being push as much processing as possible into the browser.

Arduino cannot run a web server so it is not possible to do what you want with just using an Arduino board?.
It seems we can run a web server, look at the answer by @Nick Gammon below.
By using a wifi shield and connecting to a local or public web server where your page is hosted you should be able to to do it.
Don't expect to load a full fledged page on an Arduino you have to try posting a few post and get requests to get this working. It will look like a terminal based login.
What is the control page you are trying to do?
If you are ok with spending more money try using a Raspberry pi + Arduino combination.

A ESP8266 would be the cheapest and easiest to use solution. Then you could run the webserver, connect the SD card and the sensors to one device without much hassle.

It is possible to do web servers (even with the Ethernet Shield). Here are a few examples; https://github.com/mikaelpatel/Cosa-HTTP/blob/master/examples/CosaPinWebServer/CosaPinWebServer.ino, https://github.com/mikaelpatel/Cosa-HTTP/blob/master/examples/CosaSDWebServer/CosaSDWebServer.ino and https://github.com/mikaelpatel/Cosa-Shell/blob/master/examples/CosaShellWebServer/CosaShellWebServer.ino

@Avamander ESP8266 wifi shield gives Arduino the ability to connect to a network not to run a webserver. Still we has to depend on other devices to get this working.

@Mr.X Using an ESP8266 as a shield is a total waste, it's like attaching a mortar to a golf cart. ESP itself can handle a web server and much more at once. (Plenty of examples on the web)

Have you tried to change Arduino Uno board to Arduino Yun board?
Yun has a Linux distribution onboard and you can easy configure a web page to control physical objects.
Here some examples:
http://scuola.arduino.cc/lesson/b4EoRkV/Arduino_Yn_Intro_to_web_server
https://github.com/mat-lo/yun-examples

I guess you could do it with Javascript and HTML, and put the pages in the micro SD card.
But it will make it harder (if not impossible) to make the automation.

I read a tutorial, in which Node.js was use for automation, stored in SD card, if that can be done, then login?

here you can found some help (but only with html)
How to make a login form using HTML that connects to the next page
though with nodejs it would be awesome

That's a good help

but it will make it harder (if not impossible) to make the automatization - why? Your answer will be more helpful if you explain your thinking here.

@Fabian W. the link u provided is a very good resource, thank you

Make simple webpage and put it in sd card. If it's just one page with few buttons and bit js even flash memory of controller would suffice.
In arduino code add lines that can detect click on particular button of webpage and control relay/motor etc.
Knowledge of basic post request using js can help. You can't implement php page in arduino as it needs complex processing at arduino side

How exactly would this process you described work? What tools are needed? Currently your answer needs more information, if you improve your answer you'll definitely get a few upvotes.


text:
Can I use IO10 as digital IO while using SPI interface?
If my arduino is the master device in a SPI network, hence not using the slave select SS pin, can I use the same pin as IO10?
I am actually using an Intel Galileo, with the same pinout as an Arduino Uno Rev3.

Can I use IO10 as digital IO while using SPI interface?

On AVR it must be OUTPUT when using SPI in master mode and INPUT in slave mode.

If my arduino is the master device in a SPI network, hence not using the slave select SS pin, can I use the same pin as IO10?

The SS pin (D10) has to be OUTPUT when using SPI master mode. It can be used for chip select on the SPI bus (slave select) or some other output function.
So far the Arduino design with AVR (e.g. ATmega328). The Intel Galileo based Arduino has the following block diagram:

IO10-IO14 are multiplexed from SPI1 or GPIO. This implies that the SPI SS (IO10) signal is hardwired to the SPI controller when enabled. Last, according to the product info SPI is master only. More details schematics details here.
Cheers!

I am actually using an Intel Galileo - I think Mikael's answer specifically addresses the Atmega328P processor. The Galileo may have different requirements.

Added some more info on Intel Galileo. Nick is very right about the different requirements.


text:
ATTiny watchdog and interrupt
I'm trying to control an Arduino Barebone from an arduino with relays.
Basically when the attiny starts it should switch on the arduino for 4 seconds.
The Arduino sends a signal back to a digital pin of the attiny and as long as it is set to high the attiny should leave it working.
If it is low the attiny should switch the relay of.
the problem is some changes to the code make the interrupt reset the attiny (which would switch of the arduino) othertimes- in this case.
the interrupt doesn't work at all.
#include <avr/sleep.h>
#include <avr/wdt.h>
#include <avr/io.h>
#include <avr/interrupt.h>

#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

int pinBoard = 0;
bool boardOn = false;
bool startBoard_flag = false;
int pinBoardReturn = 3;

volatile boolean f_wdt = 1;

void setup() {
  cli();//disable interrupts during setup
  pinMode(pinBoard, OUTPUT);
  pinMode(pinBoardReturn, INPUT);
  setup_watchdog(9);
  cbi(ADCSRA, ADEN);                   // switch Analog to Digitalconverter OFF
  // cli();//disable interrupts during setup
  for (int i = 0; i < 10; i++) {
    digitalWrite(pinBoard, HIGH);
    delay(100);
    digitalWrite(pinBoard, LOW);
    delay(100);
  }

  PCMSK |= (1 << PCINT1); //sbi(PCMSK,INTERRUPTPIN) also works but I think this is more clear // tell pin change mask to listen to pin2 /pb3 //SBI
  GIMSK |= (1 << PCIE);   // enable PCINT interrupt in the general interrupt mask //SBI

  startBoard();

  DDRB &= ~(1 << DDB1); //cbi(DDRB, DATADIRECTIONPIN);//  set up as input  - pin2 clear bit  - set to zero
  PORTB |= (1 << PB1); //cbi(PORTB, PORTPIN);// disable pull-up. hook up pulldown resistor. - set to zero
}

void startBoard() {
  digitalWrite(pinBoard, HIGH);
  boardOn = true;
  startBoard_flag = false;
  cli();                                  // Disable interrupts
  delay(4000);
}

void shutdownBoard() {
  digitalWrite(pinBoard, LOW);
  boardOn = false;
}

void loop() {
  if (f_wdt == 1) { // wait for timed out watchdog / flag is set when a watchdog timeout occurs
    f_wdt = 0;     // reset flag
    if (startBoard_flag) {
      startBoard();
    }
    bool boardReturn = digitalRead(pinBoardReturn);
    if (boardOn && !boardReturn) {
      shutdownBoard();
    }
    system_sleep();
  }
}

//****************************************************************
// set system into the sleep state
// system wakes up when wtchdog is timed out
void system_sleep() {

  // GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
  // PCMSK |= _BV(PCINT3);                   // Use PB3 as interrupt pin

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement
  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sleep_cpu();                            // sleep

  // PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
  sleep_disable();                        // Clear SE bit

  // sei();                                  // Enable interrupts
}

//****************************************************************
// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
// 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
void setup_watchdog(int ii) {

  byte bb;
  int ww;
  if (ii > 9 ) ii = 9;
  bb = ii & 7;
  if (ii > 7) bb |= (1 << 5);
  bb |= (1 << WDCE);
  ww = bb;

  MCUSR &= ~(1 << WDRF);
  // start timed sequence
  WDTCR  |= (1 << WDCE) | (1 << WDE);
  // set new watchdog timeout value
  WDTCR  = bb;
  WDTCR  |= _BV(WDIE);
}
//****************************************************************
// Watchdog Interrupt Service / is executed when  watchdog timed out
ISR(WDT_vect) {
  f_wdt = 1; // set global flag
}

ISR(PCINT_VECTOR) {
  for (int i = 0; i < 4; i++) {
    digitalWrite(pinBoard, HIGH);
    delay(1000);
    digitalWrite(pinBoard, LOW);
    delay(1000);
  }
  startBoard_flag = true;
  f_wdt = 1; // set global flag
}

Sequence like "cli(); delay(...);" is not a very good idea as delay() depends on Timer interrupts.

@MikaelPatel Is it? I believe it's just a loop with "NOP" instructions?
Wait, this: http://forum.arduino.cc/index.php?topic=46452.0 - tells me it uses milis, which does use a timer I believe! (AVR delay functions didn't use timers).

@Paul Might a well check the source code. Do you have a link to the ATtiny core that you are using? Let's check delay().

So i would rather have a counter for the watchdog in order to wait for the specified time?

Disassembling the delay code indicates it uses micros which needs interrupts on to work.
void delay(unsigned long ms)
{
 27a:   cf 92           push    r12
 27c:   df 92           push    r13
 27e:   ef 92           push    r14
 280:   ff 92           push    r15
 282:   cf 93           push    r28
 284:   df 93           push    r29
 286:   6b 01           movw    r12, r22
 288:   7c 01           movw    r14, r24
    uint16_t start = (uint16_t)micros();
 28a:   d3 df           rcall   .-90        ; 0x232 <micros>
 28c:   eb 01           movw    r28, r22

    while (ms > 0) {
 28e:   c1 14           cp  r12, r1
 290:   d1 04           cpc r13, r1
 292:   e1 04           cpc r14, r1
 294:   f1 04           cpc r15, r1
 296:   79 f0           breq    .+30        ; 0x2b6 <delay+0x3c>
        yield();
 298:   ea d0           rcall   .+468       ; 0x46e <yield>
        if (((uint16_t)micros() - start) >= 1000) {
 29a:   cb df           rcall   .-106       ; 0x232 <micros>
 29c:   6c 1b           sub r22, r28
 29e:   7d 0b           sbc r23, r29
 2a0:   68 3e           cpi r22, 0xE8   ; 232
 2a2:   73 40           sbci    r23, 0x03   ; 3
 2a4:   a0 f3           brcs    .-24        ; 0x28e <delay+0x14>
            ms--;
 2a6:   81 e0           ldi r24, 0x01   ; 1
 2a8:   c8 1a           sub r12, r24
 2aa:   d1 08           sbc r13, r1
 2ac:   e1 08           sbc r14, r1
 2ae:   f1 08           sbc r15, r1
            start += 1000;
 2b0:   c8 51           subi    r28, 0x18   ; 24
 2b2:   dc 4f           sbci    r29, 0xFC   ; 252
 2b4:   ec cf           rjmp    .-40        ; 0x28e <delay+0x14>
        }
    }
}
 2b6:   df 91           pop r29
 2b8:   cf 91           pop r28
 2ba:   ff 90           pop r15
 2bc:   ef 90           pop r14
 2be:   df 90           pop r13
 2c0:   cf 90           pop r12
 2c2:   08 95           ret

That appears to confirm that the code in wiring.c is indeed what is being used on the ATtiny85 core:
void delay(unsigned long ms)
{
    uint16_t start = (uint16_t)micros();

    while (ms > 0) {
        yield();
        if (((uint16_t)micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

Turning interrupts off and then doing a delay is a Bad IdeaTM.

So i would rather have a counter for the watchdog in order to wait for the specified time?

Using the watchdog timer is certainly one way of waiting for 4 seconds.

Excellent effort and description.

+1 for the Bad Idea(TM). I like it! The rest of the answer deserves it too of course.


text:
Arduino GSM Shields stacking
I'm researching options for a project in which I need to send/receive SMS messages to/from multiple users of different service providers.
Hoping to reduce costs, I'm thinking of forwarding the messages to a different SIM card, depending of the user's service provider (since all of them have plans with free SMS for numbers of the same provider).
Arduino GSM Shield seemed like a good option, except the shield has only one SIM card slot.
I wonder: would it be possible to stack 3 shields (there are 3 mayor service providers in my country) on the same Arduino Board and use some reasonably straightforward programming to handle the task?
Thanks in advance.

Yes, that is easy. You need multiplexer (MUX) to forward communication pins (2 & 3) to the right GSM shield. Google for it to find the one that suits your budget.

Hardware-wise this should be pretty easy to do. You need to connect pins 2 and 3 of each GSM shield to separate serial ports on the Arduino board. The best way to do this is to use an Arduino Mega, which has 4 hardware serial ports, this leaves you Serial for uploading sketches and communication to Serial Monitor. It's also possible that you could use a software serial library like AltSoftSerial but I wouldn't recommend it. You can carefully bend the pins 2 and 3 of two of the shields out before stacking them and then use jumper wires to connect those pins to the hardware serial pins of the Mega. The other pin of interest is pin 7, which is the modem reset pin. If you leave all the modems connected to pin 7 on the Arduino that means that there is no way to only reset a single modem. I'm not sure how much of an issue that would pose. So you might be better off to bend pin 7 on two of the shield out also and connect those to separate pins. You will also need to be sure to provide a power supply capable of supplying sufficient current. The product page says each shield may require up to 1000mA.
Software-wise it gets much more tricky. Unfortunately the stock Arduino GSM library was not written to be very flexible. Instead of allowing you to pass it a Serial object it's hardcoded to do software serial on pins 2 and 3 so you would need to do quite a bit of work on the library to make it work for your needs. I'd recommend looking around to see if a more suitable library exists.

Stacking might be hard, since they communicate on pins 2&3.  But if you work around that somehow, you could use Software Serial to access multiple GSM devices.
I think the GSM library has hardcoded the pins, and it might not share well with multiple, but you might be able to use SoftwareSerial or AltSoftSerial to do multiple connections, but that would be less straightforward.

authors: الأسطورة واو