body:
Addition to `Peter R. Blommfield`

What is your problem?

Connect your device, run this sketch and you are good to go :)

    /* TEST */
    #include <SoftwareSerial.h>

    /* Connect device Rx - 10, Tx - 11 */
    SoftwareSerial mySerial(10, 11);

    void setup() {
      Serial.begin(9600);   // This will communicate with PC via USB
      mySerial.begin(4800); // This will communicate with device via 10,11 pins with 4800 baud rate
    }
    void loop() {
        Serial.println("HELLO");   // Sends string to PC to Serial Monitor
        mySerial.println("HELLO"); // Sends string to device
        delay(100);                // Waits here 100ms and then goes on
    }


sender: user

message:
how to calculate correct resistor value to use with LEDs Potentiometer and other devices?

I have been following http://arduino.cc/en/Tutorial/Fade to fade and LED. But I don't know why they are using a 220 Ohm resistor.
According to Ohms law if LED is of 2.2 V and it runs on 0.025Amps and is connected to 5V pin of Arduino then the resistor should be of 120 Ohms but why we are using 120 Ohm resistor ?
One more thing. How can I collect value of resistor to be used with different output and input devices ?

Thanks in advance

sender: assistant

body:
If the LED has a forward voltage of 2.2V and is rated for 25 mA, then you're correct that a 120 Ohm resistor should be OK. It's theoretically calculated as the voltage across the resistor divided by the desired current in the LED. (In practice, it's often more complicated than that, but that's a good starting point.)

It's important to note that not all LEDs are rated the same though. I imagine the 220 Ohm resistor was selected for the tutorial to provide a bit of a safety margin, as that should be OK for most LEDs a hobbyist is likely to use. If you don't have access to the full specifications then it's probably better to under-drive it. The LED might be a little dim, but at least it's unlikely to be destroyed.

Here's a useful online tool for calculating theoretical resistor values for one or more LEDs:

 * http://led.linear1.org/led.wiz

For other devices, the resistor values required can depend on a huge number of factors. The best thing to do is to check the datasheets. For some components (such as ICs), you'll often find an "Applications" section towards the back which shows various ways you might want to connect the item to an external circuit. If things like capacitors and resistors are required, it will often explain how to select the correct ones for a given situation.


message:
ATtiny85. How do I burn a bootloader? What is the process?

I want to use all six I/O pins of an ATtiny85, that means also using the reset pin as an I/O pin, however, I found out that if I disable the RESET pin, I can no longer program the ATtiny using an ISP programmer.

However, I found out that there are bootloaders for ATtiny which, as far as I understand, allow me to program the ATtiny through USB, without the need of the RESET pin.

**My question is**: How do I burn such a bootloader (such as [micronucleus][1] for example) to the ATtiny85? And how do I need to connect the ATtiny to USB after that (like [this?][2])? How do I program it after that? Keep in mind that in terms of burning bootloaders and modifying fuses, I am a complete newbie.

Also, I'm using the ArduinoISP sketch as my ISP programmer since I don't have a real ISP programmer, but as far as I read, that won't be a problem.

EDIT: I do have this thing I bought for a couple dollars on eBay, which I don't know how and if I need to to use: ![enter image description here][3]

  [1]: https://github.com/micronucleus/micronucleus
  [2]: http://littlewire.cc/downloads.html
  [3]: https://i.stack.imgur.com/5U8Nr.jpg

body:
True, if you use the reset pin as IO then you need <strike>a special programmer that I believe provide high voltage (12v if i remember) or something like that</strike> to apply a 12v source to that pin to force it into programming mode then program using a normal programmer (or another arduino). However, what you are looking for is something like what is being done in the Arduino. The arduino is programmed with a special bootloader through ISP so when you power the microcontroller that bootloader will execute first and for few milliseconds will check the UART pins for activities and if it sees something valid it switched into programming mode where it waits for the new code to come through UART (not ISP) and write that into the program location, otherwise the bootloader will simply hand the code execution to the existing program if any.

**Here is a simple explanation of how it works:**
Let say your microcontroller flash size is 1KB, and the bootloader is 100B so your program can be stored at location 101B+, and its max size is (1KB-100B).
So when the bootloader starts and there is no activitiy on the UART pins it jumps to the location of your program (at 101B) while if programming activity is detected it starts reading the new code and overwrites the flash starting at 101B (so it won't over write itself).

And you will need the USBASP to program the bootloader for the first time. And you don't program the ATtiny85 through usb since that chip doesn't support USB, however, you use a USB to serial chip/module that emulates serial protocol over the USB. Some atmel microcontrollers have built in serial support and others can be done through software emulation.

* And as Chris suggested, don't disable the reset pin until you test and validate that your bootloader works.


body:
 - Yes, there are USB interfaces for ATtiny85. Just look at one of the open hardware designs out there, e.g. [Digispark](http://digistump.com).
 - An USB interface is going to require two pins, so using one to save one pin doesn’t strike me as cost effective.
 - I agree with @FAD, that you don’t really need an USB stack, and simply could do a time-delay-at-boot thing with the UART pins.
 - HVSP (the high voltage programming) is not hard to do. If you’re already comfortable with ArduinoISP, you can try [ScratchMonkey](http://microtherion.github.io/ScratchMonkey/index.html), which uses the same approach (with a 12V power supply and one transistor) to do HVSP programming.


body:
I have just finished my Arduino-Plugin with full integration of TinySafeBoot (TSB) for ATtiny84A, ATtiny85 and ATmega328P.

The project can be found here:
https://mesom.de/atflash/index_english.html
https://mesom.de/atflash/tinysafeboot/index_english.html

You could use it as it is now, and then use the Reset Pin as an analog in. Only watch for the voltage never to go below `0.6 * VCC`.

As an alternative you could modify the fuses in `boards.txt` to have this pin available:
Go to Arduino Preferences and click on the link to `preferences.txt` (Mine: `/Users/stefan/Library/Arduino15/preferences.txt`). In this folder navigate to `/packages/atflash/hardware/avr/0.1.0`. Open the `boards.txt` and go to the section
`ATTSB85.name=ATtiny85 (TSB)(Int. 8 MHz)`

Change the line
`ATTSB85.bootloader.high_fuses=0xdf`
to
`ATTSB85.bootloader.high_fuses=0x5f`

Restart Arduino and burn bootloader via Arduino menu.

---------------------------

If you even then want to get another Pin from ATtiny85: you can change the bootloader to use just one Pin for RX and TX (see the TSB website). But why all the effort? Simply take the ATtiny84A. It has 14 Pins instead of 8 and costs nearly the same.

Stefan


body:
> I do have this thing I bought for a couple dollars on eBay, which I don't know how and if I need to to use:

it is infinitely better than your arduinoisp.

google avrdude / avrdudess.


message:
How do I change fuse bits - not communicating?

Currently I'm working on a project using an [ATmega 2560 microcontroller card][1] with a 10 MHz crystal. My main goal is to use the Arduino IDE to upload sketches to this chip to run my bread board circuit. In the beginning I had planned to use Atmel Studio to upload Arduino Sketches, but I decided to go with the more direct route. I am using two programmers, the Atmel ICE, and the Atmel AVR ISP MKii.

Anyway, here is my issue. I tried to use the Arduino IDE and the MKii to burn the bootloader to the chip. However, it did not work. It uploaded, but I was at that point no longer able to communicate with the device. When I switched to Atmel Studio, and used the ICE programmer, my chip could not be read and recognized (whereas before it could). I can't even program it. (I had bought two.)

I then figured I would try and read the fuse bits on the other programmer and burn the bootloader using Atmel Studio (since the Arduino IDE has no information on this), and I looked up [the proper bits to change][2] and then burned the bootloader. It worked fine, and I then changed the fuse bits which resulted in an error and now I again could talk to the device.

I am guessing that something is going wrong with the suggested fuse bits, but I do not know how to change them or how to fix this. The original fuse bits that I read from the device are listed below (before I messed it up).

I checked my wiring a billion times and it is all perfect. I just need suggestions to fix this mess, thanks.

    BODLEVEL = DISABLED
    OCDEN = [ ]
    JTAGEN = [X]
    SPIEN = [X]
    WDTON = [ ]
    EESAVE = [ ]
    BOOTSZ = 4096W_1F000
    BOOTRST = [X]
    CKDIV8 = [ ]
    CKOUT = [ ]
    SUT_CKSEL = INTRCOSC_6CK_0MS
    EXTENDED = 0xFF (valid)
    HIGH = 0x98 (valid)
    LOW = 0xC2 (valid)
    LB = NO_LOCK
    BLB0 = NO_LOCK
    BLB1 = NO_LOCK

    LOCKBIT = 0xFF (valid)

    Detected device
    Device name       ATmega2560
    Device signature  0x1E9801

  [1]: http://www.tme.eu/en/details/mikroe-229/atmel-development-kits/mikroelektronika/mcu-card-atmega2560/#
  [2]: http://www.avr-developers.com/bootloaderdocs/index.html

body: If AVR is bricked because of wrong fuses I suppose it's typically non-working external oscillator you need provide signal to particular AVR pin to get programmer working again. Thread related to unbricking http://www.avrfreaks.net/forum/locked-out-atmega-328p-possible-clocklow-fuse-byte-issue.


message:
Does porting code to different MCU clock frequency affect serial baud rate?

Tried to upload my Arduino Uno sketch that writes to serial UART at 9600 baud rate onto my ATtiny2313 running at 1MHz. Not getting the signal on the ATtiny, does this have to do with my clock frequency of the MCUs being 16 vs 1MHz?

body: Yes, it does. As can be seen in the "USART" section of the datasheet the baud rate is generated directly from both *fosc* (aka `FCPU`) and the value contained in UBRR. The tables at the end of the section gives the appropriate value for UBRR for a given CPU frequency, desired bit rate, and state of the USART clock doubler.


message:
Change the backlight of 2x16 LCD

Today I ordered a 2x16 character LCD with white characters on black background.

Now I am wondering if I can change the backlight LED, which I guess is white for the characters, with a RGB LED to change the character color.

Did anyone do this before?
Is it even possible that way?

I've seen RGB negative LCDs from Adafruit and Sparkfun.

body:
The product you linked looks like a fairly standard LCD module, so it's probably very difficult to swap the backlight LED. Like most electronics, they're not designed to be modified by hand. It would likely need some precision re-soldering.

When you see LCDs with other types/colours of backlight, it's usually because they were originally manufactured that way.


body:
The backlight led ([sample](http://www.adafruit.com/product/1622)) is just a simple led with a large transparent panel, the size of the lcd, attached to it. This panel is diffused on the top in such a way that it distributes the light evenly. If you get a rgb led, file the top flat, and glue it to the side of this panel (where the leads get out of the plastic) you should get a pretty good effect.

I tested it on my white-on-blue lcd, by holding and led to the side of this panel, and it worked. Just note that you need a very bright led. Mine was pretty bright but the letters didn't light up that much.


message:
How to connect Arduino Pro Mini with PC?

I'm about to buy Arduino Pro Mini (http://arduino.cc/en/Main/ArduinoBoardProMini).
As far as I can see it requires FTDI or similar circuit to program it.

Should FTDI be present for communication with PC after sketch is uploaded to chip or there is a way to connect Arduino Pro Mini DIRECTLY to USB cable and PC?

Is this also case with Arduino Pro Micro? (https://www.sparkfun.com/products/12640)

Thanks in advance
Petar

body:
V-USB can be used to create a low-speed USB device in software, but you will need to program the chip before you can use it. It also has a number of caveats that must be adhered to regarding electrical and software specifications, so it not the best choice for an absolute beginner.

A USB-UART bridge (not necessarily a FTDI chip, although that is (was?) the most popular solution) will allow you to program and communicate with the chip over its serial port, but any AVR ISP programmer can also be used to program it without requiring a preexisting bootloader in place.


body:
The "Arduino Pro Micro" has its own USB interface so you don't need extra stuff for it to work. However, a number of existing libraries that deals with Arduino shields do not support the new chip inside the Arduino Pro Micro (ATmega32U4) so check first to make sure it will work with what you need.

For the "Arduino Pro Mini" (which I use a lot since it is very very cheap, about $3 from ebay) to program it I use "USPASP" (also cheap ~$3) so I have three of them but you only need one to program as many Pro Minis as you like. And for communication I use a "USB to TTL UART" (based on the "CP2102" chip which works with Linux, Windows and Mac) they are also super cheap (about $2) and you connect it to the serial pins on your Pro Mini.

(Just search ebay for the terms I put in quotes and you will find many of them at low prices, they ship from china so it will take about a month to get to you which is why I ordered more than I need for future projects, or for a little extra you might find local sellers with same products)


message:
releasing memory in sub-function

I'm doing a program who get a line from the SD and shows it, this function is called *getData()*

FULL CODE:

    #include <SD.h>
    #include <MemoryFree.h>

    File myFile;
    int stringIndex = 0;
    int cursorPosition = 0;
    char inputString [25];
    char inputChar;
    boolean endOfLine;
    char fullPath[11];

    void setup(){

      Serial.begin(9600);

      Serial.print("Initializing SD card.");
      pinMode(10, OUTPUT);
      digitalWrite(10, HIGH);

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        return;
      }
      Serial.println("initialization done.");

    }

    void loop(){

      Serial.println(getDataSD());

      Serial.print("freeMemory()=");
      Serial.println(freeMemory());
    }

    String getDataSD(){

      memset(inputString, 0, sizeof(inputString));

      getFileNameSD();

      myFile = SD.open(fullPath);

      if(myFile){
        myFile.seek(cursorPosition);

        endOfLine = false;

        while(myFile.available() && endOfLine == false){
          inputChar = myFile.read();

          if(inputChar == '*'){
            while(inputChar != '\n'){
              inputChar = myFile.read();
            }
          }else{
            cursorPosition = myFile.position()-1;

            if(inputChar == 10 || inputChar == ' ') inputChar = myFile.read();

            while(inputChar != '\n'){
              if(stringIndex < 25){
                inputString[stringIndex] = inputChar;
                stringIndex++;
                inputChar = myFile.read();
              }
            }
            inputString[stringIndex-1] = '\0';
            stringIndex    = 0;
            endOfLine      = true;
          }
        }
        myFile.close();
      }
      return inputString;
    }

    void getFileNameSD (){

      char folder[] = "/ACC";

      checkFolderSD(folder);

      myFile = SD.open(folder);
      myFile = myFile.openNextFile();

      if(!myFile) myFile.rewindDirectory();

      if(myFile){

        strcpy(fullPath,folder);
        strcat(fullPath,"/");
        strcat(fullPath,myFile.name());

        myFile.close();
      }
    }

I don't have problem with this function(getDataSD). To get the name of the file, I've created another function who looks for a file in a specific folder, this function is called *getFileNameSD()*

I'm having problem with this last function, it's not releasing or overwriting some data, so every time it's called, it is stored new data in memory

I've included the [memory Free library][1] to see where is the problem. When I call the *getDataSD* and write the file manually I dont have problem.

    myFile = SD.open("/ACC/11001");

Serial monitor

    freeMemory()=6592
    /-27/-26/-56/
    freeMemory()=6592
    /-27/-26/-56/
    freeMemory()=6592
    /-27/-26/-56/
    freeMemory()=6592
    /-27/-26/-56/
    freeMemory()=6592
    /-27/-26/-56/
    freeMemory()=6592
    /-27/-26/-56/
the memory always is the same.

but not when I call the *getFileNameSD()*

    myFile = SD.open(getFileNameSD());

Serial monitor

    freeMemory()=6571
    /-27/-26/-56/
    freeMemory()=6540
    /-27/-26/-56/
    freeMemory()=6509
    /-27/-26/-56/
    freeMemory()=6478
    /-27/-26/-56/
    freeMemory()=6447
    /-27/-26/-56/

I know I'm doing something wrong with *getFileName()* but I don't know what is, can anybody help/explain me?

  [1]: http://github.com/maniacbug/MemoryFree

body:
Ok,

I don't know, why your memory is leaking, but anyway, your program won't work safely.
You defined an array (fullPath) inside the local scope of your function. You return it, which means, you return a pointer to this array. But at the same time, this array gets invalid, because you leave the local scope of your function.

Better define that string outside the function and give it as a parameter to the function. Then you aren't in danger of accessing an invalid pointer. Furthermore your memory leak won't appear.


body:
Well, finally someone found where was the problem.
In the *getFileName()* function, I open two instances of the file but I close just one.

here is the answer:

    #include <SD.h>
    #include <MemoryFree.h>

    File myFile;
    int stringIndex = 0;
    int cursorPosition = 0;
    char inputString [25];
    char inputChar;
    boolean endOfLine;
    char fullPath[11];

    void setup(){

      Serial.begin(9600);

      Serial.print("Initializing SD card.");
      pinMode(10, OUTPUT);
      digitalWrite(10, HIGH);

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        return;
      }
      Serial.println("initialization done.");

    }

    void loop(){

      Serial.println(getDataSD());

      Serial.print("freeMemory()=");
      Serial.println(freeMemory());
    }

    void getDataSD(){

      memset(inputString, 0, sizeof(inputString));

      getFileNameSD();

      myFile = SD.open(fullPath);

      if(myFile){
        myFile.seek(cursorPosition);

        endOfLine = false;

        while(myFile.available() && endOfLine == false){
          inputChar = myFile.read();

          if(inputChar == '*'){
            while(inputChar != '\n'){
              inputChar = myFile.read();
            }
          }else{
            cursorPosition = myFile.position()-1;

            if(inputChar == 10 || inputChar == ' ') inputChar = myFile.read();

            while(inputChar != '\n'){
              if(stringIndex < 25){
                inputString[stringIndex] = inputChar;
                stringIndex++;
                inputChar = myFile.read();
              }
            }
            inputString[stringIndex-1] = '\0';
            stringIndex    = 0;
            endOfLine      = true;
          }
        }
        myFile.close();
      }
    }

    void getFileNameSD (){

      char folder[] = "/ACC";
      File myDir = SD.open(folder);

      memset(fullPath, 0, sizeof(fullPath));

      if (myDir){
        myFile = myDir.openNextFile();

        if(myFile){
          strcpy(fullPath,folder);
          strcat(fullPath,"/");
          strcat(fullPath,myFile.name());
          myFile.close();
          myDir.close();
        }else{
          // Handle file not found
          myDir.close();
          fullPath[0] = '0';
        }
      }else{
        // Handle directory not opened
        fullPath[0] = '0';
      }
    }


message:
Sending a floating point number from python to arduino

I am trying to send a floating point number from a python script to an Arduino.  I am not sure how to do this, especially in a pythonic way.

A little bit of research brought me to this very similar question:
https://arduino.stackexchange.com/questions/3753/how-to-send-numbers-to-arduino-uno-via-python-3-and-the-module-serial
I vaguely understand why this would work for an int but don't know how to modify it.

1) In this question it makes sense to convert to a char, send, and then convert back to a int by casting on the Arduino, I can't think how to do that for a float.

2) Why do they convert to a Char anyway?

3) What code do I run on the arduino to get this back into a float?

4) Can I use bitwise operators on floating point numbers?

I'm new to python and also to low level programming. I am also aware that python and low level don't mix to well. I am using Linux but ideally I need a cross platform solution. Although I would prefer to get it working then worry about cross platform later.

body:
> In this question it makes sense to convert to a char, send, and then convert back to a int by casting on the Arduino, I can't think how to do that for a float.

Instead of using a format specifier of `B` for an unsigned byte, use `f` for a single-precision float. AVR-GCC doesn't support double-precision floats, so don't bother with `d`.

> Why do they convert to a Char anyway?

You don't. You convert it to bytes (hence the `b` prefix on the representation of the value) so that the byte-oriented serial protocol can transmit it. On Python 2.x `str` is already bytes, so no prefix is required there.

> What code do I run on the arduino to get this back into a float?

Use `Serial.readBytes()` to dump the bytes from the serial connection into a `float` variable.

    float f;
     ...
    if (Serial.readBytes((char*)&f, sizeof(f)) != sizeof(f)) {
       ...

> Can I use bitwise operators on floating point numbers?

... Well... no... because they may not necessarily remain valid floating point numbers afterwards.


body:
Floating point numbers are (should) be stored in [IEEE 754 format][1].

If you simply write the binary bytes of a floating point number down the serial line, it should be possible to unpack them at the other end.

To do this (Arduino C/C++), make a pointer from your variable, by casting the address of it to char*. Void* would probably work too.

     float my_value = 22.812;
     my_port.write((const char *)&my_value, sizeof(float)/*4*/);

And the unpacking - there's a few ways to do this, but I like:

     float incoming_value;
     unsigned char buffer[4];

     // If we read enough bytes, unpacked it
     if (my_serial.readBytes(buffer, sizeof(float)) == sizeof(float))
         memcpy(&incoming_value, buffer, sizeof(float));
     else
         // I/O error - no data, not enough bytes, etc.
         incoming_value = 0

On the other end (python), bytes are best handled with the **struct** module.  This will handle the packing and unpacking for you.

    import struct
    ...

    try:
        ieee754_data = my_serial.read(4)
        my_float = struct.unpack('f', ieee754_data)
    catch:
        # I/O Error, or junk data
        my_float = 0.0

And packing:

     ieee754_data = struct.pack('f', my_float)
     try:
         my_serial.write(ieee754_data)
     catch:
         pass #TODO - I/O Error

One more note - You might consider using doubles instead of floats for extra precision.  Python floats have the precision of a C/C++ double already.

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


message:
Ideas for setting I2C device IDs

I am using I2C to communicate between a collection of ATtiny85s that are acting as controllers for various parts of a system and the "Main Brain" -- a RaspberryPi. Most of the ATtiny85s only have a couple of free pins left (usually Pins 1 and 2 -- the reset and the pin that can't be used for PWM) so I can't use something like a DIP switch to directly set device IDs. I'd rather not hardcode the device IDs when I push code to the tinys but I can't think of a good, simple, and reliable way to do it otherwise. Anyone here have a suggestion?

body:
You could use the analog input on pin 1.

Have a table in your code to map voltage thresholds to I2C IDs.

Then build a voltage divider circuit as input that you can adjust with switches or by installing different resistors.


body: Put the address in EEPROM. It's still "on the chip" but it can be programmed independent of the flash, and can be changed on the fly if deemed appropriate.


message:
Why does the RCSwitch.available return false?

I am trying to use this example code from the [RCSwitch library](https://github.com/sui77/rc-switch):

    /*
      Simple example for receiving

      https://github.com/sui77/rc-switch
    */

    #include <RCSwitch.h>

    RCSwitch mySwitch = RCSwitch();

    void setup() {
      Serial.begin(9600);
      mySwitch.enableReceive(0);  // Receiver on inerrupt 0 => that is pin #2
    }

    void loop() {
      if (mySwitch.available()) {
        Serial.print("Is avail");
        int value = mySwitch.getReceivedValue();

        if (value == 0) {
          Serial.print("Unknown encoding");
        } else {
          Serial.print("Received ");
          Serial.print( mySwitch.getReceivedValue() );
          Serial.print(" / ");
          Serial.print( mySwitch.getReceivedBitlength() );
          Serial.print("bit ");
          Serial.print("Protocol: ");
          Serial.println( mySwitch.getReceivedProtocol() );
        }

        mySwitch.resetAvailable();
      }
    }

It seems like the mySwitch.available() is returning false, but since there seems to be no documentation for the library I don't know what it means.

So why is that?

I am trying to use this code on a A-Star 32U4 Micro, which supports Arduino code.

body: I think that the value of available just determine if there is a message to receive or not.


body:
Your code is OK. It seems that the transmitter's remote control frequency is different from the receiver. Both transmitters and receivers must have the same frequency.
433MHZ - TX with 433MHZ - RX
315MHZ - TX with 315MHZ - RX


message:
How do I transfer more than 1 byte at once via SPI bus?

I have an [AD5685R DAC](http://www.analog.com/static/imported-files/data_sheets/AD5686R_5685R_5684R.pdf) that I am trying to communicate with over SPI. Per the datasheet,

> ...These [24] bits are transferred to the input register on the 24 falling edges of `SCLK` and are updated on the rising edge of `/SYNC`

where `/SYNC` is used as chip-select.

I believe Arduino's [`SPI.transfer`](http://arduino.cc/en/Reference/SPITransfer) waits to receive 8 bits after sending 8 bits. But for this particular DAC, I need to send 24 straight bits on 24 clock edges before releasing the chip-select. Is this possible?

body:
> I believe Arduino's `SPI.transfer` waits to receive 8 bits after sending 8 bits.

Incorrect. With SPI, a byte is clocked in *at the same time* as a byte is clocked out. It may be that this byte is simply a dummy byte though, if the slave has nothing to say.

So for 24 bits, simply clock out 3 bytes without deasserting the select. Since SPI is a synchronous protocol there should be no issue with having a delay in between bytes provided the select is maintained.


body:
Looks like it just set cs low and do three byte transfers then bring it high.   Here's someone's example on how to do it:

http://www.reigndesign.com/blog/controlling-a-10-bit-digital-potentiometer-via-spi-with-arduino/

Code below taken from above page.

    #include <SPI.h>

    const int csPin = 10;

    void setup() {

     SPI.begin();
     SPI.setBitOrder(MSBFIRST); //We know this from the Data Sheet

     pinMode(csPin,OUTPUT);
     digitalWrite(csPin, HIGH);
    }

    void loop() {
     for(int i=0; i<1023; i++) {
      digitalPotWrite(0,i);
      delay(10);
     }
    }

    void digitalPotWrite(int address, int value) {
     digitalWrite(csPin, LOW); //select slave
     byte command = 0xB0; //0xB0 = 10110000
     command += address;
     SPI.transfer(command);
     byte byte1 = (value >> 8);
     byte byte0 = (value & 0xFF); //0xFF = B11111111
     SPI.transfer(byte1);
     SPI.transfer(byte0);
     digitalWrite(csPin, HIGH); //de-select slave
    }


body:
In the SPI protocol, you get one byte back for every one you send.  If you are not interested in the response from a device, you can just ignore the return bytes.

SPI has no handshaking.  You just must send no faster than the slave device can handle.  In the case of the AD5685R, that is 50 MHz.

For multibyte transfer, you keep the chip select asserted (low) between every byte by setting the transferMode to SPI_CONTINUE in the SPI.transfer call.  For the last byte, you will deassert the chip select (set it high) by setting the transferMode parameter to SPI_LAST in the SPI.transfer call..


body:
Note that there is also a version of [`SPI.transfer`](https://www.arduino.cc/en/Reference/SPITransfer) for multi-byte (buffer) transfers:

    SPI.transfer(buffer, size)

I used the buffer transfer in my [library](https://github.com/ulrichstern/Tlc59711/wiki) for the TLC59711 (see [code](https://github.com/ulrichstern/Tlc59711/blob/v1.0.1/Tlc59711.cpp#L91)) and found the buffer transfer faster than transferring bytes individually using `SPI.transfer(val)`; the switch to buffer transfers is _one_ of the reasons my library is about 3.5 times faster than a previous library for the TLC59711.


message:
Individually control ~200 LEDs

I am planning to build a LED polar clock, so it will need about 181 LEDs (12 Month, 31 Day, 7 Day-of-week, 12 Hour, 60 Minute, 59 Second) and I need to control each one individually. I will be buying everything from scratch so I ask for help on:

 - Which arduino to use
 - How to make it keep time
 - How to control the LEDs

The LEDs need to stay on once they're lit, e.g. at 5 o'clock, the 1-5 LEDs would be on.
This is why I don't know that multiplexing or charlieplexing will work, as I read that it is better if the LEDs wont be remaining on/only a few are on. The most that could be on is 179 (Friday, December 31, 11:59:59 [Won't happen until 2021]).

Thanks in advance.

body:
Multiplexing will work fine in this case (Charlieplexing isn't practical here).

You create an array of leds, and light up only one row at a time. If you rotate through all the rows at more than 50 times a second your eyes won't notice it.

In the case of 181 leds, you'd need and array of e.g. 13x14. This will mean you need a minimum of 27 IO-pins. More than the regular Arduinos provide.

So you probably need some additional ICs. You could use simple shift registers, or dedicated led-matrix drivers like the max7219 or some other IC. The Max7219 is probably the easiest, as you don't have to do the multiplexing yourself. The can light upto 64 leds (8x8), so you'd need 3 of them.

PS I get a different number though; 12 (month) + 31 (day) + 7 (weekday) + 23 (hours) + 59 (min) + 59 (sec)= 191


body:
Instead of a multiplexer you can use a "shift register"; the difference is that it keep the last state of the pin, while the multiplexer goes unconnected (and this is because you need at least 30fps, and even so you'll get low light as you are PWMing the leds).
This is why shift register are also called "led driver".

Official tutorial can be found here http://arduino.cc/en/Tutorial/LEDDriver


body:
Check out the TLC5916. It has two advantages over the HC595:

- it can sink a lot of current
- it only needs one resistor

I use it with seven-segment displays. Basically, you tell it "I'm about to send a command." Then you send it, say, "01010101" to turn on every other light. Then you say "okay, make that live." You can chain them together.

Many use the MAX7219 but for me the cost is a drawback.

I might come back and edit this post later to add a Github link to demonstrate...


body:
If the cost is allowed to be moderately higher, your simplest solution could be to use WS2012b individually-addressable LEDs. Since longer chains sometimes have timing problems with the serial communication, I’d probably split them into three groups, attached to three digital pins.

Multiplexing probably requires some flip-flops or other buffers; else, the LEDs may not be bright enough.


message:
how to serially communicate the arduino leonardo to pc through hyperterminal

I have connected mc to a pc using USB. I need data on hyperterminal through serial to USB connection, hence I connected TX, RX and gnd pins of the Leonardo to the rs232 pins and one other side of rs232 to USB to pc. However, the data is still transmitting on serial monitor, but not on hyperterminal.

    int count = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(3,INPUT); // This is the pin to which we have connected the button
      attachInterrupt(0, IRsensor, CHANGE);
    }

    void loop() {
      if (Serial.available()) {
        /* read the most recent byte */
        /*ECHO the value that was read, back to the serial port. */
        Serial.write(count);
      }
    }

    void IRsensor() {
      if(digitalRead(3) == 1) {
        count++;
        Serial.println(count);
      }
    }

body:
To be sure, please add code.

You can use usb on Arduino to communicate with pc. You don't need RS232/USB converter. Just open hyperterminal with the port of arduino. Arduino port can be found in:

 1. Arduino IDE Tools>Port
 2. My Computer>Properties>Device manager>Ports

If you really need `SoftwareSerial` then connect Rx,Tx and don't forget GND!

**UPDATE**

To communicate with RS232/USB converter you have to add RS232/TTL converter to Arduino side. The schematic would look like PC <-> USB/RS232 <-> RS232/TTL <-> Arduino:

1. PC - your computer
2. [USB/RS232][1] to convert from usb to RS232. On RS232 side the voltage is -5V to +5V
3. [MAX232][2] RS232/TTL. To convert the voltage
4. Arduino - your MCU

**UPDATE 2**

As i said, connect your arduino to PC like you do while programming.

![enter image description here][3]
Next, upload this sketch:

    void setup() {
      Serial.begin(9600);
    }

    void loop() {
      if(Serial.available()){
       Serial.print("\nReceived: ");
       Serial.write(Serial.read());
      }
    }

Open HyperTerminal: choose port with Arduino,

![enter image description here][4]

Connect to arduino, **Serial Monitor has to be closed**

![enter image description here][5]

  [1]: https://www.sparkfun.com/products/11304
  [2]: http://www.ti.com/lit/ds/symlink/max232.pdf
  [3]: https://i.stack.imgur.com/PG9JV.jpg
  [4]: https://i.stack.imgur.com/fA2Pp.png
  [5]: https://i.stack.imgur.com/L1moo.png


message:
Why doesn't pin 9 blink?

I use simple LED blinking code on an [Arduino MEGA 2560][1]. I simulate it in Proteus. But pin number 9 doesn't power up. What is the problem?

My code:

    // Set up the DATA direction
    void setup()
    {
      for(int i = 1; i<9; i++)
        pinMode (i, OUTPUT);
    }

    // The main program
    void loop()
    {
      for(int j=2; j<=10; j++)
      {
        digitalWrite(j, HIGH);
        delay(100);
        digitalWrite(j, LOW);
      }

      for(int j=9; j>=2; j--)
      {
        digitalWrite(j, HIGH);
        delay(100);
        digitalWrite(j, LOW);
      }
    }

And the circuit is:

![Enter image description here][2]

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560
  [2]: https://i.stack.imgur.com/DeHzm.png

body:
It looks like your main problem is the loop in `setup()`:

    for(int i = 1; i<9; i++)
        pinMode (i, OUTPUT);

This will call `pinMode()` with values 1 to 8 (inclusive), and then stop. That means you aren't configuring pin 9 as an output. You need to change the loop condition to **`i<=9`**.

However, if your circuit diagram is accurate then you will have another problem. When implementing the circuit for real, you absolutely **must** have a suitable resistor in series with each LED (maybe something around 200 Ohms, depending on the exact specifications). If not, you seriously risk destroying the LEDs and maybe damaging your Arduino.


message:
Why is resolution 20?

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

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.


message:
How this smal infrared work

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.

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.


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

I've been trying to work with an [AD5685R DAC](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.

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


message:
Lessons 2: Spaceship interface

I'm just starting to discover Arduino. Currently, I've done 2 lessons from Arduino book and I have few questions about second circuit.
![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

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


message:
Arduino Nano no serial port for MacBook Air 2013

# Problem

I have an Arduino Nano connected via a USB cable (Type A to Mini Type B) to my MacBook Air (Mid 2013 Model). The PWR LED is on while the arduino is connected.

Opening the Arduino software, pulling down the `Tools > Serial Port` menu does not show me a valid serial port. All I see is:

    /dev/tty.Bluetooth-Incoming-Port
    /dev/cu.Bluetooth-Incoming-Port
    /dev/tty.Bluetooth-Modem
    /dev/cu.Bluetooth-Modem

## What I've tried and did not work

* I have installed the correct FTDI driver (v2.2.18). x64 for my MacBook Air's Corei5, file `FTDIUSBSerialDriver_10_4_10_5_10_6_10_7.mpkg`. Restarted after installation.

* Tried connecting arduino to both USB ports on my Air.

## More Info

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

If it helps, I can see the USB Serial in my `Apple Logo > About This Mac > System Report` under `Hardware > USB`

    USB2.0-Serial:

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

I'm out of ideas and options. Any help would be greatly appreciated.

Thanks in advance :)

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


message:
Delay not working in function other than loop

So I just got an Arduino and thought I would play around a bit.

However not five minutes in I already ran into a problem.

I tried programming a simple SOS blinking light sequence. To get rid of code duplication I refactored the on and off turning of the LED into functions and then again refactored a short blink and a long blink function which are expected to turn the LED on for a short time and then for a long time.

The problem is the delay in those functions is completely ignored.

    int ledPin = 13;

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

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

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

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

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

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

My expected behavior would be that it does an SOS and then waits 5 seconds and repeats.

What really happens however is that it stay continuously lit for a second or so then turns off for 5 seconds.

Using

    on();
    delay(1000);
    off();

In the main loop works so I guess it simply ignores the delays that are put into the other functions. My question would be why and ho do I fix it?

I know that I can use other timer function constructs however I really think this is something that should work by default.

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


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

I have a very simple circuit: 5v -> LED (5mm, forward voltage of 2 V and max. current of 20mA) -> 1k ohm resistor -> GND.

I want to know how much current is flowing in my circuit. I am using this formula:

U = R x I

Since U = 5, and R = 1000 the current is (according to the formula): 5/1000 = 0.005A.

So far so good. The problem is when I try to check the voltage drop over the resistor and the LED. For calculating the voltage drop in the resistor I would use the same formula where I is my current (0.005A) and R is the resistor 1k ohm. The result is: 5 V.

Something very weird is happening here cause the voltage drop around my resistor should not be 5 V cause I know there must be another voltage drop around the LED. If 5V is in the resistor it would mean that 0v is around the LED (and it should not light up but it does).

Thank you helping me with this basic calculus.

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.


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

I have a source power with 2 V and 100mA. I have an LED that has a forward voltage of 2 V and a max current of 20mA.

Should I use a resistor to reduce the current? I see many formulas in the internet saying the the resistor value should be:

(Source Voltage - LED forwared voltage)/LED max current

This formula always worked fine for me, but now that I have a 2 V source power this formula tells me that the resistor should be 0 ohm. Of course this would damage my LED cause the 100mA provided by my source power is way above the 20mA current limit of the lED.

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.


message:
What does Arduino do in 15ms?

I was wondering why there is a 15 ms delay between each iteration of a the main loop.

**Code**:
The following code shows the execution time expressed in microsec between each loop

    void setup()
    {
      Serial.begin(9600);
    }

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

**Output**:

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

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

What does Arduino do between each loop?

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.


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

I have a simple project with a close deadline.

I am trying to light up 5 LEDs as part of the project. The first 4 light up in sequence fine, and if I light up just the last one it lights up fine, but if all 5 are lit at once the very last LED is very dim. I swapped out cables, the pin on the Arduino, resistor, LED.

What would explain that? Input amperage? Too strong a resistor?

I have a 330 ohm resistor in between each LED and ground. I am using one of the neat resistors from SparkFun that packages up the 5 330 ohm resistors together, with a common ground wire. I bought two and tried swapping it out with no change.

https://i.stack.imgur.com/QZ4qU.jpg

Here is my code:

    /* Blink without Delay
     http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
     */

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

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

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

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

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

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

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

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

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

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

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

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

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

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.


message:
Infrared sensor has a frequency to activate it?

I am trying to understand 2 sensors that I have here. One says that is "infrared sensor of 38kHz" and the other is "infrared optical reflexive sensor -> http://www.robosoftsystems.co.in/wikidocs/index.php?title=TCRT_5000_Reflective_Optical_Sensor"

I thought that infrared sensor would tell me if an infrared light is passing on it. Infrared light has a wavelenght, right? Can infrared light be emited in different frequencies? Or the frequency of infrared light is the same to all infrared lights?

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


message:
How does an analog input pin work?

I have a potentiometer of 10k and I connected it this way:

5v -> potentiometer -> analog input pin of Arduino

When I turn the potentiometer I change the resistance of the circuit but in the Arduino documentation they say that an analog pin in INPUT mode will have 1 megaohm resistance. So, for example, if I turn the potentiometer to the middle it will generate 5k of resistance + 1 megaohm of the analog pin it will result in a tiny, very tiny current. If I use U = R x I across the potentiometer it will be:

U = 5000 x 0.0000001

U ~ 0 across the potentiometer. So U will be 5 V at the analog input because there was no drop of voltage in the circuit. If turn the potentiometer all way up to 10k resistance the voltage in the analog input will also be 5 V because the voltage drop across the potentiometer is still really small.

I know that an analog pin in INPUT mode will read 0 V as 0 and 5 V as 1023. But as I showed you it should always read 5 V even when I turn the potentiometer all way up because the voltage is not being changed. I know I am wrong cause when I log the input pin it shows different values as I turn the potentiometer. So how does this work?

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.


message:
Blue LED not switching off

I have a circuit with a blue led, 470ohm resistor and one IR led. I want the led to be switched off when the IR led has a digitalRead value of LOW(i move my hand over it). So I wrote the code:-

    void setup() {
    // initialize digital pin 13 as an output.
    pinMode(13, OUTPUT); // this is the blue led
    pinMode(10, INPUT);  // this is the IR sensor's O/P

    }

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

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

    }

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

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


message:
Infrared led and sensor: how it work

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

I know that infrared light has a wavelegnth, but does it also have a frequency?

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


message:
What project design tools are available?

What do you guys use for project designing?

I just found out about AutoDesk's 123D Circuits, which is nice but I wonder if there is something with more components, tools, etc?

For example, I can add an accelerometer to my project there but no signs of a LCD. I have been learning hardware recently and I feel there should be more complete tools out there.

I know this question may be opinion based but I could not find anywhere to ask. Thanks,

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


message:
Include my header files

let's suppose I have folder called AES, in this folder is file "AES.ino" where is code and folder "AESLib" what is library. In "AESLib" is file called "AESLib.h",

now when I try to include AESLib.h with

    #include "AESLib/AESLib.h"

 in my AES.ino, then Arduino command line tool complain that its not able to find "AESLib.h"

Where could be the catch?

Thanks

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.


message:
ATmega32u4 bootloader

Hey all this would be my first encounter needing to burn the Arduino IDE bootloader onto a blank ATMega32u4 that I bought from Digikey.

What all do I need to buy in order to program the bootloader for that chip? In the manual for the 32u4 it says it comes with a bootloader but I'm guessing its not the arduino bootloader?

Is the pinout for the ISP all that I would need in order to upload the Arduino bootloader?

I've seen this post:

![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

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.


message:
Arduino server to read from multiple clients

Socket programming question here.

My interface comprises of an Android device(client), A wireless module hosting an access point, and an Arduino Uno(server).

My Android client class works when 1 user connects and sends commands to my Arduino server class.

I want to make my program friendly to many users at the same time.  My server will only read in values from 1 connected client at a time.

After some research I've found that Arduino does not allow multithreading naturally, which is why i've decided to look into a number of libraries.

The Arduino library that I've decided to use for this specific issue is `protothreads`.  Unfortunately, i've been unable to find any examples of creating a server with Arduino to accept a client's commands.  Furthermore I'm having a lot of trouble figuring out how to make this library work in my favor.

Now for my question,

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

Or is there something I can do on the client side that would make this communication possible?

A lot of work is handled by my Wifly Module.
I was able to telnet in and set my ipaddress/port#/etc..
Anything sent over IP goes straight through my Module and straight to my arduino.

My
[Client Code][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

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>


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

I'm working on a project and I need to print serial to a LCD but only if the first letter of the serial is ":"

I have the serial being stored in a char and a if statement reading the first letter of the char to see if it is ":" From there I can't get it to print to the LCD without the first letter. I also don't know how to clear the char.

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

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

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

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

      }
     }

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

    lcd.print(inData + 1);


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

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

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


message:
Extremely cheap "Arduino" for single tasks?

I have been thinking of a million things to do with my Arduino, but those things are extremely simple and it would leave my Arduino as a $25 waste.

For example, programming Arduino to control my living room lights with my smartphone ... I was thinking of connecting the Arduino in the wall, onto the light switch wires. I am looking for a "permanent" solution, but I figure this would leave me with a $25 waste of circuitry inside my wall.

Are there any "Arduino" types of electronics that perhaps have many less ports, JUST enough to get a single task done?

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.


message:
Trouble reading from multiple analog ports

So I'm trying to read 4 different analog values and store each one to a variable.  I imagine doing this by first initializing the ADC registers and each time it enters the ADC ISR checking which port it read from and saving it to the corresponding variable.  Then setting the ADMUX to the next ADC port and repeating the whole process.  Unfortunately something goes wonky and I just can't figure out what it is.  If I get rid of the switch case and just read from one port it all works fine, but if I put the switch case back in and try to cycle through them it stops working.  Please ignore the rest of code as this is not complete.  I just included everything I could.  Eventually this will take in 4 values.  Then use them for error checking and a PID loop.

Thanks for any help!

    /*
     * Throttle_by_Wire.c
     *
     * Basic throttle by wire controller
     * for the 2015 Formula Hybrid car
     *
     *  Created on: Nov 24, 2014
     *  Author: Austin R. Bartz
     *
     * Pin Connections:
     *  PB2 - Motor Speed (Enable pin) (PWM)
     *  PB4 - Direction control (Counter-Clockwise)
     *  PB5 - Direction control (Clockwise)
     *  PC0 - Throttle Pedal Sensor A (TPA) (Shallower Slope)
     *  PC1 - Throttle Pedal Sensor B (TPB) (Steeper Slope)
     *  PC2 - Throttle Valve Sensor A (TPSA) (Negative Slope)
     *  PC3 - Throttle Valve Sensor B (TPSB) (Positive Slope)
     */

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

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

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

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

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

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

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

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.


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

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

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