text:
Is my Arduino Ethernet Shield broken?
I have an Arduino setup from which I can control my RGB LED strip from my computer using LAN.
It worked like a charm in the start, but after two days, my Ethernet Shield W5100 for Arduino Uno stopped working, and I can't figure out why.
When I connect the Ethernet Shield, the red LED "pwr" is solid red and the "FULLD" flashes orange every second.
The setup:
I have followed an Adafruit guide, connecting the Arduino as such:
On top of the Arduino, I have the Ethernet Shield. All this is powered by an 12V/4A power supply connected to the Arduinos 2.1mm jack.
As I said, this setup worked fine for a few days. While it was on, I noticed the Arduino getting somewhat hot, but some google searches assured me that Arduino Uno can handle high temperatures, so I did not pay any attention to it.
The LED strip is not too long - about 2 meters with about 150 LEDs.
What I have tried:

When I detach the Arduino from my breadboard, the Ethernet Shield
will still not connect
I have tried connecting the Shield to another Power Supply (Computer USB) using another Arduino, but the Shield would still not connect.
I have added a debugging Serial.print message in the Arduino loop function. When using serial monitor, this message is printed over and over again (as if it is stuck in a reset loop)
I have verified for MAC address collisions, even changed the MAC address of the Shield multiple times.

Have I somehow burned the Ethernet Shield? Why won't it work anymore?

I'm sorry to tell you but i think you damaged your board severely that's because you took more energy from the pins than an arduino can handle.
150 LEDs takes way too much power for the arduino to handle as you can see here.
So you likely burnt something on your board and might have to replace it :/
make sure which board is damaged(the arduino itself or the shield) before replacing it.
If the ATmega328P(The chip on the arduino) is damaged then this should be an easy fix.
Instead of what you did, you shoud have powered the LED strip from another power supply(not from the arduino pins) and used the arduino to turn "this power supply" on and off(probably using transistors).

You are right. I should have an external power supply.
The Arduino seems to have survived it with no problems, although it got pretty hot. The ethernet shield however, is dead :(.
Thanks for the answer!


text:
Trying to play audio files on arduino via Usb Host Shield
I want to build a program that will seek audio file inside a USB DOK (DisK On Key/Pen Drive) when it is inserted to the Circuits@Home USB Host shield. After a specified file will be found i want it to be played via the Audio library and the Teensy 3.1 12 Bit Analog Output.
Alternatively, I can use an Arduino MEGA with the shield and the TMRpcm library: https://github.com/TMRh20/TMRpcm/wiki
I've saw that there's a sample with SD card and I've fiddled a lot to get the USB Host Shield 2.0 library to work and succeeded. However I've found a simpler implementation of it in the UsbFat library: https://github.com/greiman/UsbFat
Now basically I need to connect between these two libraries but sadly I've failed to understand how to convert "play_sd_wav.h" to use the UsbFat Library.
Or, more simply put, how do I command a USB pen drive like it is a SD card and pull an audio file from it?
Anyone can help please?
Thank You,
Ziv

source: Stack Exchange

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

sort: votes


text:
Speed sensors for sport
Fair warning: I'm a newbie when it comes to Arduino, so if I'm not too great at describing things, let me know so I can learn!
I have recently built a fairly accurate laser timer to time sprinters through a section of a soccer pitch, giving a nice reading of their average speed through the zone.
The limitation is that we would love to be able to see their speed as a progressive measurement throughout the sprint.
My problem? I have NO idea where to start. Google has so far come up empty...
All I have is the following link, Best of the 2015 NHL All-Star Skills Competition, illustrating the sort of thing we would like to accomplish. The bit in question starts at around 0:35 when they are talking about sensors in the players' jerseys.
Any one able to point me in the right direction?

I'd think video processing would be a good, non-invasive, and relatively inexpensive.  Or duplicate a series of your laser timers for more resolution.

Really depends if your system has to "work on it's own", if you need the values directly and if it has to identify the different runners.

Kinovea is good but this would be post processing not live. You need record video and then you can track each runner on time. Another one is Typhon program but it involves programming and calibrating (then you can track live).

You can use photo cells. Just get some light sensors and direct lasers on to them. I got 100 lasers for £10 from eBay. You don't need to connect them to any controller, just connect them to a power supply to provide light for sensors. The sensors I got from eBay were, I think, 100 for about £5 or £10, then you can use an Arduino Mega and connect sensors to it.
When you cross the sensor, light will trigger and send a signal to Excel (you can use parallax program) and use Arduino code for interrupts when the sensor is triggered, you will get data to Excel (time and triggered sensor). If you call sensors like: first one 1 millisecond, 2 milliseconds, and so on, so you know what distance and what speed. But I think would be tricky if you need to measure a few guys simultaneously. It should work for single one though.

You have already answered this question. You could edit your previous answer and add this answer to that one.

I would use an ultrasonic sensor pointed at them it will give you a list of distanced at the rate that the sensor collects information (e.g. 5Hz) this could be used to plot a graph of distance over time then a graph of speed over time, then acceleration over time ect.

Your are unlikely to get a sufficiently strong ultrasonic reflection over sprint distances, so this would require sensors along the course or active ultrasonic transponders on the runners.

An option would be to use a GPS module which would give you actual speed accurately, this data can be logged to EEPROM or SD and downloaded later or it can be sent wirelessly to a base station.
There is a wearable GPS module from adafruit, there are a few tutorials on getting started with it. You can the make a jacket or something light that can go onto the sprinters with the system attached.

You could use an IMU(Inertial measurement unit), this uses an Accelerometer, Gyro and Magnetometer. There is an article on using IMUs for measuring velocity of an object with basic modules and not using the expensive systems.
This article by CH Robotics covers a starting point, also googling this should give a whole load more of links. As the article says:

It depends entirely on how much accuracy is needed. In general, accelerometer-based position and velocity estimates from low-cost sensors ... are very poor and are simply unusable.

The next line in that article says "In general, accelerometer-based position and velocity estimates from low-cost sensors ... are very poor and are simply unusable", which I think is a much more accurate summarization of what CH Robotics was getting at.

@BrettAM - I was going to add that to discourage the use and left it out which was probably stupid.

You will likely need to buy a relativly high quality GPS for each runner. Alternatly, if you could get a camera mounted so it could see large portions on track from a good angle it could probably perform pretty well with the right optical recoginition code.
IMU's are not going to be capable of tracking a runners velocity. Even constrained to linear motion the position and velocity measurements from integrating a consumer accelerometer become garbage in a few seconds because of accumulated error. Once you add the fact that the sensor will not be level all the time and your angle estimation is at best within 1 degree, I'd estimate the velocity and position of a runner recorded by a normal 9-dof IMU would be irrelevent after at most 5 seconds.
Have a look at the table on this page for a detailed analysis of orientation based errors:http://www.chrobotics.com/library/accel-position-velocity

Your best bet would be to use a module of Gyro, Accelerometer and Magnetometer much like MPU-9150. These devices communicate using I2C and you can log in data about the direction and the change in direction as well as acceleration. Using this data you can easily find out the speed in a particular direction and even overall data like the average speed, distance travelled, etc.
Another idea is using the accelerometer to measure a jerk.A jerk can be taken as a footstep and using appropriate calculations you can find out how much a person has moved throughout the sprint.
You can use ultrasonic sensors too which would tell you the position of the sprinter from a point but they have their disadvantages like small pressure changes due to air will affect the readings and you won't get accurate reading.

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


text:
Why does my LED turn off automatically after about 18 seconds on its own?
I am using the Arduino Due and I am programming it with Atmel Studio 6.2. I have had a HUGE learning curve using this IDE and the Atmel ASF. Nothing is straightforward as it is in the Arduino IDE. Nonetheless, I want to toggle an LED on and off with a simple interrupt on a pull-up configured tactile button. This is my code:
#include <asf.h>
#include "pio.h"

// Define the LED pins
#define BLUE_LED2 PIO_PC28 // Arduino Due pin 3
#define BLUE_LED3 PIO_PC26 // Arduino Due pin 4
#define BLUE_LED4 PIO_PC25 // Arduino Due pin 5
#define BLUE_LED5 PIO_PC24 // Arduino Due pin 6
#define BLUE_LED6 PIO_PC23 // Arduino Due pin 7

// Define the button pins
#define BUTTON_1 PIO_PC22
#define BUTTON_2 PIO_PC21

// Define function prototype for button interrupt
void button_press_handler(uint32_t, uint32_t);
void toggle_LED(uint32_t);

int main (void)
{
    /* Initialize the SAM system. */
    sysclk_init();

    // Initialize input/out
    ioport_init();
    pmc_enable_periph_clk(ID_PIOC);
    pmc_enable_periph_clk(ID_PIOB);

    // Set LED pins as outputs and set there default values (off)
    pio_set_output(PIOC, BLUE_LED2, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED3, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED4, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED5, LOW, DISABLE, ENABLE);
    pio_set_output(PIOC, BLUE_LED6, LOW, DISABLE, ENABLE);

    // Set button pins as pull-up inputs
    pio_set_input(PIOC, BUTTON_1, PIO_PULLUP);
    pio_set_input(PIOC, BUTTON_2, PIO_PULLUP);

    // Configure button input pin interrupt mode and handler (Falling Edge)
    pio_handler_set(PIOC, ID_PIOC, BUTTON_1,  PIO_IT_RISE_EDGE, button_press_handler);
    pio_handler_set(PIOC, ID_PIOC, BUTTON_2,  PIO_IT_RISE_EDGE, button_press_handler);

    // Enable the interrupts
    pio_enable_interrupt(PIOC, BUTTON_1);
    pio_enable_interrupt(PIOC, BUTTON_2);
    NVIC_EnableIRQ(PIOC_IRQn);

    while(1){
         // Doing stuff in here...
    }
}

Then this is my interrupt routine:
// Interrupt handler for button press
void button_press_handler(uint32_t a, uint32_t b)
{
    // Turn the LED's on or off
    toggle_LED(BLUE_LED2);
    toggle_LED(BLUE_LED3);
    toggle_LED(BLUE_LED4);
    toggle_LED(BLUE_LED5);
    toggle_LED(BLUE_LED6);
}

// Function to toggle LED on/off
void toggle_LED(uint32_t LED){

    if (pio_get(PIOC, PIO_TYPE_PIO_OUTPUT_0, LED))
    pio_clear(PIOC, LED);
    else
    pio_set(PIOC, LED);
}

Things work normal and as expected up until about 18 seconds in. After 18 seconds, the LED turns off if it is on. I tested this by setting LED 2 HIGH by default and removing the interrupt all together:
pio_set_output(PIOC, BLUE_LED2, HIGH, DISABLE, ENABLE);

In this case, the LED will stay on forever, but about every 18 seconds, the LED will flash off then back on once quickly. Why is this happening?

I realized that the problem was occurring due to the fact that I was not initializing the board. All I needed to do was add "board_init();" underneath my system clock initialization code in main(void) and now it works.

You should answer yourself and mark that as the answer so that other people will realize the question has a solution.  This is expected behavior http://arduino.stackexchange.com/help/self-answer

accept your own answer to close this question

Again, figured this out. I simply forgot to put in board_init(); Also, since board_init() already calls ioport_init(), I had to disable that.
Now I have this:
int main (void)
{
    /* Initialize the SAM system. */
    sysclk_init(); // Initialize the System Clock
    board_init();  // Initialize the board

....

The symptoms you describe are consistent with your program crashing after 18 seconds.  I expect you will find something in this that is the problem:
while(1){
     // Doing stuff in here...
}

To debug this, add something to the startup that is unique or clearly identifiable:

a print "reset" to a serial port if you have one
in your case, blink the led's in sequence 2,3,4,5,6

Once you confirm that your program is resetting, strip out everything in the
// Doing stuff in here...

With the program stripped down, it should keep the LED's lit.
If the LED's still do not stay lit, but you see your reset indicator, consider power.  Microcontrollers will reset when the voltage droops too low.  The LED's might be consuming enough power to reduce the voltage below the trip point.  Connect a voltmeter to the supply voltage to see if it is stable.
The time delay can be associated with the power supply heating at higher current.  The LM2734 chip on the Due has a thermal shutdown, same as most voltage regulators.  If your hardware draws enough current to overheat, the chip will shutoff, cool down and turn back on.

About drawing too much current, I don't think that is the case because all the LED's work perfectly in Arduino IDE. I made absolutely no hardware changes on the board. It works in Arduino, but not in Atmel Studio so I think this must be a software issue.

Also, as for the while loop, I literally have nothing in there. I simply have the comment to remind me to do stuff once I sort this issue out.

Improper handling of interrupts will cause a reset.

@JohnAugust It would be best to add what you have already tried in the question.

I fixed the issue, it was because I did not include "board_init();"

This may be because the ATSAM3X8E chip has a watchdog: from the datasheet section 15.1,

The Watchdog Timer can be used to prevent system lock-up if the software becomes trapped in a deadlock. It
  features a 12-bit down counter that allows a watchdog period of up to 16 seconds (slow clock at 32.768 kHz). It
  can generate a general reset or a processor reset only. In addition, it can be stopped while the processor is in
  debug mode or idle mode.

board_init() almost certainly disables the watchdog.

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


text:
Microphone Data on Arduino to Wav File on RaspPi
Working on an Arduino + Raspberry Pi project and hoping that this question fits into this category. I'm recording audio using a MEMS microphone on the Arduino and transmitting it over to the Pi to store in a playable file (WAV).
What I currently have setup is TCP transmission from the Arduino to the RaspPi. This part is fine and dandy for the purpose of seeing the data transmission that I am looking for.
Where my issue lies, is the audio data being recorded on the Arduino.
At the moment, I see data from my analogRead() function displaying like the following:
2035
2046
2030
2031
2044
2038
2034
2031
2034
2019
2028
2030
2024
2032
2028

My question is, what does this mean? How would I translate this, preferably on the Pi, as usable data that I can store in a WAV file?
Any libraries or hints/clues that can steer me in the right direction would be great.

That's probably not going to work, or at least not well especially if you need to record at decent quality or for more than a fraction of a second without skipping.  Network interfaces introduce substantial packetization latency, and the Arduino doesn't really have enough memory to store data until it can be sent, plus its ADC is fairly marginal for audio quality sampling to begin with.  If you want to stick the with Arduino you may do better with high baud rate serial since that is streaming rather than buffered, but really an Arduino is not the right choice here.

Why use the arduino, when you can use the Pi directly? I would get a high quality ADC, connect the mic to it, and then make the Pi write the value from the ADC directly to file. The arduino simply isn't fast enough for good quality audio recording - the ADC is 10-bit, 9.6 khz. At best you could get a stereo 8-bit 8khz wav file. With a good ADC on the Pi, you would be able to go up to stereo, 16-bit(maybe even 24-bit), 44.1 khz. Also, the Arduino would be massively slowed down by sending the data, so the actual sample rate would be much lower.

It's difficult to answer this without seeing any code, but I will take a wild guess and assume you are not using any sort of FFT processing on the input. You could try looking into this library. Alternately, people seem to have good luck with this one too.

This is not a meaningful answer to the question asked.  There is no reason to do an FFT as the goal is a .wav file, ie, linear PCM data in the time domain.  Nor is an Arduino fast enough to do a continuous FFT of audio without throwing away the vast majority of the collected information - so even if a frequency domain representation (or alternately filtering in the frequency domain and transformation back) were desired, it would appropriately be done on the pi, not the Arduino.


text:
Turn on led by phone and phone contacts
I would like ask for help. Can you give me an advice how to create (contacts) nubers who can turn on led.
#include <GSM.h>
#define PINNUMBER ""
GSM gsmAccess;
GSMVoiceCall vcs;
char numtel[20];

void setup()
{
 pinMode(13, OUTPUT);

Serial.begin(9600);
while (!Serial) {
;
}

Serial.println("Receive Voice Call");

boolean notConnected = true;

while (notConnected)
{
if (gsmAccess.begin(PINNUMBER) == GSM_READY)
  notConnected = false;
else
{
  Serial.println("Not connected");
  delay(1000);
}
}

vcs.hangCall();

Serial.println("Waiting for a call");
}

void loop()
{

switch (vcs.getvoiceCallStatus())
{
case IDLE_CALL:

  break;

case RECEIVINGCALL:

  Serial.println("RECEIVING CALL");

  vcs.retrieveCallingNumber(numtel, 20);

  digitalWrite(13, HIGH);

  vcs.answerCall();
  vcs.hangCall();
  digitalWrite(13, LOW);

  break;

  }
  delay(1000);
  }

Can you elaborate a bit on what you are trying to achieve?

Now when i call to my number arduino do   digitalWrite(13, HIGH); and low after. But i need something as adress book with numbers who when call arduino do  digitalWrite(13, HIGH); afer low and hangcall, but when call something who not is on the list of my contact arduino only hang call. Sorry for my english. And thanks for answer

I do not know the GSMVoiceCall library, but I assume retrieveCallingNumber may return the number of the caller in the string (character array) numtel. So you need to compare that against your list of predefined numbers that are allowed to switch the LED. Have a look at http://www.arduino.cc/en/Tutorial/StringComparisonOperators

So, retrieveCallingNumber is documented in here. It "retrieves the calling number, and stores it" in a character array passed as second argument.
The simplest solution to check if this number is among the allowed ones is to construct a string from this and compare it against a predefined string for equality. (If you have more than one allowed number, repeat for all.)
Something like this:
vcs.retrieveCallingNumber(numtel, 20);
String s = String(numtel);
if (s == "allowed number goes here") {
    // toggle LED etc.
}


text:
My button control working in reverse
I built this circuit to learn button control.

But my code (or button) is working in reverse. I want to initialize led flash effect when the button is pressed with this code
buttonState = digitalRead(8);
if (buttonState == HIGH)
  doFlash();

Instead the effect runs continuously and pauses if I push and hold the button. If change the condition as if (buttonState == LOW) code is working as expected. (Effect starts when I push the button.)
This is just the opposite of what I read in tutorials. What is wrong in my circuit or code?
Full code:
 void setup(){
  for(int i=2;i<=6;i++)
  pinMode(i,OUTPUT);
  pinMode(8,INPUT_PULLUP);
 }

 void loop(){
  int buttonState;

  buttonState = digitalRead(8);
  if (buttonState == LOW)
    doFlash();
 }

void doFlash() {
    int i;
    for (i=2;i<=6;i++) {
        digitalWrite(i,HIGH);
        delay(100);
        digitalWrite(i,LOW);
    }
    for (i=6;i>=2;i--) {
        digitalWrite(i,HIGH);
        delay(100);
        digitalWrite(i,LOW);
    }
}

Most tutorials will make the code more "intuitive" by adding additional components to the circuit. E.g.

Here you can see one end of the button is connected to 5 volt, will the other end is connected to a digital input, and via a (pull-down) resistor to ground.
If the button isn't pressed the pull-down resistor will make the input read LOW. If the button is pressed the input will go to 5v (overpowering the pull-down resistor) and the input will read HIGH.
Like you I found the pull-up version a bit weird. But once I figured out how both versions worked, I now prefer the pull-up one. For once, because you don't need an addition resistor. (And secondly because I don't like to use unrestricted 5v signals. If in the above example you accidentally set the input to an output, and press the button, you create a short, and could blow up the micro controller.)

This behavior is expected: INPUT_PULLUP means the pin is pulled up via the internal pull up, i.e. it will read as high if not connected externally.
With your push button you connect it to ground (0 volts), thus bringing it to low level and it will read as low. Therefore, in your code, you need to check for low level (LOW) to check if the button is pressed (as you found out by changing the code).

There are two kinds of logic: "active high" and "active low". (At least that's one way to characterize it.) Your circuit is "active low", and there's nothing wrong with it. If fact, when you use the internal pull-up resistors of the microcontroller you're bound to use active low logic. (More modern microcontrollers have configurable pull-up or pull-down resistors.)
If this confuses you you can use a #define in your code:
#define ACTIVE LOW

if (buttonState == ACTIVE)
  doFlash();

i had the same problem and no body solved it for me.but i got the solution and it works.

This is a basic pulldown circuit, same as described in Geben's answer two years ago.  Given the duplication, and that you provide no explanation of how this works or changes the sense of the input, it's not a very helpful contribution to the site at this point.

Welcome to Arduino SE.  Please take the tour to get the most out of this site at https://arduino.stackexchange.com/Tour.  Meanwhile, note that the input to an Arduino input pin needs to be between 0-5 Volts and have about 10K or a bit more across it.  1K isn't enough.  Search on "Arduino input pull-down" and I think you will find what you are looking for.


text:
Arduino Java SerialEvent not being called (Rasberry PI) XPOST from stack overflow
I am following a simple example found here (example one), to have an Arduino connected to a Raspberry Pi and read some data from the Arduino on the Pi in Java.
The issue is that the SerialEvent method is never called, which implies that no data is coming in. However, when I open the Serial Monitor I can see that data is being read correctly.
The correct serial port is being used as well.
Here is the Java code.
//This class:
// - Starts up the communication with the Arduino.
// - Reads the data coming in from the Arduino and
//   converts that data in to a useful form.
// - Closes communication with the Arduino.

//Code builds upon this great example:
//http://www.csc.kth.se/utbildning/kth/kurser/DH2400/interak06/SerialWork.java
//The addition being the conversion from incoming characters to numbers.

//Load Libraries
import java.io.*;
import java.util.TooManyListenersException;

//Load RXTX Library
import gnu.io.*;

class ArduinoComm implements SerialPortEventListener
{

   //Used to in the process of converting the read in characters-
   //-first in to a string and then into a number.
   String rawStr="";

   //Declare serial port variable
   SerialPort mySerialPort;

   //Declare input steam
   InputStream in;

   boolean stop=false;

   public void start(String portName,int baudRate)
   {

      stop=false;
      try
      {
         //Finds and opens the port
         CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portName);
         mySerialPort = (SerialPort)portId.open("my_java_serial" + portName, 2000);
         System.out.println("Serial port found and opened");

         //configure the port
         try
         {
            mySerialPort.setSerialPortParams(baudRate,
            mySerialPort.DATABITS_8,
            mySerialPort.STOPBITS_1,
            mySerialPort.PARITY_NONE);
            System.out.println("Serial port params set: "+baudRate);
         }
         catch (UnsupportedCommOperationException e)
         {
            System.out.println("Probably an unsupported Speed");
         }

         //establish stream for reading from the port
         try
         {
            in = mySerialPort.getInputStream();
         }
         catch (IOException e)
         {
            System.out.println("couldn't get streams");
         }

         // we could read from "in" in a separate thread, but the API gives us events
         try
         {
            mySerialPort.addEventListener(this);
            mySerialPort.notifyOnDataAvailable(true);
            System.out.println("Event listener added");
         }
         catch (TooManyListenersException e)
         {
            System.out.println("couldn't add listener");
         }
      }
      catch (Exception e)
      {
         System.out.println("Port in Use: "+e);
      }
   }

   //Used to close the serial port
   public void closeSerialPort()
   {
      try
      {
         in.close();
         stop=true;
         mySerialPort.close();
         System.out.println("Serial port closed");

      }
      catch (Exception e)
      {
      System.out.println(e);
      }
   }

   //Reads the incoming data packets from Arduino.
   public void serialEvent(SerialPortEvent event)
   {

      //Reads in data while data is available
      while (event.getEventType()== SerialPortEvent.DATA_AVAILABLE && stop==false)
      {
         try
         {
            //-------------------------------------------------------------------

            //Read in the available character
            char ch = (char)in.read();

            //If the read character is a letter this means that we have found an identifier.
            if (Character.isLetter(ch)==true && rawStr!="")
            {
               //Convert the string containing all the characters since the last identifier into an integer
               int value = Integer.parseInt(rawStr);

               if (ch=='A')
               {
                  System.out.println("Value A is: "+value);
               }

               if (ch=='B')
               {
                  System.out.println("Value B is: "+value);
               }

               //Reset rawStr ready for the next reading
               rawStr = ("");
            }
            else
            {
               //Add incoming characters to a string.
               //Only add characters to the string if they are digits.
               //When the arduino starts up the first characters it sends through are S-t-a-r-t-
               //and so to avoid adding these characters we only add characters if they are digits.

               if (Character.isDigit(ch))
               {
                  rawStr = ( rawStr + Character.toString(ch));
               }
               else
               {
                  System.out.print(ch);
               }
            }
         }
         catch (IOException e)
         {
         }
      }
   }

}

And here is the Arduino Sketch
//Arduino code for Part 01

//First we will define the values to be sent
//Note: The java code to go with this example reads-
//-in integers so values will have to be sent as integers
int valueA = 21;
int valueB = 534;

void setup()
{
   Serial.begin(115200);
   Serial.println("Start");
}

void loop()
{

   //We send the value coupled with an identifier character
   //that both marks the end of the value and what the value is.

   Serial.print(valueA);
   Serial.print("A");

   Serial.print(valueB);
   Serial.print("B");

   //A delay to slow the program down to human pace.
   delay(500);

}

I have read that changing Serial.print() to Serial.write() is the new way to do this, but changing this had no result.

So the reason for no events being triggered was due to the program exiting and ending before it had the chance to.
To solve this i added a thread with a loop inside it inside the main thread.
public static void main(String[] args) throws Exception {
 ArduinoComm = new ArduinoComm ();
 main.start("/dev/ttyUSB0",115200);
 Thread t=new Thread() {
 public void run() {
 try {
 //Messy implementation but it works for this demo purpose
    while(true){
      //optional sleep
      thread.Sleep(500);
    }
 } catch (InterruptedException ie) {}
 }
 };
 t.start();
 System.out.println("Started");
 }

Bit of an oversight on my part.

Good to see you fixed your problem already! You might want to accept this as your answer (when you can, I know, it takes some time ;) ).
A thing I like to do is add debug printlines/cout's at the start and end of my program. So you can see whenever your program finishes or starts. I've had troubles with a microcontroller restarting itself (so the start of a program is an interesting event). And sometimes a device can cause undefined behaviour when breaking out of the main loop. So a while(true); (with debug lines) might indeed do the trick.


text:
need help for saving the millis function when arduino was rebooted
I have two questions want to ask

I'm using Arduino Uno with 16*2 LCD Blue ( also I have temp. sensor and two motors also 3 limit switches) ,, my code is working good, but sometimes my lcd stop printing the values of Temperature and time [print nothing i.e. print all the leds on] \\ then when I reboot it everything works good .... why this problem happened ?
Is there any way to save the value of millis function when the arduino was rebooted ?

thanks for your help
regards

My code is for an egg incubator , it consists of

Dht22 sensor [humidity + Temp]
three limit sw.
one motor
16*2 lcd
lamp [acting as  heaters]

As I said previously,  millis function  that I'm using is for controlling the motor movement every 3 hours and stop the movement after 18 days of working
The main problem I faced is POINT 1 that I mentioned previously (I don't need to lose the time when I reboot the LCD)
If any one can help by giving me a short code as an example who to deal with EEPROM or any other idea.
Here is my code
#include "DHT.h"  //includes lib for the temperature-humdity sensor
#include <LiquidCrystal.h> //lcd lib

#define DHTPIN 13 //pin that DHT is connected to
#define DHTTYPE DHT22 //Sensor we are using

DHT dht(DHTPIN, DHTTYPE); //defines location for DHT

int sw1,sw2,sw3;
const int LM1=0;
const int LM2=1;
const int LM3=6;
const int LAMP=8;
const int CW=10;
const int CCW= 9;
const int Buzzer=7;
long previousMillis = 0;        // will store last time LED was updated
unsigned long RealTime = 0;
float MOTORTime =0;// This is the real time that present on LCD now.
unsigned long MOTORSTOP = 0;// store the valve after 18 days of ranning ,,

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 10800000;           // interval at which to blink (milliseconds)(3 hours waiting)

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {

  lcd.begin(16, 2);   // set up the LCD's number of rows and columns: [LCD that we have (Colomn,Row)]
  pinMode(LAMP,OUTPUT);
  pinMode(LM1,INPUT);
  pinMode(LM2,INPUT);
  pinMode(LM3,INPUT);
  pinMode(CW,OUTPUT);
  pinMode(CCW,OUTPUT);

 }
void loop() {
  sw3=digitalRead(LM3);
      unsigned long currentMillis = millis();
MOTORSTOP = currentMillis;
if (MOTORSTOP < 1555200000){ // 18 days
  float h = dht.readHumidity(); //defines the variable for humidity
  float t = dht.readTemperature(); //defines the variable for temperature
  // set the cursor to column 0, line 0
  lcd.setCursor(0,0);
  // print the humidity
  lcd.print("H ");
  lcd.print(h);
  lcd.print("% ");
  //move line down
  lcd.setCursor(0,1);
  lcd.print("T ");
  lcd.print(t);
  lcd.print("C ");

  lcd.setCursor(10,0);
  lcd.print("MOTOR"); // to print motor working time

if (t==37.65)digitalWrite(LAMP,LOW);// Lamp OFF
else if (t>37.65)digitalWrite (LAMP,LOW); // Lamp OFF
else { digitalWrite(LAMP,HIGH);}// Lamp ON

  delay(2000); //wait two sec. before taking another reading.
  ///////////////stepper motor control and delay time 2.45 hours.
 sw1= digitalRead(LM1);
  sw2= digitalRead(LM2);

  RealTime = currentMillis - previousMillis;
  MOTORTime=((RealTime/(1000))/60); ////////////////////////////////////////////
  MOTORTime = 180 - MOTORTime;

  if (MOTORTime >= 1){
   lcd.setCursor(10,1);
  lcd.print(MOTORTime); }// this will print the ACTUAL Time Remaining on LCD
  else {
    lcd.setCursor(10,1);
   lcd.print("<1 MIN");}

  if(RealTime > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

  if (sw1==LOW && sw2==HIGH){
    digitalWrite (CW,LOW);
    digitalWrite (CCW,LOW);
    do {
      digitalWrite(Buzzer,HIGH);
      digitalWrite (CW,HIGH);// change the direction of rotation (DOWN Movement)
      digitalWrite (CCW,LOW);

      sw2= digitalRead(LM2);}
      while(sw2==HIGH);}

      else if (sw1==HIGH && sw2==LOW){

      digitalWrite(CW,LOW);
      digitalWrite(CCW,LOW);

        do {
          digitalWrite(Buzzer,HIGH);
          digitalWrite(CW,LOW);// change the direction of rotation (UP Movement)
          digitalWrite(CCW,HIGH);

          sw1= digitalRead(LM1);}
          while(sw1 == HIGH);}}
}
//----------------------------------------------------------------------------------------------------------------------
else if (((MOTORSTOP/10800000)>= 144 )&& (LM3== LOW)&&(MOTORSTOP >= 1555200000)){
  digitalWrite (CW,LOW);
    digitalWrite (CCW,LOW);

   float h = dht.readHumidity(); //defines the variable for humidity
  float t = dht.readTemperature(); //defines the variable for temperature
  // set the cursor to column 0, line 0
  lcd.setCursor(0,0);
  // print the humidity
  lcd.print("H ");
  lcd.print(h);
  lcd.print("% ");
  //move line down
  lcd.setCursor(0,1);
  lcd.print("T ");
  lcd.print(t);
  lcd.print("C ");

  lcd.setCursor(10,0);
  lcd.print("MOTOR"); // to print motor working time
  lcd.setCursor(10,1);
  lcd.print("OFF");

if (t==36.70)digitalWrite(LAMP,LOW);// Lamp OFF
else if (t>36.70)digitalWrite (LAMP,LOW); // Lamp OFF
else { digitalWrite(LAMP,HIGH);}// Lamp ON

  delay(2000); //wait two sec. before taking another reading.

}
}

You can save things permanently in the EEPROM. Just store your counter there, and it will be available after a reset. Just don't use it too often, it's only good for maybe 1 million writes, which can be used up quite quickly.

You might try a real-time clock module instead of the millis() function. They keep time in external hardware and are battery backed so continue through a power down, you get calendar date and clock time instead of milliseconds since restart, and they don't overflow every 50 days.

It has been suggested to you to save the millis value in the EEPROM.
Although this can work, there is a big issue with the frequency at which
you save it. If you save too often, you will burn your EEPROM, as it is
only rated to 105 writes. If you do not save often enough,
you will have most of the time a very outdated value in EEPROM. The
problem can be mitigated by adopting a wear-leveling strategy, but this
adds significant complexity.
There is a simpler solution to this problem: instead of using the
EEPROM, save the value in RAM. Actually, the millis value already lives
in RAM, and since the RAM is not initialized by hardware on reset, you
will find, when your program starts, that the last millis is right where
you left it! It is then cleared by your program, in a function called
__do_clear_bss that belongs to the C runtime and runs before
setup().
In order to preserve millis across a reset, you can do the following:

Write a function that copies the millis value into some other global
variable. This function must run early in the startup sequence, before
__do_clear_bss clears millis. This can be achieved by putting
the function in the .init3 section of the program, as explained in
the avr-libc documentation on memory
sections.
And the global variable must be in the .noinit section in order for
the C runtime not to mess with it.
In setup(), restore the millis value from that global variable.

This way you will have a continuous millis across resets, with one
caveat: on a cold boot, it will start with an unpredictable value. This
should be no issue if you take care to never rely on absolute time but
only on time differences, which is a good practice if only to avoid
issues when millis rolls over. If you nevertheless want to reset millis
on a cold boot, you have several options:

Connect a "reset time" button to your Arduino and hold the button
pressed when you power it up. setup() would then know it should not
restore the millis value.
Write some magic
number
in RAM. If you find this number at startup, it is extremely likely
that the program is starting from a warm reset.
If your Arduino has a fairly recent version of optiboot, you
will find the reset flags in the CPU register r2 when your program
starts. These flags tell you whether you come from a cold boot or a
warm reset.

The program below is an example that implements strategy 2. It prints
the millis value on the serial port roughly every second. On reset, it
prints “-- starting --” and continues from where it left.
// If this is in RAM at startup, we come from a warm reset.
volatile const unsigned long magic = 0x12345678;

// This is where Arduino core keeps the millis() value.
extern volatile unsigned long timer0_millis;

// Here we will save a copy of timer0_millis.
unsigned long __attribute__((section(".noinit"))) savedMillis;

// Save the millis value at startup.
void __attribute__((section(".init3"),naked)) saveMillis()
{
    if (magic == 0x12345678)  // very likely a reset
        savedMillis = timer0_millis;
    else                      // cold boot
        savedMillis = 0;
}

void setup()
{
    // DO THIS FIRST: Restore the saved value of millis.
    noInterrupts();
    timer0_millis = savedMillis;
    interrupts();

    // Other initializations can be done now.
    Serial.begin(9600);
    Serial.println("-- starting --");
}

void loop()
{
    Serial.println(millis());
    delay(1000);
}

The fact that one can keep data in RAM across a reset is something I learned from the article Odometer/Speedometer Pendant by David Johnson-Davies.

Summary:
You have an incorrect variable type assignment for previousMillis ('long' instead of 'unsigned long') resulting in illegal mixing of types in a subtraction.
It is not certain that this is causing your problems but, if not, it will cause problems at some stage if millis() is never reset  - if only when millis() passes its halfway point.
It is not possible to prove with certainty that the mixing of types is not causing a problem without examining the compiled code as the action is 'illegal' and so no assurance is possible.
(We hope that the compiler writer 'got it right' :-) ).

Details:
Where you now use

long previousMillis = 0;

You should use

unsigned long previousMillis = 0;

Both 'long' and 'unsigned long' are 32 bit data types but long is signed and effectively "wraps around" at half value.
Apart from having funny things happen after about 25 days, if you mix data types in a calculation as you do in

RealTime = currentMillis - previousMillis;
  where

RealTime = unsigned long
currentMillis = unsigned long , but
previousMillis = long

then there is no certainty as to what the code will do when subtracting a long' from an 'unsigned long'.
We know what we would like it to do, and we hope that the compiler writer made the same assumptions as we do, but there is no guarantee.
Interestingly, while it does no harm for RealTime to be of type 'unsigned long', this is usually not essential, as we know that

up to about 25 days the result will fit in the lower 31 bits of a 'long' and
  up to 65.535 seconds the result will fit in the 16 bits of an unsigned int and
  up to 32.767 seconds the result will fit in the lower 15 bits of an int.

So, if your period between millis() tests is guaranteed to fit in the above ranges then the lower range variables may be used.
While the mixing of types in the actual subtraction produces a technically undefined result, the use of a different type for the result than is used in the calculation is acceptable as the calculation result is well defined as long as the subtraction is performed correctly.

millis() wrap-around - NOT a problem:
People have expressed concern about incorrect results when millis() overflows after about 50 days, but this need not be a concern if correct data typing is used.   When two variables or 'counters' (in this case eg millis() and previousMillis), both of type 'unsigned long' are subtracted or compared, the result is arithmetically valid, even if the "upper" variable ( millis() ) has reached the top of its range and 'wrapped around'. This result is true for any two unsigned integer counters which are both of the same length.
ie the result of eg

delay = millis() - previousMillis

will ALWAYS be valid if millis() and previousMillis are both 'unsigned long's.
This result is not intuitively obvious to most people and there are many "solutions" to this "problem" on web which seek to correct a problem that does not exist. If you are interested in making use of this fact in other situations it is worth taking pencil and paper (or your favoured equivalent) and using eg 3 or 4 bit variables, working through how this works and why. What happens is that the overflowing / wrapping around higher counter (millis() in this case) "looks like" a longer unsigned variable with additional bits above its MSb. When the subtraction is carried out an MSb "bowwow" may occur  - this is being "borrowed" from data bits that do not exist but this matters not when only the lower N bits (32 in this case) are of importance.

Variable (including the state of millis() ) can be saved in EEROM memory prior to a reboot. IF the data has to be validly written when a power outage occurs the system must detect the outage and continue to run long enough to validly write to EEROM. This requires proper design of power supply holdup time - without which EEROM corruption may occur due to power loss while writing to memory. As well as internal EEROM, it is possible to use low cost I^2C EEROM memory if non volatile storage requirements exceed uC EEROM capacity.

More detail on any of the above available if required.

+1 for your explanation of the millis() rollover issue. I too have come across a few misguided attempts to fix this non-problem. OTOH, (unsigned long) - (long), although certainly a bad idea, is well-defined by the rules of usual arithmetic conversion: the signed argument is implicitly converted to unsigned.

@EdgarBonet You may be right re the (UL - L) result. In C++ certainly, in Arduino code, probably and hopefully. In a language that isn't exactly the same as any formally defined one, and which also includes a GUI of sorts, programming code  and more, all rolled together and implemented by a team of competent enthusiasts, where things like this are not explicitly covered in the 'reference' you'd hope the results were what you'd expect from the nearest relevant language(s) - but if it didn't work the way expected, you'd have no real comeback. But, as you say, it's probably "standardised".

You could be running out of memory. Posting your code would be helpful.

2. Not without some external memory such as an SD card.

As David points out in the comments the Arduino does have EEPROM memory (512bytes or 1024bytes depending on which version you have). See here for the library: http://www.arduino.cc/en/Reference/EEPROM

Many microcontrollers have EEPROM or self-writable flash that can be used to store values internally in a non-volatile way.


text:
Arduino UNO + Arduino GSM Shield + Sparkfun Venus GPS
I am using an Arduino UNO that is connected to an Arduino GSM shield (http://www.arduino.cc/en/Main/ArduinoGSMShield).
Now, I want to connect the SparkFun Venus GPS module to this combination. (*unfortunately due to my rep I can only post two links)
The Venus GPS works fine with the Arduino UNO by itself, but I am having some trouble getting the GPS module to communicate with the Arduino when the GSM shield is stacked on top.
The GPS powers on and begins blinking (which means it has a lock), but the serial monitor is not showing any information.
Coming from the programming side of things, I really don't understand much about electronics, so please pardon me if I am missing something basic here.
Based on what I've managed to figure out so far, I think it has something to do with the shield requiring 5V operating voltage and the Venus operating at 3.3V.
I think that when the GSM shield is plugged in, its expecting a 5V input, but the Venus GPS is only capable of sending a 3.3V signal.  Furthermore, any other 5V sensors that I am currently using don't have any problems communicating with the UNO through the GSM shield.
So, I actually have two questions:

Is this assumption correct or could something else be the cause of my issue?
If this is correct, could I use something like this logic level converter (https://solarbotics.com/product/50550/) to step up the Venus GPS input signal?

Thank you in advance for any help and guidance you are able to provide.

hi can u provide the source code

I received my logic level converter today and wired it in between the Venus GPS and the Arduino GSM shield.
The issue seems to be resolved and I'm able to properly receive information from the TX on the Venus GPS.  It would seem that my assumption was correct and I needed to "step-up" the 3.3V TX signal from the Venus GPS in order to use it with the GSM shield.


text:
Arduino with WS2812 using Adafruit NeoPixel library fade in/out different patterns
Hey all I have been trying to figure out a way to random set patterns for my fade in/ out code below:
int PIN = 3;
int totalLEDs = 11;
int ledFadeTime = 5;

Adafruit_NeoPixel strip = Adafruit_NeoPixel(totalLEDs, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOut(0, 0, 255, ledFadeTime); // Blue
}

void rgbFadeInAndOut(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }

     strip.show();
     delay(wait);
  };

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }
     strip.show();
     delay(wait);
  };
};

The code above works great. Fades the blue in and out infinity times. However, I am wanting random LEDs to be off or have a lighter/darker shade of the color I choose (in the above it's blue).
Example:
[off][blue][blue][off][off][dark blue][blue][off][dark blue][dark blue][off]
[blue][blue][blue][dark blue][off][blue][dark blue][blue][dark blue][off][off]
etc etc...

Would anyone happen to have code already like this?
Any help would be great! Thanks!

To make randomly-changing colours for the whole strip, change:
void loop() {
  rgbFadeInAndOut(0, 0, 255, ledFadeTime); // Blue
}

to:
void loop() {
  rgbFadeInAndOut(random (256),
                  random (256),
                  random (256), ledFadeTime); // random colour
}

If you want to make individual pixels different colours you could set up an array of colours, randomly initialize it, and use that. Like this:
#include <Adafruit_NeoPixel.h>

int PIN = 3;
int totalLEDs = 11;
int ledFadeTime = 5;

Adafruit_NeoPixel strip = Adafruit_NeoPixel(totalLEDs, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOut(ledFadeTime);
}

void rgbFadeInAndOut(uint8_t wait) {

  uint8_t red [totalLEDs];
  uint8_t green [totalLEDs];
  uint8_t blue [totalLEDs];

  // randomly set each colour
  for (int i = 0; i < totalLEDs; i++)
    {
    red [i] = random(256);
    green [i] = random(256);
    blue [i] = random(256);
    }

  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red [i] * b/255, green [i] * b/255, blue [i] * b/255);
     }

     strip.show();
     delay(wait);
  }

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red [i] * b/255, green [i] * b/255, blue [i] * b/255);
     }
     strip.show();
     delay(wait);
  }
}


text:
How to upgrade Arduino UnoR3 clock
A little background:
I need to generate a 40KHz frequency as accurately as possible.
(One of my other posts is here:
Stable frequency generation)
My code is solid- I'm using an Uno R3 and generating the most accurate frequency I can at this point. The only way to get a more accurate frequency is to upgrade the ceramic resonator to a crystal oscillator.
So, my over-arching question is: How do I actually upgrade the ceramic resonator to a crystal oscillator?
Things I'm considering are:
Is it worth it to actually upgrade my Uno R3 - and is it even possible? Is there a clone that drives the ATMega328p with a crystal oscillator that I could use instead? Is there simply just a better model for this application?

It's really easy to take an ATmega328 chip and wire it up on it's own.  There are even instructions on the Arduino site on how to do it.  Take a look at http://www.arduino.cc/en/Main/Standalone .
You could even pull the 328 out of the Uno, add the crystal and a few caps and then program it with the Uno board.  I've done this a few times myself and it worked just fine for my needs.

I was trying to avoid using a bare chip as I'm using a 12v supply to power the Uno and utilizing the onboard 5v for some other circuitry.

A 7805 voltage regulator would be easy to add to that circuit to give you a nice 5v to power the atmega and any other circuitry you have. They are relatively cheap and plentiful as well.

Looking at the Arduino R3 reference design, it should have a crystal! But in practice it seems that the manufacturers are cutting corners and using a resonator because it is cheaper. I don't like your chances of fitting an xtal instead of a resonator. Unless you are a soldering expert and have suitable facilities, the most likely outcome is a dead board.
If your board has the MCU chip in a socket, you could bend the xtal pins so they don't go into the socket and solder a xtal and a couple capacitors to them. Not exactly a production line solution, but it will be fine if you just want a one-off - and anyone reasonably at home with a soldering iron could do it.
Freetronics (an Australian company) make a R3 compatable with xtals for both processors. These are very well made (I own two), and have a prototyping area as well. Downside is the higher cost. See http://www.freetronics.com.au/products/eleven#.VT3F-PCo1BA

The eleven may have its LEDs on the edge (where they belong), but the reset button is still in the middle of the board, which is not R3 compatible, and won't be reachable with a shield on top. Besides, two identical crystals this close together is kinda stupid. They could have done with one crystal and use a buffer to bring the clock to the other microcontroller. And yes, AUD 40 is expensive.

@JorisGroosman The site I pointed to is AUD 29.00 - a bit less but still quite expensive (and they are out of stock)

@kiwiron I do like the idea of slightly bending the pins as a one off solution... Although the Eleven would work perfectly if I could find one. Without trying to get off topic from my original question, can I run my code on a Freeduino? (I would be able to solder a crystal into the kit).


text:
Direct port manipulation to write 40 bits
I have 5 shift register changed in series and want to shift the data quickly. I have learned that the internal shiftOut function is slow and direct port manipulation can speed up the things.
However, I am not sure to write code in the specific way.
The current working code block is:
#define SensDataPin 4
#define SensClockPin 9
#define SensLatchPin 8
updateAllShifters()
{
digitalWrite(SensLatchPin, LOW);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_1);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_2);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_3);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_4);
shiftOut(SensDataPin,SensClockPin,LSBFIRST,byte_5);
digitalWrite(SensLatchPin, HIGH);
}

As the code shows, I have 5 bytes which are written by independent functions and just before the return statement, these functions call "updateAllShifters()" to mark the changes.
I have followed few tutorials over the internet and have re-written the logic like:
#define MSDATAHIGH PORTD |= (1<<PD4)
#define MSDATALOW PORTD &= ~(1<<PD4)
#define MSLATCHHIGH PORTB |= (1<<PB0)
#define MSLATCHLOW PORTB &= ~(1<<PB0)
#define MSCLOCKHIGH PORTB |= (1<<PB1)
#define MSCLOCKLOW PORTB &= ~(1<<PB1)
updateAllShifters()
{
MSLATCHLOW;
for(int i=0;i<40;i++)
{
HOW TO CODE HERE USING THE DEFINED MACROS!
}
MSLATCHHIGH;

Edit: Coding example of this (but want a more optimized way):
#define MSDATAHIGH PORTD |= (1<<PD4)
#define MSDATALOW PORTD &= ~(1<<PD4)
#define MSLATCHHIGH PORTB |= (1<<PB0)
#define MSLATCHLOW PORTB &= ~(1<<PB0)
#define MSCLOCKHIGH PORTB |= (1<<PB1)
#define MSCLOCKLOW PORTB &= ~(1<<PB1)
updateAllShifters()
{
MSLATCHLOW;
for(byte i=0;i<8;i++)
{
 if(!!(byte_1 & (1 << i)));// LSBFIRST
   {
   MSDATAHIGH;
   }else
   {
   MSDATALOW;
   }
}
 MSCLOCKHIGH;
 MSCLOCKLOW;
//DO ABOVE FOR ALL REMAINING 4 BYTES
MSLATCHHIGH;
}

Is there a reason why you aren't using SPI?

I have few SPI ADC which have forced SPI bus down to 1 Mhz. I understand that the shiftout works at 14Khz which is too slow. I just want to optimize it to maximum possible level.

I have few SPI ADC which have forced SPI bus down to 1 Mhz. I understand that the shiftout works at 14Khz which is too slow.

You can change the SPI speed at any time. Once the device is selected (Slave Select asserted) then reconfigure the SPI bus for high speed operation.
eg.
SPI.setClockDivider(SPI_CLOCK_DIV2);

SPI is definitely the fastest way you can communicate with a shift register.


text:
What is the best way to define an I/O pin?
I read definitions like
const int ledPin = 9;

and also
#define ledPin 9

I know that a definition like
int ledPin = 9;

is a bad practice if you're not going to change it (which you usually won't), though I've see this several times in Arduino programs.
Which one of the other two is preferred?

#define ledPin 9 is preferred. By doing int ledPin = 9; you will be allocating an int memory whose value is used every time you use ledPin. #define is different in the sense it doesn't allocate memory. there is no memory called ledPin. Before compiling all "ledPin"s in the code(other than strings) are replaced by 9. So basically
digitalWrite(ledPin);

becomes
digitalWrite(9);

Advantages of #define : Saves memory and since all ledPin are replaced by 9 before execution, it saves processor time.
Doesn't really matter in small codes...

Are embedded compilers really so bad they don't do constant folding when using const int?

@chuu as far as I know Arduino uses gcc for avr. So it should almost definitely be optimized out. The answers here don't show much understanding of good practice in C++

in C++, const int ledPin = 9; is preferred over 2 other options. This will NOT allocate memory for an int except if you define a pointer to it somewhere, which nobody would do.

Const int does allocate memory @jfpoilpret. #define doesn't take up any memory cuz its just a symbolic name of an expression and not the name of a memory...

Check out this link http://www.cplusplus.com/forum/beginner/28089/ and see for yourself. Otherwise just perform the check with Arduino IDE: check the data size with const and with #define.

#define is not even a datatype to take up space. The link doesnt say anything about memory. Anyway it does point out the advantage of const in terms of scope...

Strictly speaking, the #define approach will use slightly less memory. The difference is usually tiny though. If you need to reduce memory usage, then other optimisations would probably be far more effective.
An argument in favour of using const int is type safety. Wherever you refer to that pin number by variable, you know exactly what data type you're getting. It might be promoted/converted implicitly or explicitly by the code which uses it, but it should behave in very clear ways.
By contrast, the value in a #define is open to interpretation. The vast majority of the time, it probably won't cause you any problems at all. You just need to be a little careful if you have code which makes assumptions about the type or size of the value.
Personally, I almost always prefer type safety unless I have a very serious need to save memory.

I was in the #define camp until I read Peter's answer. Guess I know who will be refactoring code this weekend. ;)

Probably the best way would be
const uint8_t LED_PIN = 9; // may require to #include <stdint.h>
    or
const byte LED_PIN = 9; // with no include necessary
const unsigned char LED_PIN = 9; // similarly
The name is in caps as per general practice in C++ (and others) to name constants.
This should not use any RAM in itself, and use about 1 byte of program memory per use.
However, there might be problems when the number is higher than 127 and is sign-extended while getting promoted to larger signed integers (not entirely sure on this), although that is unlikely to happen with pin numbers.

Not only will
const int ledPin = 9;

take up RAM, but in this case, will use more RAM than necessary as digitalWrite(uint8_t, uint8_t) only needs one-byte arguments, and an int is usually two bytes (compiler-dependent, but typical). Note that you can give the literal an explicit type in the #define:
#define ledPin ((int)9)

though in a context such as a function argument where a specific type is required (because the function was properly prototyped!) it would either be implicitly cast or get an error message if the types don't match.

@DrivebyDownvoter, would you comment on your reasons?


text:
Cannot bootload again after changing the board?
We are so tired and would like to get help with this. We are trying to bootload using the arduino Uno.
We have an atmega 328p smd , that we are trying to bootload. We have connected all the right pins, added to the boards.txt the  "Atmega328 on a breadboard(8mhz internal clock)".
Then I have chosen from the "board" menu, this option (internal clock), and uploaded the program. it worked .
Later, I wanted to try and bootload for external clock so I chose from the boards menu the pro mini with 5v board.(is it wrong?)
Not only that I got an error, now, I can't bootload the internal clock again !!
Why can't we bootload again? Did we damage something? Can it be reset again?
How can you bootload for external 16Mhz ??
error :
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again

When burnt the Pro Mini bootloader did it work?

Check This out my problem have been solved.
https://www.youtube.com/watch?v=IYi815scN2A&ab_channel=LearnItAllAcademy

Please check capacitor value it must be in between 18pF to 20pF(The capacitors used for crystal)

Not only that I got an error, now, I can't bootload the internal clock again !

You need an external clock source, such as a crystal and two capacitors. Once you switch the fuses to the external clock it won't work any more unless you have such a clock.
I have a bootloader uploader sketch that also provides a clock signal if you need it.


text:
ATMega I/O maximum current
According to the ATmega328P datasheet, the total current from all I/O pins must not exceed 200mA.
Let's say that an Output pin sources 30mA and an Input pin sinks 10mA. The total current should be 30+10=40mA or 30-10=20mA?

Neither. First, inputs don't draw current. Whether you're sourcing current or draining it, it will always be an output pin.
The 200 mA rule is probably determined by the bonding wires for the Vcc and ground pins on the die. That means that all outputs which are sourcing current shouldn't source more than 200 mA combined, as this current will have to enter the device through the Vcc pin.
Likewise all outputs sinking current shouldn't sink more than 200 mA combined, as this current will drain through the ground pin.

Could you possibly explain the "sourcing - sinking" difference?  I thought than Output pins are sourcing current and Input pins are sinking.

@user3060854: in an input pin there doesn't flow any current. If an output pin is high it can provide current to a load connected to ground. It then sources current (which comes from the microcontroller's Vcc). When the output is low, it can draw current from a load connected to Vcc. It then sinks the current (and drains it to ground).

Usually you sum the magnitudes of the currents - so
|+30| + |-10| = 30 + 10 = 40 mA in your example.
Predictably but unfortunately. the principle of TANSTAAFL  usually applies in such matters :-).
Such limitations are often (but not solely) dissipation based.
A low level output pin is dissipating ~= (Vo_low) x I low and
a high level pin dissipates (Vdd-Vo_high) x I_high.
For low currents versus I_pin_max, Voutlow is ~= 0  and Vouthigh is ~= Vdd.
As currents approach design capacities Voutlow starts to rise and Vouthigh starts to fall (due to the internal 'switch' not being able to handle the current) and dissipation rises.
IF you pulled a high pin fully low or a low pin fully high then
at 5V and 200 mA IC dissipation = 1 Watt.
Under that sort of abuse other bad things may happen.
There MAY be some specialist cases where you can treat SOME high and low currents as semi independent but this would need a good understanding of the IC and probably still lies outside specification.


text:
calculating the input current
I have been a bit confused about calculating the input current, so I'd be much obliged if someone could help.
Let's say that we have a potentiometer connected with an analog input as shown below. In a middle position the resistance of the potentiometer is spitted to R1 and R2.
How can I calculate the current in A0?
How much will be the current value if (R1=0, R2=Rmax), (R1=Rmax, R2=0), (R1 and R2 !=0,Rmax)?
 5V --------
           |
           R1
           |
 A0 --------
           |
           R2
           |
          GND

Just in case you didn't realise, it's maybe worth noting that the analog pins measure voltage rather than current.

You are right, I just want to know the current value which passes through the analog pin

When reading an analog voltage an analog pin has a very high resistance - usually very very much higher than the resistance of any potentiometer used, and input current to A0 can be regarded as zero for practical purposes.
For practical purposes the current drain from the supply will be that which flows from 5V to ground via R1 & R2.
I = V/R = 5V/(R1  + R2)
As for a potentiometer the sum of R1 + R2 is constant, the position of the pot-wiper makes no difference to current draw.
eg 10k pot. I_supply  = V/r = 5V/10K = 0.5 mA.
An I_A0 ~= 0

The upper value of a potentiometer which should be used for an analog input is covered by the uC (microcontroller) data sheet. The key parameter is uC input bias currents flowing in the potentiometer and causing small voltages which affect the analog reading. A rule of thumb is to keep such voltages under about one LSB (least significant bit) of the ADC.

The input current of the ADC is low enough not to change the potentiometer's characteristic (which won't be perfectly straight, anyway).
The only requirement is that the impedance of the potentiometer (according to Thévénin equal to R1 parallel to R2) shouldn't be greater than 10 kΩ. That's because otherwise it takes too long for the ADC's capacitor to get charged.


text:
Do I need Kalman Filter after I read DMP data on MPU6050?
In my project I need to use as noiseless as possible data from a MPU6050, I do have some nice DMP data, what will happen if I apply Kalman filter above it? Will I get more noiseless data? Or will it become unreliable anymore? Are there any benefits to do that ?

That would entirely depend on your filter - do a good job and you can remove noise and trivialities from the signal, but do a bad job and you can remove any meaning.   Keep in mind that micrco-machined accelerometers have limitations - integrating to a position is a loosing proposition.

The DMP data from the MPU6050 is already filtered, and while I have not expirimented with the DMP data much myself I believe it is pretty clean. If there is a calibration process you can do to improve it, that is probably worth expirimenting with, but you should not filter the values a second time.
You should figure out what your application's noise tolerance actually is before worrying about different filters. There are potential benefits to your own filter, I think knowing exactly how it performs in edge cases and being able to calibrating it to your specific problem could be beneficial; However, it could also end up being worse than the DMP. Don't forget that filter calculations can generally take a few milliseconds for an arduino to run that you don't have to worry about with the DMP.
If you do work on your own filter, you will need to turn off the DMP and filter the raw values. Look into complementary, mahoney, and madgwick filters as well as kalman, which is quite computationally expensive. Using an existing library or an implementation from an open source quadcopter project is probably most efficient. The math associated with kalman filters and 3d rotations gets very complicated very quickly.


text:
How I could make a bus connection in a prototype shield?
I am a programmer but pretty new to electronics , I recently bought a prototyping shield like the picture :

In my view there is no bus connections here . I have lots components need connect to solder into a single board , and some ports like GND and VCC , SDA and SCL need connect via buses , how could I make solder such a bus connection by using this shield?
Should I just continuously solder through the holes I want to form a bus?
Thanks..!

If the board has copper on both sides you can solder a copper wire on the bottom to create a "bus".

Sounds reasonable ,however I don't have copper currently , can I just use the solder?

You can, but solder doesn't really want to stick to the solder-mask between the pads. You can just strip some electrical cable, speaker cable, whatever you have laying around.

Thanks Gerben , so should I put copper wire straight on the back face of the board and cover holes , then I soldering other wires in the front face ? or should I soldering wires first , and use a copper attach them and solder together both in front face ?

Doesn't really matter. Whatever works for you. I never liked protoboard. So went almost straight to developing my own circuit-boards.

I would mount the components to the board first then create busses with wire. Depending on the components you might be able to use the same row the component leads are in or you may need to lay the bus in the adjacent row and bridge the gap with component leads.
A quick search turned up an image that sort of gives an idea of what I'm talking about. If you look closely you can see the wire bridging the gap between each solder pad.
https://www.bing.com/images/search?q=soldering+protoboard+bus+wiring&view=detailv2&&&id=EF1514CA6486FC44E0132E7DE1CFBFDBFD015809&selectedIndex=15&ccid=vQ%2beHllm&simid=608022938507020230&thid=JN.TBpqHtXSA7o3dTvD8dPVaQ&ajaxhist=0


text:
Arduino Ethernet shield server and client at the same time
Hardware:

Arduino Mega 2560 Rev3
Ethernet Shield Rev3
A sensor

Goal:

Take value from sensor, upload it to ThingSpeak.
Host a web page on the Arduino.

Question:
I've done both things in the past. But now I want to upload the data to ThingSpeak and host a page on the board at the same time , and it doesn't seem to work. Should I try to make two clients? I'm really new two the whole networking stuff.
I'm basically trying to stitch up ThingSpeak's example code with Zoomkat's client/server code. Here is what I'm trying. The webpage does work, but it doesn't upload to ThingSpeak for some reason.

//zoomkat 12-08-11, combined client and server
//simple button GET with iframe code
//for use with IDE 1.0
//open serial monitor and send an g to test client and
//see what the arduino client/server receives
//web page buttons make pin 4 high/low
//use the \ slash to escape the " in the html
//address will look like http://192.168.1.102:84 when submited
//for use with W5100 based ethernet shields

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
IPAddress ip(192, 168, 0, 197); // ip in lan
IPAddress gateway(192, 168, 0, 1); // internet access via router
IPAddress subnet(255, 255, 255, 0); //subnet mask

// ThingSpeak Settings
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "2M6SFMKICXR7MU1A";
const int updateThingSpeakInterval = 4 * 1000;

// Variable Setup
long lastConnectionTime = 0;
boolean lastConnected = false;
int failedCounter = 0;

EthernetServer server(84); //server port
EthernetClient client;
String readString;

void setup() {
  pinMode(4, OUTPUT); //pin selected to control
  Ethernet.begin(mac, ip, subnet, gateway);
  server.begin();
  Serial.begin(9600);
  Serial.println("server/client 1.0 test 12/08/11");
  // keep track of what is loaded
  Serial.println("Send an g in serial monitor to test client");
  // what to do to test client
}

void loop() {
  // Print Update Response to Serial Monitor
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
  // Disconnect from ThingSpeak
  if (!client.connected() && lastConnected) {
    Serial.println("...disconnected");
    Serial.println();
    client.stop();
  }

  if(!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval)) {
    Serial.println("sendPost function started");
    sendPost();
  }
  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += c;
          //Serial.print(c);
        }
        //if HTTP request has ended
        if (c == '\n') {
          Serial.println(readString);
          //print to serial monitor for debuging
          //now output HTML data header
          if (readString.indexOf('?') >= 0) { //don't send new page
            client.println("HTTP/1.1 204 ");
            client.println();
            client.println();
          } else {
            client.println("HTTP/1.1 200 OK"); //send new page
            client.println("Content-Type: text/html");
            client.println();
            client.println("");
            client.println("");
            client.println("<TITLE>Arduino test page</TITLE>");
            client.println("");
            client.println("");
            client.println("
THIS IS A TEST
");
            client.println("");
            client.println("");
          }
          delay(1);
          //stopping client
          client.stop();
          readString = "";
        }
      }
    }
  }
}

void sendPost() {
  Serial.println("function initiated");
  client.stop();
  String tsData = String(analogRead(A0), DEC);
  if (client.connect(thingSpeakAddress, 80)) {
    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + writeAPIKey + "\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(tsData.length());
    client.print("\n\n");
    client.print("field1=");
    //// is this the prob?
    client.print(tsData);
    lastConnectionTime = millis();
    if (client.connected()) {
      Serial.println("Connecting to ThingSpeak...");
      Serial.println();
      failedCounter = 0;
    } else {
      failedCounter++;
      Serial.println("Connection to ThingSpeak failed ("+String(failedCounter, DEC)+")");
      Serial.println();
    }
  } else {
    failedCounter++;
    Serial.println("Connection to ThingSpeak Failed ("+String(failedCounter, DEC)+")");
    Serial.println();
    lastConnectionTime = millis();
  }
}

What's the issue you're facing with this? What do you expect to happen? Please edit your question to include exactly what you need. Thanks!

I don't know how to make a single program that does both server and post requests to ThingSpeak.

I edited the question with the code I'm trying.

I think you want to look at timeouts and then in loop poll to see if there is any data to send to the socket.  What you want to do is achievable normally, but I don't know if you can do it with this library.  An alternative is to use two Arduinos and get them to talk via serial.

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


text:
LCD Display hangs the computer
I'm trying to connect 16x2 LCD screen to clone Arduino UNO via PF8574T backpack. 4 cables are connected to +5V, GND, SDA and SDL pins.
When I tried this I2C scanner code from arduino.cc. It returned strange characters in serial monitor at first couple of tries. And now, when I try computer hangs.
When I use A4 A5 pins on the Arduino instead of SDA and SDL, i2c reported the device is on 0x27. It is ok. But if i keep LCD connected to Arduino, my iMac shutdowns after for a while. In error log i see there was a problem regarding USB serial device. I assume it as a power problem.
I'm on OS X Yosemite. Why this can be happening and how can I fix?
Note: Computer is hanging as soon as the Arduino usb cable connected.

Update: When I removed the LCD, the it connected without error so I could delete I2C scanner sketch.

Update2: I have updated my question. It seems as a power problem.

Sometimes my system hangs in the way you describe  ("hanging as soon as the Arduino usb cable connected")  if I mistakenly connect  the +ve and -ve supply lines to an i2c device the wrong way round.

It seems there is short in the backback circuit. Or may be the pin markings are wrong.


text:
Ethernet shield and sd card not working togather on arduino mega
I am making a web-client with an Arduino mega and Ethernet Shield. I am trying to receive data from a web-server running a php script and saving that data to the SD card located in the Arduino Ethernet shield. I have separately tested to read and write to SD and to Get data from the the php script using the Ethernet. But when i tried to merge those two code into one, i found that Ethernet is unable to connect to the web-server(php Script).But the Ethernet connects fine when i remove the SD Card from its slot. During my research i found that Arduino mega has different SPI pin configuration that the uno. And the libraries are supposed to handle the SPI data-line independently. But i still tried to manually controlled the SPI bus, but it did not work. As far as i know, i am now unable to change the SPI bus using the D4 pin for SD card and D10 pin for Ethernet.
I am using native Ethernet library and SDFat library.(I Even used the native SD library but the result is the same).
#include <Ethernet.h>
#include <SPI.h>
#include <SdFat.h>
#define Ethernet_ss_pin 53
#define Sd_ss_pin 4

// On the Ethernet Shield, CS is pin 4. SdFat handles setting SS
/////////////////////////////////////////////////////////////////////////////////
////////SD Config
/////////////////////////////////////////////////////////////////////////////////

SdFat sd;
SdFile myFile;
//const int chipSelect = 4;
const char* fileName="database.txt";

/////////////////////////////////////////////////////////////////////////////////
////////Ethernet Config
/////////////////////////////////////////////////////////////////////////////////
//String server = "rfid.unisec-bd.org"; //ip Address of the server you will connect to

//The location to go to on the server
//make sure to keep HTTP/1.0 at the end, this is telling it what type of file it is
String location = "/getData.php HTTP/1.0";

// if need to change the MAC address (Very Rare)
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
////////////////////////////////////////////////////////////////////////

EthernetClient client;

char inString[3200]; // string for incoming serial data
int stringPos = 0; // string index counter
boolean startRead = false; // is reading?

void setup() {
  Serial.begin(9600);
  pinMode(53,OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(10,OUTPUT);
  ChipSelect(0);
  Ethernet.begin(mac);
  String pageValue;
  pageValue=connectAndRead(); //connect to the server and read the output
  Serial.println(pageValue); //print out the findings.
  ChipSelect(1);
  // Initialize SdFat or print a detailed error message and halt
  // Use half speed like the native library.
  // change to SPI_FULL_SPEED for more performance.
  if (!sd.begin(Sd_ss_pin, SPI_HALF_SPEED)) {
    sd.initErrorHalt("Sd initialization failed");
  }else{
    Serial.println("Sd card Initialized");
  }
  ChipSelect(0);

}

void loop() {
  Serial.println("Type any character to start");
  while (Serial.read() <= 0) {}
  delay(1000);  // catch Due reset problem
  ChipSelect(2);
  String pageValue = connectAndRead(); //connect to the server and read the output
  Serial.println(pageValue); //print out the findings.
  ChipSelect(1);
  writeSd(pageValue);
  readSd();
  ChipSelect(0);
}
void readSd(){
  //const char path=(const char)fileName;
  if (!myFile.open(fileName, O_READ)) {
    sd.errorHalt("file read error");
  }
  Serial.println(fileName);
  // read from the file until there's nothing else in it:
  char data;
  int c=0;
  while ((data = myFile.read()) >= 0) {
    data=char(data);
    Serial.print(data);
    //Serial.println(c);
    c++;
  }
  // close the file:
  myFile.close();
}

void writeSd(String storeData){
  // open the file for write at end like the Native SD library
  if (!myFile.open(fileName, O_RDWR | O_CREAT | O_AT_END)) {
    sd.errorHalt("opening database.txt for write failed");
  }
  // if the file opened okay, write to it:
  Serial.print("Writing to database.txt...");
  myFile.println(storeData);

  // close the file:
  myFile.close();
  Serial.println("done.");
}

String connectAndRead(){
   ///////// Pin 10,11,12,13 are used as SPI Bus of the ethernet Shield
/// MOSI-         pin 11
/// MISO-         pin 12
/// CLK-          pin 13
/// CS for sdCard-pin 4
/// ss-           pin 10
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output
  // or the SD library functions will not work.
        //digitalWrite(Sd_ss_pin,HIGH); //SD is not active

 /*       USE THIS CODE FOR PROXY SERVER IN BRAC UNIVERSITY
        // if you get a connection, report back via serial:
  if (client.connect("192.168.1.5", 8080)) {  // This is connecting to the proxy
    Serial.println("connected");
    // Make a HTTP request through proxy:
    client.println("GET rfid.unisec-bd.org/getData.php HTTP/1.0");
    client.println();
  }
*/
  //connect to the server
  Serial.println("connecting...");
  while(!client){;}
  //port 80 is typical of a www page
  if (client.connect("rfid.unisec-bd.org", 80)) {
    Serial.println("connected");
    client.print("GET ");
    client.println(location);
    client.println("Host: rfid.unisec-bd.org"); // SERVER ADDRESS HERE TOO
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.println();
    //Connected - Read the page
    return readPage(); //go and read the output
  }else{
    return "connection failed";
  }
}

String readPage(){
  //read the page, and capture & return everything between '<' and '>'
  stringPos = 0;
  memset( &inString, 0, 3200 ); //clear inString memory
  while(true){
    if (client.available()) {
      char c = client.read();
      if (c == '!' ) { //'!' is our begining character
        startRead = true; //Ready to start reading the part
      }else if(startRead){
        if(c != '@'){ //'@' is our ending character
          inString[stringPos] = c;
          stringPos ++;
        }else{
          //got what we need here! We can disconnect now
          startRead = false;
          client.stop();
          client.flush();
          Serial.println("disconnecting.");
          return inString;
        }
      }
    }
  }
}
void ChipSelect(int s){
  if(s=0){                              //Both Device is off
    //digitalWrite(53,HIGH);
    digitalWrite(10,HIGH);
    digitalWrite(4,HIGH);
  }else if(s=1){                        //Only SD is active
    //digitalWrite(53,HIGH);
    digitalWrite(10,HIGH);
    digitalWrite(4,LOW);
  }else if(s=2){                        //Only Ethernet is Active
    //digitalWrite(53,HIGH);
    digitalWrite(10,LOW);
    digitalWrite(4,HIGH);
  }
  Serial.print("Ethernet SS:");
  Serial.println(digitalRead(10));
  Serial.print("SD SS:");
  Serial.println(digitalRead(4));
}

I suppose you have seen this one: http://electronics.stackexchange.com/a/67214/140185

You have to switch off and then on pin 2 (connected to Vcc on SD reader) using digitalWrite
https://stackoverflow.com/questions/41277010/how-to-connect-rc522-rfid-module-and-sd-card-adapter-to-one-arduino-board/46797716#46797716

`//HEADER FILES##################################
#include <SPI.h>
#include <MFRC522.h>
#include <SoftwareSerial.h>
#include <EEPROM.h>
#include <SD.h>
//ARDUINO MEGA
//MISO 50
//MOSI 51
//SCK 52
//ON/OFF SD CARD READER 2
//SD Card DEfinitions###########################
File root;
const int chipSelect = 4;
const int chipONOFF = 2;
//RF_ID Definitions#############################
#define SS_PIN 7
#define RST_PIN 6
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup()
{
Serial.begin(9600);
SPI.begin();
pinMode(chipONOFF,OUTPUT);
digitalWrite(chipONOFF, LOW);
tc_03_rfIDbasicTest();
digitalWrite(chipONOFF, HIGH);
tc_02_SDcardConnectTest();
digitalWrite(chipONOFF, LOW);
tc_03_rfIDbasicTest();
}

void loop()
{ }

void tc_02_SDcardConnectTest()
{
Serial.println("");
Serial.println("");
Serial.println("-----TEST 2: FUNCIONAMIENTO BASICO DE SD-----");
Serial.println("");
if (!SD.begin(chipSelect))
{
Serial.println("Falla en comunicacion, asegurate que la uSD esté insertada e intenta de nuevo");
Serial.println("FAIL");
}
else
{
Serial.println("Tarjeta uSD Detectada");
Serial.println("PASS");
root = SD.open("/");
printDirectory(root, 0);
}
}

int tc_03_rfIDbasicTest()
{
Serial.println("-----TEST 3: FUNCIONAMIENTO BASICO DE RFid-----");
mfrc522.PCD_Init(); // Init MFRC522 chip again per each write attemp
mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details

if ( ! mfrc522.PICC_IsNewCardPresent())
    Serial.println("Targeta fuera de alcance");
else
    Serial.println("Targeta dentro de alcance");
if ( ! mfrc522.PICC_ReadCardSerial())
    Serial.println("Falla en lectura de tarjeta");
else
{
    Serial.println("RFid OK :) !");
    Serial.println("PASS");
    String nuid="";
    for (byte i = 0; i < 4; i++)
        nuid+=mfrc522.uid.uidByte[i];
    mfrc522.PICC_HaltA();
    mfrc522.PCD_StopCrypto1();
    Serial.println(nuid);
}
}

void printDirectory(File dir, int numTabs)
{
while (true)
{
File entry = dir.openNextFile();
if (! entry)
break;
for (uint8_t i = 0; i < numTabs; i++)
{
Serial.print('\t');
}
Serial.print(entry.name());
if (entry.isDirectory())
{
Serial.println("/");
printDirectory(entry, numTabs + 1);
}
else
{
Serial.print("\t\t");
Serial.println(entry.size(), DEC);
}
entry.close();
}
}`

and this what you get on serial monitor.
`-----TEST 3: FUNCIONAMIENTO BASICO DE RFid-----
Firmware Version: 0x92 = v2.0
Targeta dentro de alcance
RFid OK :) !
PASS
215103959

-----TEST 2: FUNCIONAMIENTO BASICO DE SD-----

Tarjeta uSD Detectada
PASS
BIO/
D70A273B.DB 44
ENROLADO.DB 57
F683B22D.DB 40
A6DE1E49.DB 38
080732DC.DB 38
08D1EF01.DB 38
08267788.DB 38
XWIFI.DB    47
CP0101.DB   26
XFEC.DB 4
CP0102.DB   26
CP0201.DB   26
SYSTEM1/
WPSETT1.DAT 12
INDEXE~1    76
CP0301.DB   26
GP01.DB 33
GP02.DB 33
GP03.DB 33
GP04.DB 32
GP05.DB 32
GS06.DB 35
GS07.DB 37
GS08.DB 36
GS09.DB 36
GS10.DB 36
GE03.DB 24
GE02.DB 20
GE01.DB 23
GS11.DB 38
AP010101.DB 69
AP010102.DB 83

-----TEST 3: FUNCIONAMIENTO BASICO DE RFid-----
Firmware Version: 0x92 = v2.0
Targeta dentro de alcance
RFid OK :) !
PASS
215103959`

Please hablo english.

Por favor, usa la lengua del Imperio.


text:
Serial LED control
Hell0!
I run in small problem. I am try to control LED's by serial port.So I am expect to send "1" and two LED's will start to blink or send "0" and only one LED is constantly lighted up. At first I thought that do-wile will work, Arduino will run do loop while value sent by serial port is "1" or "0". However at first I sent "0" and one LED are lighted, after I send "1" and two LED's are blinking. But when I send "0" again, LED's keeps blinking. What should I change in my code?
const int ledPin2=2;
const int ledPin3=3;
const int ledPin4=4;

void setup()
{

  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);

 Serial.begin(9600);
}

void loop()
{
  while (Serial.available()==0);

  int serialVal = Serial.read()-'0';

  do
   {
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4,HIGH);
    } while(serialVal==0);

  do
    {
      digitalWrite(ledPin4,LOW);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, LOW);

      delay(100);

      digitalWrite(ledPin3, HIGH);
      digitalWrite(ledPin2, LOW);

      delay(100);

  }while (serialVal==1);
};

I don't think you understand how your code is being executed. I would recommend trying the following.
const int ledPin2=2;
const int ledPin3=3;
const int ledPin4=4;
int serialVal;

void setup()
{

  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);

 Serial.begin(9600);
}

void loop()
{
  // If data is available, then read it!
  if (serial.available() > 0)
  {
      serialVal = serial.read()-'0';
  }

  // If serial val is 1, turn on LEd4, turn off Led3
  if (serialVal == '1')
  {
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4,HIGH);
  }

  // If serial val is 0,
  // turn on LED2. Turn off Led3
  // delay for 100ms
  // turn of LED2, turn on LED3
  // delay for 100 ms
  if (serialVal == '0')
  {
      digitalWrite(ledPin4,LOW);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, LOW);

      delay(100);

      digitalWrite(ledPin3, HIGH);
      digitalWrite(ledPin2, LOW);

      delay(100);
  }

}

The reason why your code doesn't work, is once you are within a do while loop, you will not be allowed to exit until the condition is met. If you are not scanning for more serial values within that do while, you will get stuck there forever.
Another reason why you might be confused, is how digitalWirte operates. There is no need to loop over a digitalWrite, as the pin will stay HIGH, or LOW until you change its state. Once you digitalWrite(HIGH) that pin will stay high until it is told to go LOW.

Okay, I just tried your code. If 1 sent by serial then LED3 will light up (HIGH) and will continue to stay on HIGH. After I sent 0 and LED1 lights up and after delay 100ms LED1 turns off and LED2 turns on, but that is all it is not continuing to repeat blinking. Is it possible to loop within last IF statement of your code, so blinking will continue?

That is because serial.available() is a blocking method, when you nest it into a while statement This means that it will not continue in the code until a serial value has been received.
Try this code https://gist.github.com/ericellb/12d7337396f6646ef3f8

If you need anything else, id be glad to help.

This is a good answer, but be careful of your wording. "you will not be allowed to exit until the contition is met", implies break statements don't exist. "serial.available() is a blocking method, when you nest in a while statement", serial.available() does not becoming a blocking method in a while loop, the loop is blocking because of its return value.

Good points BrettAM.

Obviously, the code shown at the moment in this answer will get 3 compile errors (“error: 'serialVal' was not declared in this scope”), at lines 18, 24, and 35.


text:
Why does timer1 not generate correct period on CTC mode with a resolution of 5us?
I have defined my code to generate an interrupt over each 5μs on CTC mode using timer1 but the output shows a time of ~15μs.
Following the equation to set the counting number to achieve the desired time
(# timer counts + 1) = (target time) / (timer resolution)

I've got OCR1A = 79 for a desired time of 5μs using no prescaler and a source clock of 16MHz on Arduino Uno.
My code is as follows:
// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>

#define LEDPIN 9

void setup()
{
    pinMode(LEDPIN, OUTPUT);
    digitalWrite(LEDPIN, HIGH);

    // initialize Timer1

    cli();          // disable global interrupts

    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
    OCR1A = 79;

    // turn on CTC mode:
    TCCR1B |= (1 << WGM12);

    // Set CS10 bit for no prescaler:
    TCCR1B |= _BV(CS10);

    // enable timer compare interrupt:
    TIMSK1 |= (1 << OCIE1A);

    sei();          // enable global interrupts

}

void loop () {}

ISR(TIMER1_COMPA_vect)
{
  digitalWrite(LEDPIN, !digitalRead(LEDPIN));
}

This is the output from my logic analyzer:

Is it a limitation of the Arduino or am I missing something?
My idea is to generate a PWM manually to control a servo motor using timer1 and precisely increase the period by 10μs during "on" time and get the desired angle.
After some experiments, I have discovered that my motor (MG996R) has a range from 0.6ms to 2.1ms during "on" time to move from 0 to 180 degrees.
I have tried the Arduino's Servo library but it goes far than 180 degrees (I don't know why). That's why I am building my own code for that purpose.

79 clock cycles might no be enough to execute all the ISR code.

@Gerben, do you any idea how to solve it instead?

I got it working just analyzing time consumption of digitalWrite and digitalRead functions. They took around 13us to execute (each one), so this added up a few extra undesired microseconds to the final period.
Instead, I set up digital output using DDRD for configuring and PORTD for setting the desired output, which results in approximately 1us to set the output value (HIGH or LOW).
I changed the prescaler to 8 and the code below shows how to get a 100kHz wave output with 5us duration of "on" time using timer1 CTC mode.
void setup()
{
    DDRD = B00001000; // pin 3 as output
    PORTD &= ~_BV(PORTD3);   // set 3 as LOW

    // initialize Timer1

    cli();          // disable global interrupts

    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
    OCR1A = 9;

    // turn on CTC (Clear Timer on Compare Match) mode:
    TCCR1B |= (1 << WGM12);

    // Set CS10 bit for clk/8 prescaler:
    TCCR1B |= _BV(CS11);

    // Output Compare A Match Interrupt Enable
    TIMSK1 |= (1 << OCIE1A);

    sei();          // enable global interrupts

}

ISR(TIMER1_COMPA_vect)
{
  PORTD = ~PORTD;
}

Glad to see you got it working.


text:
Level tracking using optical or capacitance sensors
I am looking to devise a level tracking system using arduino and some sensors. My particular situation is I have solute that is coming out of solution and I want to track the formation rate of the solid phase as the salts settle at the bottom and build a bed of particulates.
I am looking for precision at about 0.5mm and over a range of like 6 inches. My initial idea was to get a sensor bar that could detect when and where light is hitting the sensor and post processes that signal. I have to design this device to sit outside the cylindrical vessel. The solvent is transparent so any form of light would work. I am stuck on finding the parts that could pull this off and I was hoping the more experienced community could point in the right direction.
* UPDATE *
a little cartoon for a clearer picture of the idea
I am leaning towards capacitance since using light seems like a rabbit hole. I was playing with some foil and it may work but I need a much more sensitive tool on the order of pico-Farads to work.

What is the distance between the sensors? If it's a short distance, you could possibly get away with using two clear tubes and putting sensors in one tube and then lights in another tube.

@AnnonomusPenguin The diameter of the tube that contains the liquid I want to measures is on the order of 3cm. My best thought thus far was to go for an approach parallel plate capacitors, but I am not sure that would work to well.  I need really high resolution since the materials would have low k values.

Ultrasonic sensor?

@RSM how would that work? I am thinking I need to account for possibly 6 inches in elevation change.

@TheCodeNovice the time from the transmit to the time of receive would change as the level increases. If the liquid level increase with proportionally to the increase of the solid the level sensor could work. Also there capacitive sensors for level sensing, partially described here http://en.m.wikipedia.org/wiki/Level_sensor

@RSM Thanks for the link! The problem is for my experiment I cannot have anything inside the tube I must measure the level externally. Also I am looking to get the level as a function of time so I need a continuous means of measurement.

@TheCodeNovice so in terms of in the tube and the ultrasonic sensor, if that works, can sit above the vessel.

@RSM top or bottom is not workable because of flow inlets and outlets. I am trying to get the height without intruding. This is tube is hooked up to a machine. I can only attack it from the sides. Thanks for all the great suggestions though!

@TheCodeNovice - possibly if you isolate the capacitive sensor on the outside of the tube from the interference of air, it should increase the accuracy to a point.

What solution is it?

@RSM how could i isolate from air interference?

@TheCodeNovice - I don't know off hand what would be best but I am sure a Google search should give something. It should basically keep the surrounding air at a constant so that it doesn't change with changing air flow(blocking movement from changing the level) if possible you could put a plastic tube around the other tube and seal the ends. That's if you can get something around withe the other stuff.

A quick search for “capacitive water sensor” gives this.

Light might be the way to go, since the preciptate might not have significantly different capacitive or acoustic properties   How about a laser-sensor pair shining through to a sensor on a movable servo or stepper-driven stage, and you move the stage upwards/tube downwards whenever the laser diffuses into the precipitate, keeping track of the motion of the stage?

What about measuring this with two resistive probes - the electricity will go through down one probe to the top of the water, across the water, and up the other probe. You can measure how much of the probe it went down, by measuring the resistance. You would need the probes to be a specific, very consistent distance apart, and be made of resistance wire.
Another option is to use a float of some kind, and measure it this way. This is a lot easier if all you need to know is full/not full.