text:
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, but I've added a version to Github with more explicit file structure.  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;
}

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.

Awesomely helpful :)  The toCharArray fix works, but you're right it does crash the arduino after a while.  Think I'll revert to array methods until I find time to rework the library..


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

Can it read, write fuse?
Can it read, write Program Flash?
Can it work 3.3 and 5 volts?
What workable clock frequency range on the MCU?
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)?
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

Keep in mind that these are getting to get you little capability compared to the Arduino-as-ISP solution - and in some configurations, limited flexibility too.

#4. Using USBASP on AVR running at 1Mhz doesn't work using the arduino IDE. You can instruct avr-dude to program at lower speeds using the -B parameter. I've had no problem using USBASP from the IDE on boards running 8Mhz and above.

Yes.
Yes.
Depends on the specific hardware. See the documentation for the exact variant you have.
See 3.
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.
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.

source: Stack Exchange

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

sort: votes


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

you could make an ad-hoc network with your computer and connect straight to that

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.

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


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

You can use an array as a queue, if you use resetting indicies (or pointers) to circularize it, but if you end up with more than one thread (anything in an interrupt) be careful of consistency.  You could also I guess do it using a linked list, but that's a heavyweight solution for a chip with such limited resources.

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:

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

To read from the queue

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

What Gerben says. This is the exact way to do it, and is explained clearly and simply. (Voted)


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

Problem some sort of installation/configuration issue.  You are going to have to make an effort to investigate and understand the failure (find error messages, etc which may be being concealed) if you want help with it.

@chris Thanks. I was seeing no error messages in the compiler and uploader console, and didn't checked the sublime text console. There were indeed an error !

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)


text:
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;
  }
}

The EyeFi card has to play some kind of algorithmic guessing game (beyond anything a disk filesystem normally defines) to decide when a file merits uploading, and it's likely that your (comparatively) slow logging interacts poorly with this. It may be that you could play some kind of game with your file system implementation where you write a lot of data to unallocated space on the card until you decide it hits your worthy-of-uploading size, and only then write its directory entry in the hopes of triggering the upload.  But that is pure speculation. It may be this is the wrong way to do wifi.

@ChrisStratton I'm not very good at programming the Arduino.  How do you go about changing the directory of a file?

@ChrisStratton NVM, I found a library that can rename.  Will give it a try tomorrow.

I was not speaking of renaming, I was speaking of having file contents on disk which the file system "catalog" has not yet been told about at all, and only creating a directory entry in the catalog for it when you are ready to have the card's algorithm discover and upload it.  But it's possible renaming would work.  And possible the idea itself is a non-starter.  Yes, this would be advanced usage, requiring you to understand and modify the filesystem code.

@ChrisStratton it works!  I logged data to a temporary file stored in the root directory of the EyeFi SD card, then when i'm done logging to it, I rename it as "DCIM/100NIKON/DSCNxxxx.JPG" using the SDfat library. Thanks for the suggestion!  Maybe you can rewrite your comment as a solution so I can mark it as the answer.

As renaming was your idea and a lot simpler than my proposal, even if I got you thinking in a useful direction that solution is really your own work.  Does the card only pay attention to things in the DCIM folder?  If so that would be a key point to mention.

@ChrisStratton Yea, seems like the card only transfers files stored in camera folders and named in the same format as common photo naming convention like IMAG0000.jpg or DSCN0000.jpg.  I guess I'll type up my solution in case anyone wants to do the same.

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)%10 + '0';
    filename[20] = (i/10)%10 + '0';
    filename[21] = i%10 + '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;
  }
}


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

Are you using a serial converter to upload the sketch?

I removed the chip on arduino uno and tried uploading sketchs using tx ,rx and reset pin.

Are you using a bootloader for the Uno, e.g. Optiboot?

I am using optiboot(arduino duemilanove or nano w/atmeg328) as bootloader i also tried optiloader.I was able to upload the bootloader on both the methods

Well, okay, but you need to behave like an Uno, since you're using an Uno as the frontend.

Do you have a crystal of the same frequency on your board?  Try making a serial echo sketch and uploading that using ISP (instead of bootloader) to test that your board works and the serial connection works.

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:

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.
Connect the tx, rx and rst pins of your atmega to your arduino.
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.

I tried removing the pull up resister on my pcb still my atmega is not talking back the rx pin is not blinking

hmm, I missed something obvious... you are powering the atmega with 5v, right?

yes am power it up with 5v from the arduino board


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

My Code (Here) :
#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?

Are you sure you have a proper remote control? How did you get the constant values from?

You should add Serial.println(results.value); after if irrecv.decode(&results)) { to check what codes are really received from your remote.

@jfpoilpret It's not printing anything, it's not going inside of that if() . I'm use I'm using a proper controller because all they came together, as a kit.

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

Yup, this was my issue as well. On macOS the files are stored in the contents of Arduino.app, so using Finder you need to go to /Applications, then right-click Arduino.app and click "Show Package Contents". Now, navigate to the folder /Applications/Arduino.app/Contents/Java/libraries and delete the folder "RobotIRremote". You can also do this easily from the Terminal using the rm -r /Applications/Arduino.app/Contents/Java/libraries/RobotIRremote command.

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.

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/

Whilst you link may answer the question, it would be preferable to include the essential parts of the linked here, and provide the link for citation. Thanks!

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

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.

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


text:
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(){
}

FWIW, I checked the ATMEL timer doc (again) and confirmed for a 8mhz'ish signal, RC should be set to 5.xxx (call it six) and RA should be set to 3 (50% duty cycle). Needless to say, this did not give me a 8Mhz signal. In that there is a very faint possibility that I have damaged the ARM (accidently put 5v on it a while back and Wire is a bit falky (but wire1 is good), is there any chance anyone with a Due and a logic analyser could run the sketch and tell me what signal you are getting on TIOA6?

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.
#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();
  }
}

p.s. obviously you don't need the serial stuff, I've just put that in there to check that the code isn't hanging.

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

Thanks for that - am checking (It seems timer5 is not the system clock). Using 3/6 on Timer 2 gives me a mixed wave of up to 6Mhz. (Also using UPDOWN_RC. 2/4 gives me a sloppy wave consisting of a 2Mhz, a bit of 6 and a bit of 4. Seems however you are right that low numbers give very inconsistent results. I agree that an external clock may be the way to go - but I am not beaten yet :-) Many thanks for responding. Stan

Thanks to all who responded and advised. Have ordered external clock generator (Adafruit). (Have also confirmed with the answers etc that I am not going nuts..... Stan


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

attiny is kind of a piece of crap. Get arduino-tiny instead.

@IgnacioVazquez-Abrams attiny is kind of a piece of crap. I assume you refer to the device? If that is the case then how does an Arduino core change anything? The "instead" statement is what confuses me.

No I think Ignacio refers to the attiny library that is referenced by the tutorial.

I am indeed talking about the extension module for the IDE.

In arduino-tiny you can use the constant EXTERNAL_INTERRUPT_0 for INT0 at physical pin 7

@Gerben - Got an implementation example?

attachInterrupt(EXTERNAL_INTERRUPT_0, blink, CHANGE);

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:

Using the Arduino-Tiny Cores
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.

The ISR should be PCINT0_vect, see the include file iotnx5.h. #define PCINT0_vect _VECTOR(2).  Or at least, that is how it is in my distribution.

Why use PCINTn, when there is INT0 on PB2?

@NickGammon you're correct. I had some Alias defined in the code that I forgot to include. (Pun intended).I updated my answer.

@RSM INT0 is the timer 0 interrupt..not the pin change interrupt(PCINTn). AttachInterrupt in Arduino is a Pin Change Interrupt.

Interrupts which occur because of a timer that affect a pin happen on OCnx pins. INT0 is a hardware input interrupt, specific to that pin, read through the interrupt.h file in avr-gcc. also you should look at this look closely at pins 2 and 3, which arduino uses as interrupts and see that it is INT0 & INT1 respectively. Also you should take a look at the arduino core files, like WInterrupts.h and see it uses INT0, PCINTx is a group of pins

@RSM we're talking about Attiny85 Chip. INT0 is a level change interrupt which can be hardware programmed to trigger on Rising Edge OR Falling Edge and PCINTn is a Pin Change interrupt which triggers the ISR on BOTH Rising and Falling edges. INT0 also has it's own ISR.

PCINTn is a WHOLE REGISTER PB0 - PB5, i.e. you would have to pick out which pin had a trigger in the ISR, more time wasted in the routine, also all interrupts are level change or edge triggered, don't see your point??? I also know its the t85, the WInterrupts.h for tiny libraries also uses INT0. Hardware interrupts can be triggered on change too. To reiterate this AVRfreaks post by clawson #2, the interrupt occurs at a change, or on the edges. INT0 is a dedicated interrupt? where is the confusion

@RSM  no confusion. You're totally wrong about the register. Setting the PCMSK register enables only the pin(s) you want to allow to call the interrupt. Not ALL pins. Yes, all of those interrupts call the SAME ISR. So, if you have PB0 - PB5 all as interrupts enabled, then I think you're using the wrong chip for your application. In my example only PCINT1 causes the ISR to be called. It is called at BOTH rising edge and falling edge, so you may need to check if the Pin is High Or Low within the ISR. Checkout the data sheet chapter 9 on interrupts.

@GisMofx - I can see this is going to go in circles, I'm right, you're right... Lets leave it at that. For simplicity I would use INTn first. Your answer is good for pointing out another way  though. also add #include <avr/interrupt.h> if in the arduino ide.

@RSM Thanks. Ok. But I personally don't use INT0 on the Attiny because that pin is used for I2C/USI/SPI. Yes you're also correct you need the #include for interrupt

@GisMofx:  May I suggest you rework your answer to provide a complete, compilable example? Also move your comments about the mask into it to clarify. You use (1 << INTERRUPTPIN) in some places, but cbi(DDRB, DATADIRECTIONPIN) in others, which is a bit inconsistent. How about DDRB &= ~(1 << DATADIRECTIONPIN) ? You might also want to mention the difference between pin-change interrupts and external interrupts.

@NickGammon Thanks for the Tip. I've added a full sample code that compiles which uses an interrupt to turn an LED on and off.


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

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 ?
How to control the light when using an external USB power supply ?

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.

What isn't explicitly mentioned here, but far more important, is that the device needs its own power supply.  It should not be connected to either the output of the Arduino's regulator, nor (at least not properly) a USB port to which the Arduino is connected.  The one exception might be if you have a higher current USB "power supply" which is not a computer.

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.

Put the lamp on the collector side.

@geometrikal You're correct, I was thinking that the transistor would come before the lamp but I suppose it should be placed after the lamp.

yep, cause you need V_BE to be saturated

power lamp from 5v source ( not from the arduino 5v port, but could be spliced into the same line powering the arduino or use a hub )
use a transistor to switch the usb 5v line

connect the base pin (and resistor) of the transistor to any arduino digital out pin

Actually, if you are going to do it that way, use an NPN transistor and switch the ground line.  But there are more issues.  For example, the light should not be powered through the Arduino's regulator.


text:
Setting EN_AA (auto ACK) to 0x01 or 0x02 makes nRF24L01+ stop sending/receiving
Test case:
2 arduino nodes with nRF24L01+ transceivers. Using maniacbug's RF24 library. Using pipes 0 and 1. (Auto-ACK is ON for all pipes by default)
When I set Auto-ACK ON for all pipes rf24.setAutoAck(true): it works.
When I set Auto-ACK OFF for all pipes rf24.setAutoAck(false): it works.
But when Auto-ACK is ON for pipe1 and OFF for pipe0 (I want pipe0 for broadcasting) rf24.setAutoAck(0,false):it stop working (no packet is received or sent).
Same thing with Auto-ACK ON for pipe0 and OFF for pipe1
Couldn't find anything about it on the datasheet neither other forums nor here. Is there something I'm missing?
Test sketches:
Node 1
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 rf24(9,8);

uint64_t pipe0 = 12312312LL;
uint64_t pipe1 = 11111111LL;

int data[2];

void setup()
{
    Serial.begin(115200);
    data[0] = 123;
    data[1] = 456;

    rf24.begin();
    rf24.setChannel(109);
    rf24.setPayloadSize(2);
    rf24.setDataRate(RF24_2MBPS);
    rf24.openReadingPipe(0,pipe0);
    rf24.openReadingPipe(1,pipe1);
    rf24.openWritingPipe(22222222LL);
    rf24.setAutoAck(0,false);
}

void loop()
{
    delay(1000);
    Serial.print("ACK: ");
    Serial.println(rf24.write(data,sizeof(data)));
}

Node 2:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 rf24(9,8);

uint64_t pipe0 = 12312312LL;
uint64_t pipe1 = 22222222LL;

int data[2];

void setup()
{
    Serial.begin(115200);

    rf24.begin();
    rf24.setChannel(109);
    rf24.setPayloadSize(2);
    rf24.setDataRate(RF24_2MBPS);
    rf24.openReadingPipe(0,pipe0);
    rf24.openReadingPipe(1,pipe1);
    rf24.setAutoAck(0,false);
    rf24.startListening();
}

void loop()
{
    if(rf24.available())
    {
        Serial.println("Got somethin");
        int incoming;
        rf24.read((byte *) &incoming,2);
        Serial.println(incoming);
    }
}

same problem here, hours wasted so far...

Workaround: enable|disable auto-ack on all pipes just before sending on the pipe you want, reestablishing previous state afterwards

You could try using the new for of RF24 maintained by TMRh20 and submit an issue if it is caused by the library.


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

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

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!

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:

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

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

I'm not sure that's the problem, though. Do you see the Console.println("Client Connected") line? That line NEVER gets called when loading the webpage from the SD card, but it DOES get called when embedding the webpage into the sketch. The problem is just getting the responses from the client and having the Linio send those responses back to the Arduino side.

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.

Zepto is the way to go. On a side note, since you call it "linino", you probably need to upgrade your yun. Check http://arduino.cc/en/Main/Software#toc8


text:
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'?

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.

As Ignacio Vazquez-Abrams mentioned, you should look into Atmel Studio. 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.


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

Realistically, this is a problem that gets solved with sonar/beacons, not inertial navigation.

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.

Thanks for the answer. That makes sense. Would an array accelerometers and a kalman filter reduce the amount of errors enough to make it work it? Is there some other sensor(s) I could add to significantly increase the accuracy?

I'm sure adding more would help your accuracy, but you still don't solve the fundamental problem that there is no check on the accumulation of error using accelerometers, so I don't think you could add enough to get long lasting accuracy. You're going to need to find some kind of absolute feedback system. Though it would require a raspi or similar, you could try using two lights to track with a camera like the wii sensor bar; Just a thought.


text:
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), but sometimes I need to run the same code on an Arduino.
I need to initialize the DHT library 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?

Is there anything stopping you using the internal clock of the ATmega on an Arduino board?

Actually one thing I want this for is to test how the clock frequency (among other things) affects the RF range.

is F_CPU set? im wondering if you can read that

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/… 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.

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.


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

Please include your code here. While one may say "code came from such-and-such", it is possible that interactions between various pieces of code can cause complications.

I have included the code.

So you're saying that just performing the analogRead() on the audio sensor alone without the rest of the code gives results from 0 to 1023? Is this regardless of whether or not the other electronics is in place?

Correct, I have discovered that the sensor reading is independent on the other electronics plugged in, yet is is dependent on the statement STRIP_PINOUT; in the setup function. If that statement is excluded from the code, the sensor reads normally, but the LED strip does not work.

To be clear, when I say the sensor reads normally, I am getting values around 0 with no sound, and no more than 500 with music playing as loud as my ears can handle, with no visible cap.

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

I can see why this example code skips the usual Arduino I/O abstraction for its direct assembly bit-banging, but it is unfortunate as it makes their code hard to combine with anything else written in terms of Arduino pin names.

I am particularly amused by the repeated __asm__("nop\n\t"); lines. I suppose they didn't know about _delay_us() et alia.

This probably gives them finer control, particularly for very short intervals.  Likely the code was tuned for maximum performance shifting data to the strip, with a scope against the data sheet, or possibly by reducing to the point of failure and then backing off.

It also locks it to a single CPU clock speed, versus using the adaptive delay macros found in AVR Libc.


text:
USB Keyboard in Retro Emulators
I have created a retro keyobard using a ZX spectrum and a PRO MICRO based on the info here: http://blog.tynemouthsoftware.co.uk/2013/04/arduino-leonardo-based-zx81-usb-keyboard.html
When plugged into my laptop or a raspberry PI it works fine. However, when running any of the emulators like FUSE it doesn't work at all.
Can anyone explain why this is and what I have to do to make it work? Searching around on the web I see it has something to do with the key mapping which I can understand for when I do shifted keys but why it doesn't work when I just press p is eluding me.
EDIT:
When using a USB sniffing program I can see that my "real" keyboard sends 0x8 bytes for an 'a' 00 00 04 00 00 00 00 00
BUT my arduino sends 0x9 for an 'a' 02 00 00 04 00 00 00 00 00
Snippets of the the code I am using is
// keyMap and keyMapShifted are both 2D arrays of type byte
byte keyMap[8][5] = { {'5', '4', '3', '2', '1' ....etc
byte key = shifted ? keyMapShifted[[r][c] : keyMap[r][c]
Keyboard.write(key)

Ideas? A Bug? Do I have to rewrite Keyboard.write?

Does a normal USB keyboard work with these emulators?  If not, then the question is off-topic here and belongs a support site for the emulator.  But if a usual USB keyboard does work, then the reasons why yours doesn't seems on-topic, and you should probably start by trying to use logging software to see the key codes it sends vs the ones your implementation sends.

Yes the normal keyboard works 100%. OK I will have a look at finding some logging software. Thanks!

OK using a USB sniffing program I can see that mky "real" keyboard send 0x8 bytes for an 'a' 00 00 04 00 00 00 00 00

BUT my arduino sends 0x9 for an 'a' 02 00 00 04 00 00 00 00 00 The code I am using is Keyboard.write(key) where key is of type byte and is assigned by byte key = shifted ? keyMapShifted[[r][c] : keyMap[r][c]. keyMap and keyMapShifted are both 2D arrays of type byte initialised by (for example) byte keyMap[8][5] = { {'5', '4', '3', '2', '1' ....etc

Edit this into your question, don't try to squeeze it into comments

Still no further along with this. Can anyone even direct me to where the code lives that ultimately sends the keycodes so I can see whether it is a simple fix to drop the leading 02?

In the library source, presumably.

Yes I am hoping someone could direct me to which of the files as there are many and I have so far been unable to identify where in the code these bytes are generated. I am not getting any ideas from the Arduino forum either.


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

You may add the LiquidCrystal.h/.cpp code to your project and modify it if necessary.

Why do I need to do that? I'm almost there. I know it only needs a little bit of understanding and a simple explanation to make it work. Someone to point what's wrong in the code.

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

...

Seriously man that's what I was talking about! A simple mistake with an easy solution. I found another code that does the same in both directions so I'll be posting both codes for future reference. Thanks 4 your time

Great! Glad to have helped.

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


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

As commented on your previous question, this is a problem usually solved with sonar.  A flow sensor can be useful, but outside of a stagnant body of water like a swimming pool or tank with no filtering system or a small pond, velocity relative to the water is not necessarily the same as velocity relative to fixed items.

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.

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.

That makes it rather impractical for "underwater" speed determination, no?


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

What do you mean by "hang"?

Main loop freezeout.

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.

I understand voltage and current. I've just been thinking of "how can voltage drops and spikes (current driftage/drifts) affect arduino". Due to parallely connected motors I may experience such things right ?

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.

I have limited space + its comfortable.

Throw in 1 or 2 CR2032 they cost less than $1 and they take virtually no space at all, and it is more comfortable than loosing power mid air.


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

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.

Yes, just figured that out. Thanks anyway.

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 Get strings from Serial.read() 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).


text:
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
I have this 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.

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.

So, why is sda label on the board if it doesn't matter what hole I stick the wire in? Does it have any advantages over other holes?

The "SDA" pin on the Arduino is paired with the "SCL" pin in order to connect I2C devices.

That humidity and temperature sensor uses a one-wire serial protocol. SDA stands for Serial Data. So in essence they are kind of right, naming it SDA. But it does indeed create confusion.