text:
How to learn enough C++ to program Arduino?
I am an experienced web developer, but my C++ skills are very basic. I struggle with the concepts because it is so different from something like Javascript (which I already know). I do not have a lot of time to learn C++, and I only need to know enough to play with Arduinos.
Are there any good resources out there for learning C++ that is specifically geared towards Arduino programming, and is there anything interactive like Codecademy?

Bad news: Arduino uses C++. And C++ is harder than C.

My bad. Like I said I have done a little Arduino programing but clearly I know very little.

@IgnacioVazquez-Abrams - Good news:  ANSI C will still compile with the Arduino IDE.

Well I would like to learn whatever the Arduino IDE uses as default and whatever else most people use.

@Comintern: And yet most of the Arduino libraries use C++.

Perhaps this question would be better if you explained what concepts confuse you. After you get down the basic C++ syntax, it's only a matter of learning the Arduino libraries. And for Codecademy: it's generally a good idea to get an Arduino book since they cover basic C++, electronics, and the usage of the Arduino libraries and how they all relate to each other.

If I were you I'd take the high road.
I was in your shoes a while ago and I didn't know how to approach Arduino. I was very lucky that I came across a book written by the famous Jack Purdum, "Learn C programming for the Arduino". It is written by a retired Purdue University professor who is well known for his extremely easy to learn teaching method. He has another
I only knew MATLAB and Simulink before starting this book. This book is amazing. It was extremely easy to follow. I now have no difficulty programming Arduino in the correct way. This book trains you to optimize everything which is very crucial with the limited resources on Arduino boards.
I suggest C instead of C++. It is the language of choice for programming embedded system. It is said to be low level, but as a MATLAB user I should tell you that syntaxes are extremely easy and intuitive. I didn't find anything hard about them.
Remember:

There isn't any problem to use C in Arduino IDE.
You don't need to worry about libraries. You only need to load them in the beginning of the code. You do not need to know how was the code written in the library.
Check the comments about the book on Amazon if you are not convinced.

Good Luck

It's worth noting that a little C++ knowledge is quite important for using many of the common Arduino libraries.

I must admit that I am not familiar with C++. On the other hand, to this day I haven't had any problem with any libraries. I just load them. But I don't know if I will need to use C++ in the simple projects. I'd be thankful if you could elaborate on this. Make a few examples where knowledge of C++ is crucial for using already written libraries. Thank you in advance.

In many cases, the library interface is a class. You have to instantiate it and call member functions on it in your code (e.g. see SoftwareSerial). It's certainly possible to just copy and adapt example code. However, I'd always recommend that at least a little knowledge of object orientation is important in understanding how to use it effectively.

Some newer C features won't work in the IDE, which is a shame since __flash is so very handy.

A very good book: Beginning C for Arduino:Learn C Programming for the Arduino, by Ph.D. , Jack Purdum

Beginning C for Arduino:Learn C Programming for the Arduino, by Ph.D. , Jack Purdum

This is not an answer.  Perhaps a comment.  Be sure to take the tour at https://arduino.stackexchange.com/Tour to see ow this works.

Since you have programming experience and you say you only want to learn enough to play with Arduinos, I think a resource worth mentioning is the built-in example programs. I've seen Arduino itself used as a learning tool for C/C++; their examples are very basic and intended for complete novices. If you keep hacking on progressively more complicated examples and googling specific things you don't understand, you will probably be able to get a good handle on things IMHO.
That isn't to say it's necessarily a good tool for learning C++ in general, since the limited memory resources and 8-bit CPU make some capabilities of the language commonly used on desktops (and the whole standard library) rarely used or unavailable on Arduino.

I have played with the examples and the most complicated thing I built used shift registers. What confuses me the most is all the variable types. Javascript is so simple but C++ is so fussy.

@ChristianJuth The reason there are so many types, is to make efficiënt use of your memory. But you can actually use Int (for integer values), float for decimal and strings for text. The other types or sub-types are to make them a little longer or smaller :) or to define wethether they can be negative (signed or unsigned) ontop of that you have boolean for true or false.

Another way to approach the problem is to come up with a project that you want to do with an Arduino and look for code samples.  Since you already have some programming experience you should be able to pick up what's going on pretty quickly and you will have a vested interest in what the code is doing.
For Example: Read temperature from a sensor and display to an LCD.
Arduinos are really good for reading from a sensor and there's a huge arduino community.  So, if you start with just reading from different types of sensors you'll find a lot of examples and learn a lot about Arduinos at the same time.


text:
Turning all 35 leds on sequentially with MM5451
I've been struggling for a long time trying to get the MM5451 chip to light up all 35 leds sequentially without any luck.  I've had intermittent help from the arduino forum, someone on youtube, and even found source code on here.  But all I've been able to accomplish is either to get all the lights lit up at once, or every other led lit up at once, or having two sets of 8 leds lighting up sequentially together.  I can't figure out how to get all of them lit on and off sequentially.  I'm sure it has to do with shifting bits but can't figure out how to do this.  Here's two sets of code that either light two sets of 8 bits together sequentially, and another program that lights every other led all at once.
Sequential lighting of two sets of 8 bits
#define CLK 2 // to MM5451 pin 21
#define dataBit  3 // to MM5451 pin 22

 byte singleled[]=  {1,2,4,8,16,32,64,128};
//   0b00000001, 0b00000010, 0b00000100,
 //  0b00001000, 0b00010000, 0b00100000,
 //  0b01000000, 0b10000000, 0b11111111 };

  byte singleled2[]=  {1,2,4,8,16,32,64,128};
 //  0b00000001, 0b00000010, 0b00000100,
 //  0b00001000, 0b00010000, 0b00100000,
 //  0b01000000, 0b10000000, 0b11111111 };

void setup() {
  pinMode(CLK, OUTPUT);
  pinMode(dataBit, OUTPUT);
  digitalWrite(CLK, 0);
  digitalWrite(dataBit, 0);
  Serial.begin(1200);
}

// the loop routine runs over and over again forever:
void loop() {

  for (int i=0; i<8; i++)   {
        // start bit
    digitalWrite(dataBit, 1);
    pulseCLK();
    // the "+ 0x80" turns on DP
    ssrWriteLSB(singleled2 [i]); // MOD myCount = 0-9
    ssrWriteMSB (singleled [i]); // eight LEDs binary count 0-255
      delay(500);
   // ssrWriteMSB(myCount);
    //Serial.println(myCount);
    delay(500);
   // Serial.println(myCount);
    zeroWrite(29); // pad remaining bits with 0s
    delay(500);
  }

} // end loop

void pulseCLK()   {
  digitalWrite(CLK, 1);
  digitalWrite(CLK, 0);
}

// LSB out first!
void ssrWriteLSB(byte value)   {
  Serial.println(value);
  for(int x =0; x < 8; x++)   {
    byte temp = value & 0x01;
    if (temp == 0x01)   digitalWrite(dataBit, 1); // data bit HIGH
    else digitalWrite(dataBit, 0); // data bit LOW
    pulseCLK();
   value = value >> 0x01; // shift right
  }
}

// MSB out first!
void ssrWriteMSB(byte value)   {
 Serial.println(value);
  for(int x =0; x < 8; x++)   {
    byte temp = value & 0x80;
    if (temp == 0x80)   digitalWrite(dataBit, 1); // data bit HIGH
    else digitalWrite(dataBit, 0); // data bit LOW
    pulseCLK();
    value = value << 0x01; // shift left
  }
}

void  zeroWrite(byte num1)   {
  digitalWrite(dataBit, 0); // data bit LOW
  for(int x = 0; x < num1; x++) pulseCLK();
}

Turns on every other light all at once:
#define dataBit 3
#define clk 2

void setup()  {
  Serial.begin(1200);
  pinMode(dataBit, OUTPUT);
  pinMode(clk, OUTPUT);
  digitalWrite(dataBit, 0);
  digitalWrite(clk, 0);
}

 void loop() {
     //digitalWrite(dataBit,1);
     for(int index=0; index < 36; index++)  {
          digitalWrite(dataBit,1);
          digitalWrite(clk,1);
          digitalWrite(clk,0);
          digitalWrite(dataBit,0);
          digitalWrite(clk,1);
          digitalWrite(clk,0);
      }
  }

Thanks in advance.
Bryan

I think you need something like this.
#define CLK 2 // to MM5451 pin 21
#define DATA  3 // to MM5451 pin 22

void setup()
{
    pinMode(CLK, OUTPUT);
    pinMode(DATA, OUTPUT);
    digitalWrite(CLK, 0);
    digitalWrite(DATA, 0);
    Serial.begin(1200);
}

// the loop routine runs over and over again forever:
void loop()
{
    for( byte led=0; led<35; led++ )
    {

        lightLed(led);

        delay(1000);
    }
}

void lightLed(byte index)
{
    //always send a one first
    sendOne();
    // turn off all leds preceding index
    for( byte i=0; i<index; i++ )
        sendZero();
    // one led on
    sendOne();
    // pad with leds off
    for( byte i=index+1; i<35; i++ )
        sendZero();
}

void sendOne()
{
    digitalWrite(DATA, HIGH);
    digitalWrite(CLK, HIGH);
    digitalWrite(CLK, LOW);
}
void sendZero()
{
    digitalWrite(DATA, LOW);
    digitalWrite(CLK, HIGH);
    digitalWrite(CLK, LOW);
}

Gerben You're a genius!!! Thank you soooo much! This works beautifully! I knew it needed two loops and two separate routines but all i had as a reference was an 8 bit count and just couldn't figure out how to implement it with a 36 bit count. Once again I can't thank you enough! Really appreciate it!!! Best regards, Bryan

source: Stack Exchange

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

sort: votes


text:
need help for saving the millis function when arduino was rebooted
I have two questions want to ask

I'm using Arduino Uno with 16*2 LCD Blue ( also I have temp. sensor and two motors also 3 limit switches) ,, my code is working good, but sometimes my lcd stop printing the values of Temperature and time [print nothing i.e. print all the leds on] \\ then when I reboot it everything works good .... why this problem happened ?
Is there any way to save the value of millis function when the arduino was rebooted ?

thanks for your help
regards

My code is for an egg incubator , it consists of

Dht22 sensor [humidity + Temp]
three limit sw.
one motor
16*2 lcd
lamp [acting as  heaters]

As I said previously,  millis function  that I'm using is for controlling the motor movement every 3 hours and stop the movement after 18 days of working
The main problem I faced is POINT 1 that I mentioned previously (I don't need to lose the time when I reboot the LCD)
If any one can help by giving me a short code as an example who to deal with EEPROM or any other idea.
Here is my code
#include "DHT.h"  //includes lib for the temperature-humdity sensor
#include <LiquidCrystal.h> //lcd lib

#define DHTPIN 13 //pin that DHT is connected to
#define DHTTYPE DHT22 //Sensor we are using

DHT dht(DHTPIN, DHTTYPE); //defines location for DHT

int sw1,sw2,sw3;
const int LM1=0;
const int LM2=1;
const int LM3=6;
const int LAMP=8;
const int CW=10;
const int CCW= 9;
const int Buzzer=7;
long previousMillis = 0;        // will store last time LED was updated
unsigned long RealTime = 0;
float MOTORTime =0;// This is the real time that present on LCD now.
unsigned long MOTORSTOP = 0;// store the valve after 18 days of ranning ,,

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 10800000;           // interval at which to blink (milliseconds)(3 hours waiting)

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {

  lcd.begin(16, 2);   // set up the LCD's number of rows and columns: [LCD that we have (Colomn,Row)]
  pinMode(LAMP,OUTPUT);
  pinMode(LM1,INPUT);
  pinMode(LM2,INPUT);
  pinMode(LM3,INPUT);
  pinMode(CW,OUTPUT);
  pinMode(CCW,OUTPUT);

 }
void loop() {
  sw3=digitalRead(LM3);
      unsigned long currentMillis = millis();
MOTORSTOP = currentMillis;
if (MOTORSTOP < 1555200000){ // 18 days
  float h = dht.readHumidity(); //defines the variable for humidity
  float t = dht.readTemperature(); //defines the variable for temperature
  // set the cursor to column 0, line 0
  lcd.setCursor(0,0);
  // print the humidity
  lcd.print("H ");
  lcd.print(h);
  lcd.print("% ");
  //move line down
  lcd.setCursor(0,1);
  lcd.print("T ");
  lcd.print(t);
  lcd.print("C ");

  lcd.setCursor(10,0);
  lcd.print("MOTOR"); // to print motor working time

if (t==37.65)digitalWrite(LAMP,LOW);// Lamp OFF
else if (t>37.65)digitalWrite (LAMP,LOW); // Lamp OFF
else { digitalWrite(LAMP,HIGH);}// Lamp ON

  delay(2000); //wait two sec. before taking another reading.
  ///////////////stepper motor control and delay time 2.45 hours.
 sw1= digitalRead(LM1);
  sw2= digitalRead(LM2);

  RealTime = currentMillis - previousMillis;
  MOTORTime=((RealTime/(1000))/60); ////////////////////////////////////////////
  MOTORTime = 180 - MOTORTime;

  if (MOTORTime >= 1){
   lcd.setCursor(10,1);
  lcd.print(MOTORTime); }// this will print the ACTUAL Time Remaining on LCD
  else {
    lcd.setCursor(10,1);
   lcd.print("<1 MIN");}

  if(RealTime > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

  if (sw1==LOW && sw2==HIGH){
    digitalWrite (CW,LOW);
    digitalWrite (CCW,LOW);
    do {
      digitalWrite(Buzzer,HIGH);
      digitalWrite (CW,HIGH);// change the direction of rotation (DOWN Movement)
      digitalWrite (CCW,LOW);

      sw2= digitalRead(LM2);}
      while(sw2==HIGH);}

      else if (sw1==HIGH && sw2==LOW){

      digitalWrite(CW,LOW);
      digitalWrite(CCW,LOW);

        do {
          digitalWrite(Buzzer,HIGH);
          digitalWrite(CW,LOW);// change the direction of rotation (UP Movement)
          digitalWrite(CCW,HIGH);

          sw1= digitalRead(LM1);}
          while(sw1 == HIGH);}}
}
//----------------------------------------------------------------------------------------------------------------------
else if (((MOTORSTOP/10800000)>= 144 )&& (LM3== LOW)&&(MOTORSTOP >= 1555200000)){
  digitalWrite (CW,LOW);
    digitalWrite (CCW,LOW);

   float h = dht.readHumidity(); //defines the variable for humidity
  float t = dht.readTemperature(); //defines the variable for temperature
  // set the cursor to column 0, line 0
  lcd.setCursor(0,0);
  // print the humidity
  lcd.print("H ");
  lcd.print(h);
  lcd.print("% ");
  //move line down
  lcd.setCursor(0,1);
  lcd.print("T ");
  lcd.print(t);
  lcd.print("C ");

  lcd.setCursor(10,0);
  lcd.print("MOTOR"); // to print motor working time
  lcd.setCursor(10,1);
  lcd.print("OFF");

if (t==36.70)digitalWrite(LAMP,LOW);// Lamp OFF
else if (t>36.70)digitalWrite (LAMP,LOW); // Lamp OFF
else { digitalWrite(LAMP,HIGH);}// Lamp ON

  delay(2000); //wait two sec. before taking another reading.

}
}

You can save things permanently in the EEPROM. Just store your counter there, and it will be available after a reset. Just don't use it too often, it's only good for maybe 1 million writes, which can be used up quite quickly.

You might try a real-time clock module instead of the millis() function. They keep time in external hardware and are battery backed so continue through a power down, you get calendar date and clock time instead of milliseconds since restart, and they don't overflow every 50 days.

It has been suggested to you to save the millis value in the EEPROM.
Although this can work, there is a big issue with the frequency at which
you save it. If you save too often, you will burn your EEPROM, as it is
only rated to 105 writes. If you do not save often enough,
you will have most of the time a very outdated value in EEPROM. The
problem can be mitigated by adopting a wear-leveling strategy, but this
adds significant complexity.
There is a simpler solution to this problem: instead of using the
EEPROM, save the value in RAM. Actually, the millis value already lives
in RAM, and since the RAM is not initialized by hardware on reset, you
will find, when your program starts, that the last millis is right where
you left it! It is then cleared by your program, in a function called
__do_clear_bss that belongs to the C runtime and runs before
setup().
In order to preserve millis across a reset, you can do the following:

Write a function that copies the millis value into some other global
variable. This function must run early in the startup sequence, before
__do_clear_bss clears millis. This can be achieved by putting
the function in the .init3 section of the program, as explained in
the avr-libc documentation on memory
sections.
And the global variable must be in the .noinit section in order for
the C runtime not to mess with it.
In setup(), restore the millis value from that global variable.

This way you will have a continuous millis across resets, with one
caveat: on a cold boot, it will start with an unpredictable value. This
should be no issue if you take care to never rely on absolute time but
only on time differences, which is a good practice if only to avoid
issues when millis rolls over. If you nevertheless want to reset millis
on a cold boot, you have several options:

Connect a "reset time" button to your Arduino and hold the button
pressed when you power it up. setup() would then know it should not
restore the millis value.
Write some magic
number
in RAM. If you find this number at startup, it is extremely likely
that the program is starting from a warm reset.
If your Arduino has a fairly recent version of optiboot, you
will find the reset flags in the CPU register r2 when your program
starts. These flags tell you whether you come from a cold boot or a
warm reset.

The program below is an example that implements strategy 2. It prints
the millis value on the serial port roughly every second. On reset, it
prints “-- starting --” and continues from where it left.
// If this is in RAM at startup, we come from a warm reset.
volatile const unsigned long magic = 0x12345678;

// This is where Arduino core keeps the millis() value.
extern volatile unsigned long timer0_millis;

// Here we will save a copy of timer0_millis.
unsigned long __attribute__((section(".noinit"))) savedMillis;

// Save the millis value at startup.
void __attribute__((section(".init3"),naked)) saveMillis()
{
    if (magic == 0x12345678)  // very likely a reset
        savedMillis = timer0_millis;
    else                      // cold boot
        savedMillis = 0;
}

void setup()
{
    // DO THIS FIRST: Restore the saved value of millis.
    noInterrupts();
    timer0_millis = savedMillis;
    interrupts();

    // Other initializations can be done now.
    Serial.begin(9600);
    Serial.println("-- starting --");
}

void loop()
{
    Serial.println(millis());
    delay(1000);
}

The fact that one can keep data in RAM across a reset is something I learned from the article Odometer/Speedometer Pendant by David Johnson-Davies.

Summary:
You have an incorrect variable type assignment for previousMillis ('long' instead of 'unsigned long') resulting in illegal mixing of types in a subtraction.
It is not certain that this is causing your problems but, if not, it will cause problems at some stage if millis() is never reset  - if only when millis() passes its halfway point.
It is not possible to prove with certainty that the mixing of types is not causing a problem without examining the compiled code as the action is 'illegal' and so no assurance is possible.
(We hope that the compiler writer 'got it right' :-) ).

Details:
Where you now use

long previousMillis = 0;

You should use

unsigned long previousMillis = 0;

Both 'long' and 'unsigned long' are 32 bit data types but long is signed and effectively "wraps around" at half value.
Apart from having funny things happen after about 25 days, if you mix data types in a calculation as you do in

RealTime = currentMillis - previousMillis;
  where

RealTime = unsigned long
currentMillis = unsigned long , but
previousMillis = long

then there is no certainty as to what the code will do when subtracting a long' from an 'unsigned long'.
We know what we would like it to do, and we hope that the compiler writer made the same assumptions as we do, but there is no guarantee.
Interestingly, while it does no harm for RealTime to be of type 'unsigned long', this is usually not essential, as we know that

up to about 25 days the result will fit in the lower 31 bits of a 'long' and
  up to 65.535 seconds the result will fit in the 16 bits of an unsigned int and
  up to 32.767 seconds the result will fit in the lower 15 bits of an int.

So, if your period between millis() tests is guaranteed to fit in the above ranges then the lower range variables may be used.
While the mixing of types in the actual subtraction produces a technically undefined result, the use of a different type for the result than is used in the calculation is acceptable as the calculation result is well defined as long as the subtraction is performed correctly.

millis() wrap-around - NOT a problem:
People have expressed concern about incorrect results when millis() overflows after about 50 days, but this need not be a concern if correct data typing is used.   When two variables or 'counters' (in this case eg millis() and previousMillis), both of type 'unsigned long' are subtracted or compared, the result is arithmetically valid, even if the "upper" variable ( millis() ) has reached the top of its range and 'wrapped around'. This result is true for any two unsigned integer counters which are both of the same length.
ie the result of eg

delay = millis() - previousMillis

will ALWAYS be valid if millis() and previousMillis are both 'unsigned long's.
This result is not intuitively obvious to most people and there are many "solutions" to this "problem" on web which seek to correct a problem that does not exist. If you are interested in making use of this fact in other situations it is worth taking pencil and paper (or your favoured equivalent) and using eg 3 or 4 bit variables, working through how this works and why. What happens is that the overflowing / wrapping around higher counter (millis() in this case) "looks like" a longer unsigned variable with additional bits above its MSb. When the subtraction is carried out an MSb "bowwow" may occur  - this is being "borrowed" from data bits that do not exist but this matters not when only the lower N bits (32 in this case) are of importance.

Variable (including the state of millis() ) can be saved in EEROM memory prior to a reboot. IF the data has to be validly written when a power outage occurs the system must detect the outage and continue to run long enough to validly write to EEROM. This requires proper design of power supply holdup time - without which EEROM corruption may occur due to power loss while writing to memory. As well as internal EEROM, it is possible to use low cost I^2C EEROM memory if non volatile storage requirements exceed uC EEROM capacity.

More detail on any of the above available if required.

+1 for your explanation of the millis() rollover issue. I too have come across a few misguided attempts to fix this non-problem. OTOH, (unsigned long) - (long), although certainly a bad idea, is well-defined by the rules of usual arithmetic conversion: the signed argument is implicitly converted to unsigned.

@EdgarBonet You may be right re the (UL - L) result. In C++ certainly, in Arduino code, probably and hopefully. In a language that isn't exactly the same as any formally defined one, and which also includes a GUI of sorts, programming code  and more, all rolled together and implemented by a team of competent enthusiasts, where things like this are not explicitly covered in the 'reference' you'd hope the results were what you'd expect from the nearest relevant language(s) - but if it didn't work the way expected, you'd have no real comeback. But, as you say, it's probably "standardised".

You could be running out of memory. Posting your code would be helpful.

2. Not without some external memory such as an SD card.

As David points out in the comments the Arduino does have EEPROM memory (512bytes or 1024bytes depending on which version you have). See here for the library: http://www.arduino.cc/en/Reference/EEPROM

Many microcontrollers have EEPROM or self-writable flash that can be used to store values internally in a non-volatile way.

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


text:
How to solve Atmega 16A Serial write (println) hang with Arduino Uno firmware?
For doing some experiments I bootloaded an Atmega16a with Arduino Uno. I am powering my Atmega16a from Arduino UNO. I am not using any external clock. Atmega16a is connected to a breadboard. For bootloading I refer the site http://hardwarefun.com/tutorials/use-arduino-as-an-isp-programmer-to-program-non-arduino-avr-microcontrollers I can run blink sketch on my Atmega16a using Arduino as ISP. TX and RX of Atmega16 is connected to Max485's DI and RO respectively.
Atmega16a pin 14 (RXD) -> MAX485 pin 1-RO
Atmega16a pin 15 (TXD) -> MAX485 pin 4-DI
Atmega16a pin 17 (D3)  -> MAX485 pin 2 and 3. Also connects a LED to the pin

I used a boards.txt downloaded from https://github.com/sudar/arduino-extra-cores/blob/master/boards.txt
Issue: hang at Serial.println
I faced issues when I started to interface with MAX485.
The program wont run if I add a Serial.println, see my program below.
void setup() {
   Serial.begin(76800); // I tried 9600 too
   pinMode(3, OUTPUT);
}

void loop() {
  digitalWrite(3, HIGH);
  delay(400);
  Serial.println("20"); //comment this code and could see the led blinks
  delay(2000);
  digitalWrite(3, LOW);
  delay(400);
}

Regression
I tried Latest Arduino IDE as well as 1.0.6 version
I could do a serial communication with Raspberrypi and Arduino Uno via MAX485 without any issues. For the complete connection detail of MAX485 and other Arduino, check my blog.
Some times I receive some string to serial port of Raspberry pi like below. I run a nodejs app in RPi, using serialport npm and parser is RAW.
<Buffer fa>
<Buffer 82>
<Buffer 86 ff>
<Buffer fe>
<Buffer fe>

How to prevent these hangs?

I suspect you are not using the correct core files. The Atmega16A and the Atmega328P have different register locations for the USART (serial hardware). The fact that it hangs suggests to me it is waiting for some register to change state, but it is checking the wrong register. What board do you have selected in the IDE?

Unfortunately you can't just simply upload the Arduino bootloader and expect it to work. The ATmega16 is not the same as the ATmega328. One quick look at the datasheet will already explain why this is not working. The UDR(USART data register) is at 0xC6 on the 328, while it's at 0x2B at the Atmega328. So the ATmega16 will look at the location where the 328 stores the received data and will not find it. This could explain the hang, but I expect that other things like UART setup will have gone wrong before you get to the receiving of data.
If you want serial communication with the ATmega16, try programming it directly in C with the AVR libraries and without the Arduino extensions. That will make it harder to figure out.


text:
How to see log from Arduino IDE?
Where can I see outputs from such instruction in an ino file ?
Serial.println("my message");

Click the magnifier icon in the top right corner of the window.

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.

Thanks. In fact I think my logs are not visible because the uploading process never ends. I use an arduino BLE nano; any idea on how to fix the problem ?

Nope. Sorry never tried anything like that. Are you saying you are uploading your sketch via BLE and it never finishes? Im not familiar with those products, but they look interesting.

No I 'm not uploading via BLE, just using the upload button on Arduino IDE, but it never ends

This helped, but I also needed to initialize the serial library in the setup method - Serial.begin(9600); - described here before logs showed up in the IDE monitor: http://forum.arduino.cc/index.php?topic=25326.0

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.

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/

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


text:
Accuracy reading two analog inputs on Arduino
I need a help with this question. I'm trying to make a Wheatstone Bridge with Arduino, the main idea is read the two legs of the circuit with two analog inputs of Arduino, for the while I'm analyzing the values with 4 equal resistors as the Arduino reads (0 to 1023 bits). The problem is when I change one of the resistors (Rx), the voltage on A0 (first leg C) should not be changed, but it happens.

I've read something about the analog inputs of the Arduino suffer interference, but I don't know how to avoid this.

You can try taking the reading twice and discarding the first one. However, if you want precision, rather than subtracting two single-ended readings, you should take one differential reading. The ACD of the Mega has this capability, with up to 200× gain.

@EdgarBonet - are you referring to the Analog Comparator here?

@NickGammon: No, I am referring to the ADC of the ATmega2560, which can operate in differential mode.

It could change in reality, if your excitation supply isn't stable.  Edgar Bonet's suggestion of differential ADC is a good one.  See page 283 of the datasheet at http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf


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

if you have something connected to digital pins 0 or 1 (rx/ tx), disconnect, and try to upload.

no improvement.. :(

The board is selected properly? If it still doesn't work, there is a bug somewhere... Also found on internet, in fact on arduino stackexchange (http://arduino.stackexchange.com/questions/804/arduino-nano-uploading-gives-error-avrdude-stk500-recv-programmer-is-not-re) that you have to press reset just before uploading... Also try: http://www.instructables.com/id/A-solution-to-avrdude-stk500getsync-not-in-syn/ and http://forum.arduino.cc/index.php?topic=273910.0. Maybe will help you!

When you say" Bootloaded with blink program " - should this read, " bootloaded with bootloader program " by any chance? You have actually got a bootloader in? How else did you get "blink" on it?

@MarkWilliams Thank you for correction but that doesn't solved my problem in any way.

got it
http://electronics.stackexchange.com/questions/106870/programming-an-atmega328-with-arduino-bootloader-via-a-ftdi-usb-serial-adapter

Does this mean the question is resolved?

Possible duplicate of "avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program

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

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


text:
Using Arduino command line on windows
I have an nmake file;
  srcpath = ..\pilot
  cmdline =  "C:\Program Files (x86)\Arduino\arduino.exe"
  cmdflags = --verify  --board arduino:avr:uno --port com4 -v --preserve-temp-files
  prefs = --pref sketchbook.path=$(srcpath) --pref build.path=build
  deps = $(srcpath)\pilot.ino $(srcpath)\commands.h $(srcpath)\publish.h $(srcpath)\motor.h

  pilot.hex :$(deps)
    type $(srcpath)\pilot.ino
    $(cmdline) $(cmdflags) $(prefs) $(srcpath)\pilot.ino

The file types out fine, but Arduino returns an error;
"failed to open sketch ..\pilot\pilot.ino"
I am setting --pref sketchbook.path=$(srcpath), but I have tried with and without (and many variations of both) and get the same error.
This is the command that is currently being invoked, and looks correct to me;
"C:\Program Files (x86)\Arduino\arduino.exe" --verify  --board arduino:avr:uno --port com4 -v --preserve-temp-files --pref sketchbook.path=..\pilot --pref build.path=build ..\pilot\pilot.ino

Any ideas?

It looks like the given path is wrong. Have you tried supplying a full path?

You are kinda correct. I posted my own answer

srcPath = C:\Users\mikep\Documents\MWPRobotics\Pilot\Pilot
bldPath = $(srcPath)\build
arduinoCmd = "C:\Program Files (x86)\Arduino\arduino.exe"
arduinoFlags = --verify --board arduino:avr:uno --port com4 -v --preserve-temp-files --preferences-file $(bldPath)\pilotPrefs.txt
prefs = --pref sketchbook.path=$(srcPath) --pref build.path=$(bldPath)

deps = $(srcPath)\Pilot.ino $(srcPath)\commands.h $(srcPath)\publish.h  $(srcPath)\motor.h

pilot.hex : $(deps)
#   type $(srcPath)\Pilot.ino
    $(arduinoCmd) $(arduinoFlags) $(prefs) $(srcPath)\Pilot.ino

Apparently it is really picky about absolute full paths (contrary to the comments that say it is relative)

I guess it's just a matter of understanding what is the working directory. If you're unsure about it, you can set it with --curdir (that, I've just found out, is undocumented), then you can use relative paths

The way the 'type' command succeeded, and Arduino would complain not found, tells me it was not doing working dir relative by default. And yes, I did not know of --curdir - that might have worked. It also seems to ignore the preferences-filename, but it put the file with its Arduino given  name in the right place. I am just happy I can run from VS.


text:
Can anyone explain how hex codes 0x1A is used for sending ctrl+z & 0x0D for Carriage Return & 0x0A for LineFeed?
Please explain in detail. How the Hexadecimal code has been assigned?
Edit: This is the code:
#include <Wire.h>
void setup()
{
   Wire.begin();
   Serial.begin(9600);
   delay(1000);
   Serial.println("AT+CMGF=1"); //set to SMS mode
   delay(1000);
   Serial.println("AT+CMGS=\"+918460588440\""); //set the phone number (wrapped in double quotes)
   delay(1000);
   Serial.println("hello world. this is arduino");
   delay(1000);
   Serial.write(0x1A); // sends ctrl+z end of message
   delay(1000);
   Serial.write(0x0D); // Carriage Return in Hex
   delay(1000);
   Serial.write(0x0A);
}
void loop() {}

Please don't ask the same question twice.

They are all to do with where in the alphabet they are.  There are 26 letters in the English alphabet, and Z is the 26th.  The 26 in hexadecimal is 0x1A.
A carriage return is a CTRL-M, and a line feed is a CTRL-J.  M is the 13th letter of the alphabet, and 13 in hexadecimal is 0x0D.  J is the 10th letter - 10 is 0x0A in hexadecimal.
Why are they CTRL-M and CTRL-J?  Well, that all stems from the old teletype interfaces used on the very early computers.  That's what they used, and that's what's stuck, and finally made it into the ASCII standard.

Why are these lines added at the end of arduino code?

Because they are.  Whatever "the code" is, it obviously requires them.  Without knowing what "the code" is I can't comment any further.

this is the code

        #include

    void setup()
    {
      Wire.begin();
    Serial.begin(9600);
    delay(1000);
    Serial.println("AT+CMGF=1"); //set to SMS mode
   delay(1000);
    Serial.println("AT+CMGS=\"+918460588440\""); //set the phone number (wrapped in double quotes)
    delay(1000);
    Serial.println("hello world. this is arduino");
    delay(1000);
    Serial.write(0x1A);  // sends ctrl+z end of message       delay(1000);
    Serial.write(0x0D);  // Carriage Return in Hex delay(1000);
    Serial.write(0x0A);
    }
    void loop()
    {}
No, that is a huge mess of text that I can't decypher.  My guess is that whatever you are talking to requires those characters as part of its protocol.

These hex values are the numbers in the ASCII table, https://en.wikipedia.org/wiki/ASCII.
Characters corresponding to values below 32 are control characters, reserved for special purposes. For the values you mention in the question:

0x0d = 1*16 + d*1 = 13 = CR (carriage return)
0x0a = 0*16 + a*1 = 10 = LF (line feed)
0x1a = 1*16 + a*1 = 26 = SUB

("control+Z" is not the ASCII control character, but how you would generate this control character (SUB) on a keyboard.)
A table with both hexadecimal and decimal numbers is also given in the Wikipedia article.

if the value is in 0d, then why add '0x' to it?

0x is a prefix that indicates that the literal is a hexadecimal value: https://en.wikipedia.org/wiki/Integer_literal

(I've formatted your code and edited it into your question).
This code is apparently driving a device - GPRS shield? - to send an SMS. No doubt the code was written to meet the requirements of the device. Note that the CR and LF literals could have been written as '\r' and '\n', respectively. The author chose to write them in hex, probably because there is no "\" code defined for Ctrl-Z, and so wrote all three in a consistent style.


text:
Using Arduino BLE Nano to switch an electric circuit on and off
I'd like to use an Arduino Nano BLE to activate or deactivate an electric circuit.
I intend to use a relay to do so, but activating a relay seems to require a current with more intensity than what we can get out of a digital output (about 20 mA).
Is there a way to get more intensity out of a BLE nano ?
Are there others components that could behave the same way as a relay but could react from a digital output ?

You can use an NPN transistor such as a 2n2222 with a 1K or so resistor on the base to actuate a small relay.  Put a diode backwards across the coil.  You will see this circuit published everywhere.  Or you can use the optoisolated version common on those cheap relay boards.  Make sure your relay is rated to handle your ultimate load.

Thanks a lot for the comment. This could be an answer isn't it ? May I ask you for a reference link about how to use an NPN transistor with an Arduino ?


text:
Reading and Writing on different clock edges with Arduino SPI interface
I'm trying to simulate a certain µController to characterize and measure a certain chip.
I need to write my data on the negative edge of the master clock and read the data coming from the slave in the positive edge of the master clock. Is there any way I can have this kind of freedom in my code? Or do I have to do it manually without using the predefined SPI interface?
Also, I would like to have my master clock running continuously without going idle… is there a way to do that too?

To set the spi to shift out on falling edge and shifting in on rising edge of the clock you need to set the spi mode to 0 or 2 (depends on idle clock polarity).
More info here
To continuously generate clock signal as far as I remember you will need to write to the SPI dummy values.


text:
Can all Arduino Due pins be used as digital input/output?
I am using an Arduino Due for a project. I am running out of digital pins, using 22 to 53. Can pins 0 to 13 and SCL1, SDA1 be used as digital inputs?
How about analog pins (A0 to A11) and DACs?
Thanks!

Bear in mind that this has nothing to do with "Electrical Engineering".
This simply is an arduino question. And should be asked on arduino Stack Exchange.
Yes.
They can be used as input/output pins. [Simple 'tutorial']
If that even isn't enough or not working on your type of arduino, you can use I/O expanders or shift registers.
Check them out on the internet. [I/O expanders]

See also the first paragraph of the official docs on Ardunio:
https://www.arduino.cc/en/Tutorial/DigitalPins

Yes, sort of. All the Analogs/digitals can be used as digital outputs with the following exceptions. TX0/RX0 (unless you are aware of what you're doing), SPI buss (SCK/MOSI/MISO), SDA1/SCL1, & CANRX/CANTX. DAC0/DAC1 may be used but be aware the min/max those two pins can output is ~0.55 to 2.75V.
And these exclusions are only for an arduino DUE. Other Arduino's will have more/less exclusions.
Correction:  I was able to use CANRX and CANTX as alias pin names to declare these two lines as digital outputs, and set the pin values high/low in the normal way.

With the min/max of ~0.55 tot 2.75V, do you mean that those outputs can't be 0V? Or that ~0.55v is at least required tot read a logic high?

That's what the Datasheet stated for those two pins, my guess is that the DAC outputs are part of an internal R2R DAC network so Vss and Vdd may not be achievable on those two pins.


text:
Arduino Uno questions
Anyways cutting to the chase I am pretty good at C++ as I have been doing it for over 6 months pretty much 1-2 hours each day and I am looking for cool things to use my knowledge on ,I have heard of the Arduino's but the problem is I don't know my arse from my elbow when it comes to electrical engineering and all that so I have a couple of questions.
1. Do I need to have a background in engineering to use an Arduino.
2. Is there any cheap alternatives to the quite costly starter kit.

There are clones available but the drivers for the USB<->Serial chips may be suspect.

I don't understand why you would need a starter kit when you want to program an Arduino. Why not just buy an Arduino (or clone)?

Or if you're willing to learn, the MCU and a programmer.

@Spehro actually the realy cheap ones ones that use an SP230x seem to be ok. It is the ones that claim to use an FT232 that might turn out to contain a knock-off chip.

@WoutervanOoijen I had some issues getting the Mac driver to work, but admittedly didn't try all that hard. The FTDI clones have a well known issue as you imply.

I don't know my arse from my elbow when it comes to electrical engineering and all that so I have a couple of questions. 1. Do I need to have a background in engineering to use an Arduino.

The answer to your first question: it depends on what you want to achieve, and how much time you are willing to spend stuck.
A bit of electrical/electronic background can help you a lot.  Basics such as Ohm's, Kirchhoff's.  Semiconductor devices (diodes, transistors, OpAmps).  It's very useful to understand what kinds of test&measurement equipment exists and how it can be used.
You can pursue C++ for 6 months 1-2 hours a day.  You can pursue electrical knowledge in the same way as well.  A solid book like "The Art of Electronics" will help you a lot (doesn't have to be the latest edition).
Then you can pursue more exciting things: sensors (for example).

If you are the "hacker" type (i.e. you are good at self-learning and you like to explore things) even if you are an absolute newbie I advice against those starter kits. They usually contain lots of overpriced parts, which you can get much more cheaply ordering directly to digikey, mouser or the like for your country (or maybe at your local shop).
On the other hand I strongly recommend buying an original Arduino board (for beginners an Arduino UNO is optimal, IMO, and comes at a reasonable price around 20-25EUR). This because the quality is guaranteed and you risk less problems. There are really good clones out there, but also tons of crappy ones, so I'll leave them to when you get more experience. Nothing is more frustrating while learning that wasting hours to debug a supposedly idiotproof project only to discover that it was not your fault, but the board's!!!
Note: if you go for an Arduino UNO choose the version with a socketed plastic DIP package MCU (that big, long chip with two parallel rows of pins), instead of the SMT version, using an MCU packaged as a tiny plastic square. The version with the socket may come handy if you accidentally fry the MCU: a new one will cost you less than 4EUR and it's easily replaceable (it is not soldered on the board). The SMT, on the other hand, is a PITA to replace and you'd need special hardware to do that. Moreover, the socketed version can be used as a "poor man's" programmer for ATMega328 MCUs. You program it on the board and then place it on an external circuit.
If you are an absolute beginner at EE, you can find lots of beginner tutorials on the Internet. Concentrate on key basic aspects. Most electronic projects can be handled with less math than you expect. You absolutely need to know Kirchhoff's laws and Ohm's law and a couple of related formulas if you want to begin learning electronics, but nothing more fancy. The rest can be learned on the way. Keep in mind that there are people out there that know much less than that and that are able to put together an electronics project successfully only by following "instructables" found on the Internet (really hardcore tinkerers! :-)
BTW, one thing you may find interesting, given your C++ background, is that what they call the "Arduino language" is really true C++! The Arduino environment "enhances" the source program (the "sketch", as they call it) and inserts all the boilerplate code needed to configure the MCU and other low-level stuff a beginner would have hard time digesting. Then the source program so enhanced is fed to AVR-GCC, in its G++ incarnation, which is nothing more that GNU GCC configured as cross-compiler for AVR MCUs. You can even use templates and derived classes, if you dare :-) Of course they don't tell you, otherwise the poor Arduino beginner would be scared away :-D
Very advanced Arduino users can bypass the Arduino environment completely and write directly C++ code and use the board as a simple prototyping board for the MCU it is based upon (ATMega328P for the Arduino UNO), exploiting all the features of the MCU without all the abstraction layers which comprises the Arduino environment.
A note of caution: when I talk about C++ I mean what is technically known as a freestanding C++ implementation, as opposed to a hosted implementation like on PC's. This means that the implementation doesn't need an OS to work, but also that it doesn't have all the standard libraries that you expect to find on a hosted implementation (sorry, no std::vector or std::cout !!!). A freestanding implementation must only provide a very limited subset of the usual standard libraries (those that handle lower level stuff, like memory allocation), and normally relies on implementation-specific libraries to do other stuff. In particular with the Arduino environment and the underlying AVR-GCC comes the AVR-LIBC library. But this is needed only when you do advanced stuff. The basic Arduino library will keep you busy for a nice amount of time until you reach such a level of expertise.

1) You do not have to have engineering background. You only need to know basics such as what a resistor is, what a transistor is, how an led works etc. (Of course the answer depends on what you want to do. For instance, if you want to work on a robotic project then yes, you need a little knowledge.)
2) Shopping questions are not answered here, but since you are asking something about "cost" then I have two answers. You can find cheaper solutions, but I, personally, always support original products for two reasons. First, you need to support the people who serves your work. Second is that original products are generally more reliable.

First question, no. Tons of tutorials for a from scratch beginner online. Second question, Google Arduino clones.

I am having loads of fun with Arduino from a background of programming with no electronics experience.  From simple "flash some LEDs" in the early days (back in Feb) through to making my own "games console" using a 32x32 LED matrix, FRAM memory chip, piezo buzzer and a home made controller for input.  I found that once I got started and browed various relevant sites, ideas started to flow.
I would suggest using straight C rather than C++, especially if you are working on one of the particularly low memory devices (such as the Uno).  I ran out of working RAM more times than I care to remember.
As for starter kits, if you search, you should be able to find cheap kits.  I got a pretty decent starter kit for around £20 but there were cheaper ones with a few less components.  Mine included (amongst other things) 30 LEDs, various IR and flame sensors, photo resistors, a 7 segment LED, a 4 digit 7 segment LED, an 8x8 LED matrix, a servo, a stepper motor, a stepper motor control board, a couple of breadboards and an Arduino Uno.


text:
Is arduino suitable for high frequency application?
Can I use the arduino for an application with a frequency of 4 MHz?
I need to create a clk with this frequency and send and receive data on the rising and falling edges. and it is not a normal SPI interface I have my own conditions so I need to do it manually.
If it is not suitable, is it technically possible?

How can we tell you whether an AVR can speak the protocol you need, if you don't tell us what that protocol is?

Most Arduinos are based on AVR chips clocked at 16 MHz. On those,
you can generate a 4 MHz clock using hardware timers. Bit-banging
data at this speed would be difficult though. It may be possible,
using unrolled loops and hand-crafted assembly... or not, depending on
the specifics of your application. Even if possible, it would be a nice
challenge for an assembly programmer.
The Arduino Due is based on an ARM chip clocked at 84 MHz. This
gives you more leeway to bit-bang at 4 MHz. But even on the Due you
would certainly need hand-crafted assembly.

No, it's not suitable due to the inherent maximum pin output frequencies in relation to the clock divider setting.
Yes, it's technically possible. Edit the divider to a value that sets the output to close to what you need. However this is annoying to do, and has serious repercussions in your code. (i.e. having to multiply every timing/bit value by 16, 8, 4, 2 or whatever you choose)
A clock of that high of a frequency would have to be some crystal to set the base time, and then a comparator circuit that could vary fast enough to push data into the edges.
You could, however, simply note the absence of the 4MHz signal as 0, and it's presence as 1, sending binary data that way it probably a lot easier than encoding it between each individual edge.


text:
Are arduino passwords safe?
Is an arduino password controlled lock safe or can the password be seen if they plug it in to a computer?

Most of the time you don't even need to connect a computer to it. Don't use a microcontroller for any sort of security unless you've spent at least a couple of months researching all the possible security issues.

When using no other tools than the regular Arduino IDE for programming the device, it is trivial to retrieve all its memory, including flash and EEPROM and with that the program, password or encryption keys. It is possible to lock the memory down, but the you can't reprogram the device any more and there are companies that specialize in reading AVR memory even when locked.

The trick here is to put the arduino behind the lock. So, unless they break the lock, which would make the password redundant? They have physical access to the arduino. And can use their debugging tools on it.
How were you thinking of inputting the password? By only giving them access to some I/O pins on the outside, I believe it becomes difficult if not impossible to retrieve the code/debug info. Be sure not to use any pins that double as programming/communication.
If someone has physical access, it's unlikely to make any protection. As they can read/re-program/bypass the arduino.

@jippie: You can reprogram a locked AVR: you just have to reset the lock bits first. This requires a chip erase though.

If "they" can get at the Arduino to "plug it into a computer" they can just activate whatever pin it is that unlocks the safe, so the question is redundant.

There are no passwords inherent to Arduino. You can implement them any way you want, resulting in any safety level from zero safely to nearly uncrackable.
Not so good: store the passwords straight in EEPROM. No protection of your data means that there's always a way to read them.
Quite safe: hash the password before storing it, for instance through SHA-512. Even if you can read the list of hashed passwords, it's pretty hard (read: nearly impossible) to reverse the algorithm to get the password back. For that reason SHA functions are called one-way functions. When you enter a password you run it through the SHA algorithm and check the hash against the list of hashes in EEPROM.

But note that "quite safe" isn't "perfectly safe"; there are a number of security attacks that don't require you to ever access the memory of the device.

@Ignacio: Yes, that's why I used the word "quite" deliberately. For applications where security is prime (no pun intended) you wouldn't use just an Arduino anyway, but for instance an Arduino combined with this Crypto-shield.


text:
Can a connection of HC-05 and Arduino Nano receive audio and display waveform on computer?
Working to receive Music for Bluetooth Speaker via HC-05

No, it can't.  The HC-05 is a Bluetooth Serial device, Bluetooth speakers are Bluetooth Audio Sink devices.
It's like asking "Can my bicycle fly?"

I think you'll agree the answer is "NO".
The only possible way of doing it using the HC-05 is to receive the audio using your computer then pre-process it and send the important information to the Arduino through the HC-05, so the Arduino can then send it back to the computer for displaying.  But then, what really is the point of the Arduino...?!

So what bluetooth modules should I use to make a Bluetooth speaker?

Like I said - a bluetooth audio sink module. I don't know if there is a "module" as such available - you are probably best off getting a real set of bluetooth speakers or a bluetooth headset and ripping it apart.

Bluetooth audio modules are sold, often at a price premium.  It's possible that in some cases they may just be a different firmware on the same silicon, but as that is typically not released its not really a do-it-yourself modification.

http://arduino.stackexchange.com/questions/9890/install-bluetooth-inside-a-home-theater-how   I too asked...


text:
Using Multiple Serial Ports with arduino nano
I am using a arduino nano to control a adafruit ultimate gps and a xbee wireless controller. However I recently ran into a problem using both at the same time (before I was using each separately until now) and read that I cannot listen to 2 software serials at the same time with a arduino. The biggest problem I see is that since I can only listen to one at a time, if I open a port, will cached data from the xbee and/or gps instantly start transferring in? Or or it more luck based that I will catch it as it comes? How should I go about coding around this? Should I just close and reopen the ports as needed(assuming there is no luck factor involved)? Any help is greatly appreciated. I will explain more if necessary.

You can use SoftwareSerial library in order to instantiate a second (soft) serial port.
By looking at the example, it seems that you can use any two digital pins to use SoftwareSerial library and instantiate a second serial port along with the hardware serial port.

You might be able to use the GPS's EN pin to enable and disable the communication to it, and also try to use the RTS/CTS pins of the XBee to control the flow, since that's their actual purpose there :)
I hope that helped.

The EN pin might shut it down and then you'll have to reconnect to sattelites?
You could however, use a transistor on the dataline so you can toggle the stream of data coming in.

The Mega and the Due have 4 UARTs. It seems like those should work, but they are much larger. I'm embarking on a project that needs to be small and use two serial ports. I'm looking at the Teensy, which has three UARTs.


text:
0-1 V input to 0-5 V Output
We have an instrument that has analog output of 0-1 volts and we need to convert this to 0-5 volts. What is the best op amp to use for this and how should the resistors be set up? Any help would be greatly appreciated.
Thanks,
Paul

For your frequency needs of course the 324 is the best, and the resistors should be setup for a gain of -5.

What have you tried? This is a very standard circuit; searching for "noninverting opamp" should turn it up. If you have specific trouble implementing it, that would be the time to ask for help with your more specific question.

Input impedance, output impedance, load impedance, frequency response, power supplies available?

Desired precision? Are we supposed to guess 10 bits because of the Arduino tag?

Since you used Arduino tag..., you don't need an opamp. Instead you can select ADC reference voltage on your arduino to 1.1V. This way you don't need any additional parts and you get the whole precision range.
analogReference(INTERNAL1V1);

http://www.arduino.cc/en/Reference/AnalogReference

+1 This is so neat, it's neat. Except if anything else needs the ADC - you are stuffed because the standard Arduinos (although there are so many these days..) only have a single ADC peripheral. Another thing is modular design - the analog instrument may not always be there or maybe needs other circuitry, so a simple general purpose rail-to-rail input/output op-amp with a gain of 5 and perhaps a passive low-pass filter going into the Arduino's ADC would be something I would do in my own design

You can switch between 5V and 1.1V ADC in software as you like, so using mixing various peripherals is not a problem.

I suppose so, but no sure how much that would affect performance.. for a slow sensor-network system or whatever it would be fine - or just scale down all the other inputs to 1V using resistors which is far simpler than scaling a signal up. The resistors wouldn't be ideal if the signal itself was already a voltage divider as you would affect it with parallel resistance.

@KyranF: Taken from the Atmega328 datasheet, Sect 24.5.2, paragraph 3: "the user may switch between AVCC [5 volts]  and 1.1V [Internal Reference] as reference selection. The first ADC conversion result after switching reference voltage source may be inaccurate, and the user is advised to discard this result."

@chaaarlie2 thanks, thats pretty good only losing 1 sample


text:
Is it possible to control the speed of DC motors with Arduino's analogWrite() using analog pins?
I'm trying to control the speed of two DC motors that are connected to a dual H bridge. I always used digital PWM pins with analogWrite() to change the speed, but since I'm making a project that will be using most of the digital pins, I wonder if I can use analog pins instead.
P.S. I know I can use analog pins as digital pins to free the digital PWM pins, but I'm not interested in doing that.

Well, I am confused. The Arduino reference page, the "Description" of analogWrite() also states: "Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. " So can it or can it not?

analogWrite() is for writing to the pins that support PWM.  As far as I can tell you can't use it for writing to pins A0, A1, etc...  Its a really confusing name for a function

No, you can't.  As it says in the Arduiuno reference page for analogWrite(): "The analogWrite function has nothing to do with the analog pins or the analogRead function."
You can use the "analog input pins" (A0..A5) of Arduino for analog input, or as digital inputs or outputs.  They cannot be used for PWM(digital)-output.  Only digital pins, and only those specifically stated for PWM-output, can actually be used for PWM output (unless you go down the path of software-PWM, though I would hesitate to do that for an H-bridge).

depends on if the OP means an "H-bridge" with a control input stage that takes a single PWM input. I agree it would be a bit dicey to go that route with two inverted SoftPWM signals coming from the AVR.

You can't do it with the analogWrite function as that is reliant on physical binding beween certain pins and hardware timers inside the AVR. But you can always use SoftPWM because the the analog pins can generally be used as digital pins just as well.

Yes, multiwii project does 'bit banging' software pwm on analog pins, but a library would be faster to implement

You can use multiplexers if you are running out of digital pins or SPI PWM drivers for the motors. There are many multichannel drivers out there like TLC5940, put a power stage after them and you're done.
*Use Soft SPI on the analog pins to control the driver.

The TLC5940 is designed for LEDs, would it be adequate for motor control?


text:
What is the use of decoupling capacitor?
I dont understand what does the word "decoupling" mean? Where and Why it is used? Can anyone give me a brief idea>?

Quite simply put, it's a little reservoir of energy for a chip or other device to dip into when it needs to get a little extra power.
In Electronics nothing happens instantly.  When a chip needs more power it has to get it from the power source.  The power source then has to respond to that by providing more energy, and that then has to make its way down the wires or traces to where it needs to be.
By placing a small capacitor near where the power is consumed the capacitor can respond to that call for more power much faster than the power supply.

So by responding in that way, I understand that it helps maintain the voltage and provide necessary current to the chip? Am i right?

Yep, that's right.  Think of it like the tank on your toilet.  You have a local supply of water for flushing, then the normal water supply fills it up slowly afterwards.  You can't flush with just the normal water supply, it's not fast enough.

What about it's use as a high-frequency transient suppresant or for AC-DC (de)coupling? The term bypass capacitor is often interchanged with decoupling capacitor so frequently - whether erroneously or not - that it deserves an inclusion, n'est pas?

That's too technical for an Arduino user.

@chaaarlie2 You may want to direct that question to the electronics stackexchange, found at http://electronics.stackexchange.com/

@Butters The questions were rhetorical; I know the answers, my point was to discover why Majenko omitted two of the three facets of "the decoupling capacitor".

@Majenko I wouldn't have thought the high-frequency aspect was too technical; it can be explained as succinctly as your existing answer and it is a reasonably fundemental principle. You almost always get two capacitors bundled with each IC on a PCB - one larger electrolytic to act as a power reservoir and one small ceramic job to negate transients. Each is invariably as important as the other, so it's a shame you haven't addressed both.

@chaaarlie2 The high frequency aspect of the capacitor isn't just down to the capacitor, but the impedance of the traces since the two together form a low-pass filter.  To properly explain that aspect it is necessary to also explain impedance, filters, Q, etc.  Far too much for an Arduino user to cope with.  If they want more detail then they can go to EE.SE where they will get an EE-centric answer covering all those aspects.

@Majenko And how would the OP know to go to EE.SE for more detail if you fail to mention that these aspects exist?

@chaaarlie2 If they are capable of understanding the concepts without first undertaking some formal learning they'll already know of the existence of EE.SE and will probably have been there many times before.  If not, and they do want more clarification, then there is this magical thing called "migration" which will send them to EE.SE. In the context of the Arduino, though, just the basics are all that are required. It's enough to know that you DO need decoupling caps, and some rough idea why you need them so you remember to use them. You don't need to know all the quantum mechanics of them.

@chaaarlie2 IF I were answering this on EE.SE then yes, there would be a huge amount more information.  You have to remember: this is an arduino site, and people that come here looking for answers generally lack even the most basic knowledge.  Giving them too much too soon is bad for them.  Look up "Wittgenstein's Ladder", better known by Pratchett fans as "Lies to Children".

Every time a logic circuit switches from a 0 to a 1 or a 1 to a 0, the 1 and 0 transistors are on at the same time for a short period of time.  In MOS circuits, this is combined with the need to charge the gate of the 1 or 0 transistor (Charge is what capacitors store, gates of MOS transistors are capacitors!).
Since all wiring is inductive, the faster the current, the higher the impedance from the main power supply and the switching device (Your processor or sensor etc).  The terms bypass and decoupling mean the same thing:  You are providing a local charge well to supply fast current demands by bypassing the main power system, i.e. supplying current via a different path and thus decoupling the switching device from the inductively isolated main supply.
This is also why we used to use two types of capacitors for decoupling: A 0.1uF ceramic and a 1uF electrolytic for instance...  You couldn't get the whole 1uF in a low resistance ceramic to cover both the Low and High speed transients without paying a lot so you used two or more parts, each covering a portion of the spectrum.  Nowadays a single SMT ceramic with low ESR, low ESL and no lead wires can do the whole job and is usually pretty economical.
Another factor is radiation:  A ringing voltage transient current through inductive wiring acts just like an antenna.


text:
What changes I have to take care while coding from Atmel Studio instead of Arduino IDE?
-Are there any changes in Bootloader?
-Why is the coding different for same chip in different softwares?
-How to upload the program from Atmel Studio?

Atmel cpp projects do not currently provide an option to upload using Arduino bootloader. Atmel only provides upload using hardware programmers.
The bootloader is deleted when you upload using a hardware programmer either from Atmel Studio or from the Arduino ide.
The underlying Atmel toolchain is not very different from the latest Arduino toolchain however Atmel does not know about the Arduino hardware/cores. You have to copy the Arduino core sources to your Atmel project if you want to compile for Arduino compatibility but that still does not give you bootloader upload.
It is not clear from your question if you have the Arduino sources in your cpp project already. If you do have the sources in your project then you can use avrisp mkII or other programmer to upload but the Arduino libraries might be an issue for you if you are using them.
There is another option in Atmel Studio however it might not be what you require ...
You can install the Visual Micro plugin for Arduino from the Atmel Gallery and work with standard Arduino sketch projects inside Atmel Studio.
The Visual Micro plugin provides full Arduino compatible sketch build and bootloader upload in Atmel Studio. Because of the nature of Arduino, the Visual Micro plugin automatically manages the include paths and Atmel project properties so that intellisense works in projects that contain .ino source code files. If the project does not contain .ino files then Visual Micro sleeps (does not interfere with cpp projects)
The plugin also provides other features such as a serial usb debugger, library manager, board manager, Arduino examples etc.
More about Visual Micro is here
Tutorials are here
Debugger overview is here

Update:
There is no difference in program execution between uploading using a physical hardware programmer or using a usb cable via bootloader.
The Arduino libraries sources can be more complicated to include/compile in a project because they often include additional folders with private source code. This is more of an issue with older Arduino libraries that have a sub folder called \utility.

You mention hardware programming. So as I understand, Bootloader is part of Hardware Programming and Atmel Studio helps in hardware programming, am I right? What is the difference between hardware programming and programming using Arduino IDE? and one more question, What is the difference between Arduino Sources and Arduino Libraries as you have mentioned it above? Assume, Blink project is my project need to be uploaded from Atmel Studio.

Have updated the answer


text:
Connect the Sparkfun CAN bus shield with an RFduino
I have a problem which I am working on for some days now. I do have knowledge in electronics, but not extensively. I also posted this question in the RFduino Forum but couldn't get any good answers.
What I am trying to do: I want to connect the Sparkfun CAN bus shield to the RFduino. I am using the code further below. It compiles without problem and does work with my Arduino Leonardo!
I used a logic analyser (ignore the filled shapes, some display error) to further narrow down the problem and found the following on the RFduino:

On the Leonardo, it looks different:

It seems like I don't get a response on the MISO line! I played around with different speeds, but nothing seemed to work.
I do have a suspicion however: The RFduino works with 3.3V, while the Leonardo works with 5V. So the logic signals on the RFduino can only achieve 3.3V P-P. I confirmed this with my old CRO, LOW is at GND and HIGH at 3.3V. The Leonardo has 5V P-P.
On page 70 of the datasheet for the MCP2515 (the chip used on the shield), it says that the supply voltage VDD ranges from 2.7V to 5.5V. So supply voltage should be ok. V_INPUT_HIGH ranges from 2.31 to 4.3V. V_INPUT_LOW ranges from -0.3V to 0.495V. I am in this range! Similarly so for the V_OUTPUT_LOW (up to 0.6V) and V_OUTPUT_HIGH (at least 2.8V). Could this nevertheless be a problem?
What would you try or change?
MCP2515 Datasheet
#include <SPI.h>

// demo: CAN-BUS Shield, send data
#include <mcp_can.h>

MCP_CAN CAN0(SS);                                      // Set CS to pin 10

unsigned char stmp[8] = {0, 1, 0, 3, 0, 5, 0, 7};

void setup()
{
  Serial.begin(115200);
  while (!Serial) {
    ;                  // wait for serial port to connect. Needed for Leonardo only
  }
  // init can bus, baudrate: 500k
  if(CAN0.begin(CAN_500KBPS) == CAN_OK) Serial.print("can init ok!!\r\n");
  else Serial.print("Can init fail!!\r\n");
               // send data per 100ms
}

void loop()
{
//    // send data:  id = 0x00, standrad flame, data len = 8, stmp: data buf
//  CAN0.sendMsgBuf(0x00, 0, 8, stmp);
}

Ok, I found the solution. The fix first: I had to physically connect the reset line from the RFduino to the MCP2515 reset pin.
On page 55 in the datasheet of the MCP2515 it says that you can either reset it by pulling the reset line low or by sending a command over the SPI. The library I used is sending this reset command, but it isn't working for some reason. The logic analyser shows me this signal, it is the first recorded. Maybe it is a timing issue, that the reset has to be sent at the same time as the RFduino resets. Connecting the reset pin solves this issue, because then the RFduino and the MCP2515 are being reset at the same time.
If anybody knows more about this, feel free to tell me!

It is difficult to tell whether your chip select is working correctly or not with the logic analyzer view.  Have you tried hooking it up to an o-scope to capture what the CS is actually doing(in the analog world)?
What cabling have you chosen between the CAN and arduino?
If you get the o-scope out, you may want to check the MISO and MOSI for ringing, which may lead back to cabling.

I just hooked up my oscilloscope. Looks like the analyser wasn't lying, the signal is good. A little bit of overshoot (0.1V at max), but the separation is good, the MOSI is only active when CS is low and so on. On the MISO I have some strange signal, about 25 MHz and very small (0.4V). It goes blank when the chips is reset. Giving the CAN shield/MPC2515 5V to work with doesn't change anything.

After looking through the data sheets, i have to ask how are you powering the CAN BUS?  From the Leonardo/RFduino?

The CAN BUS schematic shows a VCC and a +12V, but the source of VCC is not shown.  If VCC is being regulated down from +5V provided by the leonarado, then VCC might not be able to be regulated down by the +3.3V provided by the rfduino.  If 3.3V is the input to an LDO somewhere and 3.3V has to be the output too, you'll definately have problems..    Moral of the story, make sure you understand the Power chain fully.

The 'power chain' with the Leonardo depends on the operation: with the CAN bus connected, the 12V goes through the Vin pin of the Leonardo to its onboard 5V regulator, which then provides 5V on a pin. This pin is via the shield connected to the VCC pin on the MCP2515. The other chain is for testing, where I just initialize the chip without actually doing anything on the CAN bus: I provide 5V via USB and the Leonardo then again provides it on the same pin as above. The RFduino provides 3.3V from USB via a regulator on the programming shield, which I connect to the VCC on the CAN bus shield.

So Leonardo+CANbus active: CAN->CAN Shield->Leonardo (12V->5V)->CAN Shield->MCP2515. Leonardo on USB: USB->Leonardo->CAN Shield->MCP2515. RFduino on USB: USB->Programming Shield (5V->3.3V)->CAN Shield->MCP2515.


text:
Which bluetooth module should I buy?
I am doing a wireless rover using arduino mega 2560 that can be controlled by a smartphone and a PC. Which bluetooth module would fit me? Again I want to control it both by my Laptop(Built-in Bluetooth) and my smartphone. Thanks in advance.

Which smartphone. iOS is pretty strict in what kind of Bluetooth modules it supports.

A little late but in case someone like me ran into this:
HC-05 seems to be the DIY choice. Can work in slave or master mode and works with Android but not iOS.
HC-06 is the same as HC-05 except that you can only use it in slave mode.
HM-10 seems to be the option for iOS users.


text:
Arduino UNO not working?
Recently I assembled my Shapeoko machine, we used Grbl shield with an Uno for the same.
For 1-2 weeks everything worked perfectly then once when I tried to work the machine, the serial communication was not working. I tried to replace the 16 MHz oscillator because I thought the problem might be with the oscillator since the LEDs were not blinking but they were lighting up.

Please visit Have I bricked my Arduino Uno? and see if the steps suggested there help solve your problem.

Did you mean 16MHz and not 16Hz?

Maybe the 5v regulator? Hard to say without the symptoms.


text:
Good tips for how to connect cables into Mux Shield II?
I just got a Mux Shield 2 and got it working as I expected. Now I started to find out how to actually connect the I/O cables to the board. Doesn't seem to be as simple as I thought. I don't want to solder cables into the board for maintenance reasons. So, does anyone have any good tips on how to do this?

if you want plugs, solder plugs onto it.

Solder 100-mil male headers onto the board, then use 100-mil crimp terminals to connect the wires.


text:
Why does this code execute?
After experiencing failures of my Arduino projects due to low memory, I decided to do some research into it so I could understand better where the problems were. I eventually came to this code:
void setup() {
  pinMode(13, OUTPUT);

  int len = 5000;
  byte *data = (byte *)malloc(len * sizeof(*data));
}

void loop() {
  int timing = 1000;
  delay(timing);
  digitalWrite(13, HIGH);
  delay(timing);
  digitalWrite(13, LOW);
}

I expected that since my Arduino Uno does not have enough RAM to hold an array of 5000 bytes (Atmel's information on the Atmega328P shows us it only has 2KB of SRAM), the code in void loop() would not be able to run due to lack of memory. As far as my understanding goes, once malloc has allocated 5000 bytes (or as many as it could of the 5000 bytes), there would physically not be enough space left in memory for the variable timing and the LED I attached on pin 13 would not flash on and off at intervals of 1 second.
However, my LED toggles at perfect intervals of 1 second. Why would this occur? Isn't memory allocated by malloc unavailable for use by anything else until free is called on it?

If you add a debugging print you will see what is happening:
void setup() {
  Serial.begin (115200);
  Serial.println ();

  pinMode(13, OUTPUT);

  int len = 5000;
  byte *data = (byte *)malloc(len * sizeof(*data));

  Serial.print ("data = ");
  Serial.println ((int) data);
}

Output:
data = 0

The malloc failed, it returned NULL, the rest of the program proceeded normally.

once malloc has allocated 5000 bytes (or as many as it could of the 5000 bytes)

malloc does not return with a partial allocation. It either allocates the amount you requested or none at all.

I guess error checking is very important and handy, thank you.


text:
What's the benefits between different interrupts on Arduino
On an Arduino you can have several different interrupt types, two of them being RISING and FALLING. Looking past that RISING is from LOW to HIGH, and FALLING is the opposite, what are the benefits of using one or the other?
To clarify; why would you use a RISING interrupt or a FALLING interrupt?

These are the ways an external IO pin can generate an interrupt. You use rising when you wnat an interrupt when the level on a pin rises from low to high. It is that simple.

Imagine that you have the circuit below:

simulate this circuit – Schematic created using CircuitLab
Let's say that you wanted to catch the user pressing the button. The input signal will go from high to low, which is a falling edge. So you would use a FALLING interrupt to catch this event. Easy, right?
Now let's say you wanted to catch a user releasing the button instead. This time the inverse is true, so you want to use a RISING interrupt.
You should note that since these interrupts are edge triggered, the simple circuit below would not be ideal. Without any debouncing, there may be several edges to trigger from, resulting in repeated interrupts. Also, given the analogue nature of the design, we can't be sure that the rise / fall times will be fast enough to trigger the edge interrupt. We can get around this by adding a 100nF capacitor across the switch and following by a Schmitt trigger (which I can't find a symbol for in the circuit editor!).
So to answer your question, you use the interrupt that is correct for the event you are trying to catch. The Arduino MCU implements both edges for completeness and flexibility in your design, so if this interrupt was coming from an external IC you have no control over the design of, you can easily match the interrupt to its behaviour without having to add in an inverter.

Very good answer. And of course if you want to detect the switch press and release, you can use a CHANGE interrupt.

Suppose you have a pushbutton that connects Arduino pin to the ground. The pin is also pulled up  to VCC (may be internally in Atmega chip, or through external resistor). Now, when the switch is open, Arduino sees HIGH, and when you press the button it sees LOW. If you would like to perform an action when the button is pressed, you would use FALLING interrupt. If you would like to know when the button is released, you would use RISING. There are no general benefits of using one over another.

The interrupt will be generated by an external circuit.  In many cases, you have the control over the design of the external circuit, and you can choose whether it will be generating low-to-high edges or high-to-low edges.  But in some cases you don't have the control over the design of the external circuit which generates the interrupt.  Then you have to adapt your firmware code to the interrupt source.


text:
Arduino Serial.write sending more than 64 bytes

I am using an Arduino Due to collect a large amount of data from an encoder (about 1kb). Afterwards I need to send the collected data to a C# application I wrote over the serial port. I serialized my tx data into a byte buffer and simply used this code to transmit:
void sendEncoderData()
{
  byte buffer[1024];

  /*** some code that populates buffer ***/

  int bytesToSend = 1024;
  Serial.write(buffer, bytesToSend);
}

When I run the code, nothing seems to get received by the C# application. In fact, I never see the Tx LED light up. However, if I change bytesToSend to a value smaller than 64 bytes everything works. Is this a limitation of Serial.write() or is it something else? What are ways I can work around this limitation?
More information： sendEncoderData() is called by an interrupt service routine. However prior to the call, I made sure to 'detachInterrupt()` on all pins including the pin associated with said ISR.

Have you tried sending in 64-byte chunks?

That's a snippet, isn't it? http://snippets-r-us.com/

@NickGammon, I would be a snippet if Serial.write() is supposed to be capable of sending more than 64 bytes at a time. If that's the case:

My assumption was wrong and perhaps you could have pointed it out. 2. I will post more code and details.

This only seems to work - define "work". It hangs? Only 64 bytes are transmitted? If so, which? The first 64? The last 64?

I(t) would be a snippet if  ... - OK, let's say you turned interrupts off. You may have, you may not have. With them off things would be different than if they were on. It may not seem important to you, but to us, it is. You are the one asking the question. It is up to you to supply as much information as you can to get a good answer.

More information： sendEncoderData() is called by an interrupt service routine. - this is absolutely crucial information, which is why I linked you to http://snippets-r-us.com/. If you had said "In an ISR I am calling this line of code ..." I would have been able to answer you straight away.

Here's the problem:

sendEncoderData() is called by an interrupt service routine.

There is an internal 64 byte serial transmit buffer that is filled by Serial.write().  That buffer is empted by sending the data a byte at a time using an interrupt.
If you are in an interrupt (at a higher priority than the serial interrupt) then the interrupt that sends the data can never happen, so the buffer just fills up and stops when it gets to 64 bytes.  It will hang until there is room for more bytes in the buffer, and that will never happen because you're not allowing the data to be sent.
The answer (as I and others have said many times in the past): Never use Serial in an interrupt.


text:
Connecting a switch and a MOSFET to an Arduino?
I have an LED strip that I am trying to turn on with a magnetic switch when a door opens. I want the LEDs to fade on when I open the door and fade off when I close it, which is where the Arduino comes in. I am using PWM for the fading. I can get each component to work separately. The fading LEDs work with the MOSFET without the switch. I tested the switch with serial output on the Arduino and it works fading a single LED without the MOSFET.
I am using:

Arduino Uno R3
Magnetic Switch
N-Channel MOSFET IRLB3034
5 Meter White LED Strip
12VDC 30W Power Supply
10k Ohm Resistors

My setup looks like this:

Schematic:

Code (if it helps):
const int buttonPin = 2;     // the number of the switch pin
const int ledPin =  9;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the switch status
int brightness = 0;
int fadeAmount = 5;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop(){
  // read the state of the switch value:
  buttonState = digitalRead(buttonPin);

  // check if the switch is ON.
  // if it is, the buttonState is LOW:
  if (buttonState == LOW) {
    // fade LED on:
    analogWrite(ledPin, brightness);
    if (brightness < 255) {
      brightness = brightness + fadeAmount;
    }
  }
  else {
    // fade LED off:
    analogWrite(ledPin, brightness);
    if (brightness > 0) {
      brightness = brightness - fadeAmount;
    }
  }
  delay(30);
}

I have a feeling the problem is with the common ground on the MOSFET and the switch. Any solutions/suggestions are appreciated.

are you able to turn on the FET via Pin D9 continuously on? With out PWM.. When D9 is high can you pls measure the voltage across drain and source of the NMOSFET? Check the voltage at D2 when the switch is closed and opened. Measure voltage at D9 when the Output of D9 pin is high. can you share the details of 5 meter LED strip? How are you powering on the Arduino? I have a feeling that issue is with the 5 meter strip LED...

I would expect R2, near the MOSFET, in the order of 100 ohm. You'll drive it hot otherwise. Also change the minimum and maximum tests from 255 resp. 0 to 250 and 5.

You do not say what problem you are having. What does it DO? | LED strip will power up over a voltage range near 12V. ie is probably off at about 9V and on at 12V. So IF voltage on strip is analog due to any filtering it will power on over end part of PWM range. If circuit IS as shown LED strip should modulate on and off at PWM frequency. This SHOULD work. Circuit as shown looks OK and code seems OK so you may6 not be doing what you think you are. Check everything. | And, what does it n fact do?

@As Jippie says- MOSFET gate resistor can be small 100 Ohms or even 10 Ohms OK. 10k as shown is probably not cause of problems but is too large.

THat's an AWESOME FET. Data sheet here

The microcontroller output is too weak to drive the gate of the IRLB3034 properly at PWM speeds (>=1 kHz). Without a resistor you'll have overcurrent at the PWM output, and with one you'll heat up the MOSFET. I solved it in a couple of my projects by building an NPN-PNP totem pole using a 2n2222 and a 2N3904 between the micro and the gate. I put one <1kΩ base resistor between the PWM pin and the totem pole, and a couple of ~10Ω resistors between each of the BJT emitters and the MOSFET gate. Works like a charm.

I think you should keep the R2 resistor, but make it 1k and put before it a pull-down resistor of 10k so that any charges stored in the NMOS Cgate capacitance are discharged, whenever there is High-Z at the port D9. Also never forget the resistor limiting the diode forward current, which is typically 20 mA, but you should check that every time in datasheet. In case of LED strip there are usually internal resistors, but if you are using higher voltage still you need to restrict the current. Could you tell us more about why you are using PWM not a simple output port with an integrator for example and what you exactly observe and measure when you turn-on-off (fade-on-off) the LED?

simulate this circuit – Schematic created using CircuitLab
How to make the diagram a bit smaller?

He's driving a 12V rated strip with internal resistors - no external LED r needed. He's using PWM because he wants a digital solution and not an analog one.

@lalamer To scale the diagrams on ESE you need to make them wider, I do this by placing a dot/segment/text to the left and/or right so it shrinks the whole diagram, works well.

@RussellMcMahon yes you are right, this is a led strip and there is a internal resistor. I have updated my answer. Thank you for committing.

There is no need for the 10KOhm. MOSFETs are voltage controlled devices unlike transistors which need controlled current. I think your problem might be in debouncing of switch. You are probably getting some false positives which might be making your software go awry.
I recommend having a small debouncing routine. For eg - only if you find 3 successive positives will the switch press be termed a true positive or so.

When switch is seen as active it does one action and then delays 30 mS before retesting so he effectively has a 30 mS debounce.

It is a good practice to have a resistor in series with gate to limit the inrush current. Remember the gate of MOSFET acts like a capacitor and needs to be charged/discharged.

To achieve this u should connect the gate of the MOSFET to the gnd(in case of NMOS).This will discharge the MOSFET gate capacitance quickly. Also, you should never leave a gate floating as it is susceptible to noise and can switch on causing a lot of damage. Always pull down the NMOS gate.


text:
Is it possible to setup a system based on Arduino Due running QNX?
I would like to create some QNX applications and test them in a hardware different than my virtual machine. Since Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU and QNX® Neutrino® RTOS supports that processor, I was wondering if it is possible make them work together.
What would be the challenges to make it work?

Since Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU and QNX® Neutrino® RTOS supports that processor, I was wondering if it is possible make them work together.

Does QNX really support ARM Cortex-M3? I believe that is not possible as the processor does not have the necessary hardware support.

Please see the BSP list.
Cheers!

Typically the challenge in porting a new OS to a board is to configure stuff like:

system clock (to drive the scheduler of the OS at the right frequence)
board specific I/O
components that are not part of the SoC (but iirc DUE doesn't have any of these)
individual HW blocks (like on which serial port redirect the character interface, if your application has any)
wakeup sources, in case you have/want low power modes and you need the board to wake up when something specific happens

None of these are impossible tasks and they are all good to learn more about the system, but otoh it's unlikely you can rush through them.
The good news is that probably you will not need them all and not immediately.
But some you will have to perform and they will require understanding how your OS works and having the technical reference manual of your board and SoC.

I guess you are talking in general as QNX is not directly open-source??


text:
what is the importance of the resistors that connect to push buttons ? can i replace them by wires?

Please, iam a junior in arduino and i want to know what is the importance of the resistors that connect to push buttons? can i replace them by wires?
thanks in advance.

They are what is known as Pull-Up resistors.  The circuit will not work if you replace them with wires.  Not only that but you will short circuit the power supply when you press a button.
Why don't you want to use resistors?
The value is not important - you could use the same value as you are using for the LED if you don't have the 10k resistors shown in the drawing.
Having said that an alternative is to leave them out and instead activate the internal pull-ups within the processor on the Arduino:
pinMode(pin, INPUT);           // set pin to input
digitalWrite(pin, HIGH);       // turn on pullup resistors

I'd say that it's not "an alternative", it's the sane thing to do :-)
Why using additional components when there are integrated ones that are perfectly suitable for the purpose?
I think the situations that require using external pullups are really few and not too likely to happen to someone who's just starting to move the first steps.

Or use the single line pinMode(pin, INPUT_PULLUP);  (which in effect does the same thing, but is a bit shorter, and more intuative)

I'm having an issue with your comment about short circuiting the power supply but am likely just "splitting hairs".


text:
Replacing atmega8 with atmega328 on Arduino Single-Sided Serial Board
i want to know that if i use atmega328-pu instead of atmega8 on this design provided by "https://www.arduino.cc/en/Main/ArduinoBoardSerialSingleSided3", will it works fine on this design or i have to use only atmega8 ?

Yes and no. It will work on this board, but won't get programmed by arduino IDE directly.
ATmega328 and ATmega8 are fully pin compatible. ATmega328 is like bigger and powerful in terms of onchip resources. However, if you want to program ATmega328 on the arduino board, you must install bootloader. Otherwise you will have to program it everytime using ISP programmers such as USBASP. This will connect to the ICSP socket shown on the above board.
Refer to: http://tutorial.cytron.com.my/2011/09/30/how-to-program-arduino-by-using-avr-usbasp-programmer/


text:
AVRdude + Arduino leonardo: can't flash over bootloader, not in sync: resp=0x3f
I would like to program an arduino leonardo board with atmega32u4 on win8.1 x64.
I have the latest AVRdude.
I installed the necessary drivers, after reset it can be enter programming mode, and I can program with arduino studio.
But now, the avrude gives this:
    C:\>avrdude -carduino -P COM5 -n -p m32u4 -b19200 -v

avrdude: Version 6.1-svn-20131205, compiled on Dec  5 2013 at 17:34:22
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "c:\GNU_GCC_ARM\bin\avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x3f

avrdude done.  Thank you.

I tried also with 57600 baud.
Any idea? Thanks.

You're specifying the wrong bootloader protocol via -carduino. The Arduino bootloader is for boards using the Diecimila bootloader. The Leonardo uses the "AVR109" bootloader - named after the Atmel Application Note which describes its protocol.
Try this command on for size:
avrdude -cavr109 -P COM5 -n -p m32u4 -b57600 -v

Don't forget to press the reset button (or open and close COM5 at 1200 baud) first to run the bootloader.


text:
Can a Ethernet USB Dongle be instead of ethernet shield for arduino?
Can a Ethernet USB Dongle be instead of Ethernet shield for arduino in order to cut costs?

No.  Arduino can't behave as USB host.

No, not directly. As @Majenko pointed out its possible but most likely over your head. I am not a big fan of the ethernet shield as I like to use my Arduino for prototyping and then build the project with the components. There are a 2 easy alternatives which are inexpensive options for accessing a network or internet via the Arduino

ENC28J60 Ethernet LAN Network Module
Esp8266 Serial Wifi Wireless Transceiver

Both are inexpensive (between $5 and $7 USD). There are tons of tutorials on line to get you up and running

One more alternative would be Wiz5100, cause it already have IP layer implementation. If you dont want to read lot of RFC-s :)

Its an option, but at  $24.95 USD I can get 3 Esp8266

Actually, you can get it for around 14$ from ebay. Still more expensive then two you mentioned...

Possibly with an Arduino Due in USB OTG mode if you want to spend months and months (or even years) delving into the USB specs, reverse engineering the driver for the USB dongle and writing the software to get it working.
"Possible" but certainly not worth it when you can use a simple Ethernet shield and have it all working within a day.
And definitely not possible on anything like an Uno, etc.
Also it's possible on an Arduino that runs a full operating system (Linux) like the Edison or (possibly) the Yun (OpenWRT side of the operations, not the Arduino side).


text:
Smart Servo Shield: How to upload code to AtMega8
I recently bought a Smart Servo Shield controller from DFrobot to use with my new AX-12A Dynamixel servos. The shield is attached to an Arduino Uno. The shield itself works fine, but it does not support all of the functions that I need. The shield has an AtMega8 on board, and they also give you the slave code that it runs to look over. If I were to modify said slave code, is there a way for me to upload to the shield's controller? If so, how would I go about doing that?
Smart Servo Shield
http://www.dfrobot.com/index.php?route=product/product&product_id=958#.VfXqzxFVhBc

Like the wiki says, remove the solder jumpers from the "UART SELECT" jumpers and connect to the "UART FOR Atmega8" connector in order to program it via serial. Don't forget to replace the solder jumpers after.
If you want to use ISP instead then make sure to remove the shield from the Arduino first since the shield connects all the ATmega8 ISP lines directly to the Arduino ISP lines.