message:
nRF24L01+ Arduino mpu6050

How do I ever understand what the Arduino IDE means when they advise you of any errors?  The reason I ask is because I got several errors that don't make sense to me as I see what the error means and what line the issue is but I don't see anything wrong with the code. It's written how it should be, the reason I say this is because before I ended the code I was compiling/verifying my code every time I write a new line just to make sure if I got new errors. It's easy to check as it was more than likely the very last line of code I just wrote, rather than write a book then do a spell check you know?

I have included the part of the code where I get errors and the errors themselves. Hopefully someone can point out to me what is it that Arduino sees that I don't and in the same token I'll learn how to counter measure those errors.

    1. //imu's
    2. #include "Wire.h" // i dont think this will be needed on this mcu's "slaves"
    3. #include "I2Cdev.h" // i dont think this will be needed on this mcu's "slaves"
    4. #include "MPU6050.h" // i dont think this will be needed on this mcu's "slaves"
    5.
    6. //motors
    7. #include "Servo.h" // select which motor this slave mcu has and comment out the other
    8. #include "Stepper.h" // select which motor this slave mcu has and comment out the other
    9.
    10. //wireless
    11. #include "nRF24L01.h"
    12. #include "RF24.h"
    13. #include "SPI.h" // i dont think this will be needed on this mcu's "slaves"
    14.
    15. #define RF_CS 12
    16. #define RF_CSN 13
    17. RF24 radio(RF_CS, RF_CSN);//RF24 radio(9, 10);
    18. const int pinCE = 9;
    19. const int pinCSN = 10;
    20.
    21. byte bArray[] = {0000, 1000, 0100, 1100, 0010, 1010, 0110, 1110}; // this are the Ch 0/7 address from Mux
    22. const uint64_t LA = 0xF0F0F0F0D2LL;//mcu1 address of Slave
    23. const uint64_t RA = 0xF0F0F0F0C3LL;//mcu2 address of Slave
    24. const uint64_t LL = 0xF0F0F0F0B4LL;//mcu3 address of Slave
    25. const uint64_t RL = 0xF0F0F0F0A5LL;//mcu4 address of Slave
    26. const uint64_t LW = 0xF0F0F0F0E6LL;//mcu5 address of Slave
    27. const uint64_t RW = 0xF0F0F0F0F7LL;//mcu6 address of Slave
    28. const uint64_t UT = 0xF0F0F0F0F8LL;//mcu7 address of Slave
    29. const uint64_t BT = 0xF0F0F0F0F9LL;//mcu8 address of Slave
    30.
    31. /* MUX CH address To simplify things, 1 is HIGH, 0 is LOW
    32.                                                                     0000 – 0
    33.                                                                     1000 – 1
    34.                   A multiplexer of this sort really just            0100 – 2
    35.                   acts as a 16 to one 1 switch. The 4 digital       1100 – 3
    36.                   pins are used to set HIGH or LOW, in a binary     0010 – 4
    37.                   fashion (0-15) to determine what pin “SIG” is      1010 – 5
    38.                   connected to. So bringing all 4 pins LOW would    0110 – 6
    39.                   switch the CD74HC4067 to channel 0 (so SIG and    1110 – 7
    40.                   C0 would be connected), bringing them all HIGH    0001 – 8
    41.                   would switch it to 15 (so SIG and C15 would be    1001 – 9
    42.                   connected)                                        0101 – 10
    43.                                                                     1101 – 11
    44.                                                                     0011 – 12
    45.                                                                     1011 – 13
    46.                                                                     0111 – 14
    47.                                                                     1111 – 15 */
    48.
    49. int recivers[8][4] = {
    50.   { 0xF0F0F0F0D2LL, { 0, 0, 0, 0 }, //0000 – 0 SDATA line from MPU to Multiplexer ch0
    51.     { 0xF0F0F0F0C3LL, { 1, 0, 0, 0 }, //1000 – 1 SDATA line from MPU to Multiplexer ch1
    52.       { 0xF0F0F0F0B4LL, { 0, 1, 0, 0,}, //0100 – 2 SDATA line from MPU to Multiplexer ch2
    53.         { 0xF0F0F0F0A5LL, { 1, 1, 0, 0 }, //1100 – 3 SDATA line from MPU to Multiplexer ch3
    54.           { 0xF0F0F0F0D6LL, { 0, 0, 1, 0 }, //0010 – 4 SDATA line from MPU to Multiplexer ch4
    55.             { 0xF0F0F0F0E7LL, { 1, 0, 1, 0 }, //1010 – 5 SDATA line from MPU to Multiplexer ch5
    56.               { 0xF0F0F0F0F8LL, { 0, 1, 1, 0 }, //0110 – 6 SDATA line from MPU to Multiplexer ch6
    57.                 { 0xF0F0F0F0F9LL, { , 1, 1, 1, 0 } //1110 – 7 SDATA line from MPU to Multiplexer ch7
    58.                 }
    59.               }
    60.             }
    61.           }
    62.         }
    63.       }
    64.     }
    65.   }
    66. }
    67.
    68. MPU6050 mpu;
    69. int16_t ax, ay, az;
    70. int16_t gx, gy, gz;
    71.
    72. long long  val[6];//6 DOF MPU 6050 thats where this val{6} come from
    73. long val;
    74. long prevVal;
    75.
    76. byte bArray[] = ( 0, 180 );
    77.
    78. //Mux control pins on the Arduino Digital pins
    79. int s0 = 8;
    80. int s1 = 7;
    81. int s2 = 6;
    82. int s3 = 5;
    83.
    84. //Mux in "SIG" pin
    85. int SIG_pin = 0;
    86. //int val = readMux(7);
    87.
    88. void setup()
    89. {
    90.   pinMode(s0, OUTPUT);
    91.   pinMode(s1, OUTPUT);
    92.   pinMode(s2, OUTPUT);
    93.   pinMode(s3, OUTPUT);
    94.
    95.   digitalWrite(s0, LOW);
    96.   digitalWrite(s1, LOW);
    97.   digitalWrite(s2, LOW);
    98.   digitalWrite(s3, LOW);
    99.
    100.   Wire.begin();
    101.
    102.   for (int i = 0; i < 10; i++) //10 mpu's
    103.   {
    104.     mpu.initialize();
    105.   }
    106.
    107.   radio.begin();
    108.   radio.payload = 6;
    109.   radio.setAutoAck(false);
    110.   radio.setDataRate(RF24_2MBPS);
    111.   radio.openWritingPipe();
    112. }
    113.
    114. void loop()
    115. {
    116.   for (int i = 0; i < 16; i ++)//Loop through and read all 16 values
    117.   {
    118.     int readMux(int channel)
    119.
    120.     int controlPin[] = {s0, s1, s2, s3};
    121.
    122.     int muxChannel[8][4] = {
    123.       {0, 0, 0, 0}, //channel 0
    124.       {1, 0, 0, 0}, //channel 1
    125.       {0, 1, 0, 0}, //channel 2
    126.       {1, 1, 0, 0}, //channel 3
    127.       {0, 0, 1, 0}, //channel 4
    128.       {1, 0, 1, 0}, //channel 5
    129.       {0, 1, 1, 0}, //channel 6
    130.       {1, 1, 1, 0}, //channel 7
    131.       {0, 0, 0, 1}, //channel 8
    132.       {1, 0, 0, 1}, //channel 9
    133.       //  {0, 1, 0, 1}, //channel 10
    134.       //  {1, 1, 0, 1}, //channel 11
    135.       //  {0, 0, 1, 1}, //channel 12
    136.       //  {1, 0, 1, 1}, //channel 13
    137.       //  {0, 1, 1, 1}, //channel 14
    138.       //  {1, 1, 1, 1}  //channel 15
    139.     }
    140.   }
    141.   //loop through the 4 sig
    142.   for (int i = 0; i < 4; i ++)
    143.   {
    144.     digitalWrite(controlPin[i], muxChannel[channel][i]);
    145.   }
    146.
    147.   //read the value at the SIG pin
    148.   int val = analogRead(SIG_pin);
    149.
    150.   //return the value
    151.   return val;
    152.
    153.   for (int i = 0; i < 6 i++)
    154.   {
    155.     mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
    156.     val[0] = map(ax, -17000, 17000, 0, 180);
    157.     val[1] = map(ay, -17000, 17000, 0, 180);
    158.     val[2] = map(az, -17000, 17000, 0, 180);
    159.     val[3] = map(gz, -17000, 17000, 0, 180);
    160.     val[4] = map(gy, -17000, 17000, 0, 180);
    161.     val[5] = map(gx, -17000, 17000, 0, 180);
    162.
    163.     radio.openWritingPipe(recievers[i].address);
    164.     radio.write(val);
    165.   }
    166.
    167.   delay(50);

        Arduino: 1.6.4 (Windows 8.1), Board: "Arduino Nano, ATmega328"

        sketch_may19a:57: error: expected primary-expression before ',' token
        sketch_may19a:66: error: braces around scalar initializer for type 'int'
        sketch_may19a:68: error: expected ',' or ';' before 'MPU6050'
        sketch_may19a:73: error: conflicting declaration 'long int val'
        sketch_may19a:72: error: 'val' has a previous declaration as 'long long int                val [6]'
        sketch_may19a:76: error: redefinition of 'byte bArray []'
        sketch_may19a:21: error: 'byte bArray [8]' previously defined here
        sketch_may19a.ino: In function 'void setup()':
        sketch_may19a:104: error: 'mpu' was not declared in this scope
        sketch_may19a:108: error: 'class RF24' has no member named 'payload'
        sketch_may19a:111: error: no matching function for call to         'RF24::openWritingPipe()'
        sketch_may19a.ino:111:25: note: candidate is:
        In file included from sketch_may19a.ino:12:0:
        C:\Program Files (x86)\Arduino\libraries\RF24/RF24.h:324:8: note: void     RF24::openWritingPipe(uint64_t)
        void openWritingPipe(uint64_t address);
        ^
        C:\Program Files (x86)\Arduino\libraries\RF24/RF24.h:324:8: note:   candidate         expects 1 argument, 0 provided
        sketch_may19a.ino: In function 'void loop()':
        sketch_may19a:120: error: expected initializer before 'int'
        sketch_may19a:139: error: too many initializers for 'int [8][4]'
        sketch_may19a:140: error: expected ',' or ';' before '}' token
        sketch_may19a:144: error: 'controlPin' was not declared in this scope
        sketch_may19a:144: error: 'muxChannel' was not declared in this scope
        sketch_may19a:144: error: 'channel' was not declared in this scope
        sketch_may19a:151: error: return-statement with a value, in function     returning     'void' [-fpermissive]
        sketch_may19a:153: error: expected ';' before 'i'
        sketch_may19a:155: error: 'mpu' was not declared in this scope
        sketch_may19a:156: error: invalid types 'int[int]' for array subscript
        sketch_may19a:157: error: invalid types 'int[int]' for array subscript
        sketch_may19a:158: error: invalid types 'int[int]' for array subscript
        sketch_may19a:159: error: invalid types 'int[int]' for array subscript
        sketch_may19a:160: error: invalid types 'int[int]' for array subscript
        sketch_may19a:161: error: invalid types 'int[int]' for array subscript
        sketch_may19a:163: error: 'recievers' was not declared in this scope
        sketch_may19a:164: error: no matching function for call to 'RF24::write(int&)'
        sketch_may19a.ino:164:20: note: candidate is:
        In file included from sketch_may19a.ino:12:0:
        C:\Program Files (x86)\Arduino\libraries\RF24/RF24.h:281:8: note: bool     RF24::write(const void*, uint8_t)
       bool write( const void* buf, uint8_t len );
        ^
        C:\Program Files (x86)\Arduino\libraries\RF24/RF24.h:281:8: note:candidate     expects 2 arguments, 1 provided
        expected primary-expression before ',' token

body:
You do know that you assign 6 different values to val, before you use the last one?

And assigning 4 interrupts? I have to question how well you understand what you are doing.

Google pastebin for a method of posting all of your code before asking for help. And be sure to include what you have already tried and how it failed. People are much more likely to help, as opposed to do it for you.

update:  As pointed out using pastebin is not a good long term solution, just a quick fix.

You are doing quite a few newb things in your code. There is nothing wrong with that we were all newbs at some point.

First, you are driving 21 servos?  Assuming you board has 21 PWM pins, do you realize they could be drawing up a half amp or more each?  If at 1/2 that it would still be around 5 amps, that is probably 100 times more than the Arduino can handle.  So I hope you have made provisions to power them externally.

The first real error is on line 130. You define a stepper motor called GzUT, then you pass it to a function expecting a pin number. This is not correct, and I also suspect the 'stepper' library would already set up the pins and there is no need for you to do that. Even beyond that, you declare the GzUT as part of a structure, but you never create a variable that is made of that structure.

This is indicative you are not an experienced programmer, and an embedded program is not the place to learn how to program.

You are trying to do too much at first.  Go slower.  Get 1 servo (or stepper) to work. then add the others once you understand how to do that. Refer to samples from the stepper library web site. ([http://www.arduino.cc/en/Tutorial/MotorKnob][1])

The MPU-6050 is also a somewhat more advanced sensor. It look like you plan on multiplexing them? With an I2C multiplexer?  Have you thought out the addressing? Do you have any idea of timing requirements of 21 servos and multiple i2c data streams and if the processor is even capable of meeting those requirements?  My experience with an Arduino UNO is it barely can keep up with 1 mpu-6050. I doubt if you can add more than one servo.

The Arduinos in general are awesome prototype platforms. They are great for learning embedded programming. But they are not so good for just learning to program in general, especially when you are trying to do a lot of work, of which 21 servos certainly qualifies as.  Again, my recommendation would be slow down, do one small thing at a time, or if this is a real project, contract it out to someone with experience.

Update: I didn't mean to offend. It is just unclear from your question and your code how much experience you have or do not have. That being said, I am not able to figure out which of the rlf2401 libraries you are trying to use. There 5 of them mentioned on this Arduino page [http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01][2]. So follow up with which one you used and I will take a look.

  [1]: http://www.arduino.cc/en/Tutorial/MotorKnob
  [2]: http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01


sender: user

message:
Use Adafruit 16-Channel 12-bit PWM/Servo Shield to switch relays

I'm wondering if using the [Adafruit 16-Channel 12-bit PWM/Servo Shield][1] is it possible to switch relays, such as use that shield as a multiplexer and use digital output without PWM.

Is it possible? example code?

  [1]: https://www.adafruit.com/products/1411

sender: assistant

body:
That will work. Just make sure you are not using Servo part of the library, but only the PWM part, and set the duty cycle to 100%. The relay should still work, even if the duty cycle is slightly lower, as the magnetic field takes a bit of time to collapse. Just make sure you don't forget to add a (flyback) diode to the relay.

Looking at the datasheet I think you need to use the following code

    pwm.setPWMFreq(1000);//put this in setup()
    ...
    // enable relay at channel 15
    pwm.setPWM(15, 1, 0);
    ...
    // disable relay at channel 15
    pwm.setPWM(15, 1, 1);


body:
Using the adafruit PWM servo shield seems like overkill, you are paying for a lot facilities (PWM) that you won't be using. If you want to use the shield to reduce the number of pins used on your arduino board,  consider a pair of shift out registers (74HC595 for example). The relays need a logic 1 or a logic 0 to change state. You send a bit pattern to the shiftout register that sets the output pins of the shift register to 1 or 0. I found [this page][1] helpful.

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


message:
Arduino: Breadboards and PCBs

I just watched this [excellent video tutorial](https://www.youtube.com/watch?v=_LCCGFSMOr4) that shows a simple Arduino program that toggles an LED via a pushbutton. Very cool!

In the video, the author is using a breadboard for prototyping his circuit. What's the next "step up" from this? In other words, say I get my breadboard circuit working perfectly, is it now time to create a PCB? If my understanding of circuitry is correct, this is *not* a trivial process. I would need a CAD program to design my circuit, and it would likely be very expensive to get the design actually fabricated. At least too expensive for simple hobby purposes. **Is there a middle ground between breadboard and PCB?**

body:
You can build your project on stripboard (aka Veroboard, which is a particular brand). The wiki page at http://en.wikipedia.org/wiki/Stripboard covers most of the salient points - it is essentially a generic PCB. You can cut tracks, either with a knife, or a specialized tool, and you can solder your parts on to the tracks.

They come in various configurations - my personal preference is just straight strips - and you can cut them to size with a hacksaw.

If your project is non-trivial, you might still like to spend some time working out a decent layout. There are free, and not quite free, products to help you - I use Kicad, which is free & opensource, there are many others.

I have also used stripboard to group a few components together - for example, 2 7-segment displays and two SIPO chips to run them - this can then be a "component" for future bread-board projects.


body:
[Eagle CAD][1] is one of the most popular E-CAD programs, and is reasonably priced [free][2] for personal use. When Libraries, tutorials and examples are made available it is most often in Eagle CAD format.

![enter image description here][3]

Once you ready your design and layout (in Eagle) you can get boards made for $30ish ([https://oshpark.com/][4])

You will have to obtain parts and solder yourself for assembly, but your time is free, right?  I have done a few. I was a software only person until I started in November 2014 ([http://www.spiked3.com/?p=5981][5])

  [1]: http://www.cadsoftusa.com/
  [2]: http://www.cadsoftusa.com/download-eagle/freeware/
  [3]: https://i.stack.imgur.com/5dQxx.jpg
  [4]: https://oshpark.com/
  [5]: http://www.spiked3.com/?p=5981


body:
If you are only making one or two the following works well:

 1. Download Kicad (Free) and design your board.
 2. Print out the layout on special film, and transfer to a blank PCB using a domestic iron.An example: http://www.maplin.co.uk/p/press-and-peel-film-pcb-transfer-system-ab15r
 3. Etch the board in ammonium persulphate or ferric chloride solution.
 4. Drill the holes. You will need some 0.8 and 1.0mm drills and a Dremel drill press or similar.
 5. Mount your components and solder away.

The above works well for single-sided boards. Double sided are possible, but will take some practice.

There is a learning curve getting to grips with Kicad, but if you are serious about electroncs, the time invested is well worthwhile. I got from being a Kicad novice to producing a specialist Arduino shield in a weekend. I had the advantage of having used similar tools in the past, and the disadvantage of being 67 years old (with eyesight to suit)

All the required parts should be available from agood electronics parts suppier (For example Jaycay here in New Zealand)


body:
> Is there a middle ground between breadboard and PCB?

A prototype PCB with breadboardlike layout is a fast way to turn a breadboard design into a permanent build. So it may be in the range of valid answers to your question.

(-: *The link below is just an example, there are lots of other names, designs and sellers and I am in no way releated to any of those...* :-)

https://www.tindie.com/products/Schmart/400-tiepoint-schmartboard-breadproto-board-bundle/


message:
Do I need the Motor Shield to drive servo motors?

I was perusing Arduino's list of official shields and noticed the [Motor Shield](http://www.arduino.cc/en/Main/ArduinoMotorShieldR3) that can be used to drive up to 2 servo motors.

Being brand new to Arduino/robotics, I am wondering: do I *really* need this shield to drive a set of servos?

* What does this shield really offer in the way of driving motors?
* What is lost by *not* using this shield?
* What if I my project has more than 2 motors?!?

body: The Motor Shield is for driving bare motors, not servos. Servos already include drive electronics and only require a PWM signal in order to control them, whereas the Motor Shield provides the drive electronics for bare motors.


body:
The shield will drive a pair of DC motors (the common small ones in models), or one stepper motor (the precision motors you find in dead printers, etc), and can also connect onwards to other stuff, which happens to include servos. I certainly wouldn't get one to run a servo...
If you want more than two motors, there are other motor shields, or you could make a custom board to suit.
There isn't enough power from Arduino outputs to drive a motor (in general) so some sort of driver is needed - for a simple DC motor, a simple transistor would do, you need bridges for steppers, or ESC's for RC-model type high-power motors. Servo's have their own drivers built-in, so can just plug-in to Arduino.
If you just want to control a couple of motors or a single stepper, the shield is quick & easy, which is where it is placed in the market.


body:
You don't need this shield to drive *servo* motors, they have their own controller, you need just a 5V power line, GND and digital output pin to generate a PWM and that's it. Usually Arduino has enough power to drive **servo motors**.

This shield you are talking about is used for DC (direct current) and stepper motor. These motors need power gain and the shield provides it and often has a chip called L298N (which implements [H-bridge][1]) with MOSFETs to properly feed the motor.

**What does this shield really offer in the way of driving motors?**

A proper circuit and components so you plug your motor and connect into your board leaving you just the programming task to control motor's position and speed.

**What is lost by not using this shield?**

Actually, you use this kind of component just for practice purposes. It is already built and you just use it. However, it's a good learning process building the H-bridge yourself and understanding how it works and why it is necessary (if you have time, this is a good task).

**What if I my project has more than 2 motors?!?**

Well, just decide how many H-bridges you need. This shield has the capacity for 2 DC motors or 1 stepper motor. In case they are servo motor, you just use this [lib][2]. It is possible to have plenty of servos working together and all you need are good battery and enough digital pins. They share timers of microcontroller, that's why it works for many motors.

  [1]: http://en.m.wikipedia.org/wiki/H_bridge
  [2]: http://www.arduino.cc/en/Reference/Servo


message:
How to tell what components are compatible with Arduino Due?

I am interested in using the [Arduino Due](http://www.arduino.cc/en/Main/ArduinoBoardDue) in an upcoming project, however I am worried that the other shields/components that I need will not be compatible with it, because, according to that link:

> The Due is compatible with all Arduino shields that work at 3.3V and are compliant with the 1.0 Arduino pinout.

The components I need to use are:

* NightShade Electronics [energyShield](http://www.ns-electric.com/products/energyshield/)
* [Solar Panel](http://www.adafruit.com/products/200)
* [Servo Motors](http://www.adafruit.com/products/1143?gclid=CjwKEAjw96aqBRDNhM6MtJfE-wYSJADiMfgguI7rTduiPEzHwVkcWxKifp1IMtwpI6VHO8btHORRKBoCStHw_wcB)

Essentially a solar panel will power the energyShield (rechargeable battery), which in turn will power multiple servo motors.

I cannot tell if the energyShield uses the 1.0 pinout or not. I am also worried that since the the solar power generates 6V it will overload the energyShield which is rated at 3.3V. At the same time, I am worried that the servo motors, which seem to require 4.8V, will not be capable of being powered by the energyShield which outputs 3.3V. Thoughts?

Bonus Points if someone can explain to me what the "1.0 Pinout" is, and whether it is the latest/most modern pinout available for Arduinos.

body:
As far as I understood this energyShiled accepts any input between 5-24V and output 5 - 3.3V. This specs are compatible with arduino Due. And with the solar panel.

You can always power servos from seperate source or from the same battery but with seperate direct line.


message:
how can I change the setting for number of upload retries in the IDE?

I run into this problem when I mess something up, and it's pretty annoying to wait for 10 not in sync timeouts before I can try some different method.

    ...
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x85

How can I set the number of "attempts" to say 2 instead of 10? Or how can I safely interrupt the upload process in the IDE?

body:
The code is not in the arduino ide but in the tool chain (.exe) that it runs.

Normally it is a program called avrdude.exe that is running so you would need to rebuild the avrdude.exe tool which is not practical.

The easiest way, but rather crude, is to pull the usb cable. If the port disappears avrdude should stop immediately.


message:
How to see log from Arduino IDE?

Where can I see outputs from such instruction in an ino file ?

    Serial.println("my message");

body:
The Serial.print statements show up on whatever terminal program is opened and connected. Their can be only one open at a time, but it could the Arduino IDE built in monitor (ctl-shft-m) or an external terminal program, eg putty, or some other program you wrote that opened the com/serial port the Arduino is on.

Remember though - only 1 can be open at a time. If you use an external program you MUST close the com port before attempting to download a new version of your sketch.  If you use the built in monitor/terminal it will automatically do this for you.


body:
It took me ages to realize that instead of remembering Ctrl-Shft-M you can just click on the little magnifying glass in the upper right of the IDE interface. Wait until after your script uploads though, it won't do anything while compiling or uploading your script.

![Screen Shot of Arduino IDE interface showing serial monitor icon][1]

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


body:
Call `Serial.begin(9600)` in your `setup()` function:

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

Call `Serial.print('example')` or `Serial.println('example')` in your `loop()` function (or one of your own functions that your `loop()` function calls:

```
void loop() {
  Serial.print('example');
  Serial.print('example');
  // Output of the two calls above: exampleexample
  Serial.println('example');
  Serial.println('example');
  // Output of the two calls above:
  // example
  // example
}
```

Go to **Tools** > **Serial Monitor** to see the output.

References:

* https://www.arduino.cc/reference/en/language/functions/communication/serial/print/
* https://www.arduino.cc/reference/en/language/functions/communication/serial/println/


message:
what ftdi windows driver for arduino nano

at http://www.ftdichip.com/FTDrivers.htm they seem to divide chips into two categories,  FT4222H vs. D2XX driver.

What's the correct for a arduino nano?

body:
The [Official Arduino Nano](http://www.arduino.cc/en/Main/arduinoBoardNano) has an FTDI FT232RL.

You want to use the [Virtual Com Port(VCP) Driver](http://www.ftdichip.com/Drivers/VCP.htm) so the FTDI device appears as a COM port under windows.

See the [getting started guide](http://www.arduino.cc/en/Guide/Windows#toc4) for details.


message:
arduino suddenly shows “avrdude: ser_open(): can't open device ”\\.\COM3" after last upload

I am using arduino uno to make a sound detector. I uploaded a program, found error in the code that it returns unintended numbers unreasonably big. I also think I used wrong code for the module, but it was connected in the way that can work properly with the proper code.

The code I uploaded was:

    const int ledPin =13;
    const int middleValue = 512;
    const int numberOfSamples =128;

    int sample;
    long signal;
    long averageReading;

    long runningAverage = 0;
    const int averagedOver = 16;

    const int threshold=400;

    void setup(){
     pinMode(ledPin, OUTPUT)
     Serial.begin(9600)
    }

    void loop(){
     long sumOfSquares = 0;
     for (int i=0; i<numberOfSamples; i++){
      sample = analogRead(0);
      signal = (sample - middleValue);
      signal *= signal;
      sumOfSquares += signal;
     }
     averageReading = sumOfSquares/numberOfSamples;
     runningAverage=(((averagedOver -1 )*runningAverage)+averageReading)/averagedOver;

     if(runningAverage>threshold){
      digitalWrite(ledPin, HIGH);
     }else{
      digitalWrite(ledPin, LOW);
     }
     Serial.println(runningAverage);
    }

When the arduino suddenly stopped sending serial numbers, I pressed reset button and uploaded the default code:

    void setup() {
    }

    void loop() {
    }

but now it shows that it cannot connect to COM3 (arduino) and cant find the device, When I can see arduino uno successfully connected to PC using device manager (windows 8.1). The led light of arduino also turns on when I connect it to power source or usb.

it shows "port not found" when I click to see the serial output

Did I just fry Arduino? How should I fix this?

Also, i checked the led pin 13 blinking three times when i plug in the usb. I just cant upload anything

body: my arduino revived the next day.... don't know why but it works!


body:
I ran into such a problem when I was accessing my Arduino board from two different windows applications like Arduino IDE and eclipse. or Eclipse and some serial monitor windows application. Make sure you close any application that programs or communicates with the Arduino board, and make sure you configure the COM you are using in Arduino IDE and try again.
Also try disconnecting any wire that is connected to RX and TX pins when you are programming the Arduino.


body:
You might have your serial monitor open at COM3 somewhere which is why AVRdude is failing to open the port again. Make sure the serial monitor is closed.

if you are opening serial ports on Python or your own developed applications, you have to explicitly close the port on exiting the program, otherwise, the port remains open and you come across such errors.


message:
Implementing Quasi-Perpetual Battery on Arduino

I am interested in seeing how much "*uptime*" I can achieve with my Arduino device/project. I am brand new to electronics/robotics, and so I wanted to bounce my idea off of this community first and see if I am overlooking anything obvious/major, or if my overall approach is incorrect.

The idea is simple:

Provide my Arduino device with 2+ "rechargeable power sources" (described next) and then provide a mechanism to route power to any viable (non-dead) power source at any time. While one power source is being used to power the Arduino device, the other "idling" power sources are recharging. The intention is to allow the device to keep switching between power sources endlessly, in perpetuity, achieving 100% uptime (perfect "high availability").

As for each "rechargeable power source" I am thinking an [energyShield](http://www.ns-electric.com/products/energyshield/) (rechargeable Li-polymer) backed by a [solar panel](http://www.adafruit.com/products/200).

I did some preliminary research and was told that if I were to wire these power sources in series with diodes, then the circuit would always by default draw power from the source with the highest voltage. As soon as another source has higher voltage, the circuit begins drawing power from that one, and the "old source" begins recharging.

I'm a noob but not a fool, and I **know** there is no such thing as perpetual energy (hence the title "quasi-perpetual"), and I'm sure factors like sunlight/weather conditions/etc. would affect the efficacy of the solar panels, etc. But I guess my first concern is: am I doin' it right? Are there any caveats/pitfalls or considerations I'm overlooking here?

Assuming I'm more or less correct in my approach, the other concern is how to actually implement power sources and diodes in a series, and how to actually rig that all up and connect it to the Arduino board. Again, I'm a total electronics newbie, so I'm just having a tough time visualizing the precise solution there.

And as for determining the *actual* number of power sources (energyShield + solar panel combo) my device would need, I was just planning on starting with 2, and running the device at max power and monitoring their recharge rates. The more sources I add, the longer the device will operate. Obviously, at some point I'll either reach a point where its uptime is sufficient for my needs, or I'll run out of money. :-)

body: You're overthinking it. Use one or more solar panels, a harvesting IC with sufficient storage, and the bare MCU and peripherals. Use enough panels and storage to run the MCU and peripherals 24/7, and to also charge the storage during the day.


body:
"I did some preliminary research and was told that if I were to wire these power sources in series with diodes, then the circuit would always by default draw power from the source with the highest voltage."

That is not correct - you need the two sources in parallel with a diode each. Then the higher voltage will become the current source.
When the sources are charging, the charge source may become the current source if that voltage is higher than the other stored charge source.


message:
Undefined functions send() and receive() on TwoWire/SPI

I have downloaded a sketch that uses SPI.  The sketch includes the Wire library but at compilation time, I am getting errors that TwoWire doesn't have methods called `send()` and `receive()`?

body: This is caused by the sketch you downloaded being old.  In prior releases, the methods called `send()` and `receive()` were used to send and receive SPI data.  These were renamed to be `write()` and `read()`.  If you change your code where there are references to `Wire.send()` and change to `Wire.write()` and also change `Wire.receive()` to `Wire.read()`, you should find that your applications compile and run correctly.


message:
How do i properly read an analog pin on attiny85?

Anyone ever run into a problem with your attiny not reading  your analog pins correctly? (-1023 or 1023 or 0 value) How did you resolve the issue?

Here's what my code looks like now :

4th revision of code as of 5/6/2015 8pm:

    int NTC = A1; // thermistor
    int switchPin = PB1; // push button
    int LED = PB0;  // led

    // button latch
    byte ButtonState;
    byte lastState = LOW;
    byte count = 0;

     //brightness level of each different mode
    int low = 50;
    int med = 140;
    int high = 255;
    int dim = 0;

    int ADCcount = 0;

    void setup()
    {

     pinMode(switchPin, OUTPUT);
     pinMode(LED, OUTPUT);

      }

     void loop()
     {

      ADCcount = analogRead(NTC);

    delay(100);

      ButtonState = digitalRead(switchPin);

      if(ButtonState && ButtonState != lastState)  // button latch, no debounce      needed.
       {
          if(count < 4) // This will check to see if the count is within a range of  0 - 255
                     // anything over that, it will reset count back to 0. Of course
          count += 1;  // same as count = count + 5;
          else
          count == 0;
            }

        lastState = ButtonState;

       if (count == 0)
      {analogWrite(LED,0);}
        else if (count == 1) { if(ADCcount < 500) {analogWrite(LED,high);}
          else{ if(ADCcount > 525){analogWrite(LED,low);}
           }
              }
          else if (count == 2 ){analogWrite(LED,med);}
          else if (count == 3) {analogWrite(LED,low);}
          if(count >=4) {count = 0;}
          delay(50);
     }

----------

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/dyIZY.png)

<!-- End schematic -->

body:
The improper bush-button event handling is likely to cause the problem. One way to properly react to the external environment signals could be constant polling or using interrupts. With constant polling, all the time is spent on the checking the status of the button. With interrupts, the program is executed as it should, and only if interrupt happens - the execution jumps to the interrupt subroutine, executes it, and goes back to the main code where it left off.

In your case, you can use pin 7, for example, for push button signal. It can have a function of _INT0_. Read *Section 9. Interrupts* of the datasheet - it is straight forward.

I do not completely understand what your program should do, but I will try to convey the general approach of using subroutines:

    volatile bool pressed = false;
    int main(void)
       {
    MCUCR |= (1<<ISC01 |1<<ISC00);  // set INT0 to interrupt on rising edge of pin7
    sei();        // enable global interrupts

       while(1){
          if (pressed) then do something; //You can disable interrupts here so your code is not interrupted by cli();
          pressed = false; // reset the state
          else do something else;
       // you can re-enable your interrupts here by sei();
       }
    }

    // only happens when the change on pin 7 is from LOW to HI
    ISR(INT0_vect){
    pressed = true; // update the pressed status
    }

If you want to use pin6 for push button, you should enable the PCINT1 instead of INT0 and change the ISR to handle the PCINT1 interrupt. In this case, pin 6 will react on voltage toggle (from HI to LOW, or the other way) and you can not discriminate rizing/falling edges. In that way, you must read pin6 within the instruction subroutine to know if it is hi or low.

**EDIT:**

I would suggest to stop the calculations in the _Temp()_ function after the

      average = SERIESRESISTOR / average;

line due to the fact that you have only three operating modes for the LED. Thus you can, back calculate the _average_ value that makes your _steinhart_ value to be, for example >30. This way, all other values greather/smaller than that value will also fall under the same condition depending on whether average/steinhart are directly/inversely proportional.

When you determine the three ranges of raw _average_ values you can use them directly in the _Mode()_ function. Eventually, you can optimize you code even further, by performing monotonic read instead of burst reads. If you keep a buffer, you do only one addition of the most recent sample and subtracting the oldest sample. For this you will need two pointers and one memory for to store _sum_, but you will not need to do nSamples additions:

    read (newSample);
    sum += newSample;
    sum -= oldestSample;
    average = sum/numSamples;
    update pointers to the memory for oldest sample and for the feature sample;


message:
Arduino YUN real time control

I have a very specific problem, exactly with real time control. For example I try to write an application where I can edit min or max temperature that after reaching it , I will receive SMS with message. I'm wondering how to edit variables "on-the-fly" because, as I know Arduino IDE use it own libraries not this from C/C++, and I don't know how to get to SD card in Arduino too. Can someone help ?

Thanks

body:
the SD card is at /mnt/sd/ . you should consider reading the yun tutorials [here][1] before going further, the ability to send and receive data is at the heart of the yun design.

  [1]: http://www.arduino.cc/en/Tutorial/Bridge


message:
Adafruit CC3000 Wifi Shield on IRQ 2?

I'm using an AdaFruit CC3000 Wifi shield as an HTTP server with an Arduino Uno.

I have a script which works fine -- logs into my Wifi and listens for connections as it should.

However, I want to use an infrared library which writes to the CC33000 default IRQ 3, so to avoid conflict I change the following setting:

    #define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!

to the only other Interrupt pin

    #define ADAFRUIT_CC3000_IRQ   2  // MUST be an interrupt pin!

The device hangs at "Initializing" .. or at least I see neither of the subsequent lines in the following code on my serial monitor:

    Serial.println(F("\nInitializing..."));
      if (!cc3000.begin())
      {
        Serial.println(F("Couldn't begin()! Check your wiring?"));
        while(1);
      }

      Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID);
      if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
        Serial.println(F("Failed!"));
        while(1);
      }

I've stripped everything back down to just the example code for HTTPServer to ensure it's not a conflict with my own code or the IR Library. I've changed the setting from 2 to 0 and 1 thinking there was some confusion over literal IRQs vs Pins, but those settings generate the "Couldn't begin" error trap.

Is there any other setting that I need to vary in order to get the CC3000 to opearate on IRQ 2 or is this a hardware bug and I'm out of luck if I want to use Pin 3?

body:
It is a "hardware bug" as you so aptly put it. As far as I know, the only way to get the CC3000 board to use pin 2 as the IRQ is to physically rewire the connections. I did exactly that on my board and it works without a problem, leaving pin 3 free to use for whatever else you want. You can see what I did [**here**][1].
It basically involves cutting the trace wire and running a jumper cable between the holes next to the pins.

The important thing to understand perhaps is that pins 2 and 3 are available to use for IRQ on the Mega and Uno, but it is an actual dedicated pin on the CC3000, hence why you have to go to this effort to change it. Also remember that once you have cut the trace to pin 3 it becomes an open/free pin and is no longer connected to the wifi shield. By the sounds of your requirements this shouldn't matter, but it is still useful to know.

If you haven't already, I recommend that you read the [documentation for the CC3000 board][2], as it really helped me understand the irritating intricacies.

But yeah, if you choose to follow this and reroute the pin, it works perfectly. Hope this helps, even if it is a bit late.

  [1]: https://arduino.stackexchange.com/questions/9740/arduino-motor-shield-and-adafruit-cc3000-wifi-shield-compatibility
  [2]: https://learn.adafruit.com/downloads/pdf/adafruit-cc3000-wifi.pdf


message:
Programming question for Time Arduino

Can you program a sketch so that if the time is between 1m and 10m then it will reset itself?
Reset I found already, it is the if that I don't know.

body:
You can use the timer interrupts. For example:

    #define F_CPU   16000000UL
    #include <avr/delay.h>
    #include <avr/io.h>
    #include <string.h>
    #include <avr/interrupt.h>
    ...
    ISR(TIMER1_COMPA_vect)
    {

      //do something every seconds when interrupt is raised.

    }
    void setup()
    {
    /*the following code will setup timer register to generate interrupt
      when 15624 is reached, at a clock frequency of 16 MHz and 1024 prescaler. This means that     every second an interrupt is generated
    */
      cli();          // disable global interrupts
      TCCR1A = 0;     // set entire TCCR1A register to 0
      TCCR1B = 0;     // same for TCCR1B

      // set compare match register to desired timer count:
      OCR1A = 15624;
      // turn on CTC mode:
      TCCR1B |= (1 << WGM12);
      // Set CS10 and CS12 bits for 1024 prescaler:
      TCCR1B |= (1 << CS10);
      TCCR1B |= (1 << CS12);
      // enable timer compare interrupt:
      TIMSK1 |= (1 << OCIE1A);
      sei();          // enable global interrupts
    }

The code works on Arduino Uno. You should calculate the value of OCR1A for your frequency.


message:
Multithreading Leds and Joystick

I'm trying to made a program that turn on and turn off leds with an input and send the coordinates of joystick, but, in the loop, the arduino makes one at a time, and i want make this in the same time. How can i make that?

body:
One way to do this is to use the millis() function.

millis() returns the current value of a timer that is incremented once per millisecond (hence the function name). You can compare the value of millis() at some past time with the current value to determine how many milliseconds have passed. By having multiple compare registers you can have multiple independent delays operating. (There is also micros() which increments at the 1 uS rate (with a "granularity" of 4uS on some processors).

This code is an example only. It MAY run but has not been tested and probably contains silly mistakes which do not affect its example purposes.

A function ToggleLED(n) is assumed which toggles the specified LED n from 1->0 or 0->1  as required.

LED1 will flash 200 mS on, 200 mS off, ...
LED2 will flash 333 mS on, 333 mS off, ...

The two loops are essentially independent.
_________________________

    unsigned long delay1; delay2;

    void setup(){

    int FlashTime1 = 200; / LED 1 will have a 200 on 200 off cycle
    int FlashTime2 = 333; / LED 2 will have a 333 on 333 off cycle

    delay1 = millis() + FlashTime1;  / Init LED timers
    delay2 = millis() + Flashtime2;
    }

    void loop()
    {
      if (millis() == delay1){ / Not until delay expired.

        ToggleLED(1);
        delay1= millis() + FlashTime1; / Reinit flash timer}

      if (millis() == delay2){

           ToggleLED(2);
           delay2= millis() + FlashTime2;}

    }


body:
> the loop is something like this:
>
>     loop() {
>     controlleds();
>     joystickevent();
>     }
>
>  but he runs, controlleds first, and joystickevent next, i want at the
> same time.

There are typically two ways to read a simple potentiometer joystick: Connect it in a voltage divider and measure the analog voltage; and connect it in an R-C circuit and measure the time for the capacitor to charge.

The first way is faster and you should not be able to notice the time difference between controlling the LEDs and reading the joystick.

The second way takes longer and you might be able to notice. If this is how your joystick controller works, you would need to separately start the joystick reading, continue to poll the buttons control the LEDs, and check whether the joystick reading is ready yet. The joystick routine must not delay, waiting for the measurement to finish.


message:
Arduino: Put Data in Other File

The below code starts off with lots of data in the beginning, distracting the reader from the actual code.  What is the best practice to clean this up:

    #include <Wire.h>
    // For LED Backpack
    #include "Adafruit_LEDBackpack.h"
    #include "Adafruit_GFX.h"
    // For LCD Shield
    #include <Adafruit_MCP23017.h>
    #include <Adafruit_RGBLCDShield.h>

    // For pixel Units, such as hero
    #include <Unit.h>

    Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix();
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    Unit *hero;
    boolean doesNeedRedraw = true;
    boolean textNeedsRedraw = true;
    int8_t lastButtonPress = 0;
    int8_t frame = 0;

    void setup() {
      /* Important Setup Routine */
    }

    static const uint8_t PROGMEM
      smile_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10100101,
        B10011001,
        B01000010,
        B00111100 },
      neutral_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10111101,
        B10000001,
        B01000010,
        B00111100 },
      frown_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10011001,
        B10100101,
        B01000010,
        B00111100 },
      walls_bmp[] =
      { B10100000,
        B10110000,
        B10010000,
        B11011100,
        B01000100,
        B01110100,
        B00010100,
        B00011100 };

    void loop() {
      /* Important Main Loop Routine */
    }

body:
One way to clean that up is to create a "Globals.inc" file and cut and paste all of your globals into there.  After that's done, simply include the globals file from your main .ino file with `#include "Globals.inc"`

(Main.ino)

    #include <Wire.h>
    // For LED Backpack
    #include "Adafruit_LEDBackpack.h"
    #include "Adafruit_GFX.h"
    // For LCD Shield
    #include <Adafruit_MCP23017.h>
    #include <Adafruit_RGBLCDShield.h>

    // For pixel Units, such as hero
    #include <Unit.h>

    #include "Globals.inc"

    void setup() {
      /* Important Setup Routine */
    }

    void loop() {
      /* Important Main Loop Routine */
    }

(Globals.inc)

    Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix();
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    Unit *hero;
    boolean doesNeedRedraw = true;
    boolean textNeedsRedraw = true;
    int8_t lastButtonPress = 0;
    // 0-255
    uint8_t frame = 0;

    static const uint8_t PROGMEM
      smile_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10100101,
        B10011001,
        B01000010,
        B00111100 },
      neutral_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10111101,
        B10000001,
        B01000010,
        B00111100 },
      frown_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10011001,
        B10100101,
        B01000010,
        B00111100 },
      walls_bmp[] =
      { B10100000,
        B10110000,
        B10010000,
        B11011100,
        B01000100,
        B01110100,
        B00010100,
        B00011100 };


body:
There is actually not a lot wrong with the way the code is.  You are writing / using embedded code. It is not expected to be some planned out UML model, and does not need to look like it is.

If you just want less lines, start by converting your binary data to hex. Otherwise the answer of a global.h is valid (and I would still convert binary to hex). You could easily shrink 24 lines down to 3.

If you could use a real IDE navigation would be unimportant, but since Arduino chose not to use a standard build process it takes extra effort (but still worth it). You could also switch to native AVR (and easily use a real IDE), which is what I plan to do as soon as the proof of concept is finished.


message:
How to transfer data from Arduino to some software in computer?

My arduino gets some data from sensors and save it into EEPROM. Now, I want that when I connect my arduino to PC there should be a software(like sketch) which can fetch data from arduino's EEPROM processes it and saves it into a file in PC. I am willing to create such a software but how will I then communicate with arduino like Sketch does?

body:
The options that I see:

* Via serial - this can either be done wirelessly via Bluetooth serial adapter, or via the standard USB connector. Your program will have to have a way of sending the data - some way to indicate that you want to download the data.
* Transfer via ICSP - these are the 2x3 grid of pins on your Arduino. You can download the data, without having to write any code. You will need something like a USBASP - they're cheap. You can download the entire EEPROM, and dissect it once you have it on your computer.

I have a vague recollection that EEPROM may be overwritten when you upload a sketch, so if you want to use serial (the first option), make sure your sketch already knows how to transfer the data before you collect it. This is not a limitation for ICSP.


body:
You should specify what programming language/compiler/IDE you want to use for the part on your pc.

I would suggest using "Processing" - https://processing.org/ it's a similiar IDE as the arduino IDE and the coding is also a bit similiar. You can use a serial library to receive data from USB/COM port.

Processing has the ability to create a window with graphics. You could read the position of something with your arduino, then send it to 'processing' and it will draw the object on the screen (after a bit of coding).

Guide: https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing


body:
Just use serial communication. Make sure you know which port your Arduino is recognized in your system, make a sketch to send data through Arduino's [serial communication][1] and try making a simple [Node.js][2] application using [**serialport**][3] package which will receive your data. There is a code sample where you can start from. Just set the port and start receiving data. And that's good, using Node.js you are really close to web tools, so it's easy to migrate your application to web.

It's really simple and you can get it done in a few minutes, even if you have not been introduced to node.

These kind of embedded applications have been accepted by Node.js and there are plenty of robotics projects which use node on the web.

    var SerialPort = require("serialport").SerialPort
    var serialPort = new SerialPort("/dev/ttyACM0", {
      baudrate: 57600
    });

Usually Arduino is recognized as ttyACM0 on Unix-based systems.
With this line of code you establish a serial communication with your board.

Going further you can register events like data, which is fired when data comes from Arduino:

    // it opens the connection and register an event 'data'
    serialPort.on("open", function () {
      console.log('Communication is on!');

      // when your app receives data, this event is fired
      // so you can capture the data and do what you need
      serialPort.on('data', function(data) {
        console.log('data received: ' + data);
      });
    });

In this example your app just receives data and log it to your terminal.

  [1]: http://www.arduino.cc/en/Serial/Write
  [2]: https://nodejs.org/
  [3]: https://www.npmjs.com/package/serialport


message:
Set start time for arduino uno clock

I'm programming an arduino uno with attached screen to be a clock and have the code below. It counts up from zero the milliseconds, seconds, minutes and hours and when it hits 24 hours it starts again from zero.
Does anyone know how I can set the start time that it automatically starts at when it is reset? It will be a one off thing and I don't want it to interfere with the clock resetting to 0 hours after it hits 24. Thanks

    #include <Wire.h>
    #include <LiquidCrystal.h>

    #define MILLIS_OVERFLOW 34359738

    /**
     * Clock Variables
     */
    unsigned long currentMillis, previousMillis, elapsedMillis;
    int seconds, minutes, hours;

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

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

    }

    void loop()
    {
        setClock();
        /**
         * After set clock now you have 3 int variables with the current time
         */
         //seconds
         //minutes
         //hours
         lcd.setCursor ( 0, 1);
         lcd.print(hours);
         lcd.print(":");
         lcd.print(minutes);
         lcd.print(":");
         lcd.print(seconds);
         lcd.print(":");
         lcd.print(elapsedMillis);

    }

    void setClock()
    {
        currentMillis = millis();
        /**
         * The only moment when currentMillis will be smaller than previousMillis
     * will be when millis() oveflows
     */
    if (currentMillis < previousMillis){
        elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
    } else {
        elapsedMillis += currentMillis - previousMillis;
    }

    /**
     * If we use equals 1000 its possible that because of the mentioned loop limitation
     * you check the difference when its value is (999) and on the next loop its value is (1001)
     */
    if (elapsedMillis > 999){
        seconds++;
        elapsedMillis = elapsedMillis - 1000;
    }

    if (seconds == 60){
        minutes++;
        seconds = 0;
    }
    if (minutes == 60){
        hours++;
        minutes = 0;
    }
    if (hours == 24){
        hours = 0;
    }

    previousMillis = currentMillis;
    }

body:
Assume you want the clock to start at 08:42:21, change

    int seconds, minutes, hours;
to

    int seconds = 21, minutes = 42, hours = 8;

Note that you should always also initialize (as in the second case above), and not only declare (as in the first case) all variables before you first read their values. Otherwise, for local variables you [cannot be sure][1] what their initial value is. (Global variables are [implicitly initialized][2] to zero if not explicitly initialized.)

  [1]: https://stackoverflow.com/a/11233616/143931
  [2]: https://stackoverflow.com/q/14049777/143931


message:
Arduino Stepper Motor Standing Desk help!

I currently have a standing desk at work, and I thought a fun way to learn Arduino would be to automate it, as it currently uses a hand crank.

I would love some help determining what I would need for this task.

What kind of motor should I use?
  -Stepper motor?
  -High/low rpm?
  -High/low torque?

What sort of power would I need?

Looking forward to hearing people's suggestions!

body:
I think this might end up being more of a fun way to electrocute yourself, but let's find out...

Energy required to lift an object with mass "m" an upward distance of "h" in the Earth's gravitational field, on the surface...  E = mgh = m(9.8)h

So, to lift a 50kg desk one meter, we will need 50 x 9.8 x 1 = 490 Joules

How fast do you want to lift it? Let's say we want it to take 10 seconds - that will give us the power level we need. Power is in watts (Joules per second) - so if we want to lift the desk in 10 seconds we need 49 watts - let's call it 50.

Now, to produce 50 watts with a 12-volt battery, that would be 4.2 Amps. This is do-able, and it's not the high power level I expected for lifting a desk. Even if we throw in some efficiency losses, we're well within the safety zone and won't have to get out the high voltage equipment. So, I'm glad I did the math - my initial impression of this task was the joke at the beginning of the post.

So, you need a 50 watt motor... that's easy to find. Hell, why not go way over that and get a 100-watt motor... google that...

http://www.electricscooterparts.com/motors24volt.html - bang! Scooter motors! Nice!

So, that's an example of how you might figure out what parts to get - it all starts with basic physics and ends with Google (or Bing if you're one of *those* people). I simplified a lot, but you get the idea.

The other part of this task is to figure out the control system. I would probably not use Arduino to do this. I would have three switches - one "directional" switch to run the motor, and two sensor switches to disconnect the directions of the motor at each end of the track. I think that's how automatic power windows in cars used to work, which explains why if you didn't hold the button down long enough, it would immediately instead of continuing to the other end - it was still sitting on the sensor.

Sticking an Arduino in the mix and having it read the sensors would just waste power all day long, but you could do it that way. It's the same idea - just mount sensors on the track, which get tripped when the desk rolls up to that spot. Coding wouldn't be that tricky - when the user activates the "change button" or whatever, check which sensor is currently active, and move the desk the other way until the other sensor activates.

You're going to need a good power supply for that motor - a 24-volt **2**00-watt power supply if you like to over-engineer like I do. You'll need a relay to control the motor - it needs to handle 24 volts/200 watts. Then you'll need some kind of activation button, and two sensors. You want some kind of sensor that is definitely going to be activated when the desk is in position, or you risk over-running your target, binding the mechanics, and burning the motor, and possibly the office as well. So, I would choose some kind of mechanical sensor, not a light sensor or something like that.

This should get you started on finding those parts...
https://www.sparkfun.com/categories/145 - these are all kinds of buttons and switches - you should be able to find something that you can mount to the track which will activate when the desk runs into it. Search on this site for the other parts - they have the relays and stuff too.

Final warning though - this may be too complicated and dangerous for a first project. At 24 volts and 100 watts, we are getting into dangerous power levels. But, these are common power levels in consumer equipment. So, if you know what you're doing you should be safe. If you don't, I strongly suggest getting an experienced electrical engineer to look at your designs. Also, you probably can't install this device in an office - there is an insurance reason that it hand-cranks, your company isn't just being cheap.

What happens if someone bumps the desk and it becomes active when you're not around? What happens when the power goes out? What happens when the power comes back on? Do we have enough fuses in the right places to shut this system down before it catches fire? You need to consider all that.


body:
For initial playing,  and possibly for a final solution, battery powered electric drills with external powering are an excellent source of reasonable wattage well geared down motors. Drills are often discarded when the batteries die and may be available free or at lo cost.

For relatively low duty cycle use 9V drills operate OK on a small 12V battery and drills rated at up to 18V usually operate well enough on 12V.

Use of a 12V lead acid battery charged by a trickle charger makes high current peaks easy to accommodate. Almot any condition battery will do - one which is too dead for eg motorcyle use probably works well enough here. Floating 12V lead acid batteries at 13.7 V allows them to be permanenetly connected to the "charger".  A power pack can be used without a battery if enough current is provided.

Battery powered drills typically have a  two stage epicyclic gearbox giving typically hundreds of RPM output speed. If desired you can use the supplied switching which has a DPDT mechanical reversing switch. If you remove the mechanical reversing switch you can feed voltage directly to the motor. Changing polarity changes direction.

Dismantling the gearbox can be educational but may be a one way journey. Beware a flood of ball bearings.


message:
Relay feedback control

I have a two-relay system set up to a DC motor. So, if I close one relay, the motor moves on one way and if I close the second relay (and open the first) the motor goes on the other direction.

I compare two variables (target inclination and real inclination) if they are not the same I would like to open one of the two relays UNTIL the are the same value.

Both variables are calculated based on inclinometer input and some aritmethics.

I do know how to calculate the variables, how to close the relay based in the comparation of variables and which relay open.

But I don´t know how I can tell to open the relay because the motor has reached target inclination.

How I can recalculate and compare constantly target inclination and real inclination when the relay is closed and the motor moving?
Is this posible on Arduino? Is this multithreading?

Thank you very much, any ideas are welcome!

body:
This is a classic system where PID will really pay off. Basically this will allow you to tune your system so that if you are off by 5 degree it will open the relays for 3 seconds. But if you are off by 1 degree it will open them for half a second. (Or whatever works for you). It might be tricky for you to get right but it will give you the smooth response that looks really good and feels natural.

Take a look here http://playground.arduino.cc/Code/PIDLibrary


body:
Answering my own question, I think I found some way to get the solar panel face the sun.

As said before, the inclinometer reads the position and makes some calculations using lookposition() function, then this happens:

    void lookforsun() {
      while ((targetElevation + 3) < realElevation | (targetElevation - 3) > realElevation) {

        Serial.println("Elevation is not correct");

        while (realElevation < targetElevation)
        { Serial.println("Moving to south");
          digitalWrite(south, LOW);
          lookposition();
        }
        digitalWrite(south, HIGH);

        while (realElevation > targetElevation)
        { Serial.println("Moving to north");
          digitalWrite(north, LOW);
          lookposition();
        }
        digitalWrite(north, HIGH);
      }

      while ((targetHourangle+3) < realHourangle |  (targetHourangle-3) > realHourangle  ) {

        Serial.print("Hour angle is not correct");
        while (realHourangle > targetHourangle)
        { Serial.println("Moving to east");
          digitalWrite(east, LOW);
          lookposition();
        }
        digitalWrite(east, HIGH);

        while (realHourangle < targetHourangle)
        { Serial.println("Moving to west");
          digitalWrite(west, LOW);
          lookposition();
        }
        digitalWrite(west, HIGH);
      }

As you can see I took the frightening way of nested while loops, but appears to work.

The first while measures if realElevation is between +-3 degrees of targetElevation, if realElevation is far away (target+-3) enters the second while loop, which determines if needs to go up or down.

I included the +-3 because the sensor is so very sensible.

Thank you very much  Russell McMahon and portforwardpodcast for your ideas!


message:
What are possible issues when moving Arduino to another microcontroller?

When Arduino was conceived AVR was very much the best 8-bit controller available. But we're 10 years on now, and still using the AVR, despite lots of better microcontrollers available, notably ARMs. In particular M0 and M0+ cores are a lot cheaper, yet are a lot faster and have many more features than AVR.
For instance the NXP LPC824 has more serial buses, more A/D channels and higher A/D resolution, is almost twice as fast as the AVR, yet costs 30% less. (Granted, it doesn't have EEPROM, but you can have that for 20 cents.)

So I was wondering if there are particular issues which prevent the use of more modern microcontrollers on Arduino.
One difference may be Vcc, which is 5V for AVR and 3.3V for ARM. But given that more peripherals work at 3.3V this seems more to be an AVR issue than an ARM issue.

PS: I'm aware of Arduino Due, but that one costs twice as much as a Uno. I'm talking about controllers which price-wise can compete with AVR.

body:
There is NO *best* 8 bit or 16 or whatever bit uC (micro controller).
There always have been "better" ones and there always will be and better changes with your need as well as with time.

If you want or need a faster or more capable processor, use one.
For many tasks the existing AVR processors are very fine indeed.

A number of people are making Arduino-like uC's using ARM right now.
You can buy them 'off the shelf'.

Running "Arduino" code is where issues arise:
If you are willing to run 100% standard Arduino code applications will usually run well on the new uC.
If applications use precompiled libraries and you wish to use eg an ARM it will not run.
If you recompile the libraries and they are written in a compatible language flavor (C or whatever) then they MAY work for your new processor.
If they use assembler then they will not work in essentially all cases.

But, existing 'Arduino' hardware can use the high level language of your choice.
A new processor with a compatible compiler will compile eg C code that runs on Arduino hardware BUT port locations, register control methods etc need to be correctly allowed for.

It gets harder and harder as you try to fit the new giants into the old not-so-giant framework. Somewhere along the way it is easier to give up the attempt and use the Arduino for what it is good for and the 'new' processor where necessary.

**Whatever the Arduino did well when new it still does well.**

In most cases the speed, peripherals and memory capabilities are entirely fine for tasks that people who wish to use it wish to do.
The main issue is that an Arduino is not something it is not, just as a small family car is not a bus or a sportscar. Use the car where it is useful and use a bus or sportscar when necessary.


message:
cannot convert error with pointers

I write a code to store patterns for LED blinking, but I got this error:

    led_basics:39: error: cannot convert 'char (*)[17][2]' to 'char*' in initialization

    led_basics:39: error: cannot convert 'char (*)[16][2]' to 'char*' in initialization

    led_basics:39: error: cannot convert 'char (*)[13][2]' to 'char*' in initialization

and so on for all pattern.
How can I fix it?
Here is the code:

    char nulla[17][2]={{0,127},{8,125},{9,121},{10,113},{12,97},{14,65},{24,67},{27,71},{28,70},{30,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}};

    char egy[16][2]={{0,0},{9,4},{16,6},{18,2},{21,3},{27,7},{28,6},{30,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}};

    char ketto[13][2]={{0,98},{7,99},{8,97},{12,113},{14,81},{20,89},{21,88},{24,74},{27,78},{30,70},{32,68},{36,64},{68,0}};

    char harom[17][2]={{0,34},{7,35},{8,33},{10,41},{14,9},{17,73},{21,72},{24,74},{27,78},{30,70},{32,68},{36,80},{42,112},{48,96},{51,32},{56,0},{68,0}};

    char negy[17][2]={{0,7},{7,6},{8,4},{9,0},{10,8},{21,9},{24,11},{27,15},{28,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}};

    char ot[14][2]={{0,39},{8,37},{9,33},{10,41},{14,9},{17,73},{28,72},{30,64},{36,80},{42,112},{48,96},{51,32},{56,0},{68,0}};

    char hat[17][2]={{0,62},{7,63},{8,61},{9,57},{12,41},{14,9},{17,73},{21,72},{24,74},{30,66},{32,64},{36,80},{42,112},{48,96},{51,32},{56,0},{68,0}};

    char het[15][2]={{0,7},{8,5},{9,1},{24,3},{27,7},{28,6},{30,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}};

    char nyolc[15][2] = {{0,127},{8,125},{9,121},{12,105},{14,73},{24,75},{27,79},{28,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}};

    char kilenc[13][2] = {{0,79},{8,77},{9,73},{24,75},{27,79},{28,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}};

    char kettospont[6][2] = {{0,0},{9,4},{12,20},{18,16},{24,0},{68,0}};

    char *karakterek[11]={&nulla,&egy,&ketto,&harom,&negy,&ot,&hat,&het,&nyolc,&kilenc,&kettospont};

body:
karakterek is an array of char pointers.  It cannot be used to store pointers to char arrays.

I'm not sure it would be possible to store pointers to your 2 dimensional arrays since they are all of different dimensions.  Someone else might know a way to do that.

Here's how I would do it (using as similar as possible a structure):

    char nulla[]={0,127,8,125,9,121,10,113,12,97,14,65,24,67,27,71,28,70,30,78,32,76,36,88,40,80,42,112,48,96,56,64,68,0};

    char egy[]={0,0,9,4,16,6,18,2,21,3,27,7,28,6,30,14,32,12,36,24,40,16,42,48,48,32,51,96,56,64,68,0};

    char ketto[]={0,98,7,99,8,97,12,113,14,81,20,89,21,88,24,74,27,78,30,70,32,68,36,64,68,0};

    char harom[]={0,34,7,35,8,33,10,41,14,9,17,73,21,72,24,74,27,78,30,70,32,68,36,80,42,112,48,96,51,32,56,0,68,0};

    char negy[]={0,7,7,6,8,4,9,0,10,8,21,9,24,11,27,15,28,14,32,12,36,24,40,16,42,48,48,32,51,96,56,64,68,0};

    char ot[]={0,39,8,37,9,33,10,41,14,9,17,73,28,72,30,64,36,80,42,112,48,96,51,32,56,0,68,0};

    char hat[]={0,62,7,63,8,61,9,57,12,41,14,9,17,73,21,72,24,74,30,66,32,64,36,80,42,112,48,96,51,32,56,0,68,0};

    char het[]={0,7,8,5,9,1,24,3,27,7,28,6,30,14,32,12,36,24,40,16,42,48,48,32,51,96,56,64,68,0};

    char nyolc[] = {0,127,8,125,9,121,12,105,14,73,24,75,27,79,28,78,32,76,36,88,40,80,42,112,48,96,56,64,68,0};

    char kilenc[] = {0,79,8,77,9,73,24,75,27,79,28,78,32,76,36,88,40,80,42,112,48,96,56,64,68,0};

    char kettospont[] = {0,0,9,4,12,20,18,16,24,0,68,0};

    char* karakterek[]={nulla,egy,ketto,harom,negy,ot,hat,het,nyolc,kilenc,kettospont};

For starters, I'd make the char arrays single dimension.  Since the 2nd dimension is always a size of 2, you could index through your values reading index 0 into x0, index 1 to y0, index 2 to x1 and index 3 to y1 (I'm assuming these are x y co-ordinate pairs).

Secondly, I'd lose the hard-coded sizes for the arrays.  If you want to add or remove entries, you don't have to keep updating the sizes.

Finally, I'd lose the '&' from your array of array pointers.  Referring to an array simply by its name gives you a pointer to it.  I think '&<array_name>' gives you a pointer to the pointer, but I could be wrong.


body:
As the second dimension is always 2, you can do this:

    typedef char Tuple[2];

    Tuple nulla[17] = {{0,127},{8,125},{9,121},{10,113},{12,97},{14,65},{24,67},{27,71},{28,70},{30,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}};
    Tuple egy[16]   = {{0,0},{9,4},{16,6},{18,2},{21,3},{27,7},{28,6},{30,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}};
    Tuple ketto[13] = {{0,98},{7,99},{8,97},{12,113},{14,81},{20,89},{21,88},{24,74},{27,78},{30,70},{32,68},{36,64},{68,0}};
    // etc.

    Tuple* karakterek[3] = {nulla, egy, ketto}; // etc.

(The `typedef` makes it easier.)


message:
How does this Motor Circuit not ruin the Microcontroller

I came across this [instructable][1] about using no external hardware but two pwm pins to control a motor in both directions. Usually you would use an H bridge. However, ever since I have had my Arduino I have heard that you are not supposed to connect a pin to another pin. So how does this circuit works. It looks like he sends a signal from one pin and in my experience it would fry the board. So basically, my question is this circuit ok with an Arduino Nano and if so how does it work? Below is a picture of the setup he gave:
![enter image description here][2]

  [1]: http://www.instructables.com/id/Simple-2-way-motor-control-for-the-arduino/
  [2]: https://i.stack.imgur.com/KPyz3.jpg

body:
You are not supposed to connect one pin directly to another pin because the current will destroy the electronics connected to the pins. The motor provides a small impedance and limits the current flowing (although the amount of current will increase if the motor stalls).

As to the other reason you missed for the MCU possibly being damaged, the answer is that it is absorbed by the input protection diodes and subsequently the supply.


body:
This is a bad idea, but not because two pins seem to be connected directly. They're not; there is a load (the motor) between the pins, and that motor will take care of different levels between the pins. High and low will make the motor turn one way, low and high the other way, and the same level on both pins will stop the motor.

Why is this bad? An I/O pin can only supply a limited current, and even for a small motor that will peak rather high. If you run the motor for some time this way you will damage the I/O ports. An H-bridge, like you mention, is the solution.
Note that electric motors cause a lot of noise in the power supply, which may cause the microcontroller to reset all the time, so that your program doesn't work. (The motor may seem to start/stop all the time.) You need to decouple the power supply with capacitors.


body:
Another problem here is when running a motor you want to include a 'flyback diode' to prevent damage from voltage spikes, which is a problem with loads like motors.

See [this article][1] for details.

  [1]: http://www.nerdkits.com/videos/motors_and_microcontrollers_101/


message:
Sending data from txt file over serial connection

I'm trying to send data saved on a txt file to arduino over serial connection. I wrote this simple sketch

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

    void loop(){
      while (Serial.available() > 0) {
        Serial.write(Serial.read());
      }
    }

When I try to send serial data from bash by typing `cat input.txt >> /dev/cu.wchusbserial1a1340` while the Arduino's serial connection window is open. It gives an error message "resource busy: /dev/cu.wchusbserial1a1340". Then I tried `cat input.txt >> /dev/tty.wchusbserial1a1340`. Now it hangs. Bash is busy, and it is not possible close Arduino IDE or serial connection window. What is wrong here?

body:
I don't know the details of why the hang is occurring.  However, the problem stems from serial ports being available to one process at a time.  When the Arduino-environment's serial-port-monitor opens a serial port, that port becomes unavailable to bash.  (To close the hung Arduino IDE process and the SPM, say `ps aux |grep arduino` and `kill` *n*, where *n* is the PID shown by the `ps` and `grep`.)

Here is a python program you can run, that sends and receives data:

    #!/usr/bin/env python
    # Send data to an Arduino and report responses.
    from time import time, sleep, asctime, localtime
    from serial import Serial
    print 'Opening serial port'
    ser = Serial('/dev/ttyACM0', 9600, timeout=3)
    sleep(1)                      # Let board initialize
    while 1:
        txt = 'It is about ' + asctime(localtime()) + ' now'
        print 'Sending  "{}"'.format(txt)
        ser.write(txt)
        s = ser.readline()          # Get result from arduino
        print 'Readback "{}" at {}'.format(s, asctime(localtime()))
        sleep(1)

Here is some sample output from it, with your sketch runing in a Mega2650.  (I'm not sure why the readback is taking so long as it apparently is.)

    Opening serial port
    Sending  "It is about Fri May  8 16:48:41 2015 now"
    Readback "It is about Fri May  8 16:48:41 2015 now" at Fri May  8 16:48:44 2015
    Sending  "It is about Fri May  8 16:48:45 2015 now"
    Readback "It is about Fri May  8 16:48:45 2015 now" at Fri May  8 16:48:48 2015
    Sending  "It is about Fri May  8 16:48:49 2015 now"
    Readback "It is about Fri May  8 16:48:49 2015 now" at Fri May  8 16:48:52 2015
    Sending  "It is about Fri May  8 16:48:53 2015 now"
    Readback "It is about Fri May  8 16:48:53 2015 now" at Fri May  8 16:48:56 2015


body:
As noted by jwpat7 the port can be accessed by one application at a time, so when the serial monitor is open no other application can access it.

The hang might happen because when first connecting to an arduino port the arduino gets reset and waits for a second or so for programming data (that's how a new sketch is updated). I don't know for sure, but this might mess up with `cat` and make it to hang up.

Best option might be to make a script like jwpat7's that would wait a second after opening the port and then send the file contents in.


message:
Sensing concentration of methane with MQ-4 methane sensor?

I'm on a project to sense any amounts of methane in the home. I have bought the popular MQ-4 methane sensor from SparkFun: https://www.sparkfun.com/products/9404

I've looked online for any sample code, but I am confused as to whether the input from the sensor is already given in parts per million, or it is just a voltage. To be specific, here is the sample code the data sheet for the sensor gives:

    int sensorValue;

    void setup()
    {
      Serial.begin(9600);      // sets the serial port to 9600
    }

    void loop()
    {
      sensorValue = analogRead(0);       // read analog input pin 0
      Serial.println(sensorValue, DEC);  // prints the value read
      delay(100);                        // wait 100ms for next reading
    }

I have also used a breakout board for these sensors: https://www.pololu.com/product/1479
The sensor is soldered on it, along with a 20K ohm load resistor, like how the spec. sheet specifies.
However, I am confused on the readings I am getting. It's always something that ranges between 259 and 261. Is this ppm of methane in my home? If it is, shouldn't the normal level be 0? I currently have no methane based heating. Or is the 259 - 261 voltage?

Thanks for any help.

body:
Actually, you are getting raw data from the sensor. A little bit of math should be done in order to calibrate it and based on the chart in datasheet, measure the real value in PPM.

The calibration basically helps you find R0, which is an internal resistance (along with RS form a voltage divider) that could be derived by doing calibration in a clean environment. After that, you use R0 to calculate a ratio and then look at the datasheet's chart to measure whatever gas you want since there is a curve describing it.

Please refer to this [tutorial][1] for more information. I have developed a similar application using MQ-4 before.

It is related to MQ-2, you may have noticed that all theses sensors have similar features and principle applications.

  [1]: http://sandboxelectronics.com/?p=165


body:
The values you're reading relate to the voltage measured by the AD converter, that is, the voltage over the load resistor. Arduino's AD converters have 10 bit resolution and measure against a 5V reference, so you can use the following line to convert it to millivolts:

`VRL = map(sensorValue, 0, 1023, 0, 5000);`

Once you have the voltage, you can compute the resistance of the sensor using the formula

Rs=(Vc/VRL-1)×RL

with Vc the circuit voltage (5V), VRL the voltage over the load resistor, and RL the resistance of the load resistor in Ohms.

The tricky part is to convert this to a concentration in ppm CH4. The curve in the datasheet gives you a starting point, but the values it gives are not absolute, but relative to the reference of 1000 ppm. The value of that reference depends on various factors, like temperature, humidity, other gases in the environment and how long the sensor has been running (the longer, the more reliable are the results).

If you really need exact ppm values, you'll need to calibrate your setup in an environment where you can exactly control the CH4 concentration. You'll also have to measure temperature and humidity along with the sensor readings.

Otherwise you'll get only a qualitative estimate of CH4 concentration, which is actually sufficient for many use cases.


message:
Unable to Upload

Not able to upload sketches to standalone arduino on breadboard (with Atmega328 bootloaded with blink LED program). Searched on the internet but there is no solution. Help ?

error :
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00

OS: Ubuntu 14.04 LTS

body: Make sure the board selected and port selected are correct. I face this problem many time but they disappear after I remove my other circuit connection and reconnect my arduino board to pc


body: Make sure the RX, TX pins are not connected to any other circuit when uploading sketches.


message:
Program ATtiny13 - 20PU

I'm trying to program my ATtiny 13 - 20PU. An it seems to work, but there is no action upon the "delay" command. If on the sketch below I comment out the "High" line, my led is off all the time and whenever I have a `Pin 4 High`, it's on all the time! Basically this seems to be a frequency/fuse/bootloader problem and made me think the upload was broken.

I added a led between the tiny's pin 3 (digital pin 4) and ground with a 1k current limiting resistor. This one is for testing with the attached sketch.
I also tried [this breadboard circuit][3], which gives exactly the same results.

Upon upload to the tiny I get this:

    Sketch uses 380 bytes (37%) of program storage space. Maximum is 1,024 bytes.
    Global variables use 8 bytes of dynamic memory.

(Everybody warns about 2 errors occuring upon a proper upload - I don't get those).

My boards.txt look like this:

    menu.cpu=Processor
    menu.clock=Clock

    attiny.name=ATtiny
    attiny.bootloader.tool=arduino:avrdude
    attiny.bootloader.unlock_bits=0xff
    attiny.bootloader.lock_bits=0xff
    attiny.build.core=arduino:arduino
    attiny.build.board=attiny
    attiny.upload.tool=arduino:avrdude

    attiny.menu.cpu.attiny45=ATtiny45
    attiny.menu.cpu.attiny45.upload.maximum_size=4096
    attiny.menu.cpu.attiny45.build.mcu=attiny45
    attiny.menu.cpu.attiny45.build.variant=tiny8

    attiny.menu.cpu.attiny85=ATtiny85
    attiny.menu.cpu.attiny85.upload.maximum_size=8192
    attiny.menu.cpu.attiny85.build.mcu=attiny85
    attiny.menu.cpu.attiny85.build.variant=tiny8

    attiny.menu.cpu.attiny44=ATtiny44
    attiny.menu.cpu.attiny44.upload.maximum_size=4096
    attiny.menu.cpu.attiny44.build.mcu=attiny44
    attiny.menu.cpu.attiny44.build.variant=tiny14

    attiny.menu.cpu.attiny84=ATtiny84
    attiny.menu.cpu.attiny84.upload.maximum_size=8192
    attiny.menu.cpu.attiny84.build.mcu=attiny84
    attiny.menu.cpu.attiny84.build.variant=tiny14

    attiny.menu.clock.internal1=1 MHz (internal)
    attiny.menu.clock.internal1.bootloader.low_fuses=0x62
    attiny.menu.clock.internal1.bootloader.high_fuses=0xdf
    attiny.menu.clock.internal1.bootloader.extended_fuses=0xff
    attiny.menu.clock.internal1.build.f_cpu=1000000L

    attiny.menu.clock.internal8=8 MHz (internal)
    attiny.menu.clock.internal8.bootloader.low_fuses=0xe2
    attiny.menu.clock.internal8.bootloader.high_fuses=0xdf
    attiny.menu.clock.internal8.bootloader.extended_fuses=0xff
    attiny.menu.clock.internal8.build.f_cpu=8000000L

    attiny.menu.clock.external8=8 MHz (external)
    attiny.menu.clock.external8.bootloader.low_fuses=0xfe
    attiny.menu.clock.external8.bootloader.high_fuses=0xdf
    attiny.menu.clock.external8.bootloader.extended_fuses=0xff
    attiny.menu.clock.external8.build.f_cpu=8000000L

    attiny.menu.clock.external16=16 MHz (external)
    attiny.menu.clock.external16.bootloader.low_fuses=0xfe
    attiny.menu.clock.external16.bootloader.high_fuses=0xdf
    attiny.menu.clock.external16.bootloader.extended_fuses=0xff
    attiny.menu.clock.external16.build.f_cpu=16000000L

    attiny.menu.clock.external20=20 MHz (external)
    attiny.menu.clock.external20.bootloader.low_fuses=0xfe
    attiny.menu.clock.external20.bootloader.high_fuses=0xdf
    attiny.menu.clock.external20.bootloader.extended_fuses=0xff
    attiny.menu.clock.external20.build.f_cpu=20000000L

    #################################################
    attiny.menu.cpu.attiny13=ATtiny13
    attiny.menu.cpu.attiny13.upload.maximum_size=1024
    attiny.menu.cpu.attiny13.build.mcu=attiny13
    attiny.menu.cpu.attiny13.build.variant=core13

    attiny.menu.clock.internal96=9.6MHz (internal)
    attiny.menu.clock.internal96.bootloader.low_fuses=0x7A
    attiny.menu.clock.internal96.bootloader.high_fuses=0xff
    attiny.menu.clock.internal96.build.f_cpu=9600000L
    ################################################

    attiny.menu.clock.internal48=4.8MHz (internal)
    attiny.menu.clock.internal48.bootloader.low_fuses=0x79
    attiny.menu.clock.internal48.bootloader.high_fuses=0xff
    attiny.menu.clock.internal48.build.f_cpu=4800000L
    ################################################

And I choose the settings: Board ATtiny, Processor ATtiny13, Clock 9.6 MHz (internal), Port Arduino Uno (same as when I upload the ISP sketch), Programmer Arduino as ISP. I upload by clicking "Upload using Programmer".

Arduino Software is 1.6.4, the programmer Arduino is an Uno SMD edition.
I used this [programmer][1] and this [tutorial][2] for smeezkitty core13.

I'm trying to upload this sketch:

    // Blink sketch to test ATtiny Chips

    //       ATMEL ATTINY13 / ARDUINO
    //
    //                 +-\/-+
    // ADC0 (D 5) PB5 1|*   |8 Vcc
    // ADC3 (D 3) PB3 2|    |7 PB2 (D 2) ADC1
    // ADC2 (D 4) PB4 3|    |6 PB1 (D 1) PWM1
    //            GND 4|    |5 PB0 (D 0) PWM0
    //                 +----+

    const int LED_PIN = 4; // digital pin
    const int DELAY_TIME = 1000; // time between blinks [ms]

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

    void loop() {
      digitalWrite(LED_PIN, LOW);
      delay(DELAY_TIME);
      digitalWrite(LED_PIN, HIGH);
      delay(DELAY_TIME);
    }

Trying to burn a bootloader with the same settings as uploading to the tiny and then tools -> burn bootloader, get's me the error:

    "efuse" memory type not defined for part "ATtiny13"
    Error while burning bootloader.

Skimming through the data sheet I noticed that the tiny13 - 20PU (the 20) stand for 20 MHz,... theoretically one should be able to downclock them to the ordinary 10 MHz, but maybe this is my problem?

  [1]: https://arduinodiy.wordpress.com/2015/03/31/1256/#comment-907
  [2]: https://arduinodiy.wordpress.com/2015/04/26/installing-attiny13-core-files-in-arduino-ide-1-6-x-and-1-7-x/
  [3]: http://highlowtech.org/?p=1706

body:
There was some mistakes in the boards.txt it seems. After finding a very detailed and extensive boards file [here](http://forum.arduino.cc/index.php?topic=89781.msg2235877#msg2235877), I modified it to have neat and tidy categories and is easier to use to become a working boards.txt. I had to burn the bootloader once to set the fuses right. After that everything works like a charm for 3 ATtiny13! No warnings or errors. This is used with Arduino 1.6.4. The folder tree is `~Arduino/hardware/attiny/avr/cores/core13` and `~Arduino/hardware/attiny/avr/boards.txt`

    # boards.txt for Arduino 1.6.4

    menu.flag=GCC Flags
    menu.cpu=Processor
    menu.clock=Clock

    attiny13.name=ATtiny13
    attiny13.upload.tool=arduino:avrdude
    attiny13.upload.using=arduino:usbtiny

    attiny13.bootloader.tool=arduino:avrdude

    attiny13.menu.cpu.attiny13=ATtiny13
    attiny13.menu.cpu.attiny13.upload.maximum_size=1024
    attiny13.menu.cpu.attiny13.upload.maximum_data_size=64
    attiny13.menu.cpu.attiny13.build.mcu=attiny13
    attiny13.menu.cpu.attiny13.build.core=core13
    # attiny13.menu.cpu.attiny13.build.variant=core13

    #################################################
    ############## clock speeds #####################
    #################################################

    #### 9.6 MHz
    ############
    attiny13.menu.clock.t13_9M6=9.6MHz (internal clock, Preserve EEPROM, BOD disable)
    attiny13.menu.clock.t13_9M6.bootloader.low_fuses=0x3A
    attiny13.menu.clock.t13_9M6.bootloader.high_fuses=0xFF
    attiny13.menu.clock.t13_9M6.upload.speed=57600L
    attiny13.menu.clock.t13_9M6.build.f_cpu=9600000L

    #### 9.6 MHz - 2.7V
    attiny13.menu.clock.t13_9M6_bod=9.6MHz (internal clock, Preserve EEPROM, BOD - 2.7V)
    attiny13.menu.clock.t13_9M6_bod.bootloader.low_fuses=0x32
    attiny13.menu.clock.t13_9M6_bod.bootloader.high_fuses=0xFB
    attiny13.menu.clock.t13_9M6_bod.upload.speed=57600L
    attiny13.menu.clock.t13_9M6_bod.build.f_cpu=9600000L

    #### 4.8 MHz - 2.7V
    attiny13.menu.clock.t13_4M8_bod=4.8 MHz (int 4.8 MHz clock, Preserve_EEPROM, BOD - 2.7V)
    attiny13.menu.clock.t13_4M8_bod.bootloader.low_fuses=0x31
    attiny13.menu.clock.t13_4M8_bod.bootloader.high_fuses=0xFB
    attiny13.menu.clock.t13_4M8_bod.upload.speed=57600L
    attiny13.menu.clock.t13_4M8_bod.build.f_cpu=4800000L

    #### 1.2 MHz
    attiny13.menu.clock.t13_1M2=1.2 MHz (int 9.6 MHz divided by 8,Preserve_EEPROM, BOD - 2.7V)
    attiny13.menu.clock.t13_1M2.bootloader.low_fuses=0x2A
    attiny13.menu.clock.t13_1M2.bootloader.high_fuses=0xFB
    attiny13.menu.clock.t13_1M2.upload.speed=9600L
    attiny13.menu.clock.t13_1M2.build.f_cpu=1200000L

    #### 600 kHz
    attiny13.menu.clock.t13_0M6=600 kHz (int 4.8 MHz divided by 8, Preserve_EEPROM, BOD disable)
    attiny13.menu.clock.t13_0M6.bootloader.low_fuses=0x29
    attiny13.menu.clock.t13_0M6.bootloader.high_fuses=0xFF
    attiny13.menu.clock.t13_0M6.upload.speed=9600L
    attiny13.menu.clock.t13_0M6.build.f_cpu=600000L

    ## 128 kHz
    attiny13.menu.clock.t13_128k=128 KHz (internal watchdog oscillator)
    attiny13.menu.clock.t13_128k.bootloader.low_fuses=0x7B
    attiny13.menu.clock.t13_128k.bootloader.high_fuses=0xFF
    attiny13.menu.clock.t13_128k.upload.speed=250
    attiny13.menu.clock.t13_128k.build.f_cpu=128000L

    ## 16 kHz
    attiny13.menu.clock.t13_16k=16 KHz (internal watchdog oscillator, Preserve_EEPROM, BOD disable)
    attiny13.menu.clock.t13_16k.bootloader.low_fuses=0x2B
    attiny13.menu.clock.t13_16k.bootloader.high_fuses=0xFF
    attiny13.menu.clock.t13_16k.upload.speed=250
    attiny13.menu.clock.t13_16k.build.f_cpu=16000L

    ##-----------------------------------
    ##--------- compiler flags ----------
    ##-----------------------------------

    attiny13.menu.flag.Os=Default
    attiny13.menu.flag.Os.compiler.c.extra_flags=
    attiny13.menu.flag.Os.compiler.c.elf.extra_flags=
    attiny13.menu.flag.Os.compiler.cpp.extra_flags=

    attiny13.menu.flag.Os_flto=Default -flto
    attiny13.menu.flag.Os_flto.compiler.c.extra_flags=-Wextra -flto
    attiny13.menu.flag.Os_flto.compiler.c.elf.extra_flags=-w -flto
    attiny13.menu.flag.Os_flto.compiler.cpp.extra_flags=-Wextra -flto

    attiny13.menu.flag.O1=-O1
    attiny13.menu.flag.O1.compiler.c.extra_flags=-O1
    attiny13.menu.flag.O1.compiler.c.elf.extra_flags=-O1
    attiny13.menu.flag.O1.compiler.cpp.extra_flags=-O1

    attiny13.menu.flag.O1_flto=-O1 -flto
    attiny13.menu.flag.O1_flto.compiler.c.extra_flags=-O1 -Wextra -flto
    attiny13.menu.flag.O1_flto.compiler.c.elf.extra_flags=-O1 -w -flto
    attiny13.menu.flag.O1_flto.compiler.cpp.extra_flags=-O1 -Wextra -flto

    attiny13.menu.flag.O3=-O3
    attiny13.menu.flag.O3.compiler.c.extra_flags=-O3
    attiny13.menu.flag.O3.compiler.c.elf.extra_flags=-O3
    attiny13.menu.flag.O3.compiler.cpp.extra_flags=-O3

    attiny13.menu.flag.O3_flto=-O3 -flto
    attiny13.menu.flag.O3_flto.compiler.c.extra_flags=-O3 -Wextra -flto
    attiny13.menu.flag.O3_flto.compiler.c.elf.extra_flags=-O3 -w -flto
    attiny13.menu.flag.O3_flto.compiler.cpp.extra_flags=-O3 -Wextra -flto


body:
The "efuse error"  on burning the bootloader is described in the article you refer to and a solution is given there as well.
It occurs when the attiny13 is defined in the same group as the attiny25/45/85 as the former has no efuse and the latter do.

Giving the attiny13 its own menu entry in the IDE -as described in that article- should solve that.


message:
How to increase Arduino's memory to save Dot Matrix Library?

I need to display some dynamic Chinese characters to 12864 using Arduino. What to show is transported from my web server. The character is stored as a 16x16 dot matrix, needing 16*16/8=32 byte. And I need to show some sentences, which contains more than 100 Chinese characters.

The problem is that I can't storage all the dot matrix data in Arduino because it has too small memory.

* If I get the dot matrix data from web server, I need to have 100*32B memory, but SPAM with EEPROM have only 3k. So that failed.
* If I save the dot matrix "library" in the Flash memory, I need 3500*32B (There are 3500 Chinese frequent-used characters), but there is only 32K Flash. Saving the "library" means that I should storage the dot matrix data of all the 3500 chars in Flash, then the server only need to send the Unicode of characters, and I can get the matrix of the char.

Any help is appreciated!

body:
1. Use a different [Arduino](http://www.arduino.cc/en/Main/Products) or [Arduino-clone](http://playground.arduino.cc/Main/SimilarBoards#goArdComp) with [more flash memory](http://www.arduino.cc/en/Tutorial/Memory)

2. Store the character bitmaps in external EEPROM ([example](http://www.hobbytronics.co.uk/arduino-external-eeprom))


body:
The basic EEPROM write, each 1 byte, as is mentioned in the above answer.

http://www.hobbytronics.co.uk/arduino-external-eeprom

The PAGE WRITE which is suitable for this situation. One can easily read 32 bytes for a dot matrix.

http://www.hobbytronics.co.uk/eeprom-page-write