body: I'm trying to make an opening and closing little door that should open or close every 12 hours. I was wondering if I could just make a small looping script with a delay() for 12 hours, delay(43 200 000 000); I guess? However, I have no idea if that's possible and/or recommendable. Some feedback/alternatives(if needed) would be nice :)

title: Very long delay() possible?

Answers: 6

body:
Do you have a sleep(unsigned int seconds) available?

If not, this would allow you to delay() a very long time:

    for (unsigned int bigloop=0; bigloop<65535; bigloop++)
    {
       for (unsigned int smallloop=0; smallloop<65535; smallloop++)
       {
          for (unsigned int tinyloop=0; tinyloop<65535; tinyloop++)
          {
             delay(65535);
          }
       }
    }

body:
`delay()` has its uses, but for long delays it's no good. It simply tells the microcontroller to do nothing for `x` clock cycles. During that time, your Arduino can't do anything else.

Your best bet would be to use a thing called a Real Time Clock (RTC). These chips are specifically made to keep track of time, and you can connect them to your Arduino with ease. [Here's an example of how you could do that.][1]

  [1]: http://playground.arduino.cc/Main/DS1302

body:
The real time clock method is the most accurate way but otherwise use `millis`

    unsigned long startMillis = millis();
    while (millis() - startMillis < LONG_DELAY_MS);

This will delay up to approx. 4294967295ms (2^32-1) or 49 days, after which the timer will catch up to the value of `startMillis`

body:
You could use the watchdog interrupt and have your MCU sleep while waiting and save power.

But notice that you'll only save power if your board also saves it. That means you have to have a low quiescent voltage regulator instead of the usual regulators that equip the most common Arduino boards, such as the Uno. Otherwise, it doesn't matter whether your MCU saves energy if your board doesn't.

Here's the code (untested):

 #include <avr/sleep.h>
 // This variable is made volatile because it is changed inside an interrupt function
 volatile int sleep_count = 0; // Keep track of how many sleep cycles have been completed.
 const int interval = 720; // Interval in minutes between waking and doing tasks.
 const int sleep_total = (interval*60)/8; // Approximate number of sleep cycles
 // needed before the interval defined above elapses. Not that this does integer math.

 void setup(void) {
  watchdogOn(); // Turn on the watch dog timer.
  // Disable the ADC by setting the ADEN bit (bit 7) to zero.
  ADCSRA = ADCSRA & B01111111;
  // Disable the analog comparator by setting the ACD bit (bit 7) to one.
  ACSR = B10000000;
  // Disable digital input buffers on all analog input pins by setting bits 0-5 to one.
  DIDR0 = DIDR0 | B00111111;
 }

 void loop(void) {
  goToSleep(); // ATmega328 goes to sleep for about 8 seconds
  // and continues to execute code when it wakes up
  if (sleep_count == sleep_total) {
   // CODE TO BE EXECUTED PERIODICALLY
  }
 }

 void goToSleep() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Set sleep mode.
  sleep_enable(); // Enable sleep mode.
  sleep_mode(); // Enter sleep mode.
  // After waking from watchdog interrupt the code continues
  // to execute from this point.
  sleep_disable(); // Disable sleep mode after waking.
 }

 void watchdogOn() {
  // Clear the reset flag, the WDRF bit (bit 3) of MCUSR.
  MCUSR = MCUSR & B11110111;
  // Set the WDCE bit (bit 4) and the WDE bit (bit 3) of WDTCSR.
  WDTCSR = WDTCSR | B00011000;
  // Set the watchdog timeout prescaler value to 1024 K
  // which will yeild a time-out interval of about 8.0 s.
  WDTCSR = B00100001;
  // Enable the watchdog timer interupt.
  WDTCSR = WDTCSR | B01000000;
  MCUSR = MCUSR & B11110111;
 }

 ISR(WDT_vect)
 {
  sleep_count ++; // keep track of how many sleep cycles have been completed.
 }

The code I copied is from this page: [Low-Power Arduino Using the Watchdog Timer](http://www.fiz-ix.com/2012/11/low-power-arduino-using-the-watchdog-timer/).

body:
This will work:

    longDelayInSeconds = 120; //two minutes;
    while (p < longDelayInSeconds) {

            delay(1000);
            p++;

    }

body:
I just use for loops when I don't want to do stuff in between:

    for (int Hours = 0; Hours < 12; Hours++) {            //Creates 12 hours
      for (int Minutes = 0; Minutes < 60; Minutes++) {    //Creates 1 hour
        for (int Seconds = 0; Seconds < 60; Seconds++) {  //Creates 1 minute
          delay(1000);                                    //Creates 1 second
        }
      }
    }


body:
I'm using the Adafruit SD shield with a Mega board and wrote a simple program to log data.  I am outputting a constant stream of data at 115200 baudrate from another Arduino to the Mega.  The data output is mostly good, but there are places where some data are skipped.  These skipped data usually occurs around a file flush.  I've tried playing around with the flush frequency and the soft buffer size, but to no avail.  I'm not sure what these hiccups are caused by and would like some help.

    void loop(void)
    {
      while (Serial1.available())
      {
        softBuffer[i] = Serial1.read();
        i++;
      }

      if (i >= SOFT_BUFFER_SIZE)
      {
        for (x = 0; x < SOFT_BUFFER_SIZE; x++)
        {
          logfile.print(softBuffer[x]);
        }

        logfile.flush();

        i = 0;
      }
    }

title: SD datalogger sometimes skips readings

Answers: 1

body:
The SD card library works by filling up a 512 byte buffer. Once full, the data is written to disk.

The `flush` command updates the directory listing with the correct size for the file and also updates the file allocation table. It only needs to be done once, just before you pull the card out.

While `flush` is doing its thing, the internal serial buffer of the Arduino is filling up with new bytes. The internal buffer is 64 bytes long so if `flush` takes too long, the internal buffer fills up and you lose characters. You could edit HardwareSerial.cpp in the Arduino program directory to make it say 256 bytes.

Because of this `softBuffer` is not needed. Simply write straight to the card and let the internal buffer handle the buffering. See https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.cpp for the Serial code.

    unsigned long bytesWritten = 0;
    void loop(void)
    {
      while (Serial1.available())
      {
        logfile.write(Serial1.read());
        bytesWritten++;
        if(bytesWritten > BYTES_PER_FLUSH) logfile.flush();
      }
    }


body:
I apologize in advance, because there is a lot of tutorials out there about programming arduinos with another arduino, however I can't find really simple one I could understand.

  I have Arduino Uno SMD version and Arduino Pro mini 328. I want to upload sketch to Arduino Pro mini using Arduino Uno in ISP mode (I guess).

  I want to know EXACTLY which pins need to be connected and if all I need is Arduino IDE to upload my sketch to Pro mini ?

Thank you for your help.

title: Programming Arduino Pro mini 328 with Arduino Uno SMD

Answers: 3

body:
check this tutorial:

> http://www.instructables.com/id/Arduino-Examples-2-Use-an-Arduino-as-a-FTDI-Progr/

Works fine for me (I have a redboard, also with SMD microcontroller). In short this is the pinMap:

    UNO BOARD (SMD)    Pro Mini 5V
           GND             GND
           5V              VCC
           RX              RX1
           TX              TX1
           Reset           GRN

body:
Please check this tutorial if you want to upload sketches to Pro mini with Arduino UNO with SDM chip
http://www.instructables.com/id/Uploading-sketches-to-Pro-Mini-using-Arduino-UNO-b

body:
Following the tutorial on http://www.instructables.com/id/Arduino-Examples-2-Use-an-Arduino-as-a-FTDI-Progr/ I was able to upload the blink sketch to the Pro Mini 5V version with an Arduino Nano. After I tried uploading the sketch that I really wanted to use but got many errors in the IDE I tried a couple more with no luck. I had stumble on another article earlier about using the Arduino Nano to program the Pro Mini http://www.electronicsmayhem.com/?p=31. I had tried that method but with no luck but using the first tutorial & only changing one thing from it with info from the article i mentioned I was able to upload the sketch without any errors. The only thing I changed was I didn't connect the TX from the Nano to the TXI of the Mini.

       Arduino Nano     Pro Mini 5V
           GND-------------GND
           5V--------------VCC
           RX--------------RX1
           Reset-----------GRN(DTR)


body:
I would like to use these 2 components with an Arduino Uno:

- Arduino Motor Shield R3
- nRF24L01 2.4GHz Wireless Transceiver

I use Stepper for the motor shield, and SPI + RF24 for the wireless transceiver.

I could write 2 sketches that work perfectly, but how can I combine them together?

My issue is that they both require access to pins 11, 12 and 13.

Any help is greatly appreciated!

title: Motor shield and wireless transceiver compete for same pins

Answers: 2

body:
This is the core of embedded design and "hacking" and highlights one of my peeves about Arduino design: too much focus on the pin numbers and physical location on the PCBs, rather than the actual functions on those pins.

So? Physically move the pins on the Motor Shield. Here are 3 options in order of the most hack-ish to most-clean:

1) Use an edge cutter to cut the bottom of the pins off the motor shield then solder jumpers to the nub to other pins that **are** free.

2) Use a hot air station to desolder that header row, solder in your jumpers, and put back only the pins you want. Board designs with such limited foresight (like your situation) is what led me to buy my hot air station. And now I pretty much use sensor shields for my interfacing outside the stack or proto shields to be intermediate layers to translate pins.

3) Cut the trace on the motor shield PCB itself to free the SPI pins. Then find pins that have your function (pwm?) and also are NOT used by any other shields in your "stack". Solder a jumper from the exposed trace on SPI pins to your free "new" pins.

If you stalk through my answers there are write-ups on two test benches I made and you can get ideas from the various work-arounds I have employed to get my hardware working.

body:
For prototyping, use male to female jumper wires to connect the Arduino Uno to the robot shield. It is a bit of a pain, but it makes it easy to free the conflicting pins for the wireless transceiver.

For a more permanent solution, look at Chris K's answer.


body:
In Linux Fedora 20 Arduino I want to use the Timer library from [here][1], from which  I have downloaded the folder `Timer-master.zip`, but, when I try to import it, I get the Arduino message that it cannot be imported because its name includes characters other than plain ACSII letters and numbers. I have tried copying the file to `Timermaster.zip` and importing that instead, but still got exactly the same failure message.

Please, how do I get out of this impasse?

  [1]: https://github.com/JChristensen/Timer

title: In Linux, how do I get this Arduino library to work

Answers: 1

body: What's causing the problem is that the folder name inside the zip has a hyphen in it, just extract the folder from this zip and rename it to `timer` instead of `timer-master`. I just imported it on Fedora 20.


body:
is it possible to perform an action maximum x times per hour on the arduino?

I made a automatic water sprinkler that sprays when the humidity is lower than 50%. but if the sprayer performs this "spray" more than 4 times an hour the humidity wil be to high and wil rise to fast.so is there a way to restrict the amount of times an action is performed per hour,and then if the next hour comes the sprayer can perform his "sprays" 4 times before it stops again

sorry for bad english, this is not the language I speak (and type) mutch

Answers: 2

body:
Sure it's possible. It would be better if you had a real time clock module. Then you could use time-of-day.

You need to define your problem a little better. Would it be ok to run the sprinkler every 5 minutes, then not again for 40 minutes, for a total of 4 sprays in an hour, but clustered together? Do you want to prevent 4 sprays in a clock hour, or not go over an average of 4 sprays per hour?

Without a realtime clock module, I guess here's what I would do:

After a spray, record the time (in millis). Then in your loop, don't spray again for 15 minutes (15*1000*3600 milliseconds.)

The code would look something like this: (not real code, more like pseudocode)

    const unsigned long fifteenMinutes = 15*1000*3600;
    unsigned long nextSprayTime = 0;

    loop()
    {
      if (millis() >= nextSprayTime)
      {
        if (humidity < 50)
        {
          spray();
          nextSprayTime = millis() + fifteenMinutes;
        }
      }
    }

Edit: You said, in comments:

> i want it not to go over 4 sprays an hour,i have the ds1307 rtc
> module. situation: ist an automatic egg incubator and the humidity
> must be between 50% and 60%.i control the sprayer whit a dht11 sensor
> an a servo connected to an spray bottle. if the humidity is below 50 %
> the servo starts whit spraying.the servo keeps on spraying every
> second until that 60% mark is reached and then shuts of.so the amount
> of water in the box is way to much and so the humidity keeps on
> climbing until the 100% mark whit is deadly for the eggs

Ok, that gives your readers a clearer picture.

You're dealing with a process control problem, not just a hardware or software problem.

When you spray water, it will likely take several minutes for the change in humidity to stabilize and be detected by your sensor.

Your current approach sounds wrong because you dump far too much water into the system, and don't give it time to reach a new equilibrium before adding more water.

You need to collect some data.

There is going to be a significant lag between putting a spray into the incubator and sensing the increase in humidity, and when the increase reaches it's max.

You need to measure that lag.

You also need to know how much a single spray increases the humidity.

You should probably **ALSO* figure out how many sprays at a time you can spray before water droplets form on the walls of your incubator and on your eggs, since I assume that is very bad and to be avoided at all costs. Thus I would add a moisture detector to your system (A small piece of cloth with electrodes on it at 2 locations a couple of CM apart, and a sensitive conductivity sensor that detects the change from insulator to weak conductor that takes place when the cloth becomes saturated with water.)

You should also figure out how fast the humidity in your incubator drops if you don't add any water, for a variety of different conditions. (Likely affected by current humidity, outside temp and outside relative humidity, so you probably want 2 humidity sensors, one inside and one outside the incubator, and to record all the variables and graph them.)

I would suggest writing a data collection program. You might want to run it with the serial cable connected to a PC constantly, or install an SD card and save your data there.

In all your tests, you probably want to wait a significant time (15 minutes? 1/2 hour? 1 hour?) for the incubator to reach equilibrium before beginning your test.

You want the conditions of your incubator to be as close to your real-world conditions as possible. You might want to put eggs (dummy eggs, grocery store eggs at room temp, or something like that) in the incubator during the test to allow for the amount of water they absorb. You want the outside temp to be as close to your real-world temp as possible. If the incubator will be exposed to direct sunlight, air vents, wind, etc, then you want those same conditions.

At each step in every test you should record the current time, the current outside temp and humidity, and the current incubator temp and humidity, and the time of each spray you trigger.

Add your condensation detector at the beginning, and any time it detects condensation you should sound an alarm, record the time that it trips, and abort the current test. If you get liquid condensation you've done something wrong and need to adjust.

Write a program for your computer that graphs all your data points over time. Every time you run a test (other than the very first test) graph all the data and look at it. Patterns will probably jump out at you.

**Test 1:**

Record the time and the current humidity. Add one spray of water, and then record the humidity for 15 minutes. Look for an increase in humidity and when it peaks. The time from adding a spray to the peak increase in humidity is what you want.

**Test 2:**

Then modify your program to log the spray-to-peak-humidity-increase time, and each time it detects the humidity starting to drop again, spray once more, log the current outside temp and humidity, the inside humidity and outside time of the spray, and repeat.

This will give you spray-to-peak-humitity lag times over a range of humidity values. Graph that data with starting relative humidity on the x axis and the lag time on the y axis and look at it. Is it a constant value? A straight line? Is it a geometric curve? Exponential? Come up with a curve that fits the data fairly well.

**Test 3:**

A test that uses an increasing number of sprays, looking for how many sprays you can do at once before you cause condensation.

Start with 2 sprays.

Look for the peak increase in humidity, and once the humidity starts to drop, increment your spray counter to 3, spray that many times, and repeat. When the condensation alarm trips, stop the test.

Note that the number of consecutive sprays you can do before the moisture alarm trips will probably change for different starting humidity levels. My guess is that the max number of sprays you can add without triggering condensation will be highest at your lowest humidity level, and as the humidity increases, you'll get condensation with less and less sprays.

**Test 4:**

Figure out how to measure the max number of sprays that trigger condensation when you start at less than your minimum humidity, at your minimum humidity, at halfway between min and max, and at max. (This experiment will take some thought since it's not easy to get to a given humidity level, and once you trigger condensation you'll have to stop, dry everything out, and start again.)

**Test 5:**

Get your incubator as close to the maximum acceptable humidity (60%) as you can at the beginning of the test, or even a little above. Simply record the humidity every minute until it drops to the lowest acceptable level (50%). Graph the data. That will show you how fast the humidity drops if you do nothing.

**Test 6:**

Repeat test 5 for the range of outside conditions you might find in your production environment. (If you're in a climate-controlled space, do you have summer and winter thermostat settings? Test for those upper and lower ranges. How much does your indoor humidity level vary?)

Now what?
--

Now you have lots and lots of data.

More than likely you have an idea of how many sprays you can add at a time without triggering condensation over your humidity range. This should be fairly simple: (for example, at humidity < 50% to 52%, you can use 3 sprays.  AT 53-55%, 2 sprays. Above 55%, 1 spray.) You should also have a rough idea how much increase you'll get in humidity for a given number of sprays.

You have an idea of how fast the humidity drops if you don't add water.

You have an idea how long it takes for a spray set of sprays to cause a peak in the humidity level.

Write a program that strives to keep the incubator in the middle of your desired range. If 50% is your absolute minimum humidity level and 60% is your max, then trigger sprays at 52%, not 50%. Spray as many sprays as you can without causing condensation (or overshooting your max humidity), then lock out sprays for the time period you calculated as the time it takes for your sprays to cause the maximum increase in humidity.

If you've found that the max number of sprays you can do at a time is different for different humidity levels, use code that comes up with a number of sprays that stays below that limit. Also try to estimate how much increase in humidity you get per spray, and each time you trigger a series of sprays, stay below the number of sprays that reaches your max humidity.

If you've found that the conditions outside the incubator have a big effect on your system, adjust your code to compensate for those changing conditions.

You want a system that uses small adjustments over time to keep a system at near equilibrium. Big adjustments will likely cause wild variations in conditions that go outside of the acceptable range.

Other considerations:
--

Do you need to open the incubator at regular intervals to check on the eggs or turn them, or do you have an egg turner? If you do need to open the incubator, you will need to figure out the effect this has on your temp and humidity levels for the range of outside conditions you face. You can probably build your system with a door sensor that detects you opening the door, the outside temp and humidity, and how long the door is open. Once you close the door, it would note the new inside temp and humidity and make an educated guess as to how much the humidity will drop after being open, and add water accordingly.

body:
You might be spraying faster than the sensor or the environment can respond, causing your humidity overshoot your goal. Try spraying way less often, experimenting with the interval until you understand more about the dynamics of the humidity.

My first guess would be to try once per minute and see whether that still overshoots or if it fails to maintain the humidity. That will tell you whether to increase the interval more or to decrease it. Writing the time and humidity readings to the terminal and plotting those may help you understand your system behavior better.


body:
My question is simple. Does Arduino set the digitalwrite() the moment it is called or at the end of the while loop. E.G.

    int ledPin = 13;
    void setup()
    {
      pinMode(ledPin, OUTPUT);
    }

    void loop()
    {for(int i=0; i<10; i++){
    if(i%2==0){
      digitalWrite(ledPin, HIGH);
      delay(1000);}else{
      digitalWrite(ledPin, LOW);
      delay(1000);      }
    }

title: Arduino Digitalwrite for while loop set

Answers: 3

body: Arduino sets the pin at the moment digitalWrite() is called.

body:
The condition

    if(i%2==0)

will be checked immediately upon entering the "for" loop, and again on every iteration of that loop. It will be the first code executed on each iteration. One form or another of the digitalWrite() will be called next, followed by the delay().

body:
A key point of the Arduino 'language' is *every* statement is completed before the next one can begin.

A simple statement has a '`;`' at the end of it.
Or followed by '`)`' instead of '`;`' in `for (...; ...; statement)` loop.

So `digitalWrite()` will set the pin, HIGH or LOW, *before* it completes and allows the next statement, `delay(...)` to begin.

Side note:
Actually `digitalWrite()` takes a small amount of time to do its work, so it is not *exactly* 'the moment' it is called. `digitalWrite()` *is* pretty quick, a few millionths of a second, which is usually near enough to be practically 'the moment' for most applications.


body: Is it possible to write an Arduino program to an AVR chip that does not have teh Arduino bootloader installed?  What is the process to do so?

title: How do I write an Arduino program to an AVR chip without the Arduino bootloader?

Answers: 2

body:
### Step 1: Get yourself a programmer.

This can be anything from a USBasp to an Arduino programmed for ISP all the way to an AVR ONE!. Some can be used from the IDE, and some cannot.

### Step 2: Set up the chip as expected from the entry in boards.txt and from the datasheet.

Add a crystal, decoupling caps, whatever. Don't connect power yet.

### Step 3: Connect the programmer.

If using ISP, connect the ISP pins. If using JTAG, connect the JTAG pins. If using something else, see the programmer and chip documentation for connection details. You may want to connect power at this point for the next step.

### Step 4: Program fuses.

Program the oscillator, BOR, CKDIV8, EESAVE fuses as desired/required. Fuse calculator.

### Step 5: Compile the program and write it to the chip.

If using the IDE, select the programmer in `Tools` | `Programmer` and then hold shift when clicking the Upload button (or press Ctrl-Shift-U). If your programmer is not supported by the IDE then compile the program (`Sketch` | `Verify/Compile` or Ctrl-R), locate the temporary directory it has been built in, and use avrdude or your JTAG program to upload it to the programmer.

### Step 6: There is no step 6. You're done.

I just wanted to see if you would read this far.

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


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

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

P.S I get the 96 mhz option.

Thanks ahead of time!

title: Teensy 3.1 no overclock option for 168 MHz

Answers: 1

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

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

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


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

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

This fails on the last line with error message:

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

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

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

ArrayList.cpp code:

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

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

    ArrayList::~ArrayList(void)
    {
    }

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

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

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

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

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

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

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

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

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

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

title: ArrayList implementation fails for string object

Answers: 1

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

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

    list->add_string_item(buf);

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

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

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

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

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

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


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

1. Can it read, write fuse?

2. Can it read, write Program Flash?

3. Can it work 3.3 and 5 volts?

4. What workable clock frequency range on the MCU?

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

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

Many thanks in advance

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

Answers: 1

body:
1. Yes.

2. Yes.

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

4. See 3.

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

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


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

title: Control Arduino via Wifi directly?

Answers: 1

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


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

title: Using an array as a queue

Answers: 1

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

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

To add an item to the queue:

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

To read from the queue

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


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

title: Why is Arduino STINO upload function not working?

Answers: 1

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

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


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

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

Answers: 1

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

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

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

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

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

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

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

    const uint8_t chipSelect = 10;

    SdFat sd;
    SdFile logfile; //create log file

    RTC_DS1307 RTC;
    DateTime filedate;

    uint16_t date;
    uint16_t time;

    int i = 0;
    int x = 0;

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

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

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

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

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

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

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

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

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

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

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

      Serial.println("Card initialized");

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

      // create new file name
      newFileName();

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

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

      Serial1.begin(115200);

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

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

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

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

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

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


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

title: Uploading bootloader on ATmega328P SMT package using Arduino Uno

Answers: 1

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

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


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

![enter image description here][2]

My Code ([Here][3]) :

    #include <IRremote.h>

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

    void setup()

    {

     Serial.begin(9600);

     irrecv.enableIRIn();

    }

    void loop() {

     if (irrecv.decode(&results))
      {

     if (results.value == CH1)

     {

     Serial.println("CH-");
     }

     if (results.value == CH)

     {

     Serial.println("CH");

     }

     if (results.value == CH2)

     {

     Serial.println("CH+");

     }

     ...

     if (results.value == BUTON8)

     {

     Serial.println("BUTON8");

     }
    if (results.value == BUTON9)

     {

     Serial.println("BUTON9");

     }
     irrecv.resume();

     }

    }

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

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

title: Using VS1838B with Arduino

Answers: 5

body:
Looking further here

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

I found the following

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

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

Either way will work

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

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

i use this code:

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

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

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

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

body:
    void loop(void) {
       int numberpulses;

       numberpulses = listenForIR();

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

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

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

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

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

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

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

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


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

title: Arduino Due - creating an 8Mhz clock signal

Answers: 3

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

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

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

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

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

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

    #include <Arduino.h>

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

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

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

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

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

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

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

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

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


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

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

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

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

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

title: ATTiny85 Interrupt id vs pin when programming with Arduino

Answers: 1

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

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

Using the [Arduino-Tiny Cores][2]

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

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

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

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

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

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

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

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

    }

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

    }

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

    }

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

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


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

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

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

Answers: 3

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

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

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

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

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


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

title: Setting EN_AA (auto ACK) to 0x01 or 0x02 makes nRF24L01+ stop sending/receiving

Answers: 0


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

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

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

Here is my arduino sketch:

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

    YunServer server;
    boolean receiving = false;

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

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

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

        boolean currentLineIsBlank = true;
        boolean sentHeader = false;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Any help would be greatly appreciated!

title: Arduino Yun Webpage Server Issues

Answers: 2

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

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

A couple of advices:

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

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

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

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

    YunServer server;
    boolean receiving = false;

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

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

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

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

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

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

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

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

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

And also by changing my webpage to this:

    <!DOCTYPE html>

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

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


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

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

Answers: 2

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

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

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


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

title: Arduino Underwater Inertial Navigation

Answers: 1

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

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

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

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


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

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

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

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

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

Answers: 2

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

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

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

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


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

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

Answers: 1

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

    #define STRIP_PINOUT (DDRC = _BV(PC0))

Uno pin mappings


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

title: USB Keyboard in Retro Emulators

Answers: 0