text:
Why is the output on the MOSI line shifted 1 bit over from what I commanded?
I've been trying to work with an AD5685R DAC. Per that datasheet, to get DAC1 to output max voltage (5V), I would perform:
SPI.begin();
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE3); // DAC uses CPHA=1, CPOL=1

digitalWrite(CS, LOW);
SPI.transfer(0x31); // upper nibble sends a "write and update" command, lower nibble says "DAC1"
SPI.transfer(0xFF);
SPI.transfer(0xFC); // 14-bit DAC, last 2 bits are dontcares, make them 0
digitalWrite(CS, HIGH);

Replace 0xFFFC with 0x0000 to get 0 volts out.
Sending this command as written somehow writes to DAC4 instead of DAC1! and while 5V will come out when I write 0xFFFC, I get to 2.5V when writing 0x0000 instead of 0V.
If I command this with a Bus Pirate and directly write the bytes out, it works exactly as desired.
I used the Bus Pirate to sniff the SPI traffic and it turns out I'm not getting what I've commanded. Rather than 0x31 0x00 0x00 for instance, I get 0x18 0x80 0x00.
If we break this out into bits:
0x310000: 0011 0001 0000 0000 0000 0000 // commanded
0x188000: 0001 1000 1000 0000 0000 0000 // actually sent

So the command actually sent out is shifted by 1 bit!
Here's the bit pattern for 16383 counts (i.e., 2^14-1):
0x31FFFC: 0011 0001 1111 1111 1111 1100 // commanded
0x18FFFE: 0001 1000 1111 1111 1111 1110 // actually sent

The opcode corresponding to 0x18 is "write to input register 4" (the output occurs because I've pulled the /LDAC pin permanently low, see the datasheet), which explains why I'm getting an output on DAC4 instead of DAC1.
This occurs with both a Sparkfun Pro Micro and an Arduino Mega 2560.
What is going on here? Why is the Arduino not sending out what I've actually commanded? Again, writing the hex codes directly to the DAC using a Bus Pirate works perfectly.

Because something is using the wrong SPI mode.

@IgnacioVazquez-Abrams this is correct, SPI mode should have been SPI_MODE2. Arduino's SPI page doesn't make clear what CPHA=0 vs CPHA=1 is (rising vs falling edge active). But maybe I'm just having a hard time comprehending words... Or, the comments on the AD5685R's sample code is incorrect.

CPOL is clock polarity, and CPHA is clock phase.
The SPI modes are:

Mode 0 (the default) - clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0)

Mode 1 - clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1)

Mode 2 - clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0)

Mode 3 - clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1)

According to your datasheet:

Data from the SDIN line is clocked into the 24-bit input shift register on the falling edge of SCLK.

Judging by the diagrams on the datasheet, Mode 1 is what you want. You want the trailing edge of high to low.
More information at SPI - Serial Peripheral Interface - for Arduino


text:
Lessons 2: Spaceship interface
I'm just starting to discover Arduino. Currently, I've done 2 lessons from Arduino book and I have few questions about second circuit.

Why we need to add 10kOm resistors after wire to 2 pin?
Why we need to add resistors after LED?
And why 3, 5, 6, 9, 10, 11 pins with "wave" symbol?

I'm surprised: isn't all that explained in the book? If not, I would not recommend it! Short answers: pulldown resistor to avoid floating input;limit current flowing through the LED to avoid burning it; those are pins allowing PWM to simulate analog output, between 0 and 5V.

Why we need to add 10kOm resistors after wire to 2 pin?

Due to some weird electronic properties, the state of the input to the Arduino is "undefined" when there is nothing connected. When the button isn't pressed down, it is neither connected to 5V or GND; it is left floating. When floating, the input isn't reliable.
To make sure that the input always has some sort of signal, we connect it to ground. However, there is a problem with directly connecting the input to ground. When you would push the button, you would create a short circuit by allowing current to flow directly from 5V to GND without any current limiting.
The solution is to add a resistor to limit the current between 5V and GND. When the button isn't pushed, the input is grounded to allow it to read LOW. When the button is pushed, the 5V rushes in and, since the 5V doesn't use a resistor, "the 5V is stronger," making the input HIGH.

Why we need to add resistors after LED?

An overly simplified explanation: A LED will theoretically pull infinite power (as current) from your power source without a resistor. With too much power, the LED will be destroyed from heat.
Because the LED has some resistance, it will pull up to a finite amount of power, but that usually is much more than the LED can handle (and sometimes what the power supply can supply). We need a resistor there to ensure that the LED can only draw as much power as it can handle.

And why 3, 5, 6, 9, 10, 11 pins with "wave" symbol?

If you look at an Arduino board, it will say DIGITAL (PWM~). That (PWM~) means that any pins with the "~" symbol are PWM pins... pins that can turn on and off their output very fast, in this case to create an illusion that the LED is dimming because the state changes faster than the human eye can detect.

http://arduino.cc/en/uploads/Main/ArduinoUnoFront240.jpg

More explanation for PWM here: Arduino docs, an answer [of mine]

Can you please also explain why the resistor can be put after the LED and not before? Seems to me like full power should already have done through the LED at this point?

@rejeep the resister after the LED is still preventing the electricity from flowing too fast throughout the circuit from the power source to the LED to the ground pin, no matter where it is in that circuit.

Not very intuitive IMO. For example water in a pipe would not behave the same way. Thanks!

source: Stack Exchange

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

sort: votes


text:
Arduino Nano no serial port for MacBook Air 2013
Problem
I have an Arduino Nano connected via a USB cable (Type A to Mini Type B) to my MacBook Air (Mid 2013 Model). The PWR LED is on while the arduino is connected.
Opening the Arduino software, pulling down the Tools > Serial Port menu does not show me a valid serial port. All I see is:
/dev/tty.Bluetooth-Incoming-Port
/dev/cu.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/cu.Bluetooth-Modem

What I've tried and did not work

I have installed the correct FTDI driver (v2.2.18). x64 for my MacBook Air's Corei5, file FTDIUSBSerialDriver_10_4_10_5_10_6_10_7.mpkg. Restarted after installation.
Tried connecting arduino to both USB ports on my Air.

More Info

Running Mac OSX 10.10 Yosemite
Same arduino and cable work when connected to a Windows machine or a Raspberry Pi.

If it helps, I can see the USB Serial in my Apple Logo > About This Mac > System Report under Hardware > USB
USB2.0-Serial:

  Product ID:               0x7523
  Vendor ID:                0x1a86
  Version:                  2.54
  Speed:                    Up to 12 Mb/sec
  Location ID:              0x14100000 / 8
  Current Available (mA):   500
  Current Required (mA):    Unknown (Device has not been configured)

I'm out of ideas and options. Any help would be greatly appreciated.
Thanks in advance :)

Is your nano a clone or a real nano?

It's a clone. Thought I've read that it's a real good one. Anyway, I found something that solved it for me. Going to put it as an answer.

Did you have it plugged into a Windows machine first or before you plug it into your Mac?it might've been bricked but the good news is you can unbrick it.

First time I tried it on my Windows. But it turns out that I needed some additional driver for Mac. See my answer.

This solved it for me.

Download this driver
Install it
Run sudo nvram boot-args="kext-dev-mode=1"
Reboot

Serial ports now showed up in the Arduino IDE and also when I used ls -1 /dev/tty*
Hopes this helps someone.
Reference: This thread

I have the same problem and using your link solves my problem. Thanks for sharing the information. Best Regards,
Jo

Runs!!!
Thanks a lot
(Macbook pro retina late 2012 - OSX 10.1.1)

Thanks for this answer. This fixed my problem as well. Setup: Yosemite, 10.10.5 and this arduino uno clone: AVR-Duino / Mega 2560 UNO

On 2016-04-13, I downloaded the (version 1.2?,  dated 2015-11-19?) driver from there, did the required reboot, and did not need to do the unsigned driver kext setting.  On plugging it in, the device showed up as '/dev/cu.wchusbserialfa130' in Arduino/Tools/Port.

Please update your answer to reflect the fact that it's not longer necessary to tinker with the OS X kernel to allow unsigned drivers to be loaded in kernel space which is a gigantic security risk. Latest OS X recognises these vendor and product IDs correctly, without the need to install any drivers. Product ID: 0x7523, Vendor ID: 0x1a86.

Oh and the unsigned kext setting is not needed anymore because this chip is widely used by Arduino and other embedded boards. Read more...

@Paul-SebastianManole - please post your own answer, pointing this out. References to supporting information would help. For example, what is "Latest OS/X" exactly? Reading that I don't know if I have the latest or not. And certainly in 5 years time people will wonder. Something better would be: "OS/X version 10.8.6 onwards supports this ..." (or whatever version it is).

@NickGammon can't you read dates? How many major version updates of OS X does apple put out in a year? Besides, my answer would be the same except that little bit of information I added. And I did post a reference.

Yes, I am familiar with dates. For a novice, it isn't obvious which part of the answer is tinkering with the OS/X kernel, and which part isn't. I suggest you post your improved answer.

Beware! Kernel Panic! on macOS Sierra, as of 25th September, 2016.

@Paul-SebastianManole - device is not recognized by El Capitan (10.11.6; newest this ancient MacBook supports in Oct 2016) and drivers still need to be installed.

@Jangid didn't see your message before installing. What did you do to fix the problem?

To those wondering: I fixed the kernel panic on macOS Sierra with this: https://www.simplicate.info/2016/09/16/ch340-drama-osx-10-12-sierra-16a313a/

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


text:
Delay not working in function other than loop
So I just got an Arduino and thought I would play around a bit.
However not five minutes in I already ran into a problem.
I tried programming a simple SOS blinking light sequence. To get rid of code duplication I refactored the on and off turning of the LED into functions and then again refactored a short blink and a long blink function which are expected to turn the LED on for a short time and then for a long time.
The problem is the delay in those functions is completely ignored.
int ledPin = 13;

void on()
{
 digitalWrite(ledPin,HIGH);
}

void off()
{
 digitalWrite(ledPin,LOW);
}

void shortB()
{
 on();
 delay(1000);
 off();
}

void longB()
{
 on();
 delay(2000);
 off();
}

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

void loop()
{
 shortB();
 shortB();
 shortB();
 shortB();
 longB();
 longB();
 longB();
 shortB();
 shortB();
 shortB();
 delay(5000);
}

My expected behavior would be that it does an SOS and then waits 5 seconds and repeats.
What really happens however is that it stay continuously lit for a second or so then turns off for 5 seconds.
Using
on();
delay(1000);
off();

In the main loop works so I guess it simply ignores the delays that are put into the other functions. My question would be why and ho do I fix it?
I know that I can use other timer function constructs however I really think this is something that should work by default.

You have no delay in between turning the LED off and turning it back on. Add one.

Ouch ... that was a really bad beginners error. That fixed it.

And it looks like your code sends 'H', 'O', 'S' (the first character is four short 4 blinks). Are you really seeing 'S', 'O', 'S'?

In addition to the other problems, you should have a break between letters. So, for example, "S" is not just dot-dot-dot it is dot-dot-dot-pause.
Example code below that implements pauses between letters, as well as longer pauses between words.
const byte LED = 13;

char * letters [26] = {
   ".-",     // A
   "-...",   // B
   "-.-.",   // C
   "-..",    // D
   ".",      // E
   "..-.",   // F
   "--.",    // G
   "....",   // H
   "..",     // I
   ".---",   // J
   "-.-",    // K
   ".-..",   // L
   "--",     // M
   "-.",     // N
   "---",    // O
   ".--.",   // P
   "--.-",   // Q
   ".-.",    // R
   "...",    // S
   "-",      // T
   "..-",    // U
   "...-",   // V
   ".--",    // W
   "-..-",   // X
   "-.--",   // Y
   "--.."    // Z
};

char * numbers [10] =
  {
  "-----",  // 0
  ".----",  // 1
  "..---",  // 2
  "...--",  // 3
  "....-",  // 4
  ".....",  // 5
  "-....",  // 6
  "--...",  // 7
  "---..",  // 8
  "----.",  // 9
  };

const unsigned long dotLength = 100;  // mS
const unsigned long dashLength = dotLength * 3;
const unsigned long wordLength = dashLength * 2;

// get a line from serial
//  forces to upper case
void getline (char * buf, size_t bufsize)
{
byte i;

  // discard any old junk
  while (Serial.available ())
    Serial.read ();

  for (i = 0; i < bufsize - 1; )
    {
    if (Serial.available ())
      {
      int c = Serial.read ();

      if (c == '\n')  // newline terminates
        break;

      buf [i++] = toupper (c);
      } // end if available
    }  // end of for
  buf [i] = 0;  // terminator
  Serial.println (buf);  // echo what they typed
  }     // end of getline

void dot ()
  {
  digitalWrite (LED, HIGH);
  delay (dotLength);
  digitalWrite (LED, LOW);
  delay (dotLength);
  }  // end of dot

void dash ()
  {
  digitalWrite (LED, HIGH);
  delay (dashLength);
  digitalWrite (LED, LOW);
  delay (dotLength);
  }  // end of dash

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (LED, OUTPUT);
  }  // end of setup

void loop ()
  {
  Serial.println ("Enter your message ...");
  char buf [60];
  getline (buf, sizeof buf);

  // for each letter
  for (char * p = buf; *p; p++)
    {
    char c = *p;
    char * sequence = NULL;

    if (c >= 'A' && c <= 'Z')
      sequence = letters [c - 'A'];
    else if (c >= '0' && c <= '9')
      sequence = numbers [c - '0'];
    else if (c == ' ')
      {
      delay (wordLength);   // gap between words
      continue;
      }

    // ignore not in table
    if (sequence == NULL)
      continue;

    // output sequence for one letter
    for (char * s = sequence; *s; s++)
      {
      if (*s == '.')
        dot ();
      else if  (*s == '-')
        dash ();
      }
    // now a gap
    delay (dashLength);
    }  // end of for each letter

  }  // end of loop


text:
How much current and voltage has my resistor + LED
I have a very simple circuit: 5v -> LED (5mm, forward voltage of 2 V and max. current of 20mA) -> 1k ohm resistor -> GND.
I want to know how much current is flowing in my circuit. I am using this formula:
U = R x I
Since U = 5, and R = 1000 the current is (according to the formula): 5/1000 = 0.005A.
So far so good. The problem is when I try to check the voltage drop over the resistor and the LED. For calculating the voltage drop in the resistor I would use the same formula where I is my current (0.005A) and R is the resistor 1k ohm. The result is: 5 V.
Something very weird is happening here cause the voltage drop around my resistor should not be 5 V cause I know there must be another voltage drop around the LED. If 5V is in the resistor it would mean that 0v is around the LED (and it should not light up but it does).
Thank you helping me with this basic calculus.

The problem is that if you're trying to measure the current directly, you're going to get the wrong answer. Whether it's due to burden voltage or the (in)accuracy of the meter, it's a hopeless situation. The 0.005A your meter is showing is actually closer to 3mA in reality, but your meter can't distinguish between the two well enough.
If you need to measure current this small then the only way to do so accurately is to use a very low-value shunt resistor and an amplifier. This is the method the µCurrent uses, and it's essentially the defacto gold standard for measuring current in small circuits.

thank you ignacio. But my question is moer about this: if I use a higher or lower resistor, will always my LED drag 2 V? I thoght that if I used a different value of resistor I would be changing the current and voltage drop across the LED. Isnt that true?

It is. But unless you change the current to either almost nothing or to too high for the LED to handle, you may not be able to measure the change; a diode's ohmic region is very steep.

Leds have a voltage-current curve. If less current is going through the led, the voltage drop will decrease somewhat. Lower voltage drop means higher voltage across the resistor, leading to slightly higher current. So the resistor and led are (kind of) working together to limit the current. So e.g. doubling the voltage doesn't mean twice the current, but less than twice.

Thank you :) So just to be clear: if I use any resistor value my LED will always drag 2V, no more no less than that? I am asking this to you cause I measured the voltage across my resistor and it was supposed to be 3 V (5 V is the source power and 2 V should be used in the LED) but it's 1 V. What is going on?

@Samul: Approximately 2V, until the current is low enough that the LED enters its flat region.

Gerben thank you! But you left me with more question: if I have a ciruit with a resistor in series with a LED of 2V forward voltage. If I use a resistor with X ohm, and them I change the resistor do 10X ohm, will the voltage across the resistor be the same and the voltage across the LED be also the same (2v)?


text:
Source power with 2 V and LED with forward voltage of 2 V
I have a source power with 2 V and 100mA. I have an LED that has a forward voltage of 2 V and a max current of 20mA.
Should I use a resistor to reduce the current? I see many formulas in the internet saying the the resistor value should be:
(Source Voltage - LED forwared voltage)/LED max current
This formula always worked fine for me, but now that I have a 2 V source power this formula tells me that the resistor should be 0 ohm. Of course this would damage my LED cause the 100mA provided by my source power is way above the 20mA current limit of the lED.

No, it would not damage your led. The forward voltage of a led is, the voltage at which the led 'conducts' the maximum current it can handle. Since diodes have a (exponential) curve, the current though a diode depends on the voltage across it.
So if you give the led 2V, it will use only 20mA. However if the voltage goes to e.g. 2.1V the current might be 25mA (since the curve is exponential), which is a bit too high, and will reduce the leds lifespan.
So for safely I'd add some resistors. E.g. a 10Ohm resistor will limit the current to 20mA max, as long as the voltage doesn't go over 2.2V
PS note that led Christmas lights use the same method to limit current, without a single resistor. I have here a 24v string of leds, grouped into 10 leds connected in series. So the voltage across each led is 2.4V. They are white leds, so they probably have a forward voltage of around 3.2v. But since they only get 2.4v, they will probably use only 5mA or less.

Thank you so much but if I add a 10 ohm resistor it will consume voltage, isnt? If it consume voltage the LED will not have it's forward voltage required in the specs ov 2V cause some of the voltage will be lost to the resistor. Will it work anyway?

The led will be a slightly less bright.

You most likely will not be able to use that power supply with that LED properly. The resistance graph of an diode is quite peculiar.

As you can see, there isn't a "hard" forward voltage, but rather a smooth curve that changes depending on what current is passing through the diode. You can try to use a value of, say 1.95V for the LED, but then you won't pass the same amount of current that you used in your calculations.
Extended reading: Load line (Wikipedia)

Thank you so much I read the wikipedia and understood well the non linear with the linear part in a circuit and the exponential behaviour of the LED with current/voltage. But if I use a 100 ohm resistor, there will be a voltage drop across the resistor right? So the LED will have not the 2 V to operate, but will it work? Can I calculate the voltage across the LED with the 100 ohm resistor in series?

The LED will still drop some voltage. Use load line analysis to figure out how much.


text:
What does Arduino do in 15ms?
I was wondering why there is a 15 ms delay between each iteration of a the main loop.
Code:
The following code shows the execution time expressed in microsec between each loop
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  Serial.println();
  Serial.print("Start: ");
  Serial.print(micros());
  Serial.print("/////////////////////");
  Serial.print("End:");
  Serial.print(micros());
}

Output:
Start: 789452/////////////////////End:821692
Start: 837292/////////////////////End:869532
Start: 885132/////////////////////End:917372
Start: 932972/////////////////////End:965212

Arduino needs 32,240 msec to print the messages to serial and to call the micros() function twice. And this it's fine. Now, considering the difference between the values of the End and the following Start, one question arises:
What does Arduino do between each loop?

Your serial connection is set to 9600 baud, which is 9600 actual data bits per second. The communication consists (*) of 8 bit characters and every bit is useful data (no parity), so you would be able to achieve at most 9600 / 8 = 1200 characters per second.
You have a message of 46 characters including the line break, which brings you to 1200 / 46 = 26 iterations per second.
1000 milliseconds / 26 iterations = about 39 milliseconds per iterations.
This is the theoretic maximum you would get if you would send the data over serial without any other overhead. Pretty close to the 32 + 15 = 47 milliseconds you measured.
Since you print a part of the message (Enter + 'Start:') between the end of the previous iteration and the start of the next (if you take the call to micros() as the start and end), it makes sense that a part of the time is in between there as well.
So the actual overhead you are looking at is about 8ms per iteration. This delay is spread out over the loop and the call overhead of the various functions you use. After all, when you call Serial.print, a lot of work needs to be done before the data can actually be sent to the serial port. You would probably gain more speed/less overhead if you would construct one big string, and send it with a single print command.
Arduino itself is slow, but still much faster than this. It should be able to do a big(ger) number of iterations per second, but you basically limited it by initialising the serial connection to such a slow speed. You can partially eliminate this by picking a higher number. I think both your Arduino and any modern serial port should be able to handle 115200 baud. Nevertheless, you will always have a relatively big overhead when you are sending data over serial. Use your bandwidth wisely, and reduce the number of calls to Serial.print as much as you reasonably can.
*
) 8 bit, no parity is the de facto default. See Serial.begin() for more information about initializing the serial connection.

Note that the 9600 figure is "bits per second", not "baud". You are right that "baud" means "actual data bits" (as opposed to overhead bits, such as start, parity and stop bits), but that distinction is often lost - and in this case incorrect. Each character is 10 bits - 1 start, 8 data, and 1 stop - so the correct number is 960 characters per scond.

@JohnBurger Thanks for that addition. The default setting is indeed 8 data bits and 1 stop bit, no parity, so with a start bit that would be 10 bits per character indeed. You can by the way configure this in the optional second parameter of Serial.begin(). Anyway, the documentation says 'bits per second (baud)', so if you are right, then the docs are wrong (or I misunderstood something).

Like I said: your definition of the original term "baud" is factually correct - but that usage has been confused with "bits per second" for so long now that the distinction is lost to the general public. They'll say "9,600 baud" when they mean "9,600 bps", so documentation follows this (incorrect) convention - although you'll note they used parentheses! In fact, if you were to say to someone "Set your baud rate to 7,680", you'd be correct but unsatisfied, as you won't be able to establish communicatons...

@JohnBurger, The distinction between "baud rate" and "bit rate" is not about which bits are data, and which bits are framing.  The "baud rate" on a wire tells how many times per second the line state changes.  When there are only two line states (usually called "0" and "1", or "mark" and "space"), then the baud rate equals the bit rate.  But when you're using modems for long-distance comms, there can be four or eight line states, and the baud rate then is 1/2 or 1/3 of the effective bit rate.  All most of us ever care about is effective bit rate.  Baud rate is for modem designers.

@jameslarge Huh. I was taught what I explained above nearly 30 years ago. I can find other articles on the web with the same misunderstanding (or indeed the opposite w.r.t. bps vs baud!) - but all the scholarly articles agree with your description. Apologies @GolezTrol!

Also note that "how many times per second the line state changes" isn't completely correct either: it should be "...the line state could change". A series of 0 or 1 bits (for NRZ encoding) would not involve line state changes, but the number of bits sent would still go up.

@JohnBurger, D'Oh!  Of course you are right.

Just check the sourcecode
for (;;) {
    loop();
    if (serialEventRun) serialEventRun();
}

So it does a check if serialEventRun is True, and then a jump back to the beginning of the for-loop. And then a call to loop.
Also note that Serial.print is blocking if the TX-buffer is full. So you might want to add a delay somewhere to ensure the buffer is never full.

Your code is slightly off if you want to accurately time this
Serial.print("End:");
Serial.print(micros());

Will get micros() before printing to serial, and then take the time to print it. You also print some text before taking the time at the top of the loop. Your 15 ms is the time to print these to serial between reading micros. For example, change the loop code to something like this:
uint32_t time, endTime;
...
void loop(){
    time = micros();

    Serial.print(endTime);
    Serial.print('\t');
    Serial.print(time);
    Serial.print('\n');

    endTime = micros();
}

and you should only see a small difference. It showed a 4 microsecond difference when I ran it. The only other thing that runs outside the loop is the serial event handlers, but if you don't use one it obviously doesn't take long.

TL;DR: The delays you measure (32.24 ms between Start and
End, and 15.6 ms between End and Start) are exactly what
is expected from the amount of data you send through the serial port.
Yes, exactly: there is zero overhead from the CPU doing other things.
Let me show how the expected timings can be computed. First, a note
about the exact baud rate. A rate of 9600 bps implies that each bit
takes about 104.17 µs to send. However, the Arduino being clocked
at 16 MHz, it cannot achieve this exact baud rate. Instead, when
you request 9600 bps, you get the closest value it can achieve,
which is about 9615 bps. Then, each bit takes exactly
104 µs. Or at least “exactly” as per the Arduino clock: it really
takes 1664 CPU cycles.
Then, as already noted in previous answers, one character is worth
10 raw bits. It thus needs 1040 µs to be transmitted.
Now, let's look at your code. It should be noted that
Serial.print(micros());

is compiled into something equivalent to
unsigned long timestamp = micros();
Serial.print(timestamp);

i.e. the timestamp is taken and then it is transmitted. Your loop()
is then equivalent to:
void loop()
{
    Serial.println();                       //  2 chars: CR and LF
    Serial.print("Start: ");                //  7 chars
    unsigned long time_start = micros();
    Serial.print(time_start);               //  6 chars
    Serial.print("/////////////////////");  // 21 chars
    Serial.print("End:");                   //  4 chars
    unsigned long time_end = micros();
    Serial.print(time_end);                 //  6 chars
}

By folding the last Serial.print() of one iteration into the beginning
of the next one, one gets the pseudo-code:
forever {
    print 15 chars;  // 15*1040 = 15600 µs
    read time_start;
    print 31 chars;  // 31*1040 = 32240 µs
    read time_end;
}

The computed durations match exactly your printout. This shows that,
once the Serial output buffer is full, the timing of your code
execution is completely governed by how fast the UART sends the bits out
the line. The time taken by the Arduino to do actual CPU work (calling
micros(), formatting numbers...) is irrelevant because the CPU works
in parallel with the UART and, being faster, it ends up waiting for
the UART anyway.

Re "zero overhead from the CPU": Because there is hardware transmit buffer (even if it is only one slot)?

@PeterMortensen: Indeed. The one-byte hardware buffer and the larger software buffer, combined, ensure that the UART is never stalled, waiting for the CPU to provide data to send. Without the hardware buffer, the latency of the “USART data register empty” interrupt would show up in the transmission.

At 9600now each data byte needs 10 bits to be transmit. Or 1ms per byte.
20 bytes will take 20me to transmit.
However, the existence of a buffer and the way the transmission is carried out can greatly impact the duration of execution of your code - actual time for transmission is invariant however.
If your transmission is done via the interrupt, the execution can be almost instantaneous.

“the existence of a buffer and the way the transmission is carried out can greatly impact the duration of execution of your code”. In the OP's example, this is true only at the very beginning. Once the output buffer is full, the timing of the code execution is entirely dictated by the UART.

("me" → "ms")


text:
Lighting 5 leds...the last one lit is always dim
I have a simple project with a close deadline.
I am trying to light up 5 LEDs as part of the project. The first 4 light up in sequence fine, and if I light up just the last one it lights up fine, but if all 5 are lit at once the very last LED is very dim. I swapped out cables, the pin on the Arduino, resistor, LED.
What would explain that? Input amperage? Too strong a resistor?
I have a 330 ohm resistor in between each LED and ground. I am using one of the neat resistors from SparkFun that packages up the 5 330 ohm resistors together, with a common ground wire. I bought two and tried swapping it out with no change.
https://i.stack.imgur.com/QZ4qU.jpg
Here is my code:
/* Blink without Delay
 http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
 */

const int startButtonPin = 6;
const int reedSwitchPin = 7;
const int ledPins[] = {8,9,10,11,13};
const int numLeds = 5;
const long interval = 1000;           // interval at which to blink (milliseconds)
const int revolutionsPerStage = 15;

int debounceDelay = 500; // for switches--interval to ignore short button presses/reed switch open/close
long lastDebounce = 0;
int buttonState = LOW;
int mapStage = 0;

unsigned long previousMillis = 0;        // will store last time LED was updated

void setup() {
  // set pin modes
  for (int thisPin = 0; thisPin < (sizeof(ledPins)/sizeof(int)) - 1; thisPin++)  {
    pinMode(ledPins[thisPin], OUTPUT);
  }
  pinMode(startButtonPin, INPUT);
  pinMode(reedSwitchPin,INPUT);

  digitalWrite(reedSwitchPin,HIGH); // activate the pull-up resistor
}

// Main program loop
void loop()
{
  buttonState = digitalRead(startButtonPin);
  //digitalWrite(8,HIGH);

  // wait for button press to begin program proper. we won't get back to this state except on first boot or if program finishes
  if (buttonState == HIGH) {
      digitalWrite(8,HIGH);
      chasingLEDs();
      //trackProgress();
  }
}

void trackProgress() {
  int blinkState = LOW;
  unsigned long currentMillis = millis();
  unsigned int numRevolutions = 0;

  do {
    digitalWrite(ledPins[mapStage], HIGH);

    // blink the current goal LED at constant interval specified earlier
    if(currentMillis - previousMillis >= interval) {
      // save the last time you blinked the LED
      previousMillis = currentMillis;
      blinkState = !blinkState;
      digitalWrite(ledPins[mapStage], blinkState);
    }
  } while (mapStage < numLeds);
}

// perform a simple welcome sequence to indicate we are ready to start pedalling
void chasingLEDs() {
   // turn LEDs on in sequence, then back off
   for (int i = 0; i < numLeds; i++){
     digitalWrite(ledPins[i], HIGH);
     delay(333);
   }

   for (int j = numLeds; j > 0; j--) {
     digitalWrite(ledPins[j], LOW);
     delay(333);
   }

   // flash the LEDs twice
   for (int k = 0; k < 2; k++) {
     for (int l = 0; l < numLeds; l++) {
         digitalWrite(ledPins[l], HIGH);
     }
     delay(500);
     for (int m = 0; m < numLeds; m++) {
         digitalWrite(ledPins[m], LOW);
     }
   }
}

I found the problem, it was a bug in my code. I had found code to read the array size online but it was off by 1.
Instead of:
for (int thisPin = 0; thisPin < (sizeof(ledPins)/sizeof(int)) - 1; thisPin++)  {
    pinMode(ledPins[thisPin], OUTPUT);
  }

When I changed it to thisPin < numLeds, it worked correctly. The last pin was simply set to be an input pin instead of an output pin.


text:
Infrared sensor has a frequency to activate it?
I am trying to understand 2 sensors that I have here. One says that is "infrared sensor of 38kHz" and the other is "infrared optical reflexive sensor -> http://www.robosoftsystems.co.in/wikidocs/index.php?title=TCRT_5000_Reflective_Optical_Sensor"
I thought that infrared sensor would tell me if an infrared light is passing on it. Infrared light has a wavelenght, right? Can infrared light be emited in different frequencies? Or the frequency of infrared light is the same to all infrared lights?

The 38kHz sensor (such as the Vishay series e.g TSOP1838) are designed for use with IR remotes and IR barrier type applications. They are designed to work with IR emitters that oscillate the IR at 38Khz and additionally modulate that frequency with lower frequency pulses. The sensor (receiver) is designed to have high gain at 38Khz and demodulates the signal. The demodulated output signal pulses can be directly decoded by a microprocessor. The main benefit is reliable functioning even in disturbed ambient light thus protecting against uncontrolled output pulses.

thank you so much! But the infrared optical reflxive sensor? Does it also read 38k or any infrared light with any frequency?

The TCRT5000 will detect just regular IR light. The output is also analog, so between 0v and 5v depending on how much IR light is reflected. These light sensors will however also pickup sunlight etc.

You are amazing, you helped a lot :)

38Khz is not the frequency of the IR light but the frequency it is pulsed on and off at, the receiver is designed to accept that frequency and reject others so as to avoid interference from sunlight etc. I see you have asked the question again in a slightly different way and received a similar answer.
Infrared led and sensor: how it work


text:
How does an analog input pin work?
I have a potentiometer of 10k and I connected it this way:
5v -> potentiometer -> analog input pin of Arduino
When I turn the potentiometer I change the resistance of the circuit but in the Arduino documentation they say that an analog pin in INPUT mode will have 1 megaohm resistance. So, for example, if I turn the potentiometer to the middle it will generate 5k of resistance + 1 megaohm of the analog pin it will result in a tiny, very tiny current. If I use U = R x I across the potentiometer it will be:
U = 5000 x 0.0000001
U ~ 0 across the potentiometer. So U will be 5 V at the analog input because there was no drop of voltage in the circuit. If turn the potentiometer all way up to 10k resistance the voltage in the analog input will also be 5 V because the voltage drop across the potentiometer is still really small.
I know that an analog pin in INPUT mode will read 0 V as 0 and 5 V as 1023. But as I showed you it should always read 5 V even when I turn the potentiometer all way up because the voltage is not being changed. I know I am wrong cause when I log the input pin it shows different values as I turn the potentiometer. So how does this work?

Potentiometers have 3 pins. One for 5v, one for ground, and one that outputs the voltage in between (depending on the orientation of the knob).

The potentiometer and the internal resistance form a voltage divider. The voltage created by this voltage divider is essentially indistinguishable from 5V regardless of what the pot is set to because the internal resistance is so high.
What you want to do is to create an external voltage divider that will cause the voltage to vary full scale between 5V and 0V. You do so by connecting one end of the pot to 5V and the other end to 0V, and drawing the voltage from the wiper.

Hi Ignacio! Thank you for helping me but I still didnt understad how a 10M ohm resistor inside the input pin helps it to read the voltage. What am I missing?

It doesn't. The ADC reads the voltage. The 10Mohm resistance means that the ADC will draw very little current when taking a measurement, but that a comparable external resistance will distort the results.

This is incorrect.  A potentiometer is by defintion a three terminal device.  It forms its own voltage divider.  The input impedance of the ADC, if substantially higher, has minimal loading effect.  Your answer would be correct if the poster had a simple two terminal variable resistor rather than a potentiometer.

@ChrisStratton: The asker never describes connecting the second terminal, only the first and the wiper.

If that were the case, then the question would be erroneous and as they would not be using a poteniometer.  Their results suggest that either  they have wired a potentiometer, or the input impedance is lower than imagined.

Or that they completely botched the circuit analysis.

I am using the 5v wire and the middle wire of my pot. I must be very dumb cause I still dont understand how an analog pin works. Please take a look at this formula (wikipedia) http://upload.wikimedia.org/math/4/4/b/44b8b16db945a778e558f2c5ffd70157.png . If Z2 is 10M ohm and Z1 a small resistor then Vout will be always the same value as Vin, it will never be 2, 3... it will always be the same as Vin independentrly of what my potentiometer effective resistance.


text:
Blue LED not switching off
I have a circuit with a blue led, 470ohm resistor and one IR led. I want the led to be switched off when the IR led has a digitalRead value of LOW(i move my hand over it). So I wrote the code:-
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT); // this is the blue led
pinMode(10, INPUT);  // this is the IR sensor's O/P

}

// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH); // first I give HIGH voltage to the blue LED

if(digitalRead(10) == LOW){  // when the voltage of the IR sensor decreases
digitalWrite(13, LOW); // the blue LED should switch off or have 0 Voltage
}

}

But the blue LED just dims and doesn't switch off. Thanks in advance

What is the ref of the IR LED you are using?

Every time through your loop, the LED is being set to HIGH voltage. This may or may not be followed by setting it to LOW voltage, but since the loop runs again immediately, it's immediately set back to high voltage. This happens so fast that the LED essentially "feels" half voltage and it will dim. Your code needs to be more like this...
void loop() {
  if(digitalRead(10) == LOW) {
    digitalWrite(13, LOW);
  } else {
    digitalWrite(13, HIGH);
  }
}

OR... even like this...
void loop() {
  digitalWrite(13, digitalRead(10));
}


text:
Connect Lilypad to LCD
I am trying to connect an LCD panel (RioRand (TM) IIC/I2C/TWI Serial 2004 20x4 LCD Module Shield For Arduino UNO MEGA R30) to a Lilypad Arduino.  How can I get them to talk to each other?   I cannot figure out how to connect them.

Looks like you have to learn what is I2C and where is I2C in Arduino Lilypad.

Thank you!  I was able to look that up and I got it to light up.  Cannot seem to get Hello World to work with the program in the tutorial.  I am new to all of this.


text:
Infrared led and sensor: how it work
I am having a difficult time to understand how an infrared sensor and led work. I have an infrared LED (like the ones you buy anywhere), does it mean that the infrared LED has the frequency os 38khz?
I know that infrared light has a wavelegnth, but does it also have a frequency?

Frequency and wavelength are the same thing. This isn't an Arduino question, it's an incredibly basic Physics question. Answered here: http://en.wikipedia.org/wiki/Frequency#Frequency_of_waves    (frequency x wavelength = velocity)

it's arduino question cause I am using an infrared sensor in arduino with 38kHz. If the speed is different then the wavelenght can have different frequency. JRobert cleared this to me.

No, it's really not. You're asking about the wavelength and frequency of the LED itself, which is not 38kHz. Infrared frequencies are in the 300GHz to 430THz range. That's the frequency of the light itself. The frequency of the electrical signal you send to the LED to light it at various brightness levels has nothing to do with that. The LED doesn't have a frequency other than the frequency of the light it produces. You're getting that confused with the frequency of the POWER SUPPLY to that LED.

An infrared LED just emits its light (primarily) in the infrared range as described by this Wikipedia article. Any emitted radiated signal (including sound) has both a frequency and a wavelength. The frequency = the velocity of the signal through space divided by its wavelength (F = V / W), or vice-versa: (W = V / F). The natural frequency of light, infrared or visible is far, far higher than 38 KHz; around 4 x 10^14 Hz.
38 KHz is simply a convenient chopping frequency for switching the LED on and off so the sensor can distinguish between infrared in sunlight, for instance, which is relatively constant - from that emitted by the LED. Your circuitry would have to create the 38KHz chopping signal.

Awesome! :) So you mean that the speed of infrared, x ray and visible light is the same? The speed in which the wave travles is the same?

YES! Light waves/particles travel at the speed of light, which is a constant of the universe and is the same everywhere. Please educate yourself about "Electromagnetic Spectrum" here: http://en.wikipedia.org/wiki/Electromagnetic_spectrum

@Samul: Yes, with the exception that I also referred to the speed of sound. The velocity of sound in air is much, much slower but the principle will be the same.

You helped me a lot!


text:
What project design tools are available?
What do you guys use for project designing?
I just found out about AutoDesk's 123D Circuits, which is nice but I wonder if there is something with more components, tools, etc?
For example, I can add an accelerometer to my project there but no signs of a LCD. I have been learning hardware recently and I feel there should be more complete tools out there.
I know this question may be opinion based but I could not find anywhere to ask. Thanks,

If the tool you're using doesn't allow you to create custom parts then, as they say, drop it like it's hot.

ok but do you suggest something? What do you use?

I currently use EAGLE, but I'll probably be jumping to CircuitMaker once it reaches open beta.

http://electronics.stackexchange.com/questions/1222/what-are-low-cost-circuit-and-pcb-design-software/1228#1228

I am using KiCad. It's a full EDA/PCB design suite that is free. It's a really nice multi-platform package. It doesn't do circuit simulation(to my knowledge). It's relatively easy to learn via some youtube tutorials and there's a healthy development community and discussion board as well. It outputs industry standard gerber files so you can quote out your designs to pcb manufacturers.
link:
http://www.kicad.org/

I use this and am fond of it

I think Fritzing is used quite a lot. I have used it myself a couple of times, and I felt it was quite comprehensive. But I haven't used it enough to say whether this is the tool to choose.

Fritzing is actually very basic once you go beyond the breadboard.

So, as the other users said, tou can use FRITZING, it is totally free and it does have LCD and a lot of other Shields. But the thing is, if you want a more complete design tool, PROTEUS 8.1 is a very used tool and by far more easy to use than any other design tool (as a complete designer solution). You can even simulate your lcd in software to test if everything is ok before start mounting your Circuit.
Proteus Site: http://www.labcenter.com/index.cfm
Proteus is not free but you can use a lot it.
Here's some images of arduinos in Proteus (The site in portuguese but you just need to see the pictures):
http://microcontrolandos.blogspot.com.br/2013/04/proteus-8-professional.html

I use ExpressSCH for doing schematics, usually for posting on web sites like this. It is free, runs on Windows only, and is simple enough to use that I picked it up quite quickly. :)
Example schematic:

The red arrows I added later in the GIMP.
It comes with quite a few symbols pre-defined. You can make others from scratch (using boxes, lines, etc.) or take an existing one, "break it apart", and then re-assemble to your desires. Once you have something the way you want it you "group as symbol" and it can be used again in the future.
The program has a sister program ExpressPCB for PCB layouts, however I haven't used that much.

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


text:
Include my header files
let's suppose I have folder called AES, in this folder is file "AES.ino" where is code and folder "AESLib" what is library. In "AESLib" is file called "AESLib.h",
now when I try to include AESLib.h with
#include "AESLib/AESLib.h"

in my AES.ino, then Arduino command line tool complain that its not able to find "AESLib.h"
Where could be the catch?
Thanks

Have you installed AESLib as a library, according to the official instructions?

Hi Peter, including code as Arduino custom library is another approach and of course working.  But this is about including your custom code, without use "library approach"

Maybe this similar post is what you are looking for. In your case, you should use the path to the sketch folder as 'PROJECT_ROOT'.
Here's the link:
https://arduino.stackexchange.com/a/9575/7741
Hope it helps.

I have the same problem using the Arduino IDE 1.5.6 beta.
Adding the library(s) using the menu (Sketch->include library->something) makes it work until the IDE is closed.


text:
ATmega32u4 bootloader
Hey all this would be my first encounter needing to burn the Arduino IDE bootloader onto a blank ATMega32u4 that I bought from Digikey.
What all do I need to buy in order to program the bootloader for that chip? In the manual for the 32u4 it says it comes with a bootloader but I'm guessing its not the arduino bootloader?
Is the pinout for the ISP all that I would need in order to upload the Arduino bootloader?
I've seen this post:

but I wont be using the through-hole design.. its going to be the surface mount SMD kind so i wouldn't be able to put that on a breadboard.
So would it be as simple as breaking out the ISP pins on the 32u4 and just hooking those up to a Arduino Duemilanove board even if its not the same ATmega chip (As in copying the atmega32u4 arduino to the Duemilanove and then transferring that to the 32u4?)?

Are you planning to connect to it via USB?

@IgnacioVazquez-Abrams yes i am

The ATmega32U4 already comes programmed with a bootloader that allows programming via USB; once you've added the basic hardware for a USB connection you should be able to use AVRDUDE, FLIP, etc. to upload firmware to the device.
Having said that, putting an ISP connection as per AVR042 is highly recommended regardless.

I know I'm late here, but I'm very interested as to how exactly I would add this "basic hardware"?


text:
Arduino server to read from multiple clients
Socket programming question here.
My interface comprises of an Android device(client), A wireless module hosting an access point, and an Arduino Uno(server).
My Android client class works when 1 user connects and sends commands to my Arduino server class.
I want to make my program friendly to many users at the same time.  My server will only read in values from 1 connected client at a time.
After some research I've found that Arduino does not allow multithreading naturally, which is why i've decided to look into a number of libraries.
The Arduino library that I've decided to use for this specific issue is protothreads.  Unfortunately, i've been unable to find any examples of creating a server with Arduino to accept a client's commands.  Furthermore I'm having a lot of trouble figuring out how to make this library work in my favor.
Now for my question,

How exactly can I allow my Arduino server to constantly listen for
  incoming messages from more than 1 client device?

Or is there something I can do on the client side that would make this communication possible?
A lot of work is handled by my Wifly Module.
I was able to telnet in and set my ipaddress/port#/etc..
Anything sent over IP goes straight through my Module and straight to my arduino.
My
Client Code:
My Server:
WiFlySerial wifi(rxPin ,txPin);

void setup() {
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  pinMode(led, OUTPUT);
}

void loop() {
  //Serial.println("I'm in the LOOP!!");
  androidLed();
  serialLed();

}

void androidLed()
{
  if(wifi.available() > 0){
    data = wifi.read();
    Serial.println(wifi.getDeviceStatus());
    Serial.println(data);
}
}

Without knowing your exact implementation details...
You should be OK as long as you don't have multiple clients connected at the same time. You may think that there are multiple clients connected to your server, but the connection is closed after the resource is obtained by the client over a protocol.*
The standard flow of a server on Arduino:

A client connects to the Arduino.
The Arduino code realizes this connection and reads the data provided by the client.
The Arduino then sends some data back to the client.
The Arduino closes the connection and waits for another client to connect.

This happens relatively fast so multiple people can connect.
If you call a function like .close(); after you send data to your client, you should be okay. If you don't, redesign your code to have this element (avoid loops and blocking functions) and make sure to have your client reconnect every time it sends a command.
I wouldn't mess with this and Protothreads because I'm not sure that the Arduino hardware is designed to be able to handle multiple connections at the same time. [Citation needed]

Good, I was hoping I was overthinking this.  I'm not using a .close() and maybe put too much focus on the android aspect of my code.  I will try this and see if it works.

@TheTokenizer are you using the Ethernet shield connected to a wireless access point or what?

I'm hosting an AP using an RN-131C.  A wifly wireless module.  With this I am able to create my AP and send commands through it via my Android device.  I am using my Arduino as a server to respond to these commands and I am using the Wifly Serial Library.

@TheTokenizer you are doing this a different way than I thought. Can you post a minified working example of your code so I can look at it and see if it closes the connection each time? (I.e. remove everything except what's needed to make a connection)

This is my working code with only 1 android device sending signals.. I'm going through the library and looking for close/open functions that would be of use now.

@TheTokenizer looking at that it seems like it's using a UART type of protocol. I'm afraid that this device only allows one connection at a time at the hardware level, forget the software level.

IS there no work around?

I don't know I'm looking it up now

@TheTokenizer does it even compile right https://github.com/perezd/arduino-wifly-serial/blob/master/WiFlySerial.h that says that there is no available() in that library...

Let us continue this discussion in chat.


text:
serial char read first letter if it is ";" print char without fists letter
I'm working on a project and I need to print serial to a LCD but only if the first letter of the serial is ":"
I have the serial being stored in a char and a if statement reading the first letter of the char to see if it is ":" From there I can't get it to print to the LCD without the first letter. I also don't know how to clear the char.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

char inData[20];
char inChar;
byte index = 0;

void setup(){
 lcd.begin(16, 2);
 Serial.begin(9600);
}

void loop()
{
  while(Serial.available() > 0)
  {
      if(index < 19)
      {
      inChar = Serial.read();
      inData[index] = inChar;
      index++;
      inData[index] = '\0';
  }
 if(inData[0] == ':') {
   lcd.print(inData);
   }

  }
 }

I'm voting to close this question as dead. It had been answered, but not accepted and the OP has disappeared more than a year ago.

The answer to this question has been accepted. So what is the issue?

Tell it to print starting from the second character.
lcd.print(inData + 1);

ok seams to work but when i do ":test" in serial monitor i get "ttetestest" any ideas

That's because the rest of your code is wrong.

whats wrong with it and do u know how to fix it?

Have you looked at your output yet?

what you mean? when I type ":test" the LCD says "ttetestest"

Yes, but have you actually looked at it?

well ya it is printing the first letter than the other letter in the char. i under stand what going on with it but dont know how to fix it. i need it to be just one work "test" not print the letters in the char in order.

Consider this question: How often are you outputting?

i did some messing around with the code and fixed it but i still need to clear the char and i dont know how.


text:
How would I go about scrolling a name across a LoL shield with a potentiometer?
I am fairly new to Arduino programming and I have been set with the task of scrolling my name across a LoL shield with a potentiometer. I really don't have any idea how to do this and when I tried to look it up online there is nothing for such a task. I did look at the library references on the LoL shield website but I couldn't make sense of it.
What I did find was a LoL shield sequencer to allow animation on the LoL shield and I figured that might help but I don't know how to use that code to create a scrolling effect with a potentiometer.

What does "with a potentiometer" mean?

@IgnacioVazquez-Abrams I think it means that the text is "linked" to the string (i.e. 0% = first part of string, 50% = middle of string, etc.)

i mean the position of the text is controlled by the current position of the potentiometer. so as the potentiometer is rotated the text scrolls across the screen. if the potentiometer stops then so does the text.

You know how wide the display is. You know how wide the text is. You know the position of the potentiometer. With those you can determine where in the text (if the text is wider) or display (if the display is wider) you need to start drawing from and where you need to stop drawing. Subtracting the text width from the display width will give you the range for performing linear interpolation with the pot position.

The LoL shield library now supports exactly1 what you want.
If you choose the LoLShield_FontTest example it will scroll "HELLO WORLD!" across your shield. Change your text as required.
static const char test[]="HELLO WORLD!   ";

Example of the word "WORLD":

And in higher contrast to make it more obvious:

(1) Except for the potentiometer. In the example code where it automatically scrolls:
  for (int8_t x=DISPLAY_COLS, i=0; ; x--) {
    LedSign::Clear();
    for (int8_t x2=x, i2=i; x2<DISPLAY_COLS;) {
       int8_t w = Font::Draw (test[i2], x2, 0);
       x2 += w, i2 = (i2+1) % strlen(test);
       if (x2 <= 0)  // off the display completely?
         x = x2, i = i2;
       }
       delay(500);
    }

You would amend it to do an analogRead to set the position of x.

Example of using a potentiometer
Based on the Charliplexing example, the code below uses a pot connected to A0 to control the scroll position:
#include "Charliplexing.h"
#include "Myfont.h"

char * test = "full ASCII charset: $ % & ! [ ] { }";
int len; // length of this string

void setup()                    // run once, when the sketch starts
{
  LedSign::Init();
  len = strlen (test);
}

void loop()                     // run over and over again
{
  // start empty
  LedSign::Clear();

  int potReading = analogRead (0);  // read A0
  int i = map (potReading, 0, 1023, 0, len * 6);  // starting pixel

  for (int j = 0; j < 14; j += 6)
    Myfont::Draw(j, test[(i + j) / 6]);

  delay(100);   // hold that image for a moment

}

I would expect to see a call to analogRead() if it supported using a pot though.

True, I left that change as an exercise for the reader. I thought the scrolling text part was the hard part, making the pot choose the position would be the easy part.

Could you please explain how to use the potentiometer to control the scrolling of a word. I have used examples and I have my word scrolling across the shield but have no idea how to control it with a potentiometer. Thank you

Ignacio's answer describes the idea. You take a reading, and use that to adjust where to start displaying the text from the middle of the string you want.

I have set two values for the potentiometer one below 127 and one above 127. So if I turn the pot one way I want the word to scroll to the right and if I turn the pot the other way the word scrolls in the other direction. I do not know how to write the code to apply this reading. Any code examples or points in the right direction would help.

Please stop posting questions as "answers" - this isn't a forum. If you want to ask your own question I suggest you start a new one. Include the code you are using in it.

See amended reply.


text:
Extremely cheap "Arduino" for single tasks?
I have been thinking of a million things to do with my Arduino, but those things are extremely simple and it would leave my Arduino as a $25 waste.
For example, programming Arduino to control my living room lights with my smartphone ... I was thinking of connecting the Arduino in the wall, onto the light switch wires. I am looking for a "permanent" solution, but I figure this would leave me with a $25 waste of circuitry inside my wall.
Are there any "Arduino" types of electronics that perhaps have many less ports, JUST enough to get a single task done?

How much are you willing to learn about electronics?

That would be more than 25 bucks... Controler, relay panel, communication (from $5 Bluetooh to $50 wifi). And what do you think would control the lights from your phone? Capacitors?

@IgnacioVazquez-Abrams As much as I can.

@Martynas Yes I figured that too, since I needed the Bluetooth add-on and perhaps even a USB board.

Digispark comes to mind, or any of the ATTiny breakout boards at Tindie. Or, make your own PCBs, I just now finished soldering a few ATMega328p circuits to boards I designed. Microcontroller is $1.50, PCBs range from $2 to $8 each, time is "free."
Also consider "compatible with" designs; while you're not directly supporting the ecosystem, if you've already paid full price once and your conscience is clear, eBay has plenty.

Perfboard will also work, if your circuit isn't too complicated.

You can embed a bootloaded ATMega328 (or any of the other compatible ATMega processors) http://arduino.cc/en/pmwiki.php?n=Main/Standalone in your project. That way, you will only need the processor and a couple of components, setting you back only a couple of dollars and saving quite a lot of space:
http://arduino.cc/en/pmwiki.php?n=Main/Standalone
If that is one bridge to far, you can have a look at the Arduino Pro or Arduino Pro Mini. Those boards are complete boards, only smaller and cheaper, and specifically designed for a more definitive use in projects.
If you need even more space and cost reduction, you can switch to a stand-alone ATTiny processor. The better models of those can also contain an Arduino program. Instructables has this great tutorial that shows you how to use an ATTiny85 or ATTiny45 as a lightweight 'Arduino'.
Recently, I have tried to use an ATTiny13A for a project, but that one only has 1KB of flash memory, which leaves you with hardly any space for the Arduino bootloader, let alone your program, so therefor I chose to program it directly using AVR Studio, at which point I think you cannot in any way call it an Arduino project anymore. :) Still, it's not that different. You only miss out on some of the library functions, and the implied application loop.

This is a typical scenario for an Arduino Uno board: you buy one and use it for prototyping your project. Once done, you design your own PCB, as small as possible, connecting only the required wires to the ATMega328p.
For the next project, you buy another ATMega328p (just the MCU), plug it on the Uno and start again.

Is there any link you can provide that describes the entire process of what you said? Sounds very interesting but I am new to Arduino and Electronics. Thanks!

One example is this instructables: http://www.instructables.com/id/DIY-Arduino-or-The-DIY-Duino/. Printing your own PCB is fairly easy using Fritzing https://www.youtube.com/watch?v=Hxhd4HKrWpg

I've had the same exact problem.
Since I like developing using the Arduino IDE I've created an how to assemble a board using just Thru Hole Components to replace the Official board.
Please visit the following link for further information http://jpralves.net/cseduino
All the components will cost about 5 USD.

Welcome to Arduino SE! Can you please add the schematic into this post so it still has value if your site would go down? Thanks!

There are good instructions here:
http://arduino.cc/en/Main/Standalone
and here:
http://arduino.cc/en/Tutorial/ArduinoToBreadboard
Alternatively you can go for an Arduino mini http://arduino.cc/en/Main/ArduinoBoardMini or a corresponding Chinese clone.


text:
Trouble reading from multiple analog ports
So I'm trying to read 4 different analog values and store each one to a variable.  I imagine doing this by first initializing the ADC registers and each time it enters the ADC ISR checking which port it read from and saving it to the corresponding variable.  Then setting the ADMUX to the next ADC port and repeating the whole process.  Unfortunately something goes wonky and I just can't figure out what it is.  If I get rid of the switch case and just read from one port it all works fine, but if I put the switch case back in and try to cycle through them it stops working.  Please ignore the rest of code as this is not complete.  I just included everything I could.  Eventually this will take in 4 values.  Then use them for error checking and a PID loop.
Thanks for any help!
/*
 * Throttle_by_Wire.c
 *
 * Basic throttle by wire controller
 * for the 2015 Formula Hybrid car
 *
 *  Created on: Nov 24, 2014
 *  Author: Austin R. Bartz
 *
 *  Pin Connections:
 *      PB2 - Motor Speed (Enable pin) (PWM)
 *      PB4 - Direction control (Counter-Clockwise)
 *      PB5 - Direction control (Clockwise)
 *      PC0 - Throttle Pedal Sensor A (TPA) (Shallower Slope)
 *      PC1 - Throttle Pedal Sensor B (TPB) (Steeper Slope)
 *      PC2 - Throttle Valve Sensor A (TPSA) (Negative Slope)
 *      PC3 - Throttle Valve Sensor B (TPSB) (Positive Slope)
 */

#include <avr/io.h>
#include <avr/interrupt.h>
#include <inttypes.h>
#include <stdlib.h>

uint16_t TPA = 0;
uint16_t TPB = 0;
uint16_t TPSA = 0;
uint16_t TPSB = 0;
uint16_t analogpin = 0;

long map(long x, long in_min, long in_max, long out_min, long out_max);

int main(void)
{
    //Configure ADC for single shot conversion
    ADMUX |= (1<<REFS0);
    ADCSRA = (1<<ADEN)|(1<<ADSC)|(1<<ADIE)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
    DIDR0 = (1<<ADC4D)|(1<<ADC3D)|(1<<ADC2D)|(1<<ADC1D)|(1<<ADC0D);
    //Configure timer/counter1 for FastPWM
    TCCR1A = (1<<COM1B1)|(1<<WGM11)|(1<<WGM10);
    TCCR1B = (1<<WGM13)|(1<<WGM12)|(1<<CS10);
    OCR1A = 800;    //20kHz
    //Set motor control pins as outputs
    DDRB = (1<<PB2)|(1<<PB4)|(1<<PB5);
    PORTB |= (1<<PB5);
    //Enable global variables and interrupts
    sei();

    while(1)
    {
        //Control PWM % to motor
        OCR1B = map(TPA, 0, 1023, 0, OCR1A);
    }
}

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

ISR(ADC_vect)
{
    //Save current conversion's ADC value
    analogpin = ADMUX & 0b00001111;
    switch (analogpin)
    {
    case 0:
        TPA = ADCW;
        //Increment ADC port to ADC1
        ADMUX |= (1<<MUX0);
        break;
    case 1:
        TPB = ADCW;
        //Increment ADC port ADC2
        ADMUX &= ~0b00001111;
        ADMUX |= (1<<MUX1);
        break;
    case 2:
        TPSA = ADCW;
        //Increment ADC port to ADC3
        ADMUX &= 0b00001111;
        ADMUX = (1<<MUX0)|(1<<MUX1);
        break;
    case 3:
        TPSB = ADCW;
        //Reset ADC Port to ADC0
        ADMUX &= ~0b00001111;
        break;
    }
    //Start next conversion
    ADCSRA |= (1<<ADSC);
}

Case 2 is missing the ~ and does not clear off the low 4 bits

ADMUX &= 0b00001111;

should be this to clear off the MUX selection bits:
ADMUX &= ~0b00001111;

Also, you have no default case.  I would agree that by design the bits can only contain the values 0-3, but what happens if it ends up 4?
The bit manipulation is hard to follow.  I would implement like this:
ISR(ADC_vect) {
  uint8_t nextMux;

  //Save current conversion's ADC value
  analogpin = ADMUX & 0b00001111;
  switch (analogpin) {
    case 0:
      TPA = ADCW;
      nextMux = (1<<MUX0);
      break;
    case 1:
      TPB = ADCW;
      nextMux = (1<<MUX1);
      break;
    case 2:
      TPSA = ADCW;
      nextMux = (1<<MUX0)|(1<<MUX1);
      break;
    case 3:
      TPSB = ADCW;
    default:
      nextMux = 0;
  }
  // set mux for next conversion
  ADMUX &= 0b11110000;
  ADMUX |= nextMux;

  //Start next conversion
  ADCSRA |= (1<<ADSC);

  return;
}

I like the consistent pattern of this because it makes errors easy to see.  With respect to code space, a few bytes should be saved.  Execution time wise, it adds one |= to the case 3.

I looked at the original, and gave up because frankly it is too hard to follow the code. If you followed better programming practice e.g. using a #define for ~0b00001111 it would be easier to follow (and less error prone).

@jdr5ca Thank you!  I changed the code to your suggested segment and it works perfectly now!  I apologize for the unclear bit manipulation.  I just started learning how to do all this last quarter (I'm a second year electrical engineering student) so it's still all relatively new to me.


text:
Arduino Leonardo is not recognized by usb cable in Windows 8
My Arduino Leonardo was working properly but for the last two hours when I connect it to a PC via a USB cable, it is reporting something like USB is not recognized and even in device manager it is not showing. However, when I press the restart button on the Arduino, the PC will detect it as an Arduino Leonardo bootloader(com 7) but after few seconds it disappears. What do I have to do? I tried to restart the PC, changed USB cable but the same issue occurs. I checked the USB by connecting another device - it works fine but the Arduino is not recognised.
I tried other PCs also but the same problem continued. What do I have to do?

It is highly likely that the sketch you loaded is causing this.

However, when I press the restart button on the Arduino, the PC will detect it as an Arduino Leonardo bootloader(com 7) but after few seconds it disappears.

For a few seconds after reset the bootloader will configure the board as a USB serial device, awaiting upload of a new sketch. Once that times out it runs the existing code. If the existing code does not configure the USB port (eg. by doing Serial.begin) then it will cease to enumerate as a USB device. This is perfectly normal.
The "fix" is to upload a sketch that uses the USB interface. For example, open a serial port, open the keyboard (Keyboard.begin()) or similar.

Nick Gammon's solution worked for me. I am adding the arduino code I used below.
While Arduino Leonardo is connected to your computer, press its reset button. A COM for Arduino Leonardo appears under the Arduino IDE: Tools > Port:
You should upload the code within a few seconds just after you press the reset button while the Leonardo COM is appearing.
The following is the code I used:
// Start of Code

void setup() {
  // make pin 2 an input and turn on the
  // pullup resistor so it goes high unless
  // connected to ground:
  Serial.begin(9600);
  pinMode(13,OUTPUT);
  digitalWrite(13,HIGH);
  pinMode(2, INPUT_PULLUP);
  Keyboard.begin();
}

void loop() {
  //if the button is pressed
  if(digitalRead(2)==LOW){
    //Send the message
    Keyboard.print("Hello!");
  }
  delay(1000);
  digitalWrite(13,HIGH);
  delay(1000);
  digitalWrite(13,LOW);
}

// End of Code

It is more reliable the other way around: Start the upload process and wait for the "PORTS ..." lines to appear (in the Arduino log window at the bottom of the screen). Only then press the "RESET" button.

It could be the settings of the serial port (you mentioned com 7). Try going on your Arduino Integrated Development Environment.
Go to Tools > Serial Port > (and try putting this setting on different serial ports)
If the Serial Port is grayed out and you cant press it, try restarting the Arduino with the restart button, and hopefully you will have an opportunity to change the Serial Port in those few seconds that the Arduino is recognized. Try all the different Serial Ports your computer has.


text:
How to make MEMS IR Thermal Sensor - D6T-44-L06 work with Arduino?
I am working on project that my team need to detect the presence of the people. At first, we tried with motion sensor but it wasn't the way that we want it to work. We want to detect presence of the people even they don't move.
We decide to go with Omron Thermal Sensor D6T-44-L06. However, there lacking of tutorial or simple code online that actually show how to connect that Omron thermal sensor with Arduino. How can I interface this with Arduino?

Yes should be really easy to implement, as it work like almost all i2c sensor; this manual as also some code example, the chip address, and finally the registry address; that is all you need.
http://www.mouser.com/pdfdocs/D6T01_ThermalIRSensorWhitepaper.pdf


text:
Garbage value Serial Monitor
I am building my own arduino.Here is my code Below. I found code working for Digital Ios like blink example ; analog reading, Problem i am facing in Serial Monitor.Whenever i open Serial monitor i get trash values.I have choose proper crystal & proper values.  Please let me know possibility for getting trash values
int led = 2;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  Serial.println("Welcome:");
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(100);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(100);               // wait for a second
}

One of my projects does this too. I leave it connected to a USB port for power so it can control a room fan. Every 4 seconds it writes a line of data to the serial output. When I open a serial terminal on the computer, I immediately see a short stream of garbage, followed by the next, and all subsequent log outputs, properly displayed. It looks as if the serial-to-USB chip has some data buffered in it which it delivers, but out of sync, as soon as the terminal connection is made, but this is just a guess.
Have you tried resetting your chip while the terminal is connected? When I do this, there are no sync issues and the displayed data is all valid.
Update:
If you only ever get garbage from your terminal, then it's likely the terminal and the Arduino aren't matched for one or both of baud-rate or frame-size.
Arduino serial hardware uses an 8N1 frame: 8 data bits, No parity bit, 1 stop bit. Your serial monitor must be set to match this (and it probably is, since this is the most common convention, but worth checking.
Second, the baud rates must match. You've set the Arduino for 9600 baud and your serial monitor program must be also (from your screenshot, it looks like it is).
You said you are using a crystal so it quite unlikely that Arduino's 9600 baud is inaccurate, but this could happen if you were using its internal clock source.
Finally, in the lower left corner of your serial monitor screen shot, it looks like you have selected "No line endings". Serial.println() ends every line with CR/LF. See if that is an available line-ending setting. It is sometimes named "OD OA" (the hex values for Carriage-Return and Line-Feed). Try that setting if it is available.
The serial protocol is one of the oldest communication protocols but it has many variations. (Did someone say "standard"? :-)  Everyone gets bitten by it, eventually.

I have done these many time. Previous board working fine. I have changed The IC also; Even i tried reset while Upload. But still Gives above issue. COde seems working fine only problem i am facing Serial Monitor.

Opening a Serial connection will reset your arduino and restart the whole program.
I learned this the hard way when coding a windows serial com-monitor for triggering systemcalls from arduino


text:
datalogging sampling frequency bottleneck
My datalogging system which consits of the Flora, RTC, SD card breakout board, LSM9DS0 sensor is shown in the picture below;
https://www.dropbox.com/s/d8pwcn59nq11lzs/2014-11-25%2012.26.56.jpg?dl=0
The sampling rate/s is capped at 30 when writing into the sd card. If I disable the sensor and only save the time it goes up to 65. Writing into the serial interface rather than the sd card makes the rate goes up even higher at 127. for my application I need at least 100 samples/s. I am thinking the sd card is the problem after making the tests mentioned. The flora clock at 16Mhz is surely able to provide a higher sampling frequency. After checking the sensor datasheet and library I haven't found any limitation either. any input on this issue?

We can't help much without any code.

What sd card model do you use? Write performance varies a lot between models.

SD cards have a lot of intermittent delay.  To stream to them well, you need to buffer a full sector worth of samples to write at once, and have spare buffer memory to hold incomming samples across the maximum expected SDcard delay until you can write to it again.  You will need a primitive form of multitasking, even if as simple as collecting your samples in an interrupt.

Add some debugging code that writes "Serial.println( millis() )" before and after the SD card write so you can figure out how long it's really taking (is that really the bottleneck?). Then make a short demo program that demonstrates just the bottleneck, post it here and let us help you make it better.

First, based on my experience with similar hardware, something about the sd card I/O stinks: it should be plenty fast enough. Using a class 4 (cheapo) sd card I've seen a 16mhz AVR do a FAT filesystem open for appending, write a new record of maybe 70 characters and close the file, all a few hundred times per second. This was with the Arduino "SD" library apparently written by Sparkfun in 2010 and improved by Adafruit sometime later.
Maybe the I/O library you're using is dog slow? Another possibility is that your SD card has a lot of files on it and something about directory (folder) traversal during an open is the bottleneck? (my experience is with just a few files on a given sd card)
But you could try buffering N samples so each sd card write records N samples.
If you do this, don't forget to "flush" any remaining samples when you go from "sampling" to "not sampling" modes, if that's possible. That is, if something is telling the thing 'start', then 'stop', part of the response to 'stop' is to get the N-m buffered samples written out to the sd card.

I have used Sparkfun's OpenLog as I have also found the SD library slow when writing many small samples.  It lets you log directly from the Serial connection, so you should be able to get at least the 127 samples per second.  You may also try increasing the baud rate, especially if you are using outputting to Serial.


text:
Arduino Mega2560 Hardware ID
Do all Arduino Mega2560's have the same VID/PID identification numbers when seen by a PC as a device? I am planning on designing I specific driver to work with the 2560 and wondering if I will be able to use the same driver for multiple Arduino. Can anyone confirm this? Thanks!

VIP/PID is realized by Atmega16u2 driver which implements USB device driver. Probably all revisions of *Arduino Atmega2560*s has implicitely the same VID/PID. Each piece has unique serial number. But you can upload own firmware into 16u2 to modify USB as you wish (ideally using LUFA library). It's clean solution for production hardware because you cannot use Arduino VID because of USB rules.


text:
Can a DC motor use more current than its datasheet?
I am using small dc motors connected to the 5V of the arduino which is known to provide 200mA without damaging it.
The motor I am using is a very common one found in toys -> https://www.sparkfun.com/datasheets/Robotics/ROB-09608.jpg
As I see the maximum current of this motor is 170mA. Does it mean that the motor will not drain more current than that or it means that I need to use a resistor in series with my 5V in order to make sure the current will not pass 170mA?

Note that (like you say) the 200mA is the limit of the VCC pin only. For the IO pins there is a safe limit of 40mA. See the playground for the numbers.

YES (typically resulting in melting the coils). The current used by standard or brushless motors is related to the voltage applied and the load applied. As you approach the load limit, current rises over the limit. There are many ways to control this but controlling the load is the easiest way. DO NOT run the motor through the Arduino even if you think it will be under the 200mA limit. Motors produce a lot of spikes and back-flow.
Here's a tutorial on safely running a motor and controlling the speed: https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/overview

Thank you so much. But if in the specs of the motor says that it consumes 170mA should I even use a resistor if my source provides more than that? I will not connect it to arduino, you told me it will damage it I will not. I will use an external plug that provides 9 V (same as motor) but it provides 1A. Do I really need to use a resistor in this 1A? I think the motor will only consume what it is designed to, isnt?

No, there is nothing about the motor itself that limits the current that will be used. The rating of the motor is how much current it can handle before something fails - usually the insulation on the coil wires overheats and melts, causing shorts and destroying the motor. I have photos of that kind of damage somewhere. It was caused by too much weight/load on the motor. Tuning the current load involves tuning the actual load on the motor. Most motor usages never come close to the limit, so people tend to ignore this issue sometimes. ALL the example programs are like that.

thank you I didnt know that. I believed that the current specified in the motor datasheet was the current it was gona use and nothign else even if I provided more current. I just did not understand this phrase of yours "Most motor usages never come close to the limit,". If I provide more current, according to you the motor would pass the limit, isnt? Or am I wrong?

What I meant by that is, in the examples, they are not loading the motor with a significant load, so they don't need to use any current-limiting scheme. It's such a light load you don't have to worry about it. I would bet most of the examples from the tutorials pull about 30mA from that motor. They are "playing it safe" with the examples, but if you want to get the most from your motor, you won't be playing it safe.


text:
USART RX Interrupt on an ARDUINO PRO MINI containing factory bootloader
Is it possible to use RXC Interrupt vector with the factory programmed bootloader still existing in the arduino pro mini?
I've written a simple echo program using RXC interrupt vector, the program prints "READY" on startup but as soon the chip receives the first character it goes into a repetitive reset loop i.e. I keep receiving READY READY READY.. so on.
I've checked the program multiple times and I think its the bootloader, I think the bootloader has shifted the interrupt table to the boot section before executing the application. Is that so?
Thanks in advance.

Could you post the code?

Once the bootloader transfers control to the main code (sketch) it may as well not exist any more. It does not affect the way the sketch runs.

I've written a simple echo program using RXC interrupt vector ...

Please post this code. For you to print "READY" you are (presumably) using the Serial port, in which case the HardwareSerial interrupt vectors are being used. I don't know how you managed to take over those vectors. Seeing your code might answer that.

Hi Nick, I can't locate the code, its ancient now, sorry. I encountered this error while I was doing some quickie code. I had to use some arduino based libraries and I also required to use the Rx interrupt. As Far I remember, I wrote the usual winavr style ISR after importing avr/interrupt.h    That time, I think, my code was causing restarts and I kept getting READY READY READY. As you say, I did use the Serial port( Serial.print )and inside main() I printed READY. I think I should not have used the interrupt vector as it was already used by the arduino Serial port.


text:
Saving data in a globally declared float array
I'm trying to send 60 float values via serial. Numbers are provided by an accelerometer and saved in a 240 bytes-long array. The array is sent to a function and these values are then copied in a structure.
The problem
The content of the array is still correct when the function is called. Then, when I copy it in the structure, something wrong happens and data are modified after the 26th float.
Where does the modification of an array of floats take place?
void sendBuffAcc(float a[])
{
  int stepCont = 1;

  // Prints the content of the globally defined array buffXAccToSend
  Serial.println();
  for (int i=0;i<sizeBuffAcc;i++)
  {
    Serial.print("val: ");
    Serial.print(i);
    Serial.print("    ");
    Serial.println(buffXAccToSend[i]);
  }
  Serial.println();

  MyShortCommand * pMyCmdShort = (MyShortCommand *)(&bufferAcc[sizeof(MyControlHdr)]);

  for (int i=0;i<sizeBuffAcc;i++)
  {
    Serial.print("val: ");
    Serial.print(i);
    Serial.print("| Global Array:");
    Serial.println(buffXAccToSend[i]);

    numFilterValuesToSend++;

    pMyCmdShort->cmd = accValuesID;
    pMyCmdShort->param1 = a[i];
    pMyCmdShort->param2 = 0;
    pMyCmdShort->param3 = 0;
    pMyCmdShort->param4 = 0;

    Serial.print("|   Param: ");
    Serial.print(pMyCmdShort->param1);
    Serial.print("|   Array:");
    Serial.println(a[i]);

    // Move the pointer to save data in next positions
    pMyCmdShort++;
  }
  stepCont++;
 }
 storeAccData = false;
 contBuffAcc=1;
}

First, the content of the global array buffXAccToSend is printed via serial, then the i-th elements of a[i] and the value assigned to the pMyCmdShort->param1. This is the output:
val: 0    -0.00
val: 1    -0.00
val: 2    0.01
val: 3    -0.01
val: 4    0.04
val: 5    0.00
val: 6    0.01
val: 7    0.03
val: 8    0.01
val: 9    -0.00
val: 10    0.00
val: 11    -0.01
val: 12    -0.00
val: 13    0.01
val: 14    -0.02
val: 15    0.03
val: 16    0.00
val: 17    0.02
val: 18    -0.01
val: 19    0.00
val: 20    0.00
val: 21    -0.00
val: 22    -0.01
val: 23    -0.01
val: 24    0.01
val: 25    0.01
val: 26    -0.00
val: 27    0.03
val: 28    -0.01
val: 29    -0.00
val: 30    0.04
val: 31    -0.01
val: 32    0.01

val: 0| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 1| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 2| Global Array: -0.01|  Param: -0.01|  Array: -0.01
val: 3| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 4| Global Array: 0.02|  Param: 0.02|  Array: 0.02
val: 5| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 6| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 7| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 8| Global Array: 0.04|  Param: 0.04|  Array: 0.04
val: 9| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 10| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 11| Global Array: -0.00|  Param: -0.00|  Array: -0.00
val: 12| Global Array: -0.01|  Param: -0.01|  Array: -0.01
val: 13| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 14| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 15| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 16| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 17| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 18| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 19| Global Array: 0.03|  Param: 0.03|  Array: 0.03
val: 20| Global Array: -0.01|  Param: -0.01|  Array: -0.01
val: 21| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 22| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 23| Global Array: 0.01|  Param: 0.01|  Array: 0.01
val: 24| Global Array: -0.01|  Param: -0.01|  Array: -0.01
val: 25| Global Array: -0.02|  Param: -0.02|  Array: -0.02
val: 26| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 27| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 28| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 29| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 30| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 31| Global Array: 0.00|  Param: 0.00|  Array: 0.00
val: 32| Global Array: 0.00|  Param: 0.00|  Array: 0.00

This is the output of avr-size:
   text    data     bss     dec     hex
  55828    3906    2978   62712    f4f8

Is it a memory related problem?

What does avr-size say about the final executable?

@IgnacioVazquez-Abrams Please see the output of the command

Are you doing any dynamic memory allocations? can you post the full code?

Please post a Minimal, Complete, and Verifiable example. Not seeing the data declarations, nor the value of sizeBuffAcc it is impossible to tell what the issue is.

The ATmega328P has 2kiB of SRAM. Your program uses almost 3kiB. Move strings and constant values into flash.

Thanks for the suggestion but I'm using the Mega 2560 which has 8KB of SRAM.

I will modify the sketch with PROGMEM as you suggested.


text:
Why is my transistor getting very hot when controlling a 12V peristalic pump?
I have followed this tutorial:
http://www.instructables.com/id/Automatically-water-your-small-indoor-plant-using-/?ALLSTEPS
Every time i try to run my circuit, My transistor gets very hot and breaks.
I have exactly the same parts as the tutorial. I have also tested the circuit with 3.3V Power supply and a diode instead of an engine, this works.
I am super thankfull for any answers.

What do you mean by "breaks?" Can you please add more information to your post? Thanks!

I would be surprised if it worked. As far as I can tell (from the poor instructions) he is connecting the base directly to the Arduino pin. This would overload the chip, although the inbuilt current limiter would protect it. I certainly wouldn't use a PN2222 to switch 300mA.

As @Milliways suggested, you need to add a resistor between the arduino pin and the transistor. Around 1k will do.

Measure the Current through the motor, the PN2222 can pass a maximum of 600mA.
I would guess that just over half an amp would be enough for the motor but you can check what you motor is trying to pull by connecting it to 12 V direct and measure the supply current.
The only thing that will make the transistor hot is excess current


text:
Arduino to Arduino Communication using HC05
I have been working on a project for work ( I'm a waiter :/ ) I was tasked to build a food wait time display that receives input from the kitchen and echoes the time via bluetooth to another display.
So that we are all on the same page I will describe what I have built and where I am stuck.
Before I do, I would like to state that I have:

been planning and prototyping this thing for over a month
googled/crawled all over the web looking for answers
read the entire manual on the HC05 module
Bound both of the bluetooth modules via AT commands One as Master the  other as Slave

Now with that out out the way here is what I have so far:

2x Arduino uno R3
2x 16x2 LCD Display
2x HC05 Bluetooth Modules (1 set as Master the other as Slave & bound using AT Commands)
2x 10K Potentiometers for adjusting the contrast
3x Momentary push Button switches on Master with pull-up resistors (timeUp, timeDown, sendButton)

Here is where I am stuck. UPDATE
I was able to get the master and slave to communicate. RX and TX on master were crossed... SMH! However now the issue is that the slave is writing both digits it receives on top of itself. First writing one digit then clearing it and then the second digit...
Enough with the prologue here is the a code:
Master
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //sets up LCD pins
int waitTime = 10; //if food comes quicker than there is no need for a display ;)
const int timeUp = 6;
const int timeDown = 7;
const int sendButton = 8;
int timeUpState = 0;
int timeDownState = 0;
int sendButtonState = 0;

void setup() {
  Serial.begin(115200);
  pinMode(timeUp, INPUT);
  pinMode(timeDown, INPUT);
  pinMode(sendButton, INPUT);
  lcd.begin(16, 2);
  lcd.print("  Sam Kullman's"); //Splash screen on start up
  lcd.setCursor(0,1);
  lcd.print("      Diner"); //Splash Screen
  delay(2000);        // Delay intended to allow the device to pair prior to use.
  lcd.clear();
  lcd.print("Essen Dauert:"); //German for "Food takes":
  lcd.setCursor(0,1);
  lcd.print("   Minuten"); // xx minutes
  }

void loop(){
  lcd.setCursor(0,1);
  timeUpState = digitalRead(timeUp);
  timeDownState = digitalRead(timeDown);
  sendButtonState = digitalRead(sendButton);
  if (timeUpState == LOW) {
  waitTime += 5;
  delay(500);  //debounce button
  lcd.print(waitTime);
  }

  if(waitTime > 90){ // Max limit for wait time
    waitTime = 10;   //default wait time
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Essen Dauert:");
    lcd.setCursor(0,1);
    lcd.print("   Minuten");
   }

 if (timeDownState == LOW){
  waitTime -= 5;
  delay(500);
  lcd.print(waitTime);
  }

  if(waitTime < 10){ //Min value waiting time
    waitTime = 10;
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Essen Dauert:");
    lcd.setCursor(0,1);
    lcd.print("   Minuten");
   }

  if(Serial.available()){  // **This is where I am stuck**
   if(sendButtonState == LOW){
   Serial.write(waitTime);
   delay(500);
  }
 }
}

Slave
#include <LiquidCrystal.h>

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

void setup() {
  Serial.begin(9600);
  Serial.flush();
  lcd.begin(16, 2);
  lcd.print("  Sam Kullman's");
  lcd.setCursor(0,1);
  lcd.print("      Diner");
  }

void loop(){

  if (Serial.available()) {
   int waitTime = Serial.read();
    delay(200);
    lcd.clear();
    lcd.print("Essen Dauert:");
    lcd.setCursor(0,1);
    lcd.write(waitTime);
    lcd.print(" Minuten");
     }
  }

Thanks in advance,
Jonathan

You'll might need debouncing here...

@AnnonomusPenguin Is the delay(500); after the state change not enough or in the wrong place? After some web crawling on "debouncing" I'm pretty sure I have denounced the buttons, or are you suggesting I take a hardware approach to denounce the buttons? I don't have an oscilloscope so I can't see exactly how the buttons are behaving.

no need for a hardware approach not a scope. If someone is trying to add 20 minutes, they are going to push it very fast, not every half of a second. You're going to miss some of the presses. There are some software libraries that I would consider if that's too big of an issue. Yes, it helps with debouncing, but it isn't the most ideal situation.

What libraries are you referring too?

something like Bounce

any reason NOT to use the I2C bus for master/slave communication?

The problem was how I was reading the incoming serial data.
After changing int waitTime = Serial.read()
to int waitTime = Serial.parseInt()
the code works.
Thanks to everyone for all your help and tips!

lcd.write(waitTime);

This line prints a single byte, whose (ASCII) value is the number in waitTime. You probably should write:
lcd.print(waitTime);

instead, which prints the number in waitTime using one ore more digits as needed.
This doesn't 100% explain the "both digits end up in the same place" symptom, since I'd expect random junk to be printed instead. But I'm pretty certain this is a problem, perhaps there's more problems :-)

Thanks for the tip, however when I use lcd.write(waitTime) I get the DEC value and lcd.print(waitTime)gives me the ASCII i.e.. 49 for 1 etc.


text:
Interfacing arduino due to MAX5724 DAC
I have a MAX5724 8 channel 10 bit DAC's connected to a due, i believe i have it wired up correctly, however when  i try to write a value to it doesn't seem to output anything. Either i misunderstood the datasheet in the wiring or im writing incorrectly to it. Since i have the LDAC connected to GND i think i can just use the CODEn command on page 21 of the datasheet.
A link to the datasheet:
http://datasheets.maximintegrated.com/en/ds/MAX5723-MAX5725.pdf
Here the code i use to write:
#include <SPI.h>

#define CS 52

void setup()
{

  Serial.begin(115200);
  SPI.begin(CS);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(CS, 1);
  SPI.setClockDivider(CS, 3); // 28MHz
  pinMode(CS, OUTPUT);
}

void loop()
{
  digitalWrite(CS, HIGH);
  digitalWrite(CS, LOW);

 byte msg1 = 0b11000010;
 byte msg2 = 0b11111111;
 byte msg3 = 0b11111111;

 SPI.transfer(CS,msg1,SPI_CONTINUE);
 SPI.transfer(CS,msg2,SPI_CONTINUE);
 SPI.transfer(CS,msg3,SPI_LAST);
 delay(4000);

}

wiring:
1 = 5V,
2 - 9 = OUTPUT,
10 = 5V,
11 = 5V,
12 = MOSI (middle pins),
13 = MISO (middle pins),
14 = SCK (middle pins),
15 = PIN 52,
16 = OUTPUT,
17 = 5V,
18 = GND,
19 = GND,
20 = GND,

I'm guessing the SAM3X didn't have enough DACs?

You swapped the MISO and MOSI. DIN should be connected to MOSI (Master Out Slave In). DOUT to MISO.

aye i realised my mistake, thanks a lot for you help