text:
Sparkfun MicroSD shield cannot open log file
I'm currently trying to log data from a GPS shield onto a microSD card using a Sparkfun microSD shield. All my code will compile, but when I open the serial monitor the microSD will initialize, but then the log file itself won't be able to be opened. I have formatted the card and reset all the shields and the Arduino itself multiple times, but nothing seems to work.
When I upload the example sketch used to show the functionality of the data logging, provided in the SD.h library by Sparkfun, everything will function properly and it will be able to open the file correctly. I used this file to give me information on how to format my code, so it is very similar.
One thing that I think may be causing the issue is the size of my code. When uploaded, the code uses 80% of total memory and 84% of dynamic. I tried commenting out a lot of the code to see if more free memory would give a different result, but still got the same error.
Any help would be awesome, and thank you in advance! I've included my code below.
// Include FONA, Watchdog, SD card and declare pins
#include "SoftwareSerial.h"
#include "Adafruit_FONA.h"
#include "Adafruit_SleepyDog.h"
#include "SPI.h"
#include "SD.h"

#define FONA_RX 2 //Reset pin
#define FONA_TX 3 //FONA serial TX pin
#define FONA_RST 4 //FONA serial RX pin

//Include software serial
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;

Adafruit_FONA fona = Adafruit_FONA(FONA_RST);

const int chipSelect = 8;

File dataFile = SD.open("data.log", FILE_WRITE);

//Set strings to hold all the data
  String Lat = "";
  String Long = "";
  String KPH = "";
  String Head = "";
  String Alt = "";

  float latitude, longitude, speed_kph, heading, altitude;

//Set integers for the data
  int GPSlat = latitude;
  int GPSlong = longitude;
  int GPSkph = speed_kph;
  int GPShead = heading;
  int GPSalt = altitude;

//Set counter and phone number for location messaging
  int Log_Counter = 0;

// Halt function called when an error occurs.  Will print an error and stop execution while
// doing a fast blink of the LED.  If the watchdog is enabled it will reset after 10 seconds.
//void halt(const __FlashStringHelper *error) {
//  Serial.println(error);
//}

//uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); //

//uint8_t type; //

void setup() {
  while (!Serial);

  //Initialize serial output
  Serial.begin(115200);
  Serial.println(F("Team Space Bread GPS - Zero-G-luten"));

  //Initialize SD card, then check if card is present
  Serial.print(F("Initializing SD card..."));
  pinMode(SS, OUTPUT);
  digitalWrite(SS, HIGH);
  if (!SD.begin(chipSelect)) {
    Serial.println(F("Card failed or is not present"));
    while (1);
  }
  Serial.println("Card initialized");

  //Open file to log data to
  if (! dataFile) {
    Serial.println(F("Error opening log file"));
    while (1);
  }

  //Initialize FONA module
  Serial.println(F("Initializing FONA.... (may take a couple seconds)"));
  fonaSerial->begin(4800);
  if (!fona.begin(*fonaSerial)) {
  // halt(F("Couldn't find FONA"));
  }
  fonaSS.println("AT+CMEE=2");
  Serial.println(F("FONA is functioning swimmingly"));

  //Enable watchdog timer; if code hangs and will not connect to GPS, WDT will run out after 10 seconds
  //and reset the code
  Watchdog.enable(10000);
  Watchdog.reset();

  //Wait for FONA to connect to cell network
  Serial.println(F("Checking for network..."));
  while (fona.getNetworkStatus() != 1) {
   delay(500);
  }

  //Enable GPS
  Watchdog.reset();
  Serial.println(F("Enabling GPS"));
  fona.enableGPS(true);
  delay(2000);
  Watchdog.reset();
  if (!fona.enableGPS(true)) {
  // halt(F("Failed to turn GPS on, resetting..."));
  }
  Serial.println(F("GPS connection successful"));

  // Start the GPRS data connection.
  Watchdog.reset();
  Serial.println(F("Enabling GPRS"));
  fona.enableGPRS(true);
  delay(2000);
  Watchdog.reset();
  if (!fona.enableGPRS(true)) {
  //  halt(F("Failed to turn GPRS on, resetting..."));
  }
  Serial.println(F("Connected to cellular"));

  //Wait a bit for connection to stabilize
  Watchdog.reset();
  delay(5000);

}

void loop() {
//Reset Watchdog at start of loop - everything must work in less than 10 seconds!
 Watchdog.reset();

// Grab a GPS reading.

  bool gpsFix = fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude);

//Define strings as data intergers
  Lat += String(GPSlat);
  Long += String(GPSlong);
  KPH += String(GPSkph);
  Head += String(GPShead);
  Alt += String(GPSalt);
//Print all data onto SD card
  dataFile.print("GPS lat: ");
  dataFile.println(Lat);
  dataFile.print("GPS long: ");
  dataFile.println(Long);
  dataFile.print("GPS speed KPH: ");
  dataFile.println(KPH);
  dataFile.print("GPS heading: ");
  dataFile.println(Head);
  dataFile.print("GPS altitude: ");
  dataFile.println(Alt);
  dataFile.print(" ");

//Flush file to save data onto card
  dataFile.flush();

//Every loop, add 1 to Log_Counter. When Log_Counter==180 (every 15 minutes), send SMS to number with location
  Log_Counter++;
  if (Log_Counter==180) {
//There has to be a more elegant way to do this, but ¯\_(ツ)_/¯

//Buffer for location and phone number
  char LocationBuffer[48];
//  char SendTo[16];

//Make latitude and longitude into one string
  String(Location) = Lat+=Long+=Alt ;

//Set phone number to text to
//  String(PhoneNumber) = "18143803250";
                       //^^^^This^^^^ is where you put the number to send the location to every 15 minutes

//Location string to char that will be able to send
  Location.toCharArray(LocationBuffer, sizeof(LocationBuffer));

////Set phone number to char
//  PhoneNumber.toCharArray(SendTo, sizeof(SendTo));

//Send SMS w/ location
fona.sendSMS("18143803250", LocationBuffer);
}

//Take mesaurement every 5 seconds
  delay(5000);
}


text:
Monitoring the state of AC relay, design considerations
I want to use a sensor and relay as a safety device to allow/deny power to an AC mains-powered electrical unit.
If the wall power is disconnected I loose the state of the relay which is stored in a variable on my Pro Mini.
My Arduino is powered from an AC-DC voltage regulator that is between the AC mains and the Power On switch of the electrical unit.
Apart from powering the Arduino with a battery/supercap, are there any circuit design tricks I'm missing?

Can you clarify your setup? Is the Arduino controlling the relay and also sensing the presence or absence of mains power (i.e., detecting a power loss?)

Yes the Arduino is controlling the relay. No, the sensor is a liquid-level sensor which indicates whether the Arduino should turn off the power on low liquid level.

When you change the state of the relay, save it to the EEPROM. In setup() read the value from EEPROM and apply it.

Ah... why didn't I think of that :-)

but is it necessary? Doesn't the state evaluate from the sensor value after the sketch starts?

If the state of the relay is fully determined by the instantaneous state of the sensor, then there is no need to store the relay state.

Yes, I think you are both right. What was confusing me was that I do need to store the relay state in a variable so that I only switch the relay when the sensor changes, and not on every iteration of the loop.

If you set a pin to HIGH and it's already HIGH, nothing happens. It's okay to "set" the relay on every iteration of the loop.

This is a latching relay and so the switching needs 3 lines of code: 1) set pin high; 2) delay for latching, 50mS; 3) set pin low

and how behaves this latching relay at Arduino restart? my changes state

@Owen Storing a separate var for anything controlled is good practice IMO. I always do so, and I won't trust reading back the value of a pin. Among other things, a separate var allows you to more easily track the time since a change was made. Besides statistics, that helps you prevent any condition  causing changes too frequently. It also offers a clue in case of circuit malfunction, if the var != the detected state. Detecting such dependencies also allows future circuit additions for a manual override.

I have run into a similar situation on a few occasions. Maybe my scheme will help. What I do is sense power loss early, so I can save a structure full of all my program states to EEPROM when the power is going away. Conversely, the first thing the program does on power up is restore the memory structure from EEPROM. Provided you save your relay state whenever it changes, this scheme should help you recover. You don't need a super cap. I use a circuit like this...
In this circuit, I use a diode to isolate a large (but not super) capacitor from the supply, and that circuit point also feeds my VIN (This is a NANO board). Then, that capacitor voltage is further isolated from a voltage divider, with another diode. The voltage divider brings down the 12V (only 11V after the diodes) to pretty near 5V. there's also a small (100nF) capacitor there to filter any noise.
If power is lost, that 2200uF capacitor will keep my NANO, a bunch of LEDs, an LCD display, and even a transistor driver and relay circuit(not shown) alive for nearly a second. But the voltage at the digital input (D2 in my case) will drop within milliseconds! So if you are polling that pin regularly, you'll have plenty of time to react by saving your states. If you doubt whether you can poll that fast, pin D2 can easily be tied to an interrupt. (that's overkill.. easier to just create you're owe version of millis(), so that whenever you have a timer wait, you can continually test the power detect pin, and react within a millisecond).
Now if for some reason you would like to ensure that the arduino doesn't lose power at all during short power line disturbances, you can add another diode to the 2200uF capacitor, and connect it to a battery pack. It the battery voltage is a little lower than the main supply, no current will flow out of it until its really needed.

Nice. I like your implementation - thank you for sharing.

You power your device and your controller from same AC source.
You loose that AC source and they both will go off line.
You get your AC source back - restart controller and check the current state of your device /relay.
What did I missed ?

You are correct and missed nothing, only the bit where I said I got confused :-)

source: Stack Exchange

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

sort: votes


text:
Unable to get keypad key in while loop
I'm a beginner into Arduino so I have a little problem where I'm trying to do a countdown on LCD using while loop but I'm also trying to get a key input inside that same while loop. Problem is that its hard to get a input in that while because there are delay because of timer. Tried to look around the internet for solution but didn't find one. If anybody got a good solution I would be great full if you post it :) Thanks again!
Here is my code:
while (gameInProgress) {

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Until boom! ");
    lcd.print(timer);
    lcd.setCursor(0, 1);
    lcd.print(passwordInputed);

    char key = keypad.getKey();
    if (key && gameInProgress) {
      passwordInputed += key;
    }

    analogWrite(buzzerPin, 145);
    delay(200);
    analogWrite(buzzerPin, 0);
    delay(800);
    timer--;
    if (timer == 0){
      gameInProgress = false;
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Boom happend!");
      lcd.setCursor(0, 1);
      lcd.print("You lost :(");
    }
  }

Write non blocking code: https://docs.arduino.cc/built-in-examples/digital/BlinkWithoutDelay

Go learn the Blink Without Delay style of timing.  If you want to have an easier time of it, put this code aside for a bit until you really understand what's going on with that style of timing.  Then come back and add it here.  If you try to just copy that code without understanding how it works then you're going to have a bad time.

Why did you mark it solved? What is the solution? This isn't a forum, solutions (aka answers) are posted below.

I’m voting to close this question because [SOLVED] is not an answer.

I removed [SOLVED] from the subject line - it doesn't make any sense.

Tried to look around the internet for solution but didn't find one - You didn't stumble across a post I wrote about this exact thing?

In general, when a program needs to perform two or more functions (for example, counting off seconds and reacting to a button press that could happen at any moment) a state machine programming pattern will provide an optimal solution.
Essentially, remove all calls to delay(). Instead, record the value returned from millis() outside the loop. If tracking a, say, 1 second (1000ms) interval, add 1000 to the recorded value. Each time through the loop, check if mills() is greater then the recorded value.  When it is, change the state, add 1000 to the recorded value again and do what ever is needed when the state indicating 1 second has elapsed has changed.  Now clear the state and wait for the cycle to repeat.
As this loop with out calls to delay() is being executed as fast as possible, a scan for a button press can be added and the necessary reaction to that button press can be very responsive.
Add states as needed for more complex behavior. Remember, in most state machines, outputs normally happen upon state changes. And there are no delays within the loop.  Tests to trigger state changes are run as fast as possible each time through the loop.

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


text:
String type replace function can't replace with no char
I want to replace the ":"(colon) in the MAC address with no char (remove the ":").
But I can't find any good solution.
String.replace(), can't replace with (void).
Note: String.replace(':',(char)0) //also doesn't work
String.remove() is ugly and requires that you know exactly where each iteration is (indexOf()), and this method doesn't return anything, it updates the string directly so you have to call : String.remove() for each occurence.
and String.substring() has most of the same problems as remove, except that it does return the substring, so you can do: String.substring(i,l).substring(i2,l)...
#include <WiFi.h>
String MAC;
char ssid[] = "WiFi SSID"
char psw[] = "WiFi PSW"
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  WiFi.begin(ssid,psw);
  MAC = WiFi.macAddress();
}

void loop() {
  // put your main code here, to run repeatedly:

  Serial.println("MAC Address unformatted")
  Serial.println(MAC);
  String MAC_f = MAC.replace(':', ' ');
  // Now print the MAC without the ":"
  Serial.println(MAC_f);
  // This replaces the ':' with a space.  I want to replace(remove) the ':' with no char
  // Looking for an elegant, simple, 1 liner to accomplish this.

  /* This looks horrible */
  MAC_f = MAC.substring(0,2)+MAC.substring(3, 5)+MAC.substring(6, 8)+MAC.substring(9, 11)+MAC.substring(12, 14)+MAC.substring(15, 17);
  /* .remove also looks terrible */
  MAC_f = MAC;
  MAC_f.remove(2,1);
  MAC_f.remove(2,1);
  // ...

}

Please do not attempt to answer questions in the comments. See How do comments work?. The comments on this question have been deleted, including the ones about "a special message". Appropriate action has been taken in regard to this message.

As stated by Mat, the empty string in C++ is "". This works:
MAC_f = MAC;
MAC_f.replace(":", "");

That being said, I concur with SBF's answer: String object are not
friendly with the Arduino's memory. SBF's solution is better than
String::replace().

@Instigator you know the difference between 'x' and "x", right. String.replace() takes String arguments, not char as you wrote. https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/replace/

Don´t use String() manipulations inside loop(). It causes heap fragmentation and program failure. Use a char array instead:
char MAC[18] = "01:23:45:67:89:AB"; // including terminating zero

for (int src = 0, dst = 0; src < sizeof(MAC); src++)
   if (MAC[src] != ':') MAC[dst++] = MAC[src];

It works because the terminating zero is copied to the end of the modified string

@Instigator in which way is this inefficient? Do you know what String.replace() does?

others a right that String is not totally Arduino friendly, WiFi.macAddress() returns String, SO
though written for ESP32 this is an approach i used
 // Get the station interface MAC address.
 // @return String MAC, no camas
String getMacAddress(void)
{
    WiFi.mode(WIFI_AP_STA);   // required to read NVR before WiFi.begin()
    uint8_t baseMac[6];
    esp_read_mac( baseMac, ESP_MAC_WIFI_STA );  // Get MAC address for WiFi station
    char macStr[18] = { 0 };
    sprintf(macStr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
    return String(macStr);
}
// END getMacAddress()

this maybe is how it should be done, but it doesn't answer the question


text:
0.96" OLED and Arduino UNO usage error
I have Arduino UNO with 0.96" OLED display with 128(width)*32(height). It is said that I have to edit Adafruit_SSD1306.h for my 128*32 OLED, okey I did it from 128*64 to 128*32 but I still get the compiler error:
ssd1306_128x32_i2c.ino:54:2: error: #error ("Height incorrect, please
fix Adafruit_SSD1306.h!");

Yes, I fixed the Adafruit_SSD1306.h file, but now, it is still gives me a compiler error:
C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h: In member
function 'uint8_t TwoWire::requestFrom(uint8_t, uint8_t, uint8_t)':
C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h:47: error:
too many arguments to function 'uint8_t twi_readFrom(uint8_t,
uint8_t*, uint8_t)'
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:85: error: at
this point in file
C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h: In member
function 'uint8_t TwoWire::endTransmission(uint8_t)':
C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h:48: error:
too many arguments to function 'uint8_t twi_writeTo(uint8_t, uint8_t*,
uint8_t, uint8_t)'
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:140: error: at
this point in file
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp: In member
function 'virtual size_t TwoWire::write(const uint8_t*, size_t)':
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:195: error:
invalid conversion from 'const uint8_t*' to 'uint8_t*'
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:195: error:
initializing argument 1 of 'uint8_t twi_transmit(uint8_t*, uint8_t)'

How can I use my four-pin OLED display with no errors?

It looks like the code you are trying to use may require a different version of the twi library.

Did you ever get this fixed?

Yes, I have already made it so perfect. Thanks.

Do you have I2C pull-ups in place? I don't see them on your breadboard.

May I suggest the following. I found this fork of the Adafruit library which works better than the one they have on their website Adafruit_ssd1306syp. The original Adafruit_ssd1306 library doesn't play nice with SPI and when you want to have your OLED running on i2c and use the SPI for something else. This is a great resource. Download, unzip to your libraries directory. Then run this sketch:
#include <Adafruit_ssd1306syp.h>

#define SDA_PIN A4
#define SCL_PIN A5

Adafruit_ssd1306syp display(SDA_PIN, SCL_PIN);

void setup() {

  display.initialize();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  printM("Starting Demo...");

}

void printM(String mess) {

  display.println(mess);
  display.update();
}

void loop() {

  printM("working");
  delay(1000);

}

You may wanna try this lib: https://github.com/olikraus/u8glib
Supports many devices and is very well documented!
Cheers

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


text:
Issues with connecting to an Adafruit FLORA board
I just bought a new Adafruit Flora board, and I haven't been able to get it working successfully. When I plug it into a USB port, the board seems to be getting power (the green PWR LED is illuminated), but there is no other output from the board. The Arduino IDE also does not recognize the board (the "port" menu under "Tools" is grayed out), and I have tried to connect to it on both Windows and Linux (Ubuntu) systems with the appropriate drivers/packages installed (including the Windows drivers and the board manager add-on in both installations of the Arduino IDE). I've also verified that the USB cable I'm using can handle data.
Previously, I was able to at least get the board to be recognized in the IDE on my Linux machine, and the red LED did light up, but after disconnecting it doesn't light up anymore (unless I try to reset the board, which makes the red LED pulse a few times).
Anything that I can try to get it recognized in the IDE?
Edit: I'm able to see the board pop up under "ports" in the IDE immediately after I hit the reset button on the board. However, as soon as the red LED stops pulsing (I think this means that the board is finished rebooting), it disappears from the list of available ports. It's also mounting under /dev/ttyACM0, not the usual /dev/ttyUSB0.

/dev/ttyACM0 is OK. upload Blink while the port is visible

@Juraj Yep, just tried this and it works. Strange. Thanks though!

it is not strange. the ATmega32u4 on board has a built in USB handled by the Arduino core linked with your sketch. if your sketch doesn't run, the USB is not handled. reset starts the bootloader which handles the USB while running.

Seems like whatever code was running on the Flora was corrupted. As soon as I hit the reset button, the board would momentarily pop up in the Arduino IDE, and after doing this a few times, I managed to upload the "Blink" sketch while the board was visible to my system. After that the board started working normally. It reports its name as "Adafruit FLORA" under "get board info", and the serial monitor/onboard LED work just fine.


text:
Different sensor readings on analog input when connected via USB to self-contained/externally powered
I am building up an electricity monitor using the ACS712 hall effect sensor.  I have tested and built the circuit having the Arduino (Nano) connected via USB to my laptop, and have tested/debugged etc., getting expected results.
I've migrated the circuit to be powered from an external 5v power supply via the VIN pin (details—this is not a "wallmart"-style supply).  It is supplying a solid 5.01v across the circuit according to multimeter readings—I've tested at multiple points in the circuit.  The 5v supply is rated at 700mA, so plenty of head room.  The ACS712 is deriving it's power directly from the supply, not the Arduino 5v pin.
I'm running a "calibration" routine that takes readings from the ACS712 (which is measuring AC current) to find the "zero" point (where the AC signal crosses over), which should be the value of half VCC with this sensor—see ACS712 sensor reading for AC current for more detail/background on this.  Usually this hovers around 512 (as expected—in the test unit I'm getting 547 when connected to an AC supply).
When I run/test this circuit with the USB connected, I get expected results.  When I remove the USB, the calibration routine returns a much higher value (about 650 in the test units) and resultant readings are therefore incorrect.  The laptop/test computer is not connected to a power supply during these tests.
When the USB is connected, there is no difference in reading across the VIN, 5V or sensor power pins, so the circuit seems to continue working from the external 5V source.  However, I have noted that the 5v output pin on the Arduino drops to about 3.95v when run off the power supply alone, vs 4.7v when powered by USB/both.
When I repeat this test by connecting an external USB power supply to the Arduino USB port (i.e. no serial connection, and removing the laptop from the equation) I get the same results (a higher calibration value and strange readings).
I've read that the analog pin is referenced to the 5V voltage.  This suggests that I should be connecting the ACS712 VCC pin to the Arduino 5V—is this the case? (Given the whole circuit is powered from the same power supply, this seemed unnecessary to me, but I'm still pretty new to this whole thing.)  The ACS is very sensitive to input voltage fluctuations, so I assumed that I'd be better powering it directly and not relying on the Arduino.
Given that I'm supplying a 5v input, should I be switching from the VIN to the 5v pin? (something I've read you can do, and that the VIN should be for 7v+ supply input only).
Is there anything else that could be causing this discrepancy?
For reference, the calibration and read routines are reproduced below.
#define SENSOR_PIN A0
#define ACS_MVPA (100)

double _numSamples = 0;
double _ampsRMSSum = 0;

int16_t acs712Calibrate() {
  uint8_t numReadings = 100;
  int16_t vals[numReadings];

  // collect a sample of readings
  for (uint8_t i=0; i<numReadings; i++) {
    vals[i] = constrain(analogRead(SENSOR_PIN), 0, 1023);
  }

  // Freq doesn't need to be 1024 wide, as the max val
  // from the ACS712 will be limited subset.
  // 20A = 100mV/A = 20*100mV/1000 = ~2v max voltage range
  // 2v / 1024 = 0.0048828125v per increment = ~410 potential increment values
  uint8_t freq[512]{0};
  uint8_t offset = 250;
  // count the frequency of specific readings
  for (uint8_t i=0; i<numReadings; i++) {
    freq[vals[i]-offset]++;
  }

  // work out the most frequent value
  // note that if there is a tie, the lowest value will be used
  uint8_t maxFreq = 0;
  int16_t modeVal = -1;
  for (int i=0; i<512; i++) {
    if (freq[i] > maxFreq) {
      maxFreq = freq[i];
      modeVal = i;
    }
  }

  modeVal = modeVal + offset;

  return modeVal;
}

void avgRead() {
  //debugSerial.println("_sample()");
  // see https://arduino.stackexchange.com/questions/19301/acs712-sensor-reading-for-ac-current for description

  int rVal = 0;
  unsigned long rSquaredSum = 0;

  // 50hz = 20 milliseconds per wavelength
  // if we measure for 100ms we will get 5 cycles
  // 60hz = 16.66667 milliseconds per wavelength, or just over ~6 cycles
  // from what I can tell, either should be sufficient for our purposes
  int sampleDuration = 100;       // 100ms

  // each logical "sample" is actually made up of a 100ms sample
  // for our internal arithmatic, we need to track the number of internal samples
  // not to be confused with _numSamples which tracks the number of times _sample()
  // is called between _log()
  int sampleCount = 0;

  // take samples for 100ms
  uint32_t startTime = millis();
  while((millis()-startTime) < sampleDuration)
  {
    rVal = analogRead(SENSOR_PIN) - _config.acs712Zero;
    rSquaredSum += rVal * rVal;
    sampleCount++;
  }

  double voltRMS = 5.0 * sqrt(rSquaredSum/sampleCount)/1024.0;

  // x 1000 to convert volts to millivolts
  // divide by the number of millivolts per amp to determine amps measured
  // in the case of the 20A component is 100 mv/A
  double ampsRMS = voltRMS * (1000/ACS_MVPA);

  _numSamples++; // update the overall sample count
  // add this reading to the summed total(which is averaged before logging)
  _ampsRMSSum += ampsRMS;
}

In preparing this question, I realised that the answer may lay in the statement "I've read that the analog pin is referenced to the 5V voltage. This suggests that I should be connecting the ACS712 VCC pin to the Arduino 5V—is this the case?"
That made sense to me, so I modified the circuit so that the ACS712 runs off the 5v pin, and I'm now getting around 510 (which is as expected) as a calibration value.
Have tested with both USB connected and unconnected and getting a consistent result.

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


text:
Genuino 101 - Can't upload my sketch - Timeout Error
I'm trying to run a sample sketch on my Genuino 101 but the following error shows up. Here is a verbose version.
Starting download script...
Args to shell: [/home/userk/.arduino15/packages/Intel/tools/arduino101load/1.6.9+1.28/x86/bin /tmp/buildc2bfbabdb2df5b87204fdf9941c899a2.tmp/Blink.ino.bin /dev/ttyACM0 verbose ATP1BLE000-1541C5635 141312]
Serial Port: /dev/ttyACM0
BIN FILE /tmp/buildc2bfbabdb2df5b87204fdf9941c899a2.tmp/Blink.ino.bin
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
Flashing is taking longer than expected
Try pressing MASTER_RESET button
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
Waiting for device...
ERROR: Timed out waiting for Arduino 101 on /dev/ttyACM0

I have installed the Intel Curie package with the Boards Manager and tried to press the Master Reset button, the reset and a combination of both. Nothing.
I have also tried the suggestions provided in this question but they did not work. I am using Ubuntu 16.04. Do you have any advice?
EDIT: Same problem with Windows 10/8/7.

did you try to use the reset button on the board??

yes, I tried but it did not work

check you COM and reboot your PC is needed

Same problem after reboot...

How u did the downgrade of Arduino 101 core? I am with the same problem and even the bootloader doesn't work...

Go to Sketch>Import Libraries -> Librariy manager > search for 101 > Select an older version and install it

Hi I understand now why there is a Timeout error... Read it here: https://forum.arduino.cc/index.php?action=profile;area=showposts;u=1472279 Thanks!

Problem solved with a downgrade of the Arduino 101 core. Try with all available versions.

Is the Genuino 101 board been recognized by the OS? Sounds like your board is not being recognized by the system.
For windows, open up your device manager before plugging into the PC. After plugging in, the device manager should refresh and display the board in the COM Port section.
For Linux (in your case Ubuntu), you can use the dmesg | tail cmd to check whether your board is being detected when you plug in the Genuino 101 board.

Something is being recognized as /dev/ttyACM0 - question would be if that is the board, or something else.

I have the same problem while uploading sketches ,
when i uploading the sketch and press  MASTER_RESET button solved my problem .
when it shows Waiting for device... just press the MASTER_RESET .
or try to update Firmware
Select Tools >> Programmer >> Arduino 101 Firmware Updater
Select Tools >> Burn Bootloader


text:
which spi mode shall i use given this timing diagram
I need some help to ensure my understanding of how this is supposed to work.
I want to know given the attached serial timing diagram which spi mode should I use?
Based on my newly found knowledge I believe it should be mode 1
How do you use SPI on an Arduino?
Is this correct?

Looks more like Mode 0.

We can see from your diagrams that the starting state of the clock line after the CS goes active is low indicating a CPOL of zero.  Also, we see that data changes after the falling edge of the clock indicating the CPHA is also zero.  This infers, according to this reference, that the SPI mode is zero.

If you look at the diagram you showed, it makes sense to use mode zero.

Clearly you need mode 0 or mode 1 because the clock is normally low.
Now looking at the change of the data vs the clock, it makes sense that you sample on the leading edge (mode 0) - the red lines - because the diagram shows that the data is held steady for a while after the clock changes (from low to high).
It wouldn't make sense to sample on the trailing edge because immediately after that (the blue line) the data changes.


text:
Arduino UNO code ignores variables selectively
This is the first code I wrote for my UNO R3 just to feel out the functions and I've already got some jankiness. Throughout this description I am referring to the first two if statements one inside the other one.
I'm trying to increment i every time the signal is activated and then j is used to create a small space of time where the button being pressed will not increment i. My problem is my if statement involving j seem to be totally ignored. I've tried multiple configurations of the if statement structure to no avail.
Here is where things get interesting. So upon setting up the serial connection back to my PC to debug this irritating problem and printing out the actual value of j (to see why it was triggering my if statement prematurely) it magically fixed the problem. It's like until the program literally acknowledges j's value in the print statement it doesn't exist but if it does it works. Any ideas on this?
Note: the serial monitor in both picture depicts consecutive iterations with the signal activated the entire time.
This picture shows the serial monitor after running with the button pressed but the print statement commented out

This picture shows the serial monitor at a space where the button was pressed and held (same time frame as image 1) but in this one it increments i to 3 and then continues incrementing j. How is this happening?

There is such a thing as "print screen" you know - makes an image that is actually readable.  Also, how about posting your code, rather than a photograph of part of your code?

The BIGGEST first thing to realise is that Te Jankiness is probably in your thinking and not in the micro controller. Once yo start from that assumption you have greater chance of sucess,

I suggest that you use {} with every if statement and also don't put two statements on the same line. This practice may seem boring but it is very important to establish good practices early

It would be far, far more helpful to copy and paste the actual code into your post. Please do this. A photograph of your computer monitor, with the code extremely blurry just doesn't cut it. You can also copy and paste the serial monitor output. When pasting your code select it and hit Ctrl+K to indent it four spaces. That turns it into a code block.

Its hard to see you code, but I think I can make a pretty good guess from your description what is going on.
It seems that you are using the time it takes to increment a value as a way to slow down your code. I think you are underestimating the speed of the arduino. The time it takes to count to 200 (if I'm reading your pictures right) is almost instant; However, you then start printing to with serial each time. Once the serial buffer is full, Serial.print() will wait until there is room in the buffer to place the new value. This time is still small, but making the code wait for it to pass 200 times will take much longer than just waiting for a number to increment to 200.
I think that having added a print statement is slowing down the code enough that your increment based delay is having a noticable effect. What you should do is use the void delay(unsigned long milliseconds); function to cause the code to stop for a bit after it first detects the button has been pressed, and then see if its still pressed afterward. You can also use delayMicroseconds(unsigned int) for shorter but more precise timing. Or better yet, use the unsigned long millis(); function to grab and store the time when the button was activated, and continue polling the current time until the desired delay has been acheived. That way is more code, It allows the code to do something productive while it waits or keep looping.

Sorry about the sub-par pictures I was in a hurry at the time. Yes I am aware of the importance of proper syntax/style, the weird structuring of the if statements is the result of muc time spent trying different things(including maximum bracketing) but they all function precisely the same. This code  runs perfectly as long as j is printed. As for the answer from BrettAM this was my initial thought as well. But upon further investigation I do not believe this is the case. Because the code still malfunctions in the same way even with other serial printing if you dont specifically print j.

I have since written other code where this same problem persists. I will write something to specifically depict this problem since it seems to be consistent. This time I will take proper screen shots and there will be no unorthodox syntax.

@JoshWiens Try making j a volatile variable. It seems like a rather extreme thing to optimize out but that might be whats happening. Also, switching to using a time based function instead of a loop like I suggest should still fix the problem. FYI posting code would be prefered to screen shots.

Yes, and I do appreciate the original answer as it is effective(something just bugs me about losing sensory capability for any amount of time), I just was not really looking for a work around but rather the engineer in me was simply interested in why the code would be responding the way it was. Anyways though I got around to writing my tester and now it's working like a charm. Maybe I was being sloppy before? Obviously I just need to do a bit more testing. I'll post the code just in case anyone is interested in seeing it(also will keep in mind the preference to actual code rather than screen shot in the future) . Thanks for the support!


text:
Using interrrupts with RC522

I have a project using the RC522 RFID module with my Arduino Uno board and miguelbalboa's rfid library. The example code and every other code I find on the internet work pooling the device in order to know if there is a new card present, but I intend to work with a interrupt-driven approach. I have the proper knowledge to do the hardware/arduino part, but I'm having trouble generating an interrupt in the IRQ pin when the card is present. Have anyone succeded on this?
Edit:
Connection:
RST -> 8
SS-> 9
MOSI -> 11
MISO -> 12
SCK -> 13
IRQ -> 2
Code:
#include <SPI.h>
#include <MFRC522.h>
#include <String.h>

#define RST_PIN     8
#define SS_PIN      9

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

void setup()
{
  Serial.begin(9600);       // Initialize serial communications with the PC
  while (!Serial);      // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin();          // Init SPI bus
  mfrc522.PCD_Init();       // Init MFRC522
  mfrc522.PCD_WriteRegister(MFRC522::ComIrqReg, 0x80); //Clear interrupts
  mfrc522.PCD_WriteRegister(MFRC522::ComIEnReg, 0x7F); //Enable all interrupts
  mfrc522.PCD_WriteRegister(MFRC522::DivIEnReg, 0x14);
  Serial.println(F("Ready..."));
  attachInterrupt(0, isr, RISING);
}

void loop()
{
}

void isr()
{
  Serial.println(F("Interrupt"));
  mfrc522.PCD_WriteRegister(MFRC522::ComIrqReg, 0x80); //Clear interrupts
}

Result:
I only get the "Ready..." on the Serial Monitor, no matter if there is a card present or not.

Welcome to Arduino SE! Code? Wiring?

@AnnonomusPenguin I have only used the example codes and wiring from the link (minor change, RST -> pin 8 and SS -> pin 9, for compatibility with the ethernet shield). As I haven't got access to an oscilloscope right now, I'm unable to check the interrupt pin, so I wrote a sketch to pool this pin and print its state via serial, 3-line code. It keeps giving me 0, no matter if the card is present or not... The documentation link says little about the interrupts and they're relation to the card reading.

Does that code deal with interrupts itself or have you modified it?

The library doesn't deal with the interrupt, they don't even use the IRQ pin...

So you did modify the code? Can you please add a minimal example of the problem (with the code and a circuit) to your question with an edit? Thanks

@AnnonomusPenguin edited...

You're going to have to do all the work yourself, because it seems nobody else has yet! First of all you need to work out the characteristics of the IRQ pin. Write a simple program, with no ISR or anything fancy, that just polls the IRQ pin and turns the onboard LED on when it's high, and off when it's low. If nothing happens, it could be because the IRQ is a pulse that's too short to see. Make a one shot program that waits until IRQ goes high (or low), then loops with the LED on.  You might have to enable the internal pullup resistor on the Uno. Good luck...

I'm quite late to this party, but I was looking for a way to have the MFRC522 generate an interrupt when it detects a compatible RFID card/key fob/sticker/etc., and this is one of the hits I got from my search. I write this now for the pilgrim who follows the same breadcrumbs I have in the hopes that it will save them at least a little time.
I tried something similar to what was suggested, found that I got interrupts quite often and continuously, and looked into the situation a bit more.
The MFRC522 does not generate interrupts for card detection. The microcontroller (or microprocessor) must command it to transmit and then query it to see if there was any response. This means that the MCU cannot go into a sleep mode and get awaken by the MFRC522 when there's a card to read.  The MFRC522 does have a timer that can generate an interrupt, but the maximum period of this timer is not huge, and the timer does not control the transceiver, it's there for the convenience of the application on the MCU.
Writing 0x7F to the "ComIEnReg" means the following:

Bit 7: IRqInv=0 - Interrupts are active high
Bit 6: TxIEn=1 - Transmitter interrupt is enabled
Bit 5: RxIEn=1 - Receive interrupt is enabled
Bit 4: IdleIEn=1 - Idle interrupt is enabled
Bit 3: HiAlertIEn=1 - "High Alert" interrupt is enabled
Bit 2: LoAlertIEn=1 - "Low Alert" interrupt is enabled
Bit 1: ErrIEn=1 - Error interrupt is enabled
Bit 0: TimerIEn=1 - Timer interrupt is enabled

The bits in the register "ComIrqReg" have the following meaning:

Bit 7: Set1 - when written as 1, a bit value of 1 in bits 6-0 of the byte written set the corresponding register bit; when written as 0, bits 6-0 clear the corresponding register bit
Bit 6: TxIRq - Set when the last bit of Tx data has been sent
Bit 5: RxIRq - Set when the receiver detects the end of a valid data stream
Bit 4: IdleIRq - Set when the CommandReg changes the command field to the idle command
Bit 3: HiAlertIRq - Set when the Status1 register HiAlert bit is set
Bit 2: LoAlertIRq - Set when the Status1 register LoAlert bit is set
Bit 1: ErrIRq - Set when any bit in ErrorReg gets set
Bit 0: TimerIRq - Set when the TCounterValReg decrements to zero

Writing 0x14 to the "DivIEnReg" has the following meaning:

Bit 7: IRQPushPull=0 - IRQ is an open-drain output pin
Bit 6: reserved=0 - no known effect
Bit 5: reserved=0 - effect unknown
Bit 4: MfinActEn=1 - Allow the MFIN active interrupt request to trigger IRQ
Bit 3: reserved=0 - boundedly undefined
Bit 2: CRCIEn=1 - Permit the "DivIrqReg" bit CRCIRq to trigger IRQ
Bit 1: reserved=0 - do not set to 1 on pain of nothing
Bit 0: reserved=0 - has no purpose other than to confuse

The register "DivIrqReg" corresponds to "DivIrqEn", and has the following bit definitions:

Bit 7: Set2 - when written as 1, a bit value of 1 in bits 6-0 of the byte written set the corresponding register bit; when written as 0, bits 6-0 clear the corresponding register bit
Bit 6: reserved - don't ask
Bit 5: reserved - don't tell
Bit 4: MfinActIRq - MFIN is active
Bit 3: reserved - just leave it at zero and back away slowly
Bit 2: CRCIRq - when 1, the CalcCRC command is active and all data is processed
Bit 1: reserved - nothing to see here
Bit 0: reserved - are you feeling lucky, punk?

The above register bit definitions were cribbed from the MFRC522 datasheet from NXP, titled "MFRC522 Standard performance MIFARE and NTAG frontend", Rev 3.9, 27-April-2016.
The library for the MFRC522 does have an interrupt example that uses a lighter weight means of polling the transceiver. see https://github.com/miguelbalboa/rfid/tree/master/examples/MinimalInterrupt, but it does not provide a means of waking your host from a low-power sleep mode when someone waves their magic ring over the hidden panel by the secret door, meaning that your secret lair will need to be wired to power the reader even if it is otherwise wireless; either that, or your henchmen will be forever changing batteries.

From your code:
void isr()
{
  Serial.println(F("Interrupt"));
  mfrc522.PCD_WriteRegister(MFRC522::ComIrqReg, 0x80); //Clear interrupts
}

Do not do serial prints inside an ISR! They will eventually hang it. What you need to do is have a volatile variable (eg. a bool), set that in the ISR, and then check that in loop. If it changes, display it. Eg.
volatile bool cardPresent;

void loop()
{
  if (cardPresent)
    {
    Serial.println(F("Interrupt"));
    mfrc522.PCD_WriteRegister(MFRC522::ComIrqReg, 0x80); //Clear interrupts
    cardPresent = false;
    }

}

void isr()
{
  cardPresent = true;
}

The other thing I would do is put a scope or logic analyzer on the IRQ pin and see if it is actually changing. It should trigger the interrupt if it does.

first of all, I apologize for the English, I can understand it but i use google translator to express myself in.
I don't use arduino, It's a interesting platform (for the ide, which is apparently object oriented programming POO), but extremely limited by the hardware
Well, entering the subject, I am also developing an implementation for the MRFC522, and the datasheet does not give examples of how do it, but indicates how enable interrupts (although I have not tried ,yet)
but if I'm not wrong, the following registers are involved:
ComIEnReg--> Control register bits to enable and disable the passing of interrupt requests.
DivIEnReg--> control bits to enable and disable the passing of interrupt requests.
ComIrqReg--> register Interrupt request bits. (I think it's read only)
DivIrqReg--> register bit descriptions (I think it's read only)
I think it's just properly setting the first two should be able to generate the interrupt on the pin irq.
i don't know if the following is correct.
set ComIEnReg to --> (in binary) 0b01111111 //enables all al interrupts
set DivIEnReg to --> 0b10000100  //I don't understand complete about MFIN (bit4) and set it to 0  but i set CRCIEn to 1 (bit 2) and bit7  to 1 "pin IRQ is a standard CMOS output pin"
// the different posible configuration to DivIEnReg

yours--> 0b00010100 -->0x14
try 1 --> 0b00000100 -->0x04
try 2 --> 0b10010100 -->0X94
try 3 --> 0b10000100 -->0X84

if you manage to the module to do the interruption, it would be kind enough to comment on how you did

Unfortunatelly I was unable to use the IRQ pin. My project is stopped right now but I'll get back to it in a little and maybe figure it out. I'm pooling the module to check for a new tag for now and for what I read back then seem like no one was able to use the interruption to detect new tags. I agree with you on the Arduino, it's very limited but as I'm only working on a POC (proof of concept), is the perfect platform!

As you mentioned "Arduino is limited" can you share other alternatives. Would like to explore them as-well.
I am completely from the software side, and would like to understand this more.


text:
Controlling Floppy Disk Drive with Arduino
I am having problems controlling a 3.5" Floppy Disk Drive with an Arduino Uno.
I have the floppy disk drive powered with a computer power supply that is switched on, and the Arduino powered by my computer's USB.  I have cut apart the ribbon of a 34-pin IDC connector to be able to route the pins to my Arduino.  I am able to turn the floppy disk motor on and move the read/write head back and forth, but I am never able to read any pulses from the Track-0 or Index pins.
I have pins 7, 15, 17, 19, and 25 from the floppy all grounded to my Arduino, and I have pins 8, 16, 18, 20, and 26 from the floppy connected to my arduino as output pins so I can control the drive.
I am expecting the Index to pulse when the disk motor makes a rotation, and for Track 0 to change when I am at the outside of the disk, but they are both always LOW.  Am I missing something?
Here is the spec I found for the back of the floppy disk unit
    2   /REDWC  Input Density Select
    4   n/c N/A Reserved
    6   n/c N/A Reserved
    8   /INDEX  Output Index
    10  /MOTEA  Input Motor Enable A
    12  /DRVSB  Input Drive Sel B
    14  /DRVSA  Input Drive Sel A
    16  /MOTEB  Input Motor Enable B
    18  /DIR    Input Direction
    20  /STEP   Input Step
    22  /WDATE  Input Write Data
    24  /WGATE  Input Floppy Write Enable
    26  /TRK00  Output Track 0
    28  /WPT    Output Write Protect
    30  /RDATA  Output Read Data
    32  /SIDE1  Input  Head Select
    34  /DSKCHG Output Disk Change/Ready

Here a schematic of what I have hooked up
(The breadboard in this circuit diagram represents the IDC connector that is plugged into the 3.5" floppy drive.)

Here is a photo of the IDC Connector and I labelled which wires are connected to the Arduino.

Here's the code I am running.
//constants
static const int IN = LOW;
static const int OUT = HIGH;
static const int pulseDelayTime = 6;

//pins
int indexPin = 2; //8 on the drive INDEX
int track0Pin = 3; //26 on the drive. TRACK 0
int dirPin = 6; //18 on the drive. DIRECTION
int stepPin = 7; //20 on the drive. STEP
int motorEnableBPin = 9; //16 on the drive. MOTOR ENABLE B

unsigned long motorSpinTime = 1000UL; //in ms

void setup() {

  //initial delay
  delay(3000);

  //setup serial monitor
  Serial.begin(9600);

  //setup pins.
  pinMode(dirPin, OUTPUT);
  pinMode(stepPin, OUTPUT);
  pinMode(motorEnableBPin, OUTPUT);
  pinMode(indexPin, INPUT);
  pinMode(track0Pin, INPUT);

  //turn the motor off initially
  digitalWrite(motorEnableBPin, HIGH);

  //print state here.
  printState("Setup done.");

  //spin the disk some.
  printState("Begin to spin motor");
  spinMotorForThisManyMs(motorSpinTime);
  spinMotorForThisManyMs(motorSpinTime);
  printState("Done spinning motor");

  //step read/write head all the way in.
  stepAllTheWayIn();

  //spin the disk some more.
  printState("Begin to spin motor");
  spinMotorForThisManyMs(motorSpinTime);
  spinMotorForThisManyMs(motorSpinTime);
  printState("Done spinning motor");

  //step read/write head all the way out.
  stepAllTheWayOut();

  //spin the disk even more.
  printState("Begin to spin motor");
  spinMotorForThisManyMs(motorSpinTime);
  spinMotorForThisManyMs(motorSpinTime);
  printState("Done spinning motor");

  //never completes.
  waitForIndex();
}

void loop() {
}

//spins the disk motor for a number of ms and prints the state
void spinMotorForThisManyMs(unsigned long msToSpin) {

  //start spinning
  digitalWrite(motorEnableBPin,LOW);

  //delay.. keep printing the state
  unsigned long maxTimeMs = millis() + msToSpin;
  while(millis() < maxTimeMs ) {
    printState("Spinning");
  }

  //stop spinning
  digitalWrite(motorEnableBPin,HIGH);
}

//step the read/write head all the way to the center
void stepAllTheWayIn() {
  for(int i=0;i<100;i++) {
    printState("Stepping In");
    stepInALittle();
  }
}

//step the read/write head all the way to the outside
void stepAllTheWayOut() {
  for(int i=0;i<100;i++) {
    printState("Stepping Out");
    stepOutALittle();
  }
}

//print the state of the index and track
void printState(const char* charPrint) {
  Serial.print(" Index:");
  Serial.print(digitalRead(indexPin));
  Serial.print(" Track:");
  Serial.print(digitalRead(track0Pin));
  Serial.print(" ");
  Serial.println(charPrint);
}

//move the head towards the outside a little
void stepOutALittle() {
  digitalWrite(dirPin,HIGH);
  stepPulse();
}

//move the head towards the center a little
void stepInALittle() {
  digitalWrite(dirPin,LOW);
  stepPulse();
}

//pulse the step pin
void stepPulse() {
  digitalWrite(stepPin,LOW);
  delay(pulseDelayTime);
  digitalWrite(stepPin,HIGH);
}

//waits for the index to trigger. this never gets completed.
void waitForIndex() {

  printState("beginning to wait for index pin to pulse");

  //start spinning
  digitalWrite(motorEnableBPin,LOW);

  //wait for pulse
  while(digitalRead(indexPin));
  //wait for end of pulse 0
  while(!digitalRead(indexPin));

  printState("end of waiting for index pin to pulse");

  //stop spinning
  digitalWrite(motorEnableBPin,HIGH);
}

Here is the output I am getting.
 Index:0 Track:0 Setup done.
 Index:0 Track:0 Begin to spin motor
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Done spinning motor
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Begin to spin motor
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Done spinning motor
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Begin to spin motor
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Done spinning motor
 Index:0 Track:0 beginning to wait for index pin to pulse

UPDATE:
I am now receiving my expected results due to geometrikal's answer.   While researching this problem I found a few code examples of Arduino to Floppy Drive. I noticed that they were setting their input pins to HIGH, but I never realized why they were doing this.  After fixing my problem, I found this in some Arduino documentation (which made me realize the code examples I had were using an older version of the Arduino IDE):
"Prior to Arduino 1.0.1, it was possible to configure the internal pull-ups      in the following manner:"
pinMode(pin, INPUT);           // set pin to input
digitalWrite(pin, HIGH);       // turn on pullup resistors`

In Arduino 1.0.1+ you can do it this way.
pinMode(pin, INPUT_PULLUP);

Both methods of enabling the pull-up work. The second method, using the INPUT_PULLUP pinMode, is better both because it uses 1 less line and because it's a lot easier to read.

If anyone is still interested/following/has opinions.... I suggest you head over to enter link description here

According to this (dead link):
http://bitsavers.trailing-edge.com/pdf/nec/FD1035_Product_Description_Jul84.pdf

This is an archived copy of the FD1035 3.5" Floppy disk drive: Product Description July 1984 - PDF:
https://archive.org/details/bitsavers_necFD1035Pl84_876629

The outputs are open-collector, so a pull-up resistor is required. You can instead enable the Arduino internal pull-ups on those pins by
pinMode(indexPin, INPUT_PULLUP);
pinMode(track0Pin, INPUT_PULLUP);

I can't thank you enough.  This is exactly what I needed.

You should replace int with unsigned long in all locations where you deal with time in milliseconds.
The point is that millis() returns an unsigned long, thus using int to store millis() value, you have a loss of information due to automatic cast performed by the compiler.
The changes you have to perform are:
unsigned long motorSpinTime = 1000UL; //in ms

and:
//spins the disk motor for a number of ms and prints the state
void spinMotorForThisManyMs(unsigned long msToSpin) {

  //start spinning
  digitalWrite(motorEnableBPin,LOW);

  //delay.. keep printing the state
  unsigned long maxTimeMs = millis() + msToSpin;
  while(millis() < maxTimeMs ) {
    printState("Spinning");
  }

  //stop spinning
  digitalWrite(motorEnableBPin,HIGH);
}

Note that I have also performed some optimization in the waiting loop by calculating the maximum time once and then compare millis() directly to that value. This is not mandatory but I just find it a bit more clean.

Great catch! Unfortunately, changing this code does not fix the unexpected output I am receiving. I am still receiving all 0's for the index and track 0 pins. I'm still stumped. I would say that perhaps the drive is bad but I bought 2 3.5" floppy drives for this project, and I get the same output with both of them (I guess they could both be bad, but what are the chances of that?).

This is potentially important, but does not in any way answer the question asked, so is the type of point which should be made as a comment.


text:
Teensy MIDI Show Control
I'd like to use my Teensy 3.1 to send MIDI Show Control messages using USB MIDI in order to control an ETC Nomad system. These are different from standard NoteOn, NoteOff, ProgramChange, etc. commands, but as far as I can tell they are not supported by the standard library.
Is there any way I can send these messages directly (using lower level commands), as seen here, or does anyone know of a library that supports this? Google has, unusually, not been much help.

Where does USB come into this? The example you linked to shows exactly how to send non-standard MIDI messages.

@JakeC I just linked to that page to differentiate between MSC messages and standard MIDI note messages. I'm not using hardware MIDI, but using the Teensy as a USB MIDI device.

In which case this is more a matter of finding computer software to send those messages if you are just having the Teensy act as a bridge.

Also, Teensy is a rather expensive way of doing this at ~$20 compared to a ~5 USB MIDI cable.

~$5 MIDI cable, a $10+ MIDI interface for my MacBook, and an extra PCB to house the ports and other components, vs a Teensy I already had on my desk

I totally understand the need it now, however, there is still nothing special you would have to do in the Teensy to make it work with MSC if you are just setting it up to relay what it gets from the computer. Any work you need to do is in what software you are using on your computer.

According to the documentation, SysEx messages are sent like any other messages:
array[0] = 0xf0;
array[1] = 0x7f;
array[2] = 0x7f;
array[3] = 0x02;
array[4] = 0x7f;
array[5] = 0x01;
array[6] = 0xf7;
usbMIDI.sendSysEx(7, array);


text:
File Size Problem with EyeFi SD Card and Arduino Mega
I've been writing to an EyeFi SD card with an Arduino Mega.  I've managed to get the files to upload wirelessly, but I noticed that my data gets cut off when the file reaches a size of 24 kb.  If I use a normal SD card, the file is able to keep logging past 24 kb.  The EyeFi card is able to upload large images, so I'm not sure what is limiting my file size for the EyeFi card.  Can I get some advice?
/*************** SETUP ***************/
void setup(void)
{
  Serial.begin(115200);

  // initialize the SD card
  Serial.print("Initializing SD card...");
  pinMode(10, OUTPUT); // make sure that the default chip select pin is set to

  // see if the card is present and can be initialized:
  if (!SD.begin(10,11,12,13))
  {
    error("Card failed, or not present");
  }
  Serial.println("Card initialized");

  // see if the directory exists, create it if not.
  if( !SD.exists(directory) && !SD.mkdir(directory) )
    error("File directory not created");

  newFile();

  Serial1.begin(115200);

  while (Serial1.peek() != '!' )
    Serial1.read();

  i = 0;
}

/*************** MAIN LOOP ***************/
void loop(void)
{
  if (Serial1.available())
  {
    logfile.print( (char)Serial1.read() );
    i++;
  }

  if (i >= SOFT_BUFFER_SIZE)
  {
    logfile.flush();

    if( logfile.size() > 20480 && logfile.size() < (20480 + SOFT_BUFFER_SIZE) )
      Serial.println("Minimum File Size Achieved.");

    i = 0;
  }
}

The EyeFi card has to play some kind of algorithmic guessing game (beyond anything a disk filesystem normally defines) to decide when a file merits uploading, and it's likely that your (comparatively) slow logging interacts poorly with this. It may be that you could play some kind of game with your file system implementation where you write a lot of data to unallocated space on the card until you decide it hits your worthy-of-uploading size, and only then write its directory entry in the hopes of triggering the upload.  But that is pure speculation. It may be this is the wrong way to do wifi.

@ChrisStratton I'm not very good at programming the Arduino.  How do you go about changing the directory of a file?

@ChrisStratton NVM, I found a library that can rename.  Will give it a try tomorrow.

I was not speaking of renaming, I was speaking of having file contents on disk which the file system "catalog" has not yet been told about at all, and only creating a directory entry in the catalog for it when you are ready to have the card's algorithm discover and upload it.  But it's possible renaming would work.  And possible the idea itself is a non-starter.  Yes, this would be advanced usage, requiring you to understand and modify the filesystem code.

@ChrisStratton it works!  I logged data to a temporary file stored in the root directory of the EyeFi SD card, then when i'm done logging to it, I rename it as "DCIM/100NIKON/DSCNxxxx.JPG" using the SDfat library. Thanks for the suggestion!  Maybe you can rewrite your comment as a solution so I can mark it as the answer.

As renaming was your idea and a lot simpler than my proposal, even if I got you thinking in a useful direction that solution is really your own work.  Does the card only pay attention to things in the DCIM folder?  If so that would be a key point to mention.

@ChrisStratton Yea, seems like the card only transfers files stored in camera folders and named in the same format as common photo naming convention like IMAG0000.jpg or DSCN0000.jpg.  I guess I'll type up my solution in case anyone wants to do the same.

After some testing and research, I found out that the Eye-Fi SD card starts a transfer once a file reaches 20kb or more and will not upload a file again once it has been transfered already.  The solution, as suggested by ChrisStratton, is to log to a temporary file and trigger a transfer once the file is ready.
I took advantage of the fact that the Eye-Fi only transferring files in the standard camera folders.  In my case, I used the Nikon naming convention: DCIM/100NIKON/DSCNxxxx.JPG  (xxxx is the photo number ranging from 0000 to 9999), but there are also others.  Check on the Eye-Fi website for compatible cameras.  I created a temporary file called TEMP.TMP and stored it to the root folder of the card and logged to it.  Once I'm ready to transfer the file, TEMP.TMP gets renamed to "DCIM/100NIKON/DSCNxxxx.JPG" and the whole file is transferred all at once.
Here's my code.  I'm using the software serial (pins 10, 11, 12, 13) of the Mega:
//Running with 256kb serial buffer (modified HardwareSerial.cpp)
//Added file time stamps

#include "SdFat.h"
#include "SdFatConfig.h"
#include <Wire.h>
#include "RTClib.h"

#define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
uint32_t syncTime = 0; // time of last sync()

#define ECHO_TO_Serial     1 // echo data to Serial port
#define WAIT_TO_START      0 // Wait for Serial input in setup()
#define MESSAGE_SIZE      11 // Message size of "!G N +1234" + CR
#define SOFT_BUFFER_SIZE  256// 25 Messages of 11 chars each

const uint8_t chipSelect = 10;

SdFat sd;
SdFile logfile; //create log file

RTC_DS1307 RTC;
DateTime filedate;

uint16_t date;
uint16_t time;

int i = 0;
int x = 0;

char directory[] = "DCIM/100NIKON";
char filename[] = "DCIM/100NIKON/DSCN0000.JPG";
char tempfile[] = "TEMP.TMP";

/*************** ERROR ***************/
void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);
  while(1);
}

/*********** TEMP FILE CREATION ***********/
void newFileName()
{
  sd.chdir("/"); //check DCIM/100NIKON directory
  // create a temp file
  for (uint16_t i = 0; i < 10000; i++)
  {
    filename[18] = i/1000 + '0';
    filename[19] = (i/100)%10 + '0';
    filename[20] = (i/10)%10 + '0';
    filename[21] = i%10 + '0';
    if (! sd.exists(filename))
    {
      Serial.print("New file name: ");
      Serial.println(filename);
      break;  // leave the loop!
    }
  }
}

/****** call back for file timestamps *****/
void dateTime(uint16_t* date, uint16_t* time) {
  DateTime now = RTC.now();

  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(now.year(), now.month(), now.day());

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
}

/*************** SETUP ***************/
void setup(void)
{
  Serial.begin(115200);
  Wire.begin();
  RTC.begin();

  if(! RTC.isrunning() )
    Serial.println("RTC is not running");

  // set date time callback function
  SdFile::dateTimeCallback(dateTime);

  // initialize the SD card
  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (! sd.begin(chipSelect, SPI_HALF_SPEED))
    error("Card failed, or not present");

  Serial.println("Card initialized");

  // see if the directory exists, create it if not.
  sd.chdir("/");
  if( !sd.exists(directory) && !sd.mkdir(directory) )
    error("File directory not created");

  // create new file name
  newFileName();

  // Scan root folder for temp files
  sd.chdir("/");
  while( logfile.openNext(sd.vwd(), O_READ)){
    if( !logfile.isDir() ) {
      logfile.printName(&Serial);
      if( logfile.fileSize() < 20480 ){
        Serial.print(" file size too small. ");
        Serial.print(logfile.fileSize());
        Serial.println(" bytes.");
        logfile.remove(); //Delete under sized files
      }else
        if( !logfile.rename(sd.vwd(), filename))
          error(" could not be renamed.");
        else{
          Serial.print(" renamed to ");
          Serial.println(filename);
        }
    }
    logfile.close();
  }

  // create temp file
  sd.chdir("/");
  if(!logfile.open(tempfile, O_WRITE | O_CREAT)) // only open a new file if it doesn't exist
    error("couldnt create temp file");

  Serial1.begin(115200);

  // Rotate the buffer
  for( int j = 0; j < 256; j++) {
    Serial1.read();
  }

  // Look for the '!' character
  while (Serial1.peek() != '!' )
    Serial1.read();

  Serial.println("Logging...");
  Serial.println();

  // Reset buffer index to 0
  i = 0;
}

/*************** MAIN LOOP ***************/
void loop(void)
{
  if (Serial1.available()){
    logfile.print( (char)Serial1.read() );
    i++;
  }

  if (i >= SOFT_BUFFER_SIZE)
  {
    logfile.sync();
    i = 0;
  }
}


text:
Mpr121 multiple using breakout
I try more solution but there are not working. i use adafruit mpr121 lib, sparkfuns solution but there are not working. Some solutions say, cut the addr socket but i am not understand. maybe you show this solutions breakout, i try my code.

Unfortunately the wording of your question is very poor, however I think you are asking how to use multiple MPR121 devices on an Arduino?
According to the Sparkfun website you can change the I2C address from the default of 0x5A to one of four other addresses by cutting the jumpers on the back and connecting it to one of the other pins:

ADDR > GND  = 0x5A (default)
ADDR > 3.3V = 0x5B
ADDR > SDA  = 0x5C
ADDR > SCL  = 0x5D

I would also recommend using the Bare Conductive libraries rather than Sparkfun/Adafruit as they are more user friendly.


text:
Arduino Uno cannot upload any sketch: avrdude: stk500_recv(): programmer is not responding
I'm newbie in Arduino Dev
I got Arduino Uno R3, at first it just worked fine.
I tried to upload my whole project sketch which almost up to the max size of arduino memory.
Then suddenly the upload failed, and i can upload any other sketch even an empty or simple sketch.
I already remove all cables connected, still failed to upload.
I really dont know how to fix this.

The answer below covers everything I would think to try, and most of us have been in this boat at one time or another. It's frustrating. If you got this going, please come back and tell us what the issue was, it might help someone else down the track. If you're still having issues, update with everything you've tried and include some more details (OS, what you've got connected to the board, alternate port results etc). And welcome to SE Arduino!

First stop for me is always the connections (which you've done), the sketch itself (which doesn't sound likely) and then the COM port / baud rate.  If your sketch involves anything with the serial connection, ISR's or power supplies, that could be an issue with the Arduino not listening.  It sounds like you've covered this as well by trying simple sketches.  Next, check the COM port on the host computer (sometimes it changes in Windows) and inside the IDE, the baud rate, and open the IDE serial port and wander through baud rate settings until you get something legible as a response in the serial window.  Also, double check inside the IDE that you still have the correct board selected.  Occasionally / rarely, I've had to reboot Windows to cure the problem.
The good news is, this pain is significant enough that you don't usually make the mistake again, and will probably never forget how you solved it....


text:
Synchronizing two sensors on uart, make one receiver and one transmitter
I need to make a transmitter and receiver with each specifically transmitting and receiving a signal. I am using two SRF-02 sensors, one is the designated transmitter, the other the receiver.
My issue is that the receiver is not currently able to pick up the reading, reason being that the receiver has no idea of when the startbyte is incoming or when the stop byte comes.
Can i send the receiver a start byte when i activate the transmitter and send an end byte for when the signal is received?

Please provide links to this sensor. Please post your code. I'm going to close this question as "unclear what you are asking". Feel free to edit it with new information. Thanks for your understanding and cooperation!


text:
Need Basic Help with Software Serial
I am testing the basic Software Serial example on the arduino website, but I cant get the myserial to print
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

 Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);
  mySerial.println("Hello, world?");
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

In the example, digital pins 10 and 11 (mySerial) on your Arduino board are used as virtual RX and TX serial lines. The virtual RX pin (pin10)is set up to listen for anything coming in on the hardware RX serial line, and to then echo that data out the virtual TX line (pin11). Conversely, anything received on the virtual RX (pin10) is sent out over the hardware TX.

but can i read the message then on my hardwired serial monitor with one arduino?

You would need to connect something to the pins 10 and 11 like a FT232RL breakout or another serial device. If you have another Arduino, connect the RX of that Arduino to pin 11 on the Arduino connected to the USB and give the other a simple program like:
void setup(){
  Serial.begin(9600);
}

void loop(){
  Serial.println("Testing mySerial on Other Arduino");
  delay(500);
}

Once the above code is loaded to second Arduino, put that example code on first Arduino and connect the two together like mentioned above; tx to rx and rx to tx and load the code on first Arduino and see results.

have a look at this posts on Aerduino forum same problem https://forum.arduino.cc/index.php?topic=409654.0


text:
Function not successfully reading sensor registers
I'm trying to write a library for an accelerometer/magnetometer sensor.  The sensor is a LSM303D chip (https://www.pololu.com/file/0J703/LSM303D.pdf).
I've written a function, readRegister() (below) that's supposed to get the data from the sensor.  However, I put in many different registers into the function into the function, but it always returns the same number.  That number changes every time I unplug my Arduino from my computer.
byte fp::readRegister(byte register_address, int numBytes) {
  Wire.requestFrom(register_address, numBytes);
  byte c;
  Serial.println(Wire.read());
  while (Wire.available()) {
    c = Wire.read();
  }
  Serial.print("0x");
  Serial.print(register_address, HEX);
  Serial.print("\t");
  Serial.print(c);
  Serial.print("\t");
  Serial.println(millis());
  return c;
}

Here's an example of the problem output:
0x8 190 2
0x9 190 3
0xA 190 11

And here is something more like what I'd expect:
0x8 193 [time]
0x9 189 [time]
0xA 195 [time]

Here is the Git repo with the rest of the code: https://github.com/fpdotmonkey/fp_accel
Thank you in advance for your help.

Could you show the rest of the code? Is there a Write.endTransmission()?

  Wire.requestFrom(register_address, numBytes);
  byte c;
  Serial.println(Wire.read());
  while (Wire.available()) {
    c = Wire.read();
  }

This has a number of problems. For one thing your (I presume) debugging print consumes the data from Wire.read, so when you go to get it into c, you have already printed it. In other words, you are reading byte #1 and printing it, but using byte #2. This seems an odd thing to do.
Next, what is this doing?
  while (Wire.available()) {
    c = Wire.read();
  }

You are reading an indefinite number of bytes, and retaining the last one. Why?
Possible rework:
byte fp::readRegister(byte register_address, int numBytes) {
  Wire.requestFrom(register_address, numBytes);
  byte c = Wire.read()
  Serial.println(c);
  Serial.print("0x");
  Serial.print(register_address, HEX);
  Serial.print("\t");
  Serial.print(c);
  Serial.print("\t");
  Serial.println(millis());
  return c;
}

Here is the Git repo with the rest of the code: https://github.com/fpdotmonkey/fp_accel

From your linked code:
  byte xlm = readRegister(fp::OUT_X_L_M, 1);
  byte xhm = readRegister(fp::OUT_X_H_M, 1);
  byte ylm = readRegister(fp::OUT_Y_L_M, 1);
  byte yhm = readRegister(fp::OUT_Y_H_M, 1);
  byte zlm = readRegister(fp::OUT_Z_L_M, 1);
  byte zhm = readRegister(fp::OUT_Z_H_M, 1);

You have the wrong end of the stick here.
  Wire.requestFrom(register_address, numBytes);

You request from the I2C address - that is the device address. The register is something else.
Judging by the datasheet you first have to send the register address, and then request the data. Something along the lines of:
byte fp::readRegister(byte register_address, int numBytes) {
  Wire.beginTransmission (DEVICE_ADDRESS);
  Wire.write (register_address);
  Wire.endTransmission (false);  // repeated start
  Wire.requestFrom(DEVICE_ADDRESS, 1);
  byte c = Wire.read()
  Serial.println(c);
  Serial.print("0x");
  Serial.print(register_address, HEX);
  Serial.print("\t");
  Serial.print(c);
  Serial.print("\t");
  Serial.println(millis());
  return c;
}

Similarly for writing to a register:
void fp::writeRegister(byte register_address, byte val) {
  Wire.beginTransmission(DEVICE_ADDRESS);
  Wire.write (register_address);
  Wire.write(val);
  Wire.endTransmission();
}

This is untested because I don't have the device here, but I know that what you had won't work. To check the actual device address run the I2C scanner I mentioned before.

I'm still experiencing the same problem.  Every register address I plug in returns the same value.

It would help to see the whole sketch and not just a function being called in an unknown way. It would also help to see your improved code. Are you sure you are communicating with the device? Can you do a WHO_AM_I and get back the right response? It's hard to debug a snippet.

Also confirm you have the right device address, and it is connected correctly. There is code to do that on my page about I2C - scroll down to the "I2C scanner".

My codebase, as well as the improved function, are in the Github link that is now in the original question.  When I try to read from WHO_AM_I, I get the same response as from every other register.

Well, see my amended reply. That is not how you access registers.

I've updated the code on Github to have what you've written as well as the address from your program, but I still get the same results.  I thought since the number it returns for every register is 255 that it may be the size of the type byte that is the problem, but I changed the function to return an int, and it did the exact same thing.  I know that the chip is good because I can get other people's libraries to run on it.

Please post the output of running the I2C scanner that I requested.

The first few lines of output, as well as the output of your I2C scanner, are here.  The chip I'm concerned with now is the 0x1D.  The 0x6B is the gyro sensor that's on the same board.

I see I made an error (or retained your error). The line which read Wire.requestFrom(register_address, 1); should have been Wire.requestFrom(DEVICE_ADDRESS, 1);. I fixed up my reply.


text:
Reading from ps2 barcode scanner
I am trying to read from a ps2 barcode scanner (Datalogic gryphon D).
The Arduino is powered by the USB. The circuit is shown below

The pinout of the ps2 is

I have used the fritzing pin assignments when making the diagram.
I am using the code from here
#include <PS2Keyboard.h>

const int DataPin = 8;
const int IRQpin =  5;

PS2Keyboard keyboard;

void setup() {
  delay(1000);
  keyboard.begin(DataPin, IRQpin);
  Serial.begin(9600);
  Serial.println("Keyboard Test:");
}

void loop() {
  if (keyboard.available()) {

    // read the next key
    char c = keyboard.read();
    Serial.print(c);
  }
}

The scanner scans and indicates that the scan was successful. The Arduino code shows "Keyboard Test:", but none of the scans show anything. What am I doing wrong?

Pin 5 isn't an IRQ pin, is it? You want pin 2 or 3 for that...

That article doesn't include those pull-up resistors. PS I doubt you need an added power supply. The maximum current of PS2 (275 mA) is below that of USB. So even adding the few mA that the arduino uses you won't reach the 500mA limit of USB.

@Majenko I have edited the question. The pins appear to be in the wrong order because I followed fritzing rather than the physical device.

@Gerben I put in the pull-up resistors because of an article I found (but can't find again). I have removed them now but it still doesn't read. PS  I was connecting through a USB repeater cable and I think it was restricting the current. Getting rid of the repeater allows the scanner to correctly start up, but it is not stable. Most scans fail when it is powered through the Arduino.


text:
arduino not loading library
I am receiving a compilation error from
#include <HX711.h>

The error is
fatal error: HX711.h: No such file or directory

However, C:\Users\user\Documents\Arduino\libraries\HX711 is there and has the correct files in it.
Sketch -> Include Library -> Manage libraries says that HX711 is installed. Strange thing is that I have another sketch that uses this library and it compiles. It uses quotes instead of angle brackets (which is strange because HX711.h is not in the same directory) and it works.
I have tried both quotes and angle brackets.
EDIT: I am really sorry about typing "define" instead of "include" into the question my only excuse was that it was late.
I copied the library directory to:
C:\Program Files (x86)\Arduino\libraries

and the problem remains.
I now have the HX711 directory in both the Arduino program files and the user directories and it still complains about it. The only way I can get it to compile is to place the hx711.h & hx711.cpp files directly into the sketch directory and change the line to #include "HX711.h"
EDIT:
Running Arduino 1.6.5 on Windows 8.1 64bit

What platform are you using? (Windows. iOS, Linux)  What IDE version are you using?

@Matt Running Arduino 1.6.5 on Windows 8.1 64bit

You're using #define when it should be #include.

I never saw that :D

you can mark my answer as the solution then :)

I thought the op had to do that.

Very sorry @H.Woszczyk that was just a silly typo. The problem remains.

Is the line of code really
#define <HX711.h>

If it is then replace < with < and that will fix it.
If the include statement has angle brackets <> around it then the file should be located in the system library folder, C:\Program Files\Arduino\Libraries on Windows.  I think there can now be a user library folder as well C:\Users\PHemans\Documents\Arduino\Libraries and I think that the <> include will pick up from here too.
If the file is in you local folder (same place as the ino) then you should use "" the file name.
It is also possible that what you are seeing is not what the compiler is seeing, so deleting the whole line and then retyping it can sometimes work, as can checking the file endings and encodings using a tool like Notepad++.

I did what you suggested @Matt I now have the HX711 directory in both the Arduino program files and the user directories and it still complains about it. The only way I can get it to compile is to place the hx711.h & hx711.cpp files into the sketch directory and change the line to #include "HX711.h"

Installing libraries to the IDE installation folder(C:\Program Files\Arduino\Libraries in your example) is a bad idea because all the libraries you install there will be lost when you update to a new IDE version. Always install the libraries to the {sketchbook}/libraries folder.

authors: محمد جواد مهدوی


text:
How to handle an error in setup()
What is the "proper" way to handle an error during setup on an Arduino -- for example some attached component is missing or returning an error code or invalid response?  The setup() function returns void so that's no help. This just doesn't seem to be an issue that is addressed in the official docs -- at least not that I have found so far.
Here are some options I have considered:

Throw an exception (but where does that go?)
Write a message to Serial and then go into an infinite loop or wait for a y/n to continue.
Set a setup_successful flag and then do if (!setup_successful) return;  in the main loop()

The setup() function returns void so that's no help.

You wouldn't be able to get the return value anyway even if it did return something - it's not you calling the setup() function, but main(), which is not in your code or control.

This just doesn't seem to be an issue that is addressed in the official docs

That is because it is not within the remit of the API and its associated documentation.

Throw an exception (but where does that go?)

It goes in the bin.  Exceptions are disabled.  They make little sense in an embedded system.  Yes, it is possible to use them, but not worth it.

Write a message to Serial and then go into an infinite loop or wait for a y/n to continue.

That kind of thing is what most people do - or variations on that kind of theme.

Set a setup_successful flag and then do if (!setup_successful) return; in the main loop()

That will just run loop() again - after all, it's called loop() for a reason.
You seem to be in the mindset of a PC programmer. Embedded programming is a very very different beast. You don't (usually) have an operating system to handle exceptions and errors and things like that. You don't have a keyboard and mouse, and a screen with pretty pictures on it. Every single thing that the board does is what you program. If you want it to raise an error when an error occurs then it is up to you to program a suitable mechanism for that to happen. Reporting that error and asking for feedback in some way is entirely governed by your system's design. If you have a TFT screen you could put an error message on that. If you have a serial connection you can use that to show error messages. If you don't have any of those you can blink an LED or use a buzzer to beep in a specific pattern (like a PC's POST beeps).

It's true, I have been an application developer (mostly unix/linux) for over 30 years so my thinking is more along those lines and since Arduino and others have made access to embedded development so accessible, there are probably a lot of people like me that art starting to cross over and blur the lines.

Same way you would handle any error in an embedded system; either try to recover from it if you can, or use whatever communications mechanism you have to let the user know that something failed.
I normally use a combination of Serial.println in case I happen to have a serial connection at the time, and also a blinking pattern on an LED (which most boards I use have). As an example, look at my code here: https://github.com/jayeye/jardino/blob/master/libard/WiFiSPIFFSConfig/src/WiFiSPIFFSConfig.cpp#L11. error() will do a sequence of slow and then fast blinks, and either return if I think the error is recoverable and I'm merely warning the user, or just stay in an infinite loop and keep blinking in despair :)
Obviously this is not an original idea -- think beep codes!


text:
Does the position in which you mount an IMU matter?
Forgive me, I'm sure this is a total noob question, but I have never seen it actually addressed in any example or demo.
When using something like a MinIMU-9 board (https://www.pololu.com/product/2738/), does it matter what position you mount the board on your project?  I mean, does it have to be positioned so the proper axes line up with the axes of your vehicle, or is there some calibration to set that alignment?
For a ground vehicle where I will concerned primarily with only one axis, are all axes interchangeable?

Single rotor helicopters inherently hover tilted at a slight angle. There's a popular micro RC helicopter with 6-axis flybarless electronics where the PCB faces forward, and the MEMS sensor is aligned on the board at the approximate opposite of that angle of rotation, so that the chip is actually standing vertically on edge in flight.  Presumably this helps prevent yaw from cross coupling to the pitch and roll gyro readings in a way that would require extra math to untangle.

If the axes of measurement don't line up with the axes of motion, then comparing the IMU outputs to vehicle-relative (VR) coordinates will require some vector arithmetic to convert one to the other. It can be done, but requires some engineering time to code it and processor time to run.
It wasn't clear to me at a quick read whether your chosen IMU can do the coordinate translation itself, or your MCU has to do it. In either case, the computation will always reduce the accuracy of the original data, maybe a lot, maybe inconsequential, but expect some degradation.
Bottom line is: if you can line them up, things get simpler.


text:
Why is Arduino STINO upload function not working?
I'm using sublime text for editing and modifying my arduino libraries. Sublime text is pretty pretty, useful and embed a very powerfull plugin system. Someone created an Arduino plugin for it. The compilation function works but the upload doesn't.
I'm trying to upload on an arduino leonardo using Windows 7 x64.
Did anyone tried to fix this problem ?

Problem some sort of installation/configuration issue.  You are going to have to make an effort to investigate and understand the failure (find error messages, etc which may be being concealed) if you want help with it.

@chris Thanks. I was seeing no error messages in the compiler and uploader console, and didn't checked the sublime text console. There were indeed an error !

I finally found it: Problem was solved after commenting those three lines in */Arduino-like IDE/app/uploader.py:
if force_to_reset:
    pre_serial_port = serial_port
    wait_for_upload_port = self.args.get('upload.wait_for_upload_port', 'true') == 'true'
    serial_port = resetSerial(pre_serial_port, self.output_console, wait_for_upload_port)
    # if self.args['cmd'] != 'avrdude':
    #   if serial_port.startswith('/dev/'):
    #       serial_port = serial_port[5:]
    if serial_port:
        for cur_command in self.command_list:
            command_text = cur_command.getCommand()
            command_text = command_text.replace(pre_serial_port, serial_port)
            cur_command.setCommand(command_text)