body:
I am using an amazing code to send/read infrared pulses without any external library. The code is fine and I took about 1 hour to fully understand it. The only thing I didnt understand is the variable RESOLUTION. I believe it should be 0 not 20. I think it should be as low as possible.

You can see the code at:

https://learn.adafruit.com/ir-sensor/using-an-ir-sensor

or below:

    /* Raw IR decoder sketch!
    This sketch/program uses the Arduino and a PNA4602 to
    decode IR received. This can be used to make a IR receiver
    (by looking for a particular code)
    or transmitter (by pulsing an IR LED at ~38KHz for the
    durations detected
    Code is public domain, check out www.ladyada.net and adafruit.com
    for more tutorials!
    */

    // We need to use the 'raw' pin reading methods
    // because timing is very important here and the digitalRead()
    // procedure is slower!
    //uint8_t IRpin = 2;
    // Digital pin #2 is the same as Pin D2 see
    // http://arduino.cc/en/Hacking/PinMapping168 for the 'raw' pin mapping
    #define IRpin_PIN PIND
    #define IRpin 2
    // for MEGA use these!
    //#define IRpin_PIN PINE
    //#define IRpin 4

    // the maximum pulse we'll listen for - 65 milliseconds is a long time
    #define MAXPULSE 65000

    // what our timing resolution should be, larger is better
    // as its more 'precise' - but too large and you wont get
    // accurate timing
    #define RESOLUTION 20

    // we will store up to 100 pulse pairs (this is -a lot-)
    uint16_t pulses[100][2]; // pair is high and low pulse
    uint8_t currentpulse = 0; // index for pulses we're storing

    void setup(void) {
      Serial.begin(9600);
      Serial.println("Ready to decode IR!");
    }

    void loop(void) {
      uint16_t highpulse, lowpulse; // temporary storage timing
      highpulse = lowpulse = 0; // start out with no pulse length

    // while (digitalRead(IRpin)) { // this is too slow!
        while (IRpin_PIN & (1 << IRpin)) {
         // pin is still HIGH

         // count off another few microseconds
         highpulse++;
         delayMicroseconds(RESOLUTION);

         // If the pulse is too long, we 'timed out' - either nothing
         // was received or the code is finished, so print what
         // we've grabbed so far, and then reset
         if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
           printpulses();
           currentpulse=0;
           return;
         }
      }
      // we didn't time out so lets stash the reading
      pulses[currentpulse][0] = highpulse;

      // same as above
      while (! (IRpin_PIN & _BV(IRpin))) {
         // pin is still LOW
         lowpulse++;
         delayMicroseconds(RESOLUTION);
         if ((lowpulse >= MAXPULSE) && (currentpulse != 0)) {
           printpulses();
           currentpulse=0;
           return;
         }
      }
      pulses[currentpulse][1] = lowpulse;

      // we read one high-low pulse successfully, continue!
      currentpulse++;
    }

    void printpulses(void) {
      Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
      for (uint8_t i = 0; i < currentpulse; i++) {
        Serial.print(pulses
    * RESOLUTION, DEC);

        Serial.print(" usec, ");
        Serial.print(pulses[1] * RESOLUTION, DEC);
        Serial.println(" usec");
      }

      // print it in a 'array' format
      Serial.println("int IRsignal[] = {");
      Serial.println("// ON, OFF (in 10's of microseconds)");
      for (uint8_t i = 0; i < currentpulse-1; i++) {
        Serial.print("\t"); // tab
        Serial.print(pulses[1] * RESOLUTION / 10, DEC);
        Serial.print(", ");
        Serial.print(pulses[i+1][0] * RESOLUTION / 10, DEC);
        Serial.println(",");
      }
      Serial.print("\t"); // tab
      Serial.print(pulses[currentpulse-1][1] * RESOLUTION / 10, DEC);
      Serial.print(", 0};");
    }

title: Why is resolution 20?

Answers: 1

body:
Most IR remotes send pulses that are at least 400 micro seconds long. E.g. on a NEC IR remote you get pulses that are 560 or 2240 microseconds long (depending on whether it's sending a 1 or a 0).

So with a RESOLUTION of 20 you get at least 20 'pulse counts' for a `0` and 80 for a `1`. Because remotes aren't that precise in you'll get somewhere between e.g. 18 and 22 or 78 and 82. Those values are different enough to easily detect whether a 0 or 1 was send.

Changing this RESOLUTION to e.g. 2 will give you 200 or 800 pulsecounts. You'll get a more precise timings from a still imprecise source. But this better precision is useless.

PS setting it to 0 could break the code, as the highpulse and lowpulse are only 16 bit integers so they will overflow after 65536, which will happen pretty fast.

Hope that helps somewhat. Just let me know is anything is still unclear.


body:
I have a code that sends 384 pulses at 38kHz with an infrared LED. It's very easy to understand it. At the beggining the code sends the pulses using the LED and in the middle of the code I check the sensor if it has any signal coming. So far so good, yes? Please, take a look:

    for(int i=0;i<384;i++) {
      digitalWrite(IRledPin,HIGH);
      delayMicroseconds(13);
      digitalWrite(IRledPin,LOW);
      delayMicroseconds(13);
    }

    if (digitalRead(IRsensorPin) == LOW){
      digitalWrite(D13ledPin,HIGH);
    } else {
      digitalWrite(D13ledPin,LOW);
    }

My question is this: I first send the pulses, so when I reach the line `if (digitalRead(IRsensorPin) == LOW){` the pulse should already have passed the sensor. So why does it work? It should not work cause I first send the pulse and then I check for the pulse but as I understand the 384 pulses should already have passed the sensor.

I have no idea why this code works. I would be glad to listen smarter people to help me understand this.

Thank you.

title: How this smal infrared work

Answers: 1

body:
The IR receiver does some filtering on the signal. It doesn't signal a LOW immediately if it lost a single pulse of light. A speck of dust, hanging in the air, might just be blocking the IR phototransitor. Or some brief flash of light, making two pulses seem like one or more.

These IR receivers a specifically build to filter out the 'noise' coming from other light sources and light obstructions.

Identically, you would want this receiver to give you a HIGH if it detect only 2 pulses of light 13uS apart. I could just be some sunlight reflected from a puddle, accidentally matching 38kHz.


body:
I've been trying to work with an [AD5685R DAC](http://www.analog.com/static/imported-files/data_sheets/AD5686R_5685R_5684R.pdf). 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.

title: Why is the output on the MOSI line shifted 1 bit over from what I commanded?

Answers: 1

body:
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)

![SPI Mode 0][1]

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

![SPI Mode 1][2]

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

![SPI Mode 2][3]

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

![SPI Mode 3][4]

---

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](http://www.gammon.com.au/spi)

  [1]: https://i.stack.imgur.com/6jUNq.jpg
  [2]: https://i.stack.imgur.com/RYDAt.jpg
  [3]: https://i.stack.imgur.com/3bNek.jpg
  [4]: https://i.stack.imgur.com/hnOoa.jpg


body:
I'm just starting to discover Arduino. Currently, I've done 2 lessons from Arduino book and I have few questions about second circuit.
![schema of second circuit][1]

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

[1]: https://i.stack.imgur.com/QfxUh.jpg

title: Lessons 2: Spaceship interface

Answers: 1

body:
> 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.

> ![Arduino Uno][1]
> *http://arduino.cc/en/uploads/Main/ArduinoUnoFront240.jpg*

More explanation for PWM here: [Arduino docs](http://arduino.cc/en/Tutorial/PWM), [an answer [of mine]](https://electronics.stackexchange.com/questions/67116/why-do-some-pins-have-signs-next-to-their-numbers)

  [1]: https://i.stack.imgur.com/8eLah.jpg


body:
# 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 :)

title: Arduino Nano no serial port for MacBook Air 2013

Answers: 1

body:
This solved it for me.

* Download [this driver][1]
* 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](http://forum.arduino.cc/index.php?topic=261375.0)

  [1]: http://www.wch.cn/downloads.php?name=pro&proid=178


body:
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.

title: Delay not working in function other than loop

Answers: 2

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

body:
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.

<!-- language-all: lang-C++ -->

    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


body:
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.

title: How much current and voltage has my resistor + LED

Answers: 1

body:
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.


body:
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.

title: Source power with 2 V and LED with forward voltage of 2 V

Answers: 2

body:
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)

body:
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.


body:
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?

title: What does Arduino do in 15ms?

Answers: 5

body:
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.

body:
Just check [the sourcecode](https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/main.cpp#L42-L45)

    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.

body:
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()](http://arduino.cc/en/Serial/begin) for more information about initializing the serial connection.*

body:
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.

body:
**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.


body:
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);
         }
       }
    }

title: Lighting 5 leds...the last one lit is always dim

Answers: 1

body:
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.


body:
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?

title: Infrared sensor has a frequency to activate it?

Answers: 2

body: 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.

body:
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.
https://arduino.stackexchange.com/questions/5152/infrared-led-and-sensor-how-it-work


body:
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?

title: How does an analog input pin work?

Answers: 1

body:
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.


body:
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

title: Blue LED not switching off

Answers: 1

body:
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));
    }


body: 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.

title: Connect Lilypad to LCD

Answers: 0


body:
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?

title: Infrared led and sensor: how it work

Answers: 1

body:
An infrared LED just emits its light (primarily) in the infrared range as described by this [Wikipedia article][1]. 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.

  [1]: https://en.wikipedia.org/wiki/Infrared


body:
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,

title: What project design tools are available?

Answers: 4

body: I think [Fritzing](http://fritzing.org/home/) 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.

body:
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

body:
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/

body:
I use [ExpressSCH](http://www.expresspcb.com/) 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:

[![ExpressSCH example][1]][1]

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.

  [1]: https://i.stack.imgur.com/Hccl8.png


body:
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

title: Include my header files

Answers: 2

body:
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.

body:
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.


body:
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:

![enter image description here][1]

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?)?

  [1]: https://i.stack.imgur.com/TU6F4.png

title: ATmega32u4 bootloader

Answers: 1

body:
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.


body:
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][1]:

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);
    }
    }

  [1]: https://github.com/EbenezerGH/WiflyClient/blob/master/app/src/main/java/com/led/androidled/MainActivity.java

title: Arduino server to read from multiple clients

Answers: 1

body:
*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:

 1. A client connects to the Arduino.
 2. The Arduino code realizes this connection and reads the data provided by the client.
 3. The Arduino then sends some data back to the client.
 4. 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. <sup>*[Citation needed]*</sup>


body:
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);
       }

      }
     }

title: serial char read first letter if it is ";" print char without fists letter

Answers: 1

body:
Tell it to print starting from the second character.

    lcd.print(inData + 1);


body:
I am fairly new to Arduino programming and I have been set with the task of scrolling my name across a [LoL shield][1] 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][2] 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.

  [1]: http://jimmieprodgers.com/kits/lolshield/
  [2]: http://sequoia.github.io/LSS/

title: How would I go about scrolling a name across a LoL shield with a potentiometer?

Answers: 2

body: 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.

body:
The [LoL shield library](https://github.com/jprodgers/LoLshield) 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":

[![Hello World][1]][1]

And in higher contrast to make it more obvious:

[![Hello World high contrast][2]][2]

---

(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

    }

  [1]: https://i.stack.imgur.com/HauiP.jpg
  [2]: https://i.stack.imgur.com/BoRrB.jpg


body:
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?

title: Extremely cheap "Arduino" for single tasks?

Answers: 5

body:
[Digispark][1] comes to mind, or any of the [ATTiny][2] [breakout][3] [boards][4] at Tindie. Or, make your own PCBs, I just now finished soldering a few ATMega328p circuits to [boards I designed][5]. Microcontroller is $1.50, PCBs range from $2 to $8 each, time is "free."

Also consider ["compatible with" designs][6]; while you're not directly supporting the ecosystem, if you've already paid full price once and your conscience is clear, eBay has plenty.

  [1]: http://digistump.com/products/1
  [2]: https://www.tindie.com/products/bot_thoughts/eezeetiny841/
  [3]: https://www.tindie.com/products/bot_thoughts/eezee-tiny-breakout-programming-board-kit/
  [4]: https://www.tindie.com/search/?q=attiny
  [5]: https://www.tindie.com/products/ptudor/jemma-clock/
  [6]: http://www.ardueasy.com/2014/10/different-varieties-of-arduino-nano.html

body:
This is a typical scenario for an [Arduino Uno][1] 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.

  [1]: http://store.arduino.cc/index.php?main_page=product_info&products_code=A000066

body:
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.

body:
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.

body:
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](http://arduino.cc/en/Main/ArduinoBoardProMini). 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](http://www.instructables.com/id/Program-an-ATtiny-with-Arduino/) that shows you how to use an ATTiny85 or ATTiny45 as a lightweight 'Arduino'.

Recently, I have [tried to use an ATTiny13A](https://electronics.stackexchange.com/questions/136919/attiny-project-resets-when-plugging-in-phone) 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.


body:
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);
    }

title: Trouble reading from multiple analog ports

Answers: 1

body:
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.


body:
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?

title: Arduino Leonardo is not recognized by usb cable in Windows 8

Answers: 3

body:
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.

body:
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.

body:
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


body:
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?

title: How to make MEMS IR Thermal Sensor - D6T-44-L06 work with Arduino?

Answers: 1

body:
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


body:
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![Serial Out][1]

    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
    }

  [1]: https://i.stack.imgur.com/WnnrQ.jpg

title: Garbage value Serial Monitor

Answers: 2

body:
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.

body:
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


body:
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 12.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?

title: datalogging sampling frequency bottleneck

Answers: 2

body:
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.

body: 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.


body: 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!

title: Arduino Mega2560 Hardware ID

Answers: 1

body: 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.


body:
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?

title: Can a DC motor use more current than its datasheet?

Answers: 1

body:
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

![enter image description here][1]

  [1]: https://i.stack.imgur.com/z7O3z.png


body:
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.

title: USART RX Interrupt on an ARDUINO PRO MINI containing factory bootloader

Answers: 1

body:
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.


body:
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?

title: Saving data in a globally declared float array

Answers: 1

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


body:
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.

title: Why is my transistor getting very hot when controlling a 12V peristalic pump?

Answers: 1

body:
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


body:
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

title: Arduino to Arduino Communication using HC05

Answers: 2

body:
    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 :-)

body:
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!**


body:
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,

title: Interfacing arduino due to MAX5724 DAC

Answers: 0


body:
I have an Arduino board which is controlling a servo. I think I read that I could only supply about 100 mA through the Arduino's 5v pin. Because of that the power supply I use is able to deliver about 2A I would like to split the power before the Arduino. How do I do that?

Do I have to take some safety for the Aduino in concern or could I just split the wire?

title: Splitting the power source between an arduino and a servo

Answers: 2

body:
If you have a 7V to 12V - 2A regulated supply, you can directly power your board using the 2.1mm connector. Do not go above 12V or you may destroy the voltage regulator on the board.

If you have a 5V to 6V - 2A regulated supply, you can supply your servo with this supply and rely on USB to supply the rest of the board (make sure you have a common ground for both the USB and the regulated supply).

body:
There is a page with information about the [current limits of Arduino][1] pins.  There's also a question on the Electrical Engineering SE site that addresses the [current limits of the board overall][2].

From the accepted answer on that question:

> The 5V output pin is good for ~400 mA on USB, ~900 mA when using an external power adapter

So that's more than the 100 mA you mentioned in your question.  (But go read the [whole answer][3]; there's more good info there.)

The easiest way to split the power is to use a separate, regulated power supply.

Except for simple tests (e.g., a single small unloaded servo), I use the digital i/o pins only for very low current signals:  buttons, status LEDs, sensors, serial communication, etc.

For example, to control an IR LED that can handle up to 50 mA, I'll supply power to the LED from the Arduino board's Vcc pin and control it with a transistor attached to a digital output pin.  Drawing 50 mA from the board's supply is well under the limit, and the digital output pin draws practically nothing.

For more than one servo, I use a peripheral PWM controller that takes power separately.  That peripheral is powered by a separate 5V 2A power adapter, which supplies the current to actually turn the motors.  I send commands to the controller using I2C from the Arduino, which is running from its own power supply.

[1]: https://playground.arduino.cc/Main/ArduinoPinCurrentLimitations
[2]: https://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins
[3]: https://electronics.stackexchange.com/a/67094/64804


body:
[Click here to see my program running][2]

I have created a 2D array (see my full code below), and each row contains one state of a battery here is  a schematic :

    row [0] : "▯▢▢▷" // this row represents an empty AAA battery
    row [1] : "▮▩▢▷"
    row [2] : "▮▩▩▷"
    row [3] : "▮▩▩ ▶"  // this row represents a Full AAA battery

Each "▩" character is a custom made character with this function:

    lcd.createChar(0, customLcdfont_squareONE);

As you saw in my video it works at the end, but it's absolutely not the way I want it to work. The code that works is a mess!

**I think the problem is that the Raw n°1 ([0]) starts with a 0, (try it out it's very strange). If we replace**

    char batteryFonts [10][5] = {
      { 0, 1, 1, 2 }, // you see { this "0", 1, 1, 2 }, is a problem I think
      { 3, 1, 1, 2 },
      {etc}, }
    lcd.print( batteryFonts[0]);  // this sentence does not work

**with**

    "char batteryFonts [10][5]={{ 4, 1, 1, 2 }, // 4 or what ever you want
      {etc},
      {etc}, }
     lcd.print( batteryFonts[0]);  // this sentence behind does work, but only with a row that does not start with a 0. Why?

It works!

Here is my full code. Just connect the pins 12, 13, 7, 4, 3, 2 to the LCD.

    //This is a simple program that charges alkaline batteries
    //Copyleft
    #include <LiquidCrystal.h>
    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 13, 7, 4, 3, 2); // why pin 13 and not 12 ? because I love the led attached to it <3

    // the empty battery - end
    byte customLcdfont_A [8] = { // B stand for "Binary" and then the pixel ...
    B01111,
    B11000,
    B10101,
    B10100,
    B10100,
    B10100,
    B11000,
    B01111

    // the empty battery body with fancy graphics enabled

    };
    byte customLcdfont_B [8] = { // B stand for "Binary" and then the pixel ...
    B11111,
    B00000,
    B11001,
    B00000,
    B00000,
    B00000,
    B00000,
    B11111
    };

    // the empty battery + end

    byte customLcdfont_C [8] = { // B stand for "Binary" and then the pixel ...
    B11100,
    B00100,
    B10111,
    B00101,
    B00111,
    B00111,
    B00100,
    B11100
    };

    // the full battery - end

    byte customLcdfont_D [8] = { // B stand for "Binary" and then the pixel ...
    B1111,
    B11111,
    B10110,
    B10111,
    B10111,
    B10111,
    B11111,
    B1111
    };

    // the FULL battery + end
    byte customLcdfont_E [8] = { // B stand for "Binary" and then the pixel ...
    B11100,
    B11100,
    B01111,
    B11101,
    B11111,
    B11111,
    B11100,
    B11100
    };

    // the full battery  body

    byte customLcdfont_F [8] = {
    B11111,
    B11111,
    B00110,
    B11111,
    B11111,
    B11111,
    B11111,
    B11111
    };

    // the 1/3 battery body

    byte customLcdfont_G [8] = {
    B11111,
    B11000,
    B00001,
    B11000,
    B11000,
    B11000,
    B11000,
    B11111
    };
    // the 2/3 battery body

    byte customLcdfont_H [8] = {
    B11111,
    B11110,
    B00111,
    B11110,
    B11110,
    B11110,
    B11110,
    B11111
    };

    /**************************************************************************/
    void setup() {
      int i = 0 ;
      // initialize serial communications at 9600 bps:
      lcd.createChar(0, customLcdfont_A);
      lcd.createChar(1, customLcdfont_B);
      lcd.createChar(2, customLcdfont_C);
      lcd.createChar(3, customLcdfont_D);
      lcd.createChar(4, customLcdfont_E);
      lcd.createChar(5, customLcdfont_F);
      lcd.createChar(6, customLcdfont_G);
      lcd.createChar(7, customLcdfont_H);

      lcd.begin(16, 2);

    // WATCH HERE IS THE PROBLEM !!!!

    //the char table behind creates my different battery states as shown in the video ;)

     char batteryFonts [10][5]={

     { 0, 1, 1, 2 }, // this is an empty one  f%*# this does not work !!!
     { 3, 1, 1, 2 },
     { 3, 6, 1, 2 },
     { 3, 7, 1, 2 },// this is a 50 % full charged battery !

     { 3, 5, 1, 2 },
     { 3, 5, 6, 2 },
     { 3, 5, 7, 2 },
     { 3, 5, 5, 2 },
     { 3, 5, 5, 4 },// this is nice full one
     };

     // this sentence behind does not work !!! but only with the raw [0]

     lcd.print( batteryFonts[0]);    // I F***ing want this to display the first raw !!!!
     lcd.setCursor(0,1 );

      lcd.print(" not working ");
     lcd.setCursor(0,0 );

            delay(9300); // this make a short pause  for us so that we can see the result
    lcd.setCursor(0,1 );

      lcd.print("    working      ");
     lcd.setCursor(0,0 );
          for (i=0; i=10 ; i+=1 ){
           delay(300);

      lcd.setCursor(6,0 );

      lcd.write(byte(0));   lcd.write(byte(1)); lcd.write(byte(1)); lcd.write(byte(2));
        delay(700); //  batterry 0/8 empty aka discharged

      lcd.setCursor(6,0 );
      lcd.write(byte(3));   lcd.write(byte(1)); lcd.write(byte(1)); lcd.write(byte(2));
        delay(1000); //batterry 1 /8

      lcd.setCursor(6,0 );
      lcd.write(byte(3));   lcd.write(byte(6)); lcd.write(byte(1)); lcd.write(byte(2));
       delay(1000);//batterry 2 /8

      lcd.setCursor(6,0 );
       lcd.write(byte(3));   lcd.write(byte(7)); lcd.write(byte(1)); lcd.write(byte(2)); //batery 3 /8

      delay(1000);

      lcd.setCursor(6,0 );
       lcd.write(byte(3));   lcd.write(byte(5)); lcd.write(byte(1)); lcd.write(byte(2));
      delay(1000); //batery 4 /8

      lcd.setCursor(6,0 );
            lcd.write(byte(3));  lcd.write(byte(5));     lcd.write(byte(6));   lcd.write(byte(2));
      delay(1000); //batery 5 /8

      lcd.setCursor(6,0 );
          lcd.write(byte(3));  lcd.write(byte(5));   lcd.write(byte(7));  lcd.write(byte(2));
            delay(1000); //batery 6 /8

      lcd.setCursor(6,0 );
          lcd.write(byte(3));  lcd.write(byte(5));   lcd.write(byte(5));  lcd.write(byte(2));
          delay(1000); //batery 7 /8

      lcd.setCursor(6,0 );
        lcd.write(byte(3));  lcd.write(byte(5));     lcd.write(byte(5));    lcd.write(byte(4)); //batery 8 /8

        delay(1000);

          }

        lcd.setCursor(15, 1);

        delay(115000);

    }

    /**************************************************************************/
    void loop() {

    //This is not interesting here
      lcd.print(" ~ The end of the code ... thank you for reading ;) ~ ");

    }

  [2]: https://www.dropbox.com/sc/ur5f8b10ifdtuhz/AADK7fM8EeLWgxXQ0I42VrGoa

title: lcd.print and 2D arrays

Answers: 1

body:
You are correct; in C a NUL (0x00) is used to indicate the end of a `char*`. You will need to use `LiquidCrystal::write()` in order to send the character data byte by byte instead of depending on `LiquidCrystal::print()` to handle it.

Also, consider moving all of that static data into flash; you're going to need to handle it manually so you may as well do it right in the first place.


body:
How can I port these structures to arduino ide, I also get error when I define pointers

    // pointer to classes example
    #include <iostream>
    using namespace std;

    class Rectangle {
      int width, height;
    public:
      Rectangle(int x, int y) : width(x), height(y) {}
      int area(void) { return width * height; }
    };

    int main() {
      Rectangle obj (3, 4);
      Rectangle * foo, * bar, * baz;
      foo = &obj;
      bar = new Rectangle (5, 6);
      baz = new Rectangle[2] { {2,5}, {3,6} };
      cout << "obj's area: " << obj.area() << '\n';
      cout << "*foo's area: " << foo->area() << '\n';
      cout << "*bar's area: " << bar->area() << '\n';
      cout << "baz[0]'s area:" << baz[0].area() << '\n';
      cout << "baz[1]'s area:" << baz[1].area() << '\n';
      delete bar;
      delete[] baz;
      return 0;
    }
In [CPP shell][1] it works

I try to put it like this

    class Rectangle {
      int width, height;
    public:
      Rectangle(int x, int y) : width(x), height(y) {}
      int area(void) { return width * height; }
    };

      Rectangle obj (3, 4);
      Rectangle * foo, * bar, * baz;
      foo = &obj;
      bar = new Rectangle (5, 6);
      baz = new Rectangle[2] { {2,5}, {3,6} };

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

    }

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

    }

I get an error

    sketch_nov27a.ino:10:3: error: 'foo' does not name a type
    sketch_nov27a.ino:11:3: error: 'bar' does not name a type
    sketch_nov27a.ino:12:3: error: 'baz' does not name a type
    Error compiling.

  [1]: http://www.cplusplus.com/doc/tutorial/classes/

title: How to prepare data structures and classes?

Answers: 2

body: You put a bunch of code in a place where you can't have it. Move the assignments into a function body.

body:
The problem is that the lines saying `foo = ...` etc. are assignment operations. C++ lets you declare and immediately initialise variables at global scope, but after that you can only assign to them inside a function. In your original program, all your declarations/assignments were inside `main()`, which is why it worked there.

For your Arduino program, you could change the assignments to initialisations instead (in global scope):

<!-- lang-all:cpp -->

    Rectangle obj (3, 4);
    Rectangle * foo = &obj;
    Rectangle * bar = new Rectangle (5, 6);
    Rectangle * baz = new Rectangle[2] { {2,5}, {3,6} };

Alternatively, you could leave the declarations in global scope and move the assignments into `setup()`:

    Rectangle obj (3, 4);
    Rectangle * foo, * bar, * baz;

    void setup() {
        foo = &obj;
        bar = new Rectangle (5, 6);
        baz = new Rectangle[2] { {2,5}, {3,6} };
    }


body:
How do you determine if an Arduino shield uses 3.3V or 5V on their pins?

Previously, I thought all Arduino shields used 5V, since that's what most  Arduinos use. However, I've been researching Arduino-compatible single-board computers like the PCDuino and Galileo, but these all seem to use 3.3V. More confusingly, they're vague about what types of Arduino shields they support. The PCDuino claims to only support 3.3V shields, but has an adapter shield to convert 5V. The Galileo has a jumper to support either 3.3V or 5V shields.

The main problem is how do you determine what voltage level Arduino shields use? I have a Seeedstudio motor shield and a Sain Smart sensor shield, and while they both take 5V power input, the docs don't mention anything about logic voltage level. How do I determine this?

title: Determine difference between 3.3V and 5V shields

Answers: 1

body: You read the schematics and datasheets. The former will tell you what power supplies are connected and how, and the latter will tell you what voltages are acceptable to the devices.


body:
Is it possible to use the [2760342 ultrasonic range sensor][1] with an Arduino Due? The docs say it takes a 5V input, but doesn't specify the output, but I'm assuming it also outputs a 5V signal. Does this make it incompatible with the Due?

I've tested it with an Uno, it it works flawlessly. I've been researching using a Due and some other ARM based single-board computers, but they all seem to use 3.3V, while almost all Arduino shields and sensors use 5V. I'm hesitant to "upgrade" to these boards if I have to purchase an entire new set of shields and sensors. And I have no interest in hacking in some clunky custom voltage level shifter. Why isn't everything standardized on 5V?

  [1]: http://www.radioshack.com/radioshack-ultrasonic-range-sensor/2760342.html

title: Wiring 5V ultrasonic sensor to Arduino Due

Answers: 2

body:
Is this too clunky?

https://www.adafruit.com/products/735

Breadboard Friendly 8-bit Logic Level Shifter, $1.50.

body:
If your question is "Why isn't everything standardized on 5v?", see this good SO answer:
https://electronics.stackexchange.com/questions/135841/voltage-standards-like-3-3v-5v-etc

Bottom line is that the voltage drops as the electronics' technology advances (12v to 5v to 3.3v).

Concretely to your problem, I honestly do not think that a level shifter is somewhat "clunky" solution to your problem, as suggested by mikeY (and as rejected by you). This is the way things are done in the electronics world - when a hardware mismatch arises, there is a hardware adapter to rescue.


body:
    #define pingTrig 6
    #define pingEcho 7

    #include

    Servo myservo;

    void setup()
    {
    pinMode(pingTrig, OUTPUT);
    pinMode(pingEcho, INPUT);
    myservo.attach(9);
    }

    void loop()
    {
    long duration, inches, cm;

    digitalWrite(pingTrig, LOW);
    digitalWrite(pingTrig, HIGH);
    delayMicroseconds(10);
    digitalWrite(pingTrig, LOW);

    duration = pulseIn(pingEcho, HIGH);

    cm = duration / 29 / 2;

    if(cm < 10 ){
    myservo.write(90);
    delay(100);
    }else{
    myservo.write(0);
    }
    delay(2000);
    }

title: Why does it say "Servo" does not name a type

Answers: 1

body:
Your include statement seems to be incomplete; add "Servo.h" to your include to make it look like this:

    #include "Servo.h"

Without including "Servo.h", the compiler doesn't know what a servo is, and thus "Servo does not name a type".