body: If there are no memory restrictions (too large program) which eliminates this option, I'd try to write the Arduino bootloader first and then continue normally. This has the advantage of simple reprogramming if required.


sender: user

message:
Teensy 3.1 no overclock option for 168 MHz

I'm sorry if this isn't the right area. Teensy uses the arduino ide.

I've seen some people show off the 144 mhz and 168 mhz option in their ide. I read in the Teensyduino 1.19 release notes that the options were added but not enabled. I would like to know how to enable it or if I somehow downloaded an older version.

P.S I get the 96 mhz option.

Thanks ahead of time!

sender: assistant

body:
Using the latest Teensyduino distribution as of this writing, 1.25, you have to uncomment the higher overclocking options in the `boards.txt` file, located here in my install-
`/hardware/teensy/avr/boards.txt`

The options look like this, just remove the # symbol-

    #uncomment these if you want to try faster overclocking
    #teensy31.menu.speed.168opt=168 MHz optimized (overclock)
    #teensy31.menu.speed.144opt=144 MHz optimized (overclock)
    #teensy31.menu.speed.120opt=120 MHz optimized (overclock)`


message:
ArrayList implementation fails for string object

I'm using a customised C++ implementation of ArrayList based on the method found in Processing. The original code is by [Obed Isai Rios][1], but I've added a [version to Github with more explicit file structure][2].  The arraylist is appended to by the `add_string_item` method, which works ok in the format `arraylist->add_string_item("text string")` but fails when the same input is a String variable.  The following script illustrates:

    #include "ArrayList.h"
    void setup(){
      ArrayList *list = new ArrayList("text1");
      list->add_string_item("text2");
      String str = "text3";
      list->add_string_item(str);
    }
    void loop(){}

This fails on the last line with error message:

    no matching function for call to 'ArrayList::add_string_item(String&)'

    sketch_aug24b.ino: In function 'void setup()':
    sketch_aug24b:7: error: no matching function for call to 'ArrayList::add_string_item(String&)'
    /Users/robinedwards/Documents/Arduino/libraries/ArrayList/ArrayList.h:17: note: candidates are: void ArrayList::add_string_item(char*)

I'm not familiar with C++ so can't figure out why this method accepts a string but not when assigned to a String object `str`.  I'm pretty sure it's because I need to coerce to char* but not sure how to do this.  I've tried `toCharArray` without success, although this seems the right direction.  Very grateful for any assistance.

ArrayList.cpp code:

    #include "Arduino.h"
    #include "ArrayList.h"

    ArrayList::ArrayList(char* init){
      stringlist = (char**)malloc(10*sizeof(char*));
      stringlist[0] = init;
      this->size = 1;
    }

    ArrayList::~ArrayList(void)
    {
    }

    void ArrayList::add_string_item(char* item){
      char **neulist = (char**)malloc((size+1)*sizeof(char*));
      for(int i=0; i<size; i++){
        neulist[i] = stringlist[i];
       }
       //
       neulist[size] = item;
       stringlist = neulist;
       size = size + 1;
    }

    void ArrayList::set_string_item(char* item, int index){
      stringlist[index] = item;
    }

    void ArrayList::remove_selected_item(int index){
      char **neulist = (char**)malloc((size-1)*sizeof(char*));
      //From Begining
      for(int i=0; i<index; i++){
        neulist[i] = stringlist[i];
      }
      //From next Index
      for(int i=index; i<=size-1; i++){
        neulist[i] = stringlist[i+1];
      }
      //free(matrix);
      stringlist = neulist;
      size = size - 1;
    }

    void ArrayList::empty_list(){
       size = 1;
       char **neulist = (char**)malloc((size)*sizeof(char*));
       stringlist = neulist;
       stringlist[0] = "EMPTY";
    }

    void ArrayList::display_string_list(){
       Serial.begin(9600);
      for(int i=0; i<size; i++){
        Serial.println(stringlist[i]);
       }
    }

    char** ArrayList::get_stringlist(){
      return this->stringlist;
    }

    char* ArrayList::get_item(int index){
      return this->stringlist[index];
    }

    void ArrayList::set_stringlist(char** stringlist){
      this->stringlist = stringlist;
    }

    int ArrayList::get_size(){
      return this->size;
    }

  [1]: https://gist.github.com/obedrios/2970053
  [2]: https://gist.github.com/geotheory/263bef188b7a164bae87

body:
*In theory*, there's no reason why you shouldn't be able to call it by using `toCharArray()`. You would need to call it like this:

    String str = "text3";
    char * buf = new char[str.length()+1];
    str.toCharArray(buf, str.length()+1);

    list->add_string_item(buf);

That allocates a `char` buffer, copies the string data into it, then passes that buffer pointer to the list to be stored. Note that the buffer is one character larger than the string, as it needs to add a null terminator at the end.

However, there is a **major** problem with the rest of your code, which could eventually cause your Arduino to crash or do other strange things (depending on how much you use the list object).

Unlike Java, C++ is not a garbage-collected language, meaning it won't automatically clean-up memory for you. If you call `new` or `malloc()` to allocate heap memory, you have to call `delete` or `free()` (respectively) when you're finished with it to deallocate it.

Simply overwriting a pointer with another call to `malloc()` is not enough; it results in a **memory leak**. This means the block of memory it was previously using is lost, and cannot be reused again as long as the program is running. On a platform like Arduino, which has limited memory, you can very quickly run out.

Fixing the design of your class is probably beyond the scope of an answer on this site. I would strongly recommend working through some C++ tutorials (of which there are hundreds online).

As a side note, you should generally use `new`/`delete` instead of `malloc()`/`free()`. It doesn't make much difference when you're using arrays of `char` or `char*`, but it's important if you want to allocate class instances.


message:
What is the capability of AVRISP and USBASP on ATMega48, 328, 2560?

For use with ATMega 48 (old Arduino?), 328 (UNO, Pro Mini) and 2560 (Mega2560) chips, what is the capability for the AVRISP and USBASP programmers on:

1. Can it read, write fuse?

2. Can it read, write Program Flash?

3. Can it work 3.3 and 5 volts?

4. What workable clock frequency range on the MCU?

5. Can it be used under Arduino ISP to write to board so as to erase the bootloader and use the FULL flash space for big user program (eliminate boot loader saves 0.5 to 8KB space on above Arduino boards)?

6. Can it be used with ATMel factory software development tools (Atmel studio and associated tools) to use MCU on chip hardware based breakpoint (Debug wire, JTag, or other names, as on different MCU)?

Many thanks in advance

body:
1. Yes.

2. Yes.

3. Depends on the specific hardware. See the documentation for the *exact* variant you have.

4. See 3.

5. No. They have their own protocol that you must use instead. They are selectable from the `Programmer` menu in the IDE though. However, you must unprogram the fuse bits outside of the IDE.

6. No. They are low-cost tools meant to be used for programming only. You will need an Atmel-supplied debugger in order to use Atmel Studio's debugging features.


message:
Control Arduino via Wifi directly?

I want to build an arduino-based RC Tank, which should be controlled with a notebook or smartphone (Android). Bluetooth would be an easy solution, but the range is a bit short for a RC Vehicle, so I want to controll it via WIFI. I found a ton of examples and tutorials on how to do that but all of them reqire a router which both the arduino and the Smartphone are connected to. Any idea on how to directly control an Arduino with an smartphone via WIFI?

body: If your computer/tablet/phone can act as a WiFi hotspot, you could use that to avoid the router. Many smartphones have that capability, as do many notebooks (as geometrikal mentioned, it's usually referred to as an 'ad-hoc' network on PCs). Create the network (or turn on hotspot capability), and connect to the network you created from your Arduino.


message:
Using an array as a queue

I recently created a state machine for my latest Arduino project. It is a simple LED control, but it has many different modes and functions. I created a template for my state machine so I can use it in the future, but I am looking to take it to the next level. Here is a copy of the current template for reference:

    /*Setup Variables here*/
    int nextState;
    int currState;

    /*Fill enum with all case names*/
    enum cases{

      init;
      idle;
      case1;
      case2;
      leave;

    };

    /*Begin Program*/
    void setup(){
      Serial.begin(9600);
      currState = init;
    }

    void loop(){
      switch(currState){

        case init:
          /*Prepare program here*/
          nextState = idle;
          break;

        case idle:
          if (input1){
            nextState = case1;
          }else if (input2){
            nextState = case2;
          }else{
            nextState = idle;
          }

        case case1:
          //Code for case1 here
          break;

        case case2:
          //Code for case2 here
          break;

      }

      currState = nextState;
    }

I am trying to make a Queued State Machine (QSM). This means that instead of a single variable nextState, I can add several states to be executed. Is the best way to do this an array? I have not found much in my research about how to add and remove elements easily, so if this is the best way, could you point me towards a good tutorial on these types of array functions?

Thanks in advanced for all the help!

body:
Have an array with fixed size, and have **two** indexes. One pointing to the first/current item in the queue, the other to the last item in the queue.

(It actually better/easier to have the second index point to where the next item has to be written)

To add an item to the queue:

 1. Check that that the queue isn't full (second index is the same as the first)
 2. If not write to second index.
 3. Increment second index, and modulo array/queue size, so it wraps around.

To read from the queue

 1. Read value at the first index
 2. Increment first index, modulo array/queue size


message:
Why is Arduino STINO upload function not working?

I'm using sublime text for editing and modifying my arduino libraries. Sublime text is pretty pretty, useful and embed a very powerfull plugin system. Someone created an Arduino plugin for it. The compilation function works but the upload doesn't.

I'm trying to upload on an arduino leonardo using Windows 7 x64.

Did anyone tried to fix this problem ?

body:
I finally found it: Problem was solved after commenting those three lines in */Arduino-like IDE/app/uploader.py:

    if force_to_reset:
        pre_serial_port = serial_port
        wait_for_upload_port = self.args.get('upload.wait_for_upload_port', 'true') == 'true'
        serial_port = resetSerial(pre_serial_port, self.output_console, wait_for_upload_port)
        # if self.args['cmd'] != 'avrdude':
        #  if serial_port.startswith('/dev/'):
        #   serial_port = serial_port[5:]
        if serial_port:
            for cur_command in self.command_list:
                command_text = cur_command.getCommand()
                command_text = command_text.replace(pre_serial_port, serial_port)
                cur_command.setCommand(command_text)


message:
File Size Problem with EyeFi SD Card and Arduino Mega

I've been writing to an EyeFi SD card with an Arduino Mega.  I've managed to get the files to upload wirelessly, but I noticed that my data gets cut off when the file reaches a size of 24 kb.  If I use a normal SD card, the file is able to keep logging past 24 kb.  The EyeFi card is able to upload large images, so I'm not sure what is limiting my file size for the EyeFi card.  Can I get some advice?

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

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

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

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

      newFile();

      Serial1.begin(115200);

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

      i = 0;
    }

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

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

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

        i = 0;
      }
    }

body:
After some testing and research, I found out that the Eye-Fi SD card starts a transfer once a file reaches 20kb or more and will not upload a file again once it has been transfered already.  The solution, as suggested by ChrisStratton, is to log to a temporary file and trigger a transfer once the file is ready.

I took advantage of the fact that the Eye-Fi only transferring files in the standard camera folders.  In my case, I used the Nikon naming convention: DCIM/100NIKON/DSCNxxxx.JPG  (xxxx is the photo number ranging from 0000 to 9999), but there are also others.  Check on the Eye-Fi website for compatible cameras.  I created a temporary file called TEMP.TMP and stored it to the root folder of the card and logged to it.  Once I'm ready to transfer the file, TEMP.TMP gets renamed to "DCIM/100NIKON/DSCNxxxx.JPG" and the whole file is transferred all at once.

Here's my code.  I'm using the software serial (pins 10, 11, 12, 13) of the Mega:

    //Running with 256kb serial buffer (modified HardwareSerial.cpp)
    //Added file time stamps

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

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

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

    const uint8_t chipSelect = 10;

    SdFat sd;
    SdFile logfile; //create log file

    RTC_DS1307 RTC;
    DateTime filedate;

    uint16_t date;
    uint16_t time;

    int i = 0;
    int x = 0;

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

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

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

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

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

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

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

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

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

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

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

      Serial.println("Card initialized");

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

      // create new file name
      newFileName();

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

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

      Serial1.begin(115200);

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

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

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

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

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

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


message:
Uploading bootloader on ATmega328P SMT package using Arduino Uno

I have been trying to upload bootloader on ATmega328P SMT package on a custom PCB using Arduino Uno as ISP, I was quite successful.

I have Googled a lot and have tried numerous ways, sometimes I was able to successfully upload the bootloader, but I am not able to upload the sketch am getting "avr sync error".

- What kind of bootloader should I use for this particular package?

- How should I upload the sketches into the chip?

body:
I've had success with bootloader of the Arduino IDE.
I used to have some trouble uploading sketches, but I solved them by doing this:

1. If the atmega is already soldered in a pcb and you have a pull up resistor, or something else connected to the reset pin, disconnect it. reset pin must be free.
2. Connect the tx, rx and rst pins of your atmega to your arduino.
3. Press the Upload button in the Arduino IDE and see the leds tx,rx in your arduino, just after the first blink, press the reset button, after that both of the leds should start blinking and in the end your code should be uploaded.


message:
Using VS1838B with Arduino

I just bought VS1838B IR module ([from here][1]) and I’m trying to make it work. Below you can find the circuit to see how I have connected the 1838B IR receiver:

![enter image description here][2]

My Code ([Here][3]) :

    #include <IRremote.h>

    int RECV_PIN = 2;
    IRrecv irrecv(RECV_PIN);
    decode_results results;
    #define CH1 0xFFA25D
    #define CH 0xFF629D
    #define CH2 0xFFE21D
    ...
    #define BUTON8 0xFF4AB5
    #define BUTON9 0xFF52AD

    void setup()

    {

     Serial.begin(9600);

     irrecv.enableIRIn();

    }

    void loop() {

     if (irrecv.decode(&results))
      {

     if (results.value == CH1)

     {

     Serial.println("CH-");
     }

     if (results.value == CH)

     {

     Serial.println("CH");

     }

     if (results.value == CH2)

     {

     Serial.println("CH+");

     }

     ...

     if (results.value == BUTON8)

     {

     Serial.println("BUTON8");

     }
    if (results.value == BUTON9)

     {

     Serial.println("BUTON9");

     }
     irrecv.resume();

     }

    }

But I'm not getting any output from Serial Monitor.
Can you help me for debugging it?

  [1]: http://www.robotistan.com/IR-Alici-Verici-Kumanda-Seti-IR-Receiver-Module-Wireless-Remote-Control-Kit,PR-1788.html
  [2]: https://i.stack.imgur.com/L6f6j.gif
  [3]: http://paste.ubuntu.com/8143467/

body:
Looking further here

http://forum.arduino.cc/index.php/topic,188236.0.h...

I found the following

"Removing
the files - libraries\RobotIRremote\IRremoteTools.cpp and
libraries\RobotIRremote\IRremoteTools.h solved the problem. They are
example files which somehow are getting included. You can move those two
files to some other location as backup."

I went to my libraries
file and did this and can confirm that the example given above then
compiles fine without downloading a new library. Its an Arduino
libraries problem .

Either way will work

[answer from here and worked for me][1]

  [1]: http://www.instructables.com/id/Remote-Control-Light-switch-ARDUINO/

i use this code:

    #include <IRremote.h>
    int input_pin = 10; //set D10 as input signal pin
    IRrecv irrecv(input_pin);
    decode_results signals;
    void setup()
    {
     Serial.begin(9600);
     irrecv.enableIRIn(); // enable input from IR receiver
    }
    void loop() {
    if (irrecv.decode(&signals)) {
      Serial.println(signals.value, HEX);
      irrecv.resume(); // get the next signal
     }
    }


body:
I could be wrong, but I believe that this receiver operates at 38kHz (at least that is listed in the specs), so the IR source must be oscillating at that frequency for this receiver to see it. Check out this link to see how to create a circuit to oscillate your IR LED:

http://www.electro-tech-online.com/threads/ir-emitter-at-38khz.94119/


body: i have also bought this IR receiver with a remote controller (as a kit), and i had the same problem, i changed the remote controller and it worked perfectly, so even if the IR and RC came as a kit it doesn't mean they will work, if you don't have another remote controller in hand you can use a lighter just to check if the IR is working.


body:
    void loop(void) {
       int numberpulses;

       numberpulses = listenForIR();

       Serial.print("Heard ");
       Serial.print(numberpulses);
       Serial.println("-pulse long IR signal");
       if (IRcompare(numberpulses, ApplePlaySignal)) {
          Serial.println("PLAY");
          if (ledState == LOW)
             ledState = HIGH;
          else
             ledState = LOW;

          // set the LED with the ledState of the variable:
          digitalWrite(ledPin, ledState);

       }
       if (IRcompare(numberpulses, AppleRewindSignal)) {
          Serial.println("REWIND");
       }
       if (IRcompare(numberpulses, AppleForwardSignal)) {
          Serial.println("FORWARD");
       }
    }


body:
connect vcc to 5V
connect Gnd to GND
connect In to D11 pin onto Uno, Nano etc.
download the library from here and follow the instructions/where to unzip and removing the other folders/:
http://z3t0.github.io/Arduino-IRremote/

Open the Arduino program and paste this code onto a new Arduino project:

    int RECV_PIN = 11;
    IRrecv irrecv(RECV_PIN);
    decode_results results;
    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
    }
    void loop()
    {
      if (irrecv.decode(&results))
        {
         Serial.println(results.value, HEX);
         irrecv.resume(); // Receive the next value
        }
    }

Select 'Sketch'/Import Library from Arduino and select IRremote from the drop-down menu.

Upload the sketch
Open Tools/Serial monitor then select 9600 as baud rate
Use a Tv remote, IR car remote or the remote from the module.
You will see the HEX code of each button after pressing it.


message:
Arduino Due - creating an 8Mhz clock signal

I am attempting to interface a OV7670 camera to an arduino Due. (I am fairly new to this although have been programming for many years).

I need to generate a clock signal for the camera at a minimum of 8Mhz - I realise using the pre-scalers I can only get an approximation but I am cool with that.

I finally got a nice steady 3mhz signal from the sketch below (note that the irq routine for TC6 is not used and will be removed very soon (as soon as I get home).

I think I have a conceptial problem with the timers because as I am initialising RA and RC to 1 and telling via TC_Configure to toggle the line, and because I am using CLOCK1 (42 Mhz), I believe with those values of RA and RC I should be getting a 21'ish MHZ signal.

Ie RA starts at zero. First CLOCK1 tick. (at second/48,000,000) interval. RA Goes to 1 COmpares to RC Because they are equal, resets RA to 0 and toggles TIOA6 Next Clock1 tick occurs.....

As I said I am only getting a 3Mhz signal.

    void TC6_Handler()
    {
            TC_GetStatus(TC2, 0);

    }

    void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq) {
            pmc_set_writeprotect(false);
            pmc_enable_periph_clk((uint32_t)irq);

            TC_Configure(tc, channel,
                   TC_CMR_WAVE |
                   TC_CMR_WAVSEL_UP_RC |
                   TC_CMR_TCCLKS_TIMER_CLOCK1|
                   TC_CMR_ACPA_TOGGLE );  // RC compare TOGGLES TIOA);

            TC_SetRA(tc, channel, 1); //50% high, 50% low
            TC_SetRC(tc, channel, 1);

            PIO_Configure(PIOC,
                       PIO_PERIPH_B,
                       PIO_PC25B_TIOA6,
                       PIO_DEFAULT);

           TC_Start(tc, channel);

    }

    void setup(){

            startTimer(TC2, 0, TC6_IRQn);
    }

    void loop(){
    }

body:
1) Timer counts close to zero are useless... i.e. they work same, as if count = 0; (I ran Due timers with TIMER_CLOCK_2 i.e. MCK/8 or 10.5MHz many times)

2) Select a reasonable pre-scalar depending on output frequency you need such that RC count will be a bit more. Here 42 MHz (TIMER_CLOCK_1)  means you need a count of RC = 5 approximately (with RA = RC/2 for 50% duty ratio) for 8 MHz. When RA closes to RC we get output of half frequency i.e. close to 4 MHz.

I think here better option is to use master clock itself i.e. 84 MHz, then RC = 10 (approximately)(with RA = RC/2 for 50% duty ratio). Master clock can be selected using TIMER_CLOCK_5 (I am not sure..please check in the data sheet).

May be Arduino Due (with its clock and using timers) is not good option to generate pulses at that higher frequency (you can't execute other routines in just 10 clock cycles!) . If no additional processing is needed, why not go for a pulse generating IC....just my opinion :-)


body:
the code below should give you a 8.4MHz signal on digital pin 7 of the due. I have used it to generate a 4.2MHz clock (by setting `REG_PWM_CPRD6 = 20;` and `REG_PWM_CDTY6 = 10;` but I think it should work for a 8.4MHz clock also.

I have been using this to provide a 4.2MHz clock signal instead of using a crystal oscillator for an ADE7913 and can confirm it is working well in that application. I have taken this from the arduino forum [here][1].

    #include <Arduino.h>

    const unsigned long serialPeriodMillis = 2000;
    unsigned long previousMillis = 0;

    void setup()
    {
      int32_t mask_PWM_pin = digitalPinToBitMask(7);
      REG_PMC_PCER1 = 1 << 4;                         // activate clock for PWM controller
      REG_PIOC_PDR |= mask_PWM_pin;                   // activate peripheral functions for pin (disables all PIO functionality)
      REG_PIOC_ABSR |= mask_PWM_pin;                  // choose peripheral option B
      REG_PWM_CLK = 0;                                // choose clock rate, 0 -> full MCLK as reference 84MHz
      REG_PWM_CMR6 = 0 << 9;                          // select clock and polarity for PWM channel (pin7) -> (CPOL = 0)
      REG_PWM_CPRD6 = 10;                             // initialize PWM period -> T = value/84MHz (value: up to 16bit), value=10 -> 8.4MHz
      REG_PWM_CDTY6 = 5;                              // initialize duty cycle, REG_PWM_CPRD6 / value = duty cycle, for 10/5 = 50%
      REG_PWM_ENA = 1 << 6;                           // enable PWM on PWM channel (pin 7 = PWML6)

      Serial.begin(115200);
      Serial.println("Serial on");
    }

    void loop()
    {
      if (millis() - previousMillis > serialPeriodMillis) {
        Serial.println("TIC");
        previousMillis = millis();
      }
    }

  [1]: http://forum.arduino.cc/index.php?topic=184799.0


body:
Example from Khalid Abdulla is correct, but I used 10.5 MHz for my ov7670 camera:

    int32_t mask_PWM_pin = digitalPinToBitMask(7);
    REG_PMC_PCER1 = 1<<4;               // activate clock for PWM controller
    REG_PIOC_PDR |= mask_PWM_pin;  // activate peripheral functions for pin (disables all PIO functionality)
    REG_PIOC_ABSR |= mask_PWM_pin; // choose peripheral option B
    REG_PWM_CLK = 0;                     // choose clock rate, 0 -> full MCLK as reference 84MHz
    REG_PWM_CMR6 = 0<<9;             // select clock and polarity for PWM channel (pin7) -> (CPOL = 0)
    REG_PWM_CPRD6 = 8;                // initialize PWM period -> T = value/84MHz (value: up to 16bit), value=8 -> 10.5MHz
    REG_PWM_CDTY6 = 4;                // initialize duty cycle, REG_PWM_CPRD6 / value = duty cycle, for 8/4 = 50%
    REG_PWM_ENA = 1<<6;               // enable PWM on PWM channel (pin 7 = PWML6)

My results: [Arduino Due and OV7670][1]

  [1]: http://privateblog.info/arduino-due-i-kamera-ov7670-primer-ispolzovaniya/


message:
ATTiny85 Interrupt id vs pin when programming with Arduino

I am using an Arduino Uno with the Arduino as ISP sketch to program an ATtiny85.

I followed this [tutorial][1] to set up to program the ATtiny, and successfully got it to run Blink and an interrupt-free version of my program.

I then added an interrupt triggered by a button and got it working on the Arduino Uno (with a software debounce in the ISR). Now I want to run that sketch, with appropriate pin changes, on the ATtiny. Which pins correspond to which interrupt IDs for `attachInterrupt()`?

Or can I not use `attachInterrupt()`? If I can't, how do I do set up an interrupt on an ATtiny85?

  [1]: http://highlowtech.org/?p=1695 "Programming an ATtiny w/ Arduino 1.0"

body:
You can setup interrupts on the Attiny with some different code, but it works the same way. It's important to note that PIN Change Interrupts are triggered at BOTH Rising and Falling Edge

Pins:
[![enter image description here][1]][1]

Using the [Arduino-Tiny Cores][2]

Below is a sample code which used a Pin Change Interrupt on PB1 which switches an LED on and off on PB4.

    //Includes
    #include <avr/io.h>
    #include <avr/interrupt.h>

    #define INTERRUPTPIN PCINT1 //this is PB1 per the schematic
    #define PCINT_VECTOR PCINT0_vect  //this step is not necessary
    #define DATADIRECTIONPIN DDB1 //Page 64 of data sheet
    #define PORTPIN PB1 //Page 64
    #define READPIN PINB1 //page 64
    #define LEDPIN 4 //PB4

    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) //OR
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) //AND

    /*
     * Alias for the ISR: "PCINT_VECTOR" (Note: There is only one PCINT ISR.
     * PCINT0 in the name for the ISR was confusing to me at first,
     * hence the Alias, but it's how the datasheet refers to it)
     */

    static volatile byte LEDState; //variable used within ISR must be declared Volatile.

    void setup() {
        cli();//disable interrupts during setup
        pinMode(LEDPIN, OUTPUT); //we can use standard arduino style for this as an example
        digitalWrite(LEDPIN, LOW); //set the LED to LOW
        LEDState = 0; //we use 0 for Low state and 1 for High
        PCMSK |= (1 << INTERRUPTPIN); //sbi(PCMSK,INTERRUPTPIN) also works but I think this is more clear // tell pin change mask to listen to pin2 /pb3 //SBI
        GIMSK |= (1 << PCIE);   // enable PCINT interrupt in the general interrupt mask //SBI

        DDRB &= ~(1 << DATADIRECTIONPIN); //cbi(DDRB, DATADIRECTIONPIN);//  set up as input  - pin2 clear bit  - set to zero
        PORTB |= (1<< PORTPIN); //cbi(PORTB, PORTPIN);// disable pull-up. hook up pulldown resistor. - set to zero
        sei(); //last line of setup - enable interrupts after setup

    }

    void loop() {
      // put your main code here, to run repeatedly:
      //If you connect a debounced pushbutton to PB2 and to VCC you can tap the button and the LED will come on
      //tap the button again and the LED will turn off.

    }

    //this is the interrupt handler
    ISR(PCINT_VECTOR)
    {
      //Since the PCINTn triggers on both rising and falling edge let's just looks for rising edge
      //i.e. pin goes to 5v
      byte pinState;
      pinState = (PINB >> READPIN)& 1; //PINB is the register to read the state of the pins
      if (pinState >0) //look at the pin state on the pin PINB register- returns 1 if high
      {
       if (LEDState == 0)
       {
        digitalWrite(LEDPIN,HIGH); //you can use Arduino Code or LowerLevel Code to write to the register
        LEDState = 1;
        }
       else
       {
        digitalWrite(LEDPIN,LOW);
        LEDState = 0;
        }
      }

    }

If you're going to be using the ATTiny85, I highly suggest you read through the data sheet to understand better how to program these chips at a lower level of code....It took me a while for it to start to make sense.

  [1]: https://i.stack.imgur.com/gpt63.png
  [2]: https://code.google.com/p/arduino-tiny/


message:
What's the best way to control a USB-powered desk light

I recently bought a USB-powered desk light. Is it possible to control (turn on/off) it with the Arduino Uno? The desk light has 3W so needs 600mA.

1. Should I connect the USB wire with the 5V pin of the Arduino (which can spend up to 800mA) or should I use an external USB power supply ?
2. How to control the light when using an external USB power supply ?

body:
You have a couple options here. The main idea is that you're going to add a switch to the light's circuit and that switch will be controlled by the arduino. It's important that you keep the electronics for the light and the electronics for your arduino separate, 600mA will damage your arduino which no one wants. You can power the light and arduino from the same power supply, make sure it can handle the power draw though.

To actually switch the circuit you could use an NPN transistor as mentioned above, with the lamp's - terminal flowing into the C pin, an arduino GPIO pin connected to the B pin and the E pin grounded. When you set your arduino's pin `HIGH` the transistor will allow current to flow and light up the lamp.

Another option that actually physically separates the circuits is to use an opto-coupler. They're little IC's that serve this exact purpose. The have a light and a light sensitive transistor inside them, so when the light illuminates, the transistor allows current to flow. In your case, you would hook up an arduino pin to the + pin on the light side of the coupler and ground the - pin. Then connect your lamp in the same to the other side, +5v into the + pin on the transistor side and the lamp's positive terminal to the output pin. Again, when the arduino pin goes `HIGH`, the lamp will light up.


body:
Use a TIP120 Darlington transistor to switch the current.
This webpage has a detailed guide. http://bildr.org/2011/03/high-power-control-with-arduino-and-tip120/
Use the example with the light bulb - no diode is needed in your case.


message:
Arduino Yun Webpage Server Issues

So, I've made a sketch on my Yun, which I would like to be able to take information from a webpage (like a button) and have the Arduino Microcontroller perform functions based on what button is being pressed. I have an html file with the webpage of buttons. I also have a sketch that responds to those button presses. When I upload the project via WiFi, everything copies over properly. The html file gets copied to the SD card, the sketch gets loaded onto the Arduino Microntroller, and I can browse to the webpage with my browser. However, whenever I click on the button within the webpage, nothing gets sent back to the Arduino Microcontroller. If actually program the webpage into the actual sketch, everything works fine, but not if the webpage is being loaded onto the SD card. After that, no data gets passed between the Linio and the Atmel Microcontroller.

I would like to be able to have the webpage be hosted by the Linio processor, but pass information about button presses to the actual Atmel Microcontroller.

Does anybody know how to do this properly? I would like to stay away from JScript and AJAX as much as possible. However, I guess I'll use them only if it's absolutely necessary.

Here is my arduino sketch:

    #include <Bridge>
    #include <Console.h>
    #include <YunServer.h>
    #include <YunClient.h>

    YunServer server;
    boolean receiving = false;

    void setup() {
      Bridge.begin();
      Console.begin();
      server.listenOnLocalhost();
      server.begin();
      Console.println("Ready");
    }

    void loop() {
      YunClient client = server.accept();

      if (client) {
        Console.println("Client Connected");
        String request = client.readString();
        Console.println(request);

        boolean currentLineIsBlank = true;
        boolean sentHeader = false;

        while (client.connected()) {
           if (client.available()) {
             char c = client.read();

           if (receiving && c == ' ') receiving = false;

           if (c == '?') receiving = true;

           if (receiving) {
              if (c == 'A') {
                Console.println("Three Beeps");
                threeBeeps();
                break;
              }
              else if (c == 'B') {
                Console.println("Fast Beeps");
                fastBeeps();
                break;
              }
              else if (c == 'C') {
                Console.println("Fast Scale");
                fastScale();
                break;
              }
              else if (c == 'D') {
                Console.println("Alarm");
                playAlarm();
                break;
              }
              else if (c == 'E') {
                Console.println("Evil Alarm");
                evilChord();
                break;
              }
            }
            if (!sentHeader) {

      /*** I COMMENTED THIS PART OUT WHEN TESTING THE ACTUAL HTML FILE ***/
      /************************* ON THE SD CARD **************************/

               //client.println("HTTP/1.1 200 OK");
               //client.println("Content-Type: text/html\n");
               //
               //client.println("<form action='' method='get'>");
               //client.println("<input type='hidden' name='A' value='1' />");
               //client.println("<input type='submit' value='Three Beeps' />");
               //client.println("</form>");
               //
               //client.println("<form action='' method='get'>");
               //client.println("<input type='hidden' name='B' value='2' />");
               //client.println("<input type='submit' value='Fast Beeps' />");
               //client.println("</form>");
               //
               //client.println("<form action='' method='get'>");
               //client.println("<input type='hidden' name='C' value='3' />");
               //client.println("<input type='submit' value='Fast Scale' />");
               //client.println("</form>");
               //
               //client.println("<form action='' method='get'>");
               //client.println("<input type='hidden' name='D' value='4' />");
               //client.println("<input type='submit' value='Alarm' />");
               //client.println("</form>");
               //
               //client.println("<form action='' method='get'>");
               //client.println("<input type='hidden' name='E' value='5' />");
               //client.println("<input type='submit' value='Evil Siren' />");
               //client.println("</form>");

                 sentHeader = true;
            }
            if (c == '\n' && currentLineIsBlank) break;

            if (c == '\n') {
               currentLineIsBlank = true;
            }
            else if(c != '\r') {
              currentLineIsBlank = false;
            }
          }
        }
        delay(5);
        client.stop();
      }
    }

    void threeBeeps() {
      for (int i = 0; i < 3; i++) {
        tone(11,2200);
        delay(100);
        noTone(11);
        delay(100);
      }
      noTone(11);
    }

    void fastScale() {
      for (int i = 0; i < 1000; i++) {
        tone(11,(i * 2));
        delay(1);
      }
      for (int i = 1000; i > 0; i--) {
        tone(11,(i * 2));
        delay(1);
      }
      noTone(11);
    }

    void playAlarm() {
      for (int i = 0; i < 5; i++) {
        for (int j = 1000; j < 4000; j++) {
          tone(11,j);
        }
        for (int j = 4000; j > 1000; j--) {
          tone(11,j);
        }
      }
      noTone(11);
    }

    void fastBeeps() {
      for (int i = 0; i < 6; i++) {
        tone(11,2000);
        delay(50);
        noTone(11);
        delay(50);
      }
      noTone(11);
    }

    void evilChord() {
      for (int i = 0; i < 5; i++) {
        tone(11,1110);
        delay(500);
        tone(11,785);
        delay(500);
      }
      noTone(11);
    }

Here's the code in my index.html file:

    <!DOCTYPE html>
    <head>
    </head>
    <body>
     <form action='' method='get'>
     <input type='hidden' name='A' value='1'>
     <input type='submit' value='Three Beeps' />
     </form>

     <form action='' method='get'>
     <input type='hidden' name='B' value='2'>
     <input type='submit' value='Fast Beeps' />
     </form>

     <form action='' method='get'>
     <input type='hidden' name='C' value='3'>
     <input type='submit' value='Fast Scale' />
     </form>

     <form action='' method='get'>
     <input type='hidden' name='D' value='4'>
     <input type='submit' value='Alarm' />
     </form>

     <form action='' method='get'>
     <input type='hidden' name='E' value='5'>
     <input type='submit' value='Evil Siren' />
     </form>
    </body>

As you can probably tell, the 5 buttons the webpage generates tells the Arduino to play a sound corresponding to the pressed button.

Like I said, I can program the webpage into the actual sketch (all commented out for the time being), and everything works just dandy. However, if I load the webpage onto the SD card in the Yun, I can still browse to it by browsing to `"Arduino.local/sd/<project name>"`, but the buttons no longer function since the webpage was sent to the client from the Linio and not the Arduino. The reason I am wanting to let the Linio handle the webpage is because it can handle much larger webpages much more quickly without taking up precious sketch room on the Arduino. Also, I CAN read an SD card with the Arduino and send the webpage to the clients that way, but it's way too slow compared to using the Linio. So, does anybody know how to take the button presses from the Linio and send them back to the Arduino?

Any help would be greatly appreciated!

body:
Your form actions are empty: when you'll press the buttons, they will send data to the current URL (something like `/sd/project_name/index.html`) instead of the `/arduino` url, which sends data to YunClient.

Reading your sketch, I think they are something like `/arduino/?A=1`, right?

A couple of advices:

 1. start from the sketch and make sure you can control it from the browser. Manually type the expected URLs and verify the played sound.
 2. Make the URLs easy to read, like `/arduino/sound/A`
 3. Use the approach of Bridge example: code something like

`String command = client.readStringUntil('/');
if (command == "sound") {
  char soundType = client.read()
  if (soundType == 'A') {
    ...`


body:
I fixed my problem by changing my sketch to this:

    #include <Bridge>
    #include <Console.h>
    #include <YunServer.h>
    #include <YunClient.h>

    YunServer server;
    boolean receiving = false;

    void setup() {
      Bridge.begin();
      Console.begin();
      server.listenOnLocalhost();
      server.begin();
      Console.println("Ready");
    }

    void loop() {
      YunClient client = server.accept();

      if (client) {
        String command = client.readString();
        command.trim();

        if (command == "threeBeeps") {
          Console.println("Three Beeps");
          threeBeeps();
        }
        if (command == "fastBeeps") {
          Console.println("Fast Beeps");
          fastBeeps();
        }
        if (command == "fastScale") {
          Console.println("Fast Scale");
          fastScale();
        }
        if (command == "siren") {
          Console.println("Siren");
          playSiren();
        }
        if (command == "evilAlarm") {
          Console.println("Evil Alarm");
          evilChord();
        }
        client.stop();
      }
      delay(50);
    }

    void threeBeeps() {
      for (int i = 0; i < 3; i++) {
        tone(11,2200);
        delay(100);
        noTone(11);
        delay(100);
      }
      noTone(11);
    }

    void fastScale() {
      for (int i = 0; i < 1000; i++) {
        tone(11,(i * 2));
        delay(1);
      }
      for (int i = 1000; i > 0; i--) {
        tone(11,(i * 2));
        delay(1);
      }
      noTone(11);
    }

    void playSiren() {
      for (int i = 0; i < 5; i++) {
        for (int j = 1000; j < 4000; j++) {
          tone(11,j);
        }
        for (int j = 4000; j > 1000; j--) {
          tone(11,j);
        }
      }
      noTone(11);
    }

    void fastBeeps() {
      for (int i = 0; i < 6; i++) {
        tone(11,2000);
        delay(50);
        noTone(11);
        delay(50);
      }
      noTone(11);
    }

    void evilChord() {
      for (int i = 0; i < 5; i++) {
        tone(11,1110);
        delay(500);
        tone(11,785);
        delay(500);
      }
      noTone(11);
    }

And also by changing my webpage to this:

    <!DOCTYPE html>

    <button onclick="threeBeeps()">Three Beeps</button>
    <button onclick="fastBeeps()">Fast Beeps</button>
    <button onclick="fastScale()">Fast Scale</button>
    <button onclick="siren()">Siren</button>
    <button onclick="evilAlarm()">Evil Alarm</button>

I also include the `zepto.min.js` Javascript file.


message:
What software is available for use with AVRISP and USBASP on ATMega48, 328, 2560?

What software is available for use with AVRISP and USBASP on ATMega328, 2560 for read/write fuse, flash and EEPROM for UNO, Pro Mini and Mega2560 board?

(a fact question not opinion) Which software did you use?

Did it work straight forward (like the software did all the needed 'auto select')?

Does it need human selection for options, etc. on the above 3 boards?

Do I need WinAVR installed before able to use the 'ISP software'?

body: Almost everyone uses either AVRDUDE (directly or indirectly, e.g. via the Arduino IDE) or the upload capability in Atmel Studio. I cannot speak for AS, but AVRDUDE does require options to tell it which programmer and device to use. WinAVR includes AVRDUDE, but is not strictly required as Win32 downloads are available at the AVRDUDE site.


body:
As Ignacio Vazquez-Abrams mentioned, you should look into [Atmel Studio][1]. You can use a 3rd party AVR programmer (Arduino w/isp) or one from Atmel. The IDE is awesome and has a lot of features like setting fuse bits.

  [1]: http://www.atmel.com/tools/atmelstudio.aspx


message:
Arduino Underwater Inertial Navigation

I am working on prototyping an underwater navigation system with Arduino. It's going to be used to track movement underwater from a starting point and then be able to tell how to get back to that point or relatively close. The unit would only be going a few hundred feet underwater.

I am using an Arduino Nano, is this going to be sufficient? Also, what IMU would you recommend? I'm sure it will need to at least have a 3-axis gyroscope, 3-axes accelerometer, and possibly a 3-axis magnetometer.

This does need to be relatively affordable. Currently I'm building a unit that can go underwater and just record data onto an SD card so that I can take the data and map it out to check the IMUs accuracy, error margin, along with test various filters on the data. Any recommendations would be greatly appreciated.

body:
The nano can run an IMU just fine, but unfortunately no accelerometer based IMU short of some fancy missile guidance tech is going to be able to track position as accurately as you seem to want.

Since the Gyro and Magnometer only help with rotational orientation, the accelerometer is the only source of info on linear motion, and it has to be integrated twice to get position or distance. This site has a great explanation:
http://www.chrobotics.com/library/accel-position-velocity

As their table shows, even with an angular error of only .1 degrees, after 1 minute your position could be off by 62 meters with a standard quality accelerometer.

As far as IMU's go, the MPU 6050 (accl, gyro) and MPU 9150 (Accl, gyro and mag) are pretty standard in the hobby area, and sparkfun has some breakouts. The AltiIMU from Pololu has similar features and comparable cost. If you don't want to do the sensor processing the UM7 from chrobotics works well, but is significantly more expensive.


message:
How to detect if running Arduino or bare Atmega328p?

I'm building something that will mostly run on bare ATmega328p at 8 MHz (as described eg. [**here**][1]), but sometimes I need to run the same code on an Arduino.

I need to **[initialize the DHT library][2]** depending on the clock frequency. For simplicity, I'd rather detect the running environment runtime, in the program itself.

So, is there a straightforward way to detect the clock speed (from fuses?) or some other difference between a stock UNO board and a bare ATmega328p using the internal 8 MHz clock?

  [1]: http://www.gammon.com.au/forum/?id=11637
  [2]: https://github.com/adafruit/DHT-sensor-library/blob/master/examples/DHTtester/DHTtester.ino#L21

body:
Bare vs Stock is nearly impossible to detect at compile time. Where it depends on what you think you are trying to determine versus detect.

The best I can think of is creating a different Board definition; one for your bare and the other being the stock (i.g. UNO). Where now in IDE 1.5 see [github.com/arduino/Arduino/wiki/…](https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification) the parameter uno.build.board=AVR_UNO, which provides is used to set a compile-time variable ARDUINO_{build.board} to allow use of conditional code between #ifdefs. So you can create bare board definition with e.g. bare.build.board=MY_BARE and then have some #ifdef's for ARDUINO_MY_BARE

Otherwise wrap some #ifdef's around F_CPU as @sechleen points out. This is viable and done often in the core libraries.


body:
The easiest way to distinguish your bare AVR from the arduino board at run time is to build the bare AVR board with a distinguishing feature - such as a known
voltage on one of the D/A ports - that won't be present on your Arduino.


message:
Arduino Uno- Analog serial monitor not reading values over 174

I am simultaneously using a LEGO sound sensor in pin A5 and a RadioShack Tricolor LED Strip (Product #2760339) in pin A0.

The sound sensor alone works as expected (producing values based on volume) running only code to read the value and output to the serial monitor. However when I upload the program to use the LED strip, read the sensor value and output to the serial monitor, the sensor value caps at 174.

The program given to run the LED strip can be found at <http://blog.radioshack.com/2013/06/tricolor-led-strip/>
The code I added to this was pulled mostly directly from the AnalogInOutSerial example provided by Arduino.

Here is the full code;

    /***************************************************************************/
    //            Hardware: RadioShack Tricolor LED Strip
    //            Arduino IDE: Arduino-1.0
    //            Date:      April 17, 2013
    //            Copyright© 2013 RadioShack Corporation
    //
    //  This library is free software; you can redistribute it and/or
    //  modify it under the terms of the GNU Lesser General Public
    //  License as published by the Free Software Foundation; either
    //  version 2.1 of the License, or (at your option) any later version.
    //
    //  This library is distributed in the hope that it will be useful,
    //  but WITHOUT ANY WARRANTY; without even the implied warranty of
    //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    //  Lesser General Public License for more details.
    //
    //  You should have received a copy of the GNU Lesser General Public
    //  License along with this library; if not, see <http://www.gnu.org/licenses/>
    //
    /*****************************************************************************/

    #include <avr/pgmspace.h>

    // ******** DEBUG ==== should auto config to adapt different mother board *********
    //#define DATA_1 (PORTF |=  0X01)    // DATA 1    // for ATMEGA
    //#define DATA_0 (PORTF &=  0XFE)    // DATA 0    // for ATMEGA
    //#define STRIP_PINOUT DDRF=0xFF  // for ATMEGA
    #define DATA_1 (PORTC |=  0X01)    // DATA 1    // for UNO
    #define DATA_0 (PORTC &=  0XFE)    // DATA 0    // for UNO
    #define STRIP_PINOUT (DDRC=0xFF)    // for UNO

    PROGMEM const unsigned long rainbow_full[5][10]={
      {0xff0000,0x00ff00,0x0000ff,0xffff00,0xff00ff,0xffffff,0xff6622,0xff0000,0xff0000,0xff0000},

    };
    PROGMEM const unsigned long off[1][10] = {
       {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
    };
    PROGMEM const unsigned long red1[1][10] = {
       {0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
    };
    PROGMEM const unsigned long red2[1][10] = {
       {0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
    };
    PROGMEM const unsigned long red3[1][10] = {
       {0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
    };
    PROGMEM const unsigned long red4[1][10] = {
       {0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
    };
    PROGMEM const unsigned long red5[1][10] = {
       {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000,0x000000},
    };
    PROGMEM const unsigned long red6[1][10] = {
       {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000,0x000000},
    };
    PROGMEM const unsigned long red7[1][10] = {
       {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000,0x000000},
    };
    PROGMEM const unsigned long red8[1][10] = {
       {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000,0x000000},
    };
    PROGMEM const unsigned long red9[1][10] = {
       {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0x000000},
    };
    PROGMEM const unsigned long redfull[1][10] = {
       {0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000,0xff0000},
    };

    /*PROGMEM const unsigned long pattern_test_blue[10][10]={
      {0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x00ff00},
    };

    PROGMEM const unsigned long pattern_test_green[10][10]={
      {0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x0000ff},
    };

    PROGMEM const unsigned long pattern_test_white[10][10]={
      {0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff},
    };

    PROGMEM const unsigned long pattern_test_comet1[][10]={
      {0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000},
      {0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff},
    };

    PROGMEM const unsigned long pattern_test_comet2[][10]={
      {0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000},
      {0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000},
      {0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000},
      {0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000},
      {0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff},
      {0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000},
      {0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000},
      {0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000},
      {0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000},
      {0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0x111111,0x444444,0xffffff},
    };

    PROGMEM const unsigned long pattern_test_comet3[][10]={
      {0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff},
      {0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0x000000,0x000000,0xffffff,0x444444},
      {0x111111,0x444444,0xffffff,0x000000,0x000000,0x000000,0x000000,0xffffff,0x444444,0x111111},
      {0x000000,0x111111,0x444444,0xffffff,0x000000,0x000000,0xffffff,0x444444,0x111111,0x000000},
      {0x000000,0x000000,0x111111,0x444444,0xffffff,0xffffff,0x444444,0x111111,0x000000,0x000000},
      {0x000000,0x000000,0x111111,0x444444,0xffffff,0xffffff,0x444444,0x111111,0x000000,0x000000},
      {0x000000,0x000000,0x000000,0xffffff,0x444444,0x444444,0xffffff,0x000000,0x000000,0x000000},
      {0x000000,0x000000,0xffffff,0x444444,0x111111,0x111111,0x444444,0xffffff,0x000000,0x000000},
      {0x000000,0xffffff,0x444444,0x111111,0x000000,0x000000,0x111111,0x444444,0xffffff,0x000000},
      {0xffffff,0x444444,0x111111,0x000000,0x000000,0x000000,0x000000,0x111111,0x444444,0xffffff},
    };

    PROGMEM const unsigned long pattern_test_rainbow[10][10]={
      {0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000},
      {0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000},
      {0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000},
      {0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff},
      {0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff},
      {0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00,0x0000ff},
      {0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00,0x00ff00},
      {0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00,0xffff00},
      {0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000,0xff7f00},
      {0xff7f00,0xffff00,0x00ff00,0x0000ff,0x6f00ff,0x8f00ff,0x000000,0x000000,0x000000,0xff0000},
    };

    */

    // ***********************************************************************************************************
    // *
    // *                            Power Up Init.
    // *
    // *
    // ***********************************************************************************************************

    int sensorvalue = 0;
    int outputvalue = 0;
    void setup() {

      STRIP_PINOUT;        // set output pin - DEBUG: should auto detect which mother board for use

      reset_strip();
      Serial.begin(9600);
      //noInterrupts();

    }

    // ***********************************************************************************************************
    // *
    // *                            Main Loop
    // *
    // *
    // ***********************************************************************************************************
    void loop()
    {

        sensorvalue = analogRead(A5);
        outputvalue = map(sensorvalue, 0, 174, 0, 18);
        if(outputvalue == 0){
          send_1M_pattern(off, 1, 20);
        }

        else if(outputvalue > 0 && outputvalue <= 3){
          send_1M_pattern(red1, 1, 20);
        }
        else if(outputvalue > 3 && outputvalue <= 5){
          send_1M_pattern(red2, 1, 20);
        }
        else if(outputvalue > 5 && outputvalue <= 7){
          send_1M_pattern(red3, 1, 20);
        }
        else if(outputvalue > 7 && outputvalue <= 9){
          send_1M_pattern(red4, 1, 20);
        }

        else if(outputvalue > 9 && outputvalue <= 11){
          send_1M_pattern(red5, 1, 20);
        }

        else if(outputvalue > 11 && outputvalue <= 13){
          send_1M_pattern(red6, 1, 20);
        }

        else if(outputvalue > 13 && outputvalue <= 16){
          send_1M_pattern(red9, 1, 20);
        }

        else if(outputvalue > 16){
          send_1M_pattern(rainbow_full, 1, 20);
        }
        Serial.print("sensor = " );
        Serial.print(sensorvalue);
        Serial.print("\t output = ");
        Serial.println(outputvalue);

        delay(2);

      /*
     frame++;
        if(frame<=10) LEDSTRIP_PATTERN_0();
        if(10<frame<=20) LEDSTRIP_PATTERN_0();
        if(20<frame<=30) LEDSTRIP_PATTERN_0();
        if(frame>30) frame=1;
       */
      //delay(1);
    }

    /*******************************************************************************
     * Function Name  : send_1M_pattern
     * Description    : Transmit pattern to whole 1 meter strip
     *
     * Input          : pointer to ROM pattern; pattern length; frame rate
     *
     * Output         : None
     * Return         : None
     *******************************************************************************/
    void send_1M_pattern(const unsigned long data[][10], int pattern_no, int frame_rate)
    {
      int i=0;
      int j=0;
      uint32_t temp_data;

      for (i=0;i<pattern_no;i++)
      {
        noInterrupts();
        for (j=0;j<10;j++)
        {
          temp_data=pgm_read_dword_near(&data[i][j]);
          send_strip(temp_data);
        }
        interrupts();

        delay(frame_rate);

      }

    }

    /*******************************************************************************
     * Function Name  : send_strip
     * Description    : Transmit 24 pulse to LED strip
     *
     * Input          : 24-bit data for the strip
     *
     * Output         : None
     * Return         : None
     *******************************************************************************/
    void send_strip(uint32_t data)
    {
      int i;
      unsigned long j=0x800000;

      for (i=0;i<24;i++)
      {
        if (data & j)
        {
          DATA_1;
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");

    /*----------------------------*/
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
    /*----------------------------*/
          DATA_0;
        }
        else
        {
          DATA_1;
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
          DATA_0;
    /*----------------------------*/
           __asm__("nop\n\t");
          __asm__("nop\n\t");
          __asm__("nop\n\t");
    /*----------------------------*/
        }

        j>>=1;
      }

    }

    /*******************************************************************************
     * Function Name  : reset_strip
     * Description    : Send reset pulse to reset all color of the strip
     *
     * Input          : None
     *
     * Output         : None
     * Return         : None
     *******************************************************************************/
    void reset_strip()
    {
      DATA_0;
      delayMicroseconds(20);
    }

body:
A5 is PC5. Your code sets it as an output. Since you only need A0 (PC0) to be an output:

    #define STRIP_PINOUT (DDRC = _BV(PC0))

Uno pin mappings


message:
Scroll String Only On Second Line Using 2x16 LCD

I'm trying to scroll a string in the second row of the LCD while letting the string on the first row stay intact. I use Serial to run that part of the code as you can see. It work at first but when I try to make it run again it doesn't display anything on the second row.

I borrowed the code from :

http://code.nishantarora.in/arduino-lcd-projects/src/3f10686e7464665c5c59d7be772c00af7a4a93e8/scrollOneLine/scrollOneLine.ino?at=master

And made some changes:

    // include the library
    #include <LiquidCrystal.h>

    // init the lcd display according to the circuit
    LiquidCrystal lcd(9, 8, 7, 6, 5, 4);

    // it's a 16x2 LCD so...
    int screenWidth = 16;
    int screenHeight = 2;

    String line1;
    String line2;

    int stringStart, stringStop = 0;
    int scrollCursor = screenWidth;

    String CompleteString;
    String stringArray[] = {"s=Plane", "i=Car", "h=Boat", "u=Rocket", "d=Jet",  "p=Submarine", "l=Truck", "b=Bicycle", "m=Skate", "enter=Train"};

    String string1 = "String";

    int countMovement=0;
    int arraylimit = 9;

    void setup() {

       lcd.begin(screenWidth,screenHeight);
       Serial.begin(9600);

    }

    void loop(){

       char ser = Serial.read();

       if ( ser == 'c' ) {
         CompleteString="";

         for (int i = 0 ; i <= arraylimit; i++) {
            CompleteString += stringArray[i] + " "; // Convert String Array To Single String
         }

         roop(string1,CompleteString);
      }

    }

    void roop(String line1, String line2) {

      countMovement = 0;

      while ( ( countMovement ) < (line2.length() + screenWidth )  ) {

         lcd.setCursor(scrollCursor, 1);
         lcd.print(line2.substring(stringStart,stringStop));
         lcd.setCursor(4, 0); // 1 = word eat array of words very cool
         lcd.print(line1);
         delay(300);
         lcd.clear();

         if(stringStart == 0 && scrollCursor > 0){
            // Serial.println(scrollCursor);
            scrollCursor--;
            stringStop++;
         } else if (stringStart == stringStop){
            stringStart = stringStop = 0;
            scrollCursor = screenWidth;
         } else if (stringStop == line1.length() && scrollCursor == 0) {
            stringStart++;
         } else {
           stringStart++;
           stringStop++;
         }

         countMovement++;

      }

      lcd.setCursor(4, 0);
      lcd.print(line1);

    }

From what I can see using Serial as debugging is that the problem resides in the function "roop" and in specific the line:

     if(stringStart == 0 && scrollCursor > 0){

It seems that the statement is being pass on and so it doesn't move the string as it's suppose to. I could be wrong but placing a Serial call in there yields no result the second time the function is called but the first time it did.

Any help would be much appreciated! And I know the community will be grateful too since it's difficult from what I can see in post to achieve this and make it autonomous so that no big modifications needs to be done.

body:
You need to reset the `stringStart`, `stringStop` and `scrollCursor` at the beginning of the roop function.

    void roop(String line1, String line2) {

      countMovement = 0;
      stringStart = 0;
      stringStop = 0;
      scrollCursor = screenWidth;

      ...

I think you also need to move the `lcd.clear` up. Or else the screen will be blanked when the roop function is done scrolling.

    ...

      while ( ( countMovement ) < (line2.length() + screenWidth )  ) {

         lcd.clear();
         lcd.setCursor(scrollCursor, 1);
         lcd.print(line2.substring(stringStart,stringStop));
         lcd.setCursor(4, 0); // 1 = word eat array of words very cool
         lcd.print(line1);
         delay(300);

    ...


body:
The answer from the user Gerben worked perfect. So I'll be posting another solution I came upon and the one from my original question for feature reference.

Original Code:

    // include the library
    #include <LiquidCrystal.h>

    // init the lcd display according to the circuit
    LiquidCrystal lcd(9, 8, 7, 6, 5, 4);

    // it's a 16x2 LCD so...
    int screenWidth = 16;
    int screenHeight = 2;

    String line1;
    String line2;

    int stringStart, stringStop = 0;
    int scrollCursor = screenWidth;

    String CompleteString;
    String stringArray[] = {"s=Plane", "i=Car", "h=Boat", "u=Rocket", "d=Jet", "p=Submarine", "l=Truck", "b=Bicycle", "m=Skate", "enter=Train"};
    String string1 = "String";
    boolean ArrayRead = true;
    int countMovement=0;
    int arraylimit = 9;

    // most of the part is pretty basic
    void setup() {

       lcd.begin(screenWidth,screenHeight);
       Serial.begin(9600);

    }

    void loop(){

       char ser = Serial.read();

       if ( ser == 'c' ) {
          CompleteString="";

          for (int i = 0 ; i <= arraylimit; i++) {
             CompleteString += stringArray[i] + " "; // Convert String Array To Single String
          }

          roop(string1,CompleteString);
       }

    }

    void roop(String line1, String line2) {

       countMovement = 0;
       stringStart = 0;
       stringStop = 0;
       scrollCursor = screenWidth;

       while ( ( countMovement ) < (line2.length() + screenWidth )  ) {

          lcd.clear();
          lcd.setCursor(scrollCursor, 1);
          lcd.print(line2.substring(stringStart,stringStop));
          lcd.setCursor(5, 0); // 1 = word eat array of words very cool
          lcd.print(line1);
          delay(300);
          lcd.clear();
          if(stringStart == 0 && scrollCursor > 0){
             scrollCursor--;
             stringStop++;
          } else if (stringStart == stringStop){
             stringStart = stringStop = 0;
             scrollCursor = screenWidth;
          } else if (stringStop == line1.length() && scrollCursor == 0) {
             stringStart++;
          } else {
             stringStart++;
             stringStop++;
          }

          countMovement++;

       }

       lcd.setCursor(4, 0);
       lcd.print(line1);

    }

The other code provided by the user "HazardsMind" for I2C LCD Module: The changes made are Serial communication and adapted for the 6 pin LCD Module.

    // include the library
    #include <LiquidCrystal.h>

    // init the lcd display according to the circuit
    LiquidCrystal lcd(9, 8, 7, 6, 5, 4);

    //char * SerialComm[70];
    //{"s = Plane i=Car h=Boat u=Rocket d=Jet p=Submarine l=Truck b=Bicycle m=Skate enter=Train"};

    #define N_CHARS  ((sizeof(MessageOut)/sizeof(MessageOut[0]))-1)
    #define N_CHARS2  ((sizeof(MessageOut2)/sizeof(MessageOut2[0]))-1)

    //int len = strlen(SerialComm);

    char MessageOut[30];
    char MessageOut2[30];

    int index = 19, index2 = 0;
    unsigned long oldTime = 0, oldTime2 = 0;

    byte indexer = 0; // Index into array; where to store the character
    char inData[58]; // Allocate some space for the string
    char inChar; // Where to store the character read

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

    void loop()

      while(Serial.available() > 0) // Don't read unless
                                                  // there you know there is data
      {
          if(indexer < 57) // One less than the size of the array
          {
             inChar = Serial.read(); // Read a character
             inData[indexer] = inChar; // Store it
             indexer++; // Increment where to write next
             inData[indexer] = '\0'; // Null terminate the string
          }
      }
      // Now do something with the string (but not using ==)

      // Serial.print(inData);
      setHeadingRight("Royal", 0, 500);
      setHeadingLeft(inData, 1, 500);

      //setHeadingRight("Hello Welcome", 0, 1000); // message, row, duration
      // setHeadingLeft("Welcome", 1, 500);
    }

    void setHeadingRight(char * msg, byte row, unsigned long duration)
    {
       strncpy(MessageOut, msg, sizeof(MessageOut));
       if(millis() - oldTime > duration) // check the difference of the current time "millis()" to the previous time "oldTime" against the duration you want.
       {
          oldTime = millis(); // update oldTime with the current time
          if(index >= 0) // make sure the index does not go under 0
          {
            index--; // decrecment index by 1
            for (int i = 0; i < N_CHARS; i++) // this part here displays the message on the display
            {
               lcd.setCursor(i,row); // set the column to show the element in the array
               if(index == N_CHARS) index = 0; // set index back to 0 if the index has reached the arrays max size.

                  if(MessageOut[index++] != NULL) // if the element @ index is anything but NULL, show it.
                      lcd.print(MessageOut[index-1]);
                  else
                      lcd.print(' '); // if the element @ index is NULL, display a space.
            }
          }
       else index = 19; // if index is less than 0, then set it back to 19
     }
    }

    void setHeadingLeft(char * msg, byte row, unsigned long duration2)
    {
      strncpy(MessageOut2, msg, sizeof(MessageOut2));
      if(millis() - oldTime2 > duration2)
      {
         oldTime2 = millis();
         if(index2 < 20) // check to see if index2 is under the array max size
         {
            index2++; // increment index
            for (int i = 0; i < N_CHARS2; i++) // same as above
            {
               lcd.setCursor(i,row);
               if(index2 == N_CHARS2) index2 = 0;

                  if(MessageOut2[index2++] != NULL)
                     lcd.print(MessageOut2[index2-1]);
                  else
                     lcd.print(' ');
                  }
               }
               else index2 = 0; // otherwise set it back to 0
         }
    }


message:
What sensor would I use to get the speed or velocity of my Arduino based nav system?

I'm building a Arduino Nano based underwater navigation system using an IMU and various sensors. The only problem with this is that I cannot get the speed or velocity(at least reliably) and it would help the accuracy of my navigation system immensely if I had accurate speed to go off of.

Does anyone have any ideas on how I could measure the speed of my Arduino underwater? I've seen some people recommend paddle wheel like sensors but this needs to be accurate for slow movement.

body: On small recreational sailboats there is a small propeller on the bottom, when it turns it dials a speedometer, the faster it turns the faster the ship goes, a similar setup should be possible. With a small propeller and 2 ball bearings and an optocoupler, (same principle you got in the scroll button on your mouse, you should be able to pull it off with minimal resistance since there is no physical parts.


body: If you want accurate data (i.e. not by dead reckoning) then possibly GPS is an option. I suspect you will need to surface for it to work, as GPS signals are fairly week at the best of times - on a previous car I had, the windscreen was enough to stop the signal.


message:
May arduino hang when current is changing over time?

As in title. I've got quadrocopter where Li-Po is parallely connected to motors as well as to arduino. May current driftage cause arduino hangs ?

body:
There really isn't any such thing as "Current driftage". If you draw too much current from your battery it will cause the voltage to drop, and if it drops too much, the Arduino will stop working.

If you have high current devices like motors being switched on the same power supply as your Arduino you should add a reservoir capacitor as close to the input of your Arduino as possible. That will even out short term drops and spikes in supply voltage as your motors switch.

If you draw too much current continuously then your supply voltage will drop and stay dropped, and a reservoir capacitor won't help. In that case you need a higher current battery (or separate power supplies for your Arduino and motors.)

Edit: From your question it's pretty clear that you don't understand voltage and current and how they relate. I suggest you read up on the subject.

In short, the amount of current that flows through a component is determined by the voltage divided by the resistance: i = v/r. (Where i = current in amps, v = voltage, and r = resistance in ohms.)

The current that will flow will be limited by the max current that the power supply can provide.

For a non-regulated supply like a battery, the voltage from the supply will drop as you draw more and more current.

For a regulated supply, the supply keeps the voltage constant up to it's maximum current limit.


body:
May i ask why you don't have a separate battery for the arduino? If it is because of weight, an arduino can run of CR2032 batteries, gives it its own power supply, this should solve the problem.

If you want a battery with more longevity Google "6v 2/3 battery" (2/3 the size of an AA battery), small with loads of voltage for the arduino and with some skilled programming it should last for a flight or two, and the +side, you can get it rechargable.


message:
Print string from arduino to serial monitor

I want to send text over serial monitor to Arduino and make Arduino return that string back to me over serial monitor.

I have made this function which reads from serial input and returns a string object.

    String readSerial() {
        String input;
        while(Serial.available() > 0)
            input.concat(Serial.read());
        return input;
    }

In the `loop()` I have:

    if(Serial.available()) Serial.print(readSerial());

If I just do something like `Serial.print("Hello world!");` everything is fine. But, if I try to return string object I get lot's of numbers.

I guess `Serial.print` doesn't know how to read `String` object and returns ASCII codes of characters or something?

**[update]**
I have checked it, and it's indeed outputing ASCII codes. For `Hi` I get `72105`.

**[update]**
I have updated my `readSerial` function to use this :

    input += (char)Serial.read();

But now I'm getting carriage return and new line after every character:

    [SEND] Hi
    H(CR)
    i(CR)

So, how can I make it return my text so that is readable?

body:
`String.concat()` takes a `String` as the second argument. `Serial.read()` returns an `int`. The compiler creates code that converts the `int` into a `String` similar to this:

    input.concat(String(Serial.read()));

This is not what you want.

Let's tell the compiler what you really want instead:

    input.concat((char)Serial.read());

This will tell the compiler to do the following:

    input.concat(String((char)Serial.read()));

We are now having the compiler call the correct `String` constructor, and the code will work as we expect.


body:
Answering the other part of the question:

* you're getting CRs because your readString is just wrong.

The problem is that you don't wait for receiving a whole line of string. For example, if you press H on the serial monitor, then it is getting received and echoed back as if it would been the whole input, ending with a new line.

You might wish to check my answer at https://arduino.stackexchange.com/questions/22474/get-strings-from-serial-read/22475#22475 that is use https://www.arduino.cc/en/Serial/ReadStringUntil which reads you the whole string until a separator (for example the whole string until it ends with a CR when you press Enter on the serial monitor).


message:
Two devices on one SDA input

I have two devices. Sensor for temperature and humidity and lcd screen. Both require SDA pin, and I have only one on my arduino.

I want my display to show current temperature but I don't know how to connect two things on one pin.

Can I somehow read from other pins maybe?

Also, what can I do if I have only 1 5V source and I have two devices that require 5V?

My arduino model is [Arduino Mega 2560 R3][1]

I have [this][2] aosong sensor (AM2301), and I have YwRobots 2 row LCD screen which I want to connect to my board along with sensor.

**So... I'm not sure how to connect those two if both require SDA and I have only one.**

  [1]: http://arduino.cc/en/Main/ArduinoBoardMega2560
  [2]: http://meteobox.tk/files/AM2301.pdf

body:
You can have multiple I2C devices on the same bus (sharing both SDA and SCL), as long as they have different addresses. The library used to access them should know (or be told, if required) what the address for the device is.

If they are not I2C devices then they cannot both use SDA.

The Aosong device is *not* an I2C device, but there is no need to connect its "SDA" pin to the Arduino's "SDA" pin; any unused digital pin should work, as long as the library is told which pin to find it on and as long as the electrical requirements of the connection are met.


message:
Arduino Shield Pin Conflict

I have a Freetronics [Etherten][1] and am trying to use the [NFC Shield][2] - both the board and shield are trying to use Pins D10,D11,D12,D13

So my question - Is there an elegant way to have these two work together.  This really applies to any combination of shield with conflicting pins.  I'm thinking maybe use some in between headers or M/F jumper wires?

Is there a neat way to do it?

  [1]: http://littlebirdelectronics.com.au/products/etherten-100-arduino-compatible-with-onboard-ethernet
  [2]: http://littlebirdelectronics.com.au/products/nfc-shield-v2-0

body:
You need this: https://www.sparkfun.com/products/11002
"The Go-Between Shield “goes between” two shields that aren’t compatible and effectively reassigns the pins. This trickery is achieved by isolating the top and bottom sides of the shield with surface mount headers and breaking them out into tables of jumpers that can be bridged to divert signals to and from different pins."


message:
how to use strstr() in serial communication?

I have a SIM900 module and Arduino, both are working fine. In my previous programs I have use strstr() command to find specific word from a string but they were constants and pre defined in the program but now I want to read serial communication from SIM900 and detect a specific word from it. But it is showing me

> invalid conversion from 'char' to 'const char'

This is my program:

    int x;
    char sms;
    char response;
    char disp;
    void setup()
    {
      Serial.begin(2400);
    }

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

      if(Serial.available() > 0)
      {
        sms = Serial.read();

        disp = sms;
        if (strstr(disp,"track")) //Comparing word entered with word stored in program
        {
          Serial.println("Found the  word!");
        }
      }
    }

body:
There are two problems.

1) you are trying to have the Arduino's single UART talk to both the SIM900 and the PC.

2) disp needs to be an array of char's, as to compare for words phrases.

Try the following. It implements a 2nd Soft serial port to which you can connect the SIM900. Along with building an array char at a time.

    #include <SoftwareSerial.h>

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

    char buffer[16];
    #define buffer_size sizeof(buffer)/sizeof(buffer[0])
    int8_t buffer_pos = 0;

    void setup() {
      //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }
      Serial.println("Serial to mySerial demo started");

      buffer_pos = 0;
    }

    void loop() {
      char inByte;
      while (mySerial.available()) {
        inByte = mySerial.read();
        while (buffer_pos >= buffer_size) {
          for (int8_t i = 0; i < buffer_size - 1; i++) { // if shift buff left if at end of buff
            buffer[i] = buffer[i + 1];
          }
          buffer_pos--;
        }
        buffer[buffer_pos++] = inByte;
        if (strcasestr(buffer, "track")) {
          buffer_pos = 0;
          Serial.println("TRACK FOUND!");
        } else {
          Serial.write(inByte);
        }
      }
    }


message:
Code does not pass `gsmAccess.begin(PINNUMBER)==GSM_READY)`

I am not able to get my code to pass
> if(gsmAccess.begin(PINNUMBER)==GSM_READY) {

I have modified the PIN number on my sim card to be `0000`, and yet its stuck on `begin`.

How do I prepare the SIM CARD to pass the begin

body:
Try putting the SIM card into a mobile phone in case it hasn't been initialised by your provider. Set up the PIN for the card using the settings on the phone, see the manual for instructions on how to do this.

Now you can use the PIN you entered on the phone to unlock the SIM in your code.


message:
Mega2560 R3 pin functions

When I read about mega2560 I saw it has 54 digital that can be used as input or output.
later on I saw the some of them are used for things like communication.

So I would like to know if the communication pin can still be used as output ? (to power leds)

body:
Yes, you can.

You are referring to SPI, I2C, and the 4 serial interfaces. If you want to use those you have to use the predefined pins for that. If you are not using those you can use them as normal GPIO.

If you want Serial communication for debugging, you shouldn't use digital pins 0 and 1.

If you need even more pins, you can even use the analog pins and digital input/output pins.


body:
Yes. ***Any* pin can be used as a digital input/output.** However, you cannot use certain communications when using those pins.

*The types of communication and their effects on the pins:*

 - **[SPI](http://arduino.cc/en/Reference/SPI):** This protocol is used for certain communications with certain breakout boards and shields. For example, the ethernet shield uses SPI to connect. On the Mega(2560), it is pins 50-53.
 - **[I2C](http://arduino.cc/en/reference/wire):** This protocol is also for connecting to external items. It is much slower than SPI, but uses only two pins. On the Mega, it uses pins 20/21.
 - **UART/Serial:** UART is a communication method that uses two wires and transmits bytes of data. It is often used to connect to things that don't need *extreme* amounts of data passed, but need a stable two way connection.
  - On all standard boards, the main UART is on pins 0 and 1. This is usually connected to a UART to USB chip which is sent to the computer. Note: you should still be able to upload sketches if they act as an *output* and random on/off won't hurt the device.
  - The Mega(2560) also has UART on pins 14/15, 16/17, and 18/19.


message:
Slice string at “:”

I need to slice a string (eg- 4:288:18464:288:4) at ":" into an array({4, 288, 18464, 288, 4}) I used the following code, but its giving only '4' in the serial monitor when "4:288:18464:288:4," is given to arduino.

    void displayString(char* s)
    {
      char* text = strtok(s,":");

      while(text != NULL){
      text = strtok(NULL,":");}
    }

    void loop()
    {
      if(Serial.available() > 0)
        {
            str = Serial.readStringUntil(',');
            str.toCharArray(text,99);
        }
      displayString(text);
    Serial.println(text);
    }

body:
You don't use `strtok` the way it should:

    char* text = strtok(s,":");
    while(text != NULL){
        text = strtok(NULL,":");
    }

Your code just replaces, in `s`, all occurrences of `:` with `0` (i.e. a byte of value 0, not the ASCII value of `'0'`), thus terminating each substring.

At the end of `displayString(text)` call from `loop()`, `text` still points to the 1st character of the original string (in your post `4:288:18464:288:4`), but that string now terminates at the position of the first `:`, which explains why `Serial.println(text)` prints just `4`.

Now if you want to split the original string into an array of substrings, as asked in your question, you need to modify `displayString` this way:

    // Maximum number of substrings expected
    const int MAX_SUBSTRINGS = 5;
    // Array of pointers to each substring after displayString() has been called
    static char* substrings[MAX_SUBSTRINGS];

    void displayString(char* s) {
        // First clear the array of substrings
        for (int i = 0; i < MAX_SUBSTRINGS; i++)
            substrings[i] = 0;
        // Now split the input string
        char* text = strtok(s,":");
        int i = 0;
        while (text != 0 && i < MAX_SUBSTRINGS) {
            // A toekn was found: append it to the array of substrings
            substrings[i++] = text;
            text = strtok(0,":");
        }
    }

After calling `displayString(text)`, you can use its result in `loop()` as follows:

    void loop()
    {
        if (Serial.available() > 0)
        {
            str = Serial.readStringUntil(',');
            str.toCharArray(text,99);
        }
        displayString(text);
        for (int i = 0; i < MAX_SUBSTRINGS; i++) {
            if (substrings[i] != 0)
                Serial.println(substrings[i]);
        }
    }

Note that this will work **ONLY** if the original string contains no more than 5 substrings delimited by `:`. If the max number of substrings cannot be known at compile time, then you'll have to use dynamic allocation, [which is generally not a very good idea on embedded platforms][1].

  [1]: https://arduino.stackexchange.com/questions/682/is-using-malloc-and-free-a-really-bad-idea-on-arduino/687#687


message:
Can I power an Arduino with a computer's motherboard?

I was thinking of using my Arduino to turn on and off a computer remotely. I would like to know if the 5v header pin on a computer's motherboard (which I’m using instead of a USB because the 5v pin provides a constant power supply) can power an Arduino UNO without frying it. If the Arduino can be powered where would the cable from the 5v motherboard pin go into the Arduino?
![][1]

↑ These are the pins I would like to use

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

body:
You want to tap off of the +5VSB pin of the [ATX](http://pinouts.ru/Power/atxpower_pinout.shtml) or [BTX](http://pinouts.ru/Power/btx_mbpower_pinout.shtml) power supply connector and send it to the 5V pin on the Arduino. Where this will directly drive the VCC(5V) of the UNO.

![enter image description here][1]

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

Note that 5V of the USB basically drives the VCC directly, except through a MOSFET that acts as a blocking diode to prevent local VCC from flowing back to the 5V_USB.
_______

Not sure if you are suggesting that the 5V USB is frying Arduino's. If so that is bad. If true; Fix that first.
_______

That said (with good 5V usb) you should be able to find or configure (BIOS) so that a USB connector will remain powered, and allow a wake up from mouse movement. Hence a possible solution would be to use a Leonardo/Micro's Mouse emulation to do just that as to wake the PC, without any hardware mod's.

Freeduino Micro's are pretty cheap.


body:
As stated by @mpflaga you can power your Arduino by the 5v power rail. As @ Gerben mentions in a comment, doing this will bypass the polyfuse. Because of this, I [create my own][1] Arduino for less than $10 (US) with a power regulator. Using a  `L7805ACP` will regulate the power.

Part List:

    • 1 x P-DIP ATMEGA328P-PU programmed with Duemilanove Bootloader
    • 3 x Through-Hole 22pF Capacitors (2 for crystal and 1 for Analog power smoothing)
    • 1 x Through-Hole HC-49S 16 MHz Crystal (for clock)
    • 1 x 5 Volt regulator (peak current 2 A, nominal )(L7805ACP
      Input Voltage = 7.5 to 18 V
      Output Voltage Low 4.8 Volts Nominal 5 Volts  High 5.2 Volts)
    • 1 x 22 uF Capacitor (to stabilize power rail during rapid current draw.

![Homemade Arduino ][2]

  [1]: https://www.virtuabotix.com/bareduino328-plus-regulate-your-bareduino/
  [2]: https://i.stack.imgur.com/q0ymm.jpg


message:
Why does an Arduino UNO need two GND ports?

I have really bad eyesight, so whenever I plug in the power wire and the GND wire I always double check if I'm actually plugging in to the power port not one of the two GND ports.

Why does an Arduino UNO have two GND ports, and for what application would one use both of them?

body:
In electronics circuits, a major point in connecting two circuits and make them "talk" together is to ensure, at the minimum, that they have a common reference of voltage (typically called `GND` and defined as `0V` voltage).

On Arduino, GND pins can be used in 2 situations:

1. to directly power the Arduino with an external supply which cannot be plugged to USB or power jack. In this case, the positive voltage of that external power source shall also be supplied to **Vin** pin.
2. to connect Arduino GND to your circuits.

Having 2 distinct GND pins is, I think, just a matter of convenience when you want to build prototypes but don't necessarily have a breadboard (if you use a breadboard, you will just need to connect its power rail to Arduino GND pin and use this power rail directly).


body:
If you are not using a shield and are directly adding components to the arduino it is nice to have 2 ground so you can attach several components without having to add a bread board.

To be precise, you have 3 ground, since the third is sitting on the left hand side of the board (looking in to the USB port)