body:
I have loaded an example sketch that came with the installation of the Arduino software onto my Uno.

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

    void loop() {

      int sensorValue = analogRead(A0);
      Serial.println(sensorValue);
      delay(1);
    }

From this time TX light is continuously on. It's remaining on even after resetting it. How do I end `void loop` so that TX light goes off.

title: Unable to terminate "void loop"

Answers: 5

body:
The TX LED is on, because this sketch is periodically printing the value of the analog pin 0 onto the serial port. The LED seems to be constantly on, because the delay between two `Serial.println()` calls is only approx. 1 ms.

If you replace the 1 with 1000 for example, the TX LED should flash once per second. Start the serial monitor in your Arduino IDE too see the transmitted analog values. Delete the `Serial.` calls to remove the serial port functionality altogether.

You might want to read the documentation of the [loop()](http://arduino.cc/en/pmwiki.php?n=Reference/Loop) and the [delay()](http://arduino.cc/en/pmwiki.php?n=Reference/Delay) functions.

body:
The implied question is how to turn off the Tx LED, which has already been answered and is probably the answer you're looking for. But the question you asked is how to end the `loop()` function. Not to be pedantic but to clarify the use of `loop`, the simple answer is, "you can't". `loop()` is called from a forever loop in the C/C++ main program, function `main()`, so returning from it, either with a `return` statement or by reaching the final close `}` causes `loop()` to be called again. This is intentional as the `main()` function in an embedded system is never supposed to return, thus it must keep re-running the application program.

Update (since this question just reappeared on the front page, I'll add the following to my answer):

`loop()` reads and prints continuously. If you had wanted that code to be executed only once, you could put in `setup()` and leave `loop()` empty. Then the sketch would initialize the serial output, read an analog value, print it - once - followed by entering the empty `loop()` and remaining there until power-down.

A way to execute the loop function once is to write an infinite loop at the end of it, so `loop()` would never return and thus never be re-executed:

    void loop() {

      int sensorValue = analogRead(A0);
      Serial.println(sensorValue);
      delay(1);

      while(1)
         ;
    }

body:
Seeing as questions about turning off the LED, and the nature of exiting `loop` have been answered, I'll also answer the question they both seem to lead to:

If the overall intention is to "turn off" the MCU, outside of turning off the power supply, it can be put into [sleep mode](http://playground.arduino.cc/Learning/ArduinoSleepCode).

Depending on how you configure the MCU before entering sleep mode, it can even be allowed to wake up on further USART communication.

body: Don't write code in the loop() that should be executed only a few times. Or use a counter. Or an external button. For the permanent light, increase the delay between calls.

body:
If your question is how to terminate the execution of your void loop code at some interval, I can mention 4 solutions:

1.If you want the Void loop() to execute only once (or a set number of times using for loop), you can use "exit(O);" at the end of the Void loop.
i.e.

    Void loop(){
             //code
             exit(0);
             }

Disclaimer: This one might not work for all Arduino boards, but it works fine with my Arduino UNO.

2.Another way would be to keep the "Void loop()" empty and put all of your code in the Void setup function.

3. use a void loop at the end of the Void loop.
E.g.

    void loop(){
    //code
    while(1){  //infinite loop }
    }

The arduino will remain in the infinite loop and won't be able to rerun the Void loop.

4. Create your own function and call it from the "Void Setup()"
E.g.

        Void setup(){
         myfunc();   //calling your function
        }
         Void myfunc(){
       //The code for the function you want to repeat only a set number of times
        }
        Void loop(){
        }

Hope someone finds it helpful.


body:
I am working off an Arduino Uno with an [AdaFruit PN532 NFC/RFID shield][1]. The goal is to have a shoe box, with a false bottom. Under that false bottom would be my prototype, which I hope will be able to detect any MIFARE tag that is in the box, above the false bottom.

The range obviously for these devices is practically touching, but I was was wondering if there is anyway to extend the reach of the NFC/RFID shield, so that the entire false bottom of the box could act as that antenna.

  [1]: http://www.adafruit.com/products/364

title: Is it possible to extend the reach of a PN532 NFC/RFID shield?

Answers: 1

body: I suspect not. NFC is designed for short range for privacy reasons. Some RFID systems have longer ranges (a few meters). They work by using an electromagnet to create a switching magnetic field. The RFID/NFC chip takes power from the magnetic field and then modulates a signal onto it, which the sensor detects. In order for it to work the chip needs to be close enough to get as strong enough field to power itself, and to modulate that field.


body: I have a PIR motion sensor and would like some ultra bright UV led lights to fade in when this is triggered. It is one unit, consisting of 225 led lights connected to 240v mains (Australia). I bought a relay for the basic on/off function but was wondering if fading on and off can be done relatively easily - this is my first arduino project. I would value any suggestions.

title: Fade in UV lights connected to mains

Answers: 1

body:
Most LED lights can't be dimmed from the mains supply.

In order to dim LEDs you have 2 choices: Limit the current through each LED or series string of LEDs, or pulse them very rapidly with a varying ratio of on/off times (known as a variable "duty cycle")

It's usually easiest to pulse them. To do that you need to be able to control the flow of DC to the LED array. If you were to take apart your IR array you would very likely find an AC to DC power supply that then feeds the LEDs through current limiting resistors.

If you can figure out the voltage and current that comes out of the DC power supply, you can select a power transistor (almost certainly a logic level power MOSFET) to wire in as an electronic switch that enables you to pulse the power to the LEDs using a logic signal from your Arduino.

This is actually a lot simpler than it sounds. You would cut 1 wire inside your LED array, solder in a single transistor to the 2 ends of the cut wire, and run the third wire from the transistor out to your Arduino.

Arduinos have several I/O lines that can be configured for PWM (Pulse Width Modulation) which is designed for this very purpose. You'd connect a PWM line to the gate of a logic level power MOSFET, and then send it a signal from 0 to 255, which would effectively dim the LED array in 255 brightness steps.

There are beginner sample projects that let you dim single visible light LEDs using this very approach. (For a single LED you don't need a transistor though, so they are really easy to wire up. All you need is a current limiting resistor.) I suggest you find and build one of those projects to get a feel for how (and how well) it works.


body:
I just begun with the Arduino starter kit, and in the second example I would like to test some changes to learn more.

The point is to have a green LED shining, and when pressing the button the two red LEDs blink.

This is the code:

    int switchState = 0;

    void setup()
    {
      pinMode(2, INPUT);
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);

      // the button is pressed
      digitalWrite(3, LOW);

      digitalWrite(4, LOW);
      digitalWrite(5, HIGH);
      delay(250); // wait for a quarter second
      // toggle the LEDs
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      delay(250); // wait fo a quarter second
    }

    void loop()
    {
      switchState = digitalRead(2);
      // this is a comment
      if(switchState == LOW)
      {
        // the button is not pressed
        digitalWrite(3, HIGH); // green LED
        digitalWrite(4, LOW); // red LED
        digitalWrite(5, LOW); // red LED
      }
      else
      {
        // the button is pressed
        digitalWrite(3, LOW);

        digitalWrite(4, LOW);
        digitalWrite(5, HIGH);
        delay(250); // wait for a quarter second
        // toggle the LEDs
        digitalWrite(4, HIGH);
        digitalWrite(5, LOW);
        delay(250); // wait fo a quarter second
      }
    } // go back to the beginning of the loop

I added a modification into the schema (a fourth LED in parallel with the green), like this:

![enter image description here][1]

![enter image description here][2]

But the added LED is not shining. It's a long time ago I finish school and I forgot a lot of things. Am I wiring the fourth LED incorrectly?

  [1]: https://i.stack.imgur.com/1jCas.jpg
  [2]: https://i.stack.imgur.com/ZcS7d.jpg

title: Arduino starter kit example LEDS modification

Answers: 1

body: Blue LEDs have a higher Vf than green LEDs, hence much less current will pass through it, not enough to make it visible. Give it its own resistor instead of sharing the resistor with the green.


body:
When I used `Serial.println()` in the code I naively believed I would see the characters that I sent displayed on that little black area just under the interface (just like a terminal).

    #include <Servo.h>

    int moveServo;

    Servo myservo;

    void setup()
    {
      myservo.attach(0);
      Serial.println("      Hello Earth");
      Serial.println();
    }

    void loop() {
    }

Can someone tell me just where `Hello Earth` would be displayed?

title: Serial.println(): Where is the text printed?

Answers: 2

body:
The IDE on your computer has a menu item under the tools menu called "Serial Monitor." On my Mac, at least, it is indeed a black area under the source editor for the current sketch.

It won't work unless you call the `Serial.begin()` function in your setup method before the first `Serial.print()/println()/write()` function call.

Something like this:

    //Set up the serial port @ 9600 baud for display back to the computer
    Serial.begin(9600);
    delay(25);
    Serial.println("Hello world!":);

body:
You can open the serial console in the Arduino IDE by pressing ctrl-shift-M (as in Monitor) or selecting it in the menu.

Also, to use the serial interface, you have to initialize it using `Serial.begin(9600);` in `setup()` before calling any other function which writes to it. You can use any other baud rate - but this is the default in the Arduino IDE, if you change it, you should change it in the IDE too.


body:
In a lot of the sample code online people add the line `Serial.begin(9600)` in the setup block.

When I look up what `Serial.begin()` is on the official documentation, it says that it controls the bit per second data transfer.

So the obvious question is, why not use 28800, the highest transfer rate? Why do people settle for 9600? What is the limitation here?

title: Serial.begin(): Why not always use 28800?

Answers: 5

body: I think the main reason people use 9600 most of the time is that it's the default baud rate in the Arduino IDE. Also, faster data rates could also be unreliable if the serial signal has to travel a long way - although I have no idea why this was selected as an optimum speed.

body: I think it is a kind of tradition to use a transfer rate that is not the slowest one (300) but also not one that could eventually cause problems in some setups (28800 or even 115200). The PC serial port (most often a FTDI232 USB adapter) can cope with higher rates but your DIY hardware may not. So 9600 bps has established itself as some kind of standard transfer rate for code examples.

body:
> Why do people settle?

People settle because it is more than fast enough.  The most common use is just to print some stuff on a terminal for debuggin.  9600 baud is 960 characters per second, or 12 x 80 character lines per second.  How fast can you read? :)

If your program is using the serial port for bulk data transfer, you would choose not to settle.

> What is the limitation...

The limits on serial are high.  Directly you can use 115200 baud in your programs and it will just work.  The Arduino terminal will allow a max of 115200, but other programs such as RealTerm would let you run higher.

Hardware serial will run to 1 M baud.  If you read around you will see people have used up to 1 M by directly controlling the UART.  You might get benefit of high baud rates for uses such as transmitting via a bluetooth chip.  If you are using the hardware serial interface to exchange from chip to chip with just a short distance, then 1 M baud is completely feasible.  Think of all the SPI and I2C devices that operate just fine at 1 MHz clock rate.

Over larger distances, you will start to have problems with noise when using logic level (plain 0 to 5V) signalling.  To use larger distances, you would add a transceiver to provide robust signalling, commonly RS-232 and less commonly RS-485.  With RS-232 you could run a mega bit at distances of 10's of feet.

The microprocessor clock speed will be the real limit.  With a hardware UART, the processor must load one byte to the UART every 10 bits (for N81).  So when you get to 1 M baud it will be a challenge for the 16 MHz processor to keep the UART supplied with data.  A new byte will be sent every 160 clock ticks, which is very few lines of code.  For a short burst of data, you might achieve that rate.  The message is, the processor will run out of speed before the UART is the limit.

Note, this all applies to **HardwareSerial**, software serial is very different.

body:
Back in the mists of time, the "gold standard" for remote keyboards (using a a telephone modem, and teletypes, if you remember those) was 9600 baud, initially achievable only over a dedicated phone line. Time moves on, slowly; technology advances, rapidly; and memory moves even more slowly than time (it seems). We can routinely communicate, at least over a several meters, at a couple of orders of magnitude faster than 9600 baud. What was once considered a gold standard is no longer gold, but still thought of as standard.

tl;dr: It's history, not technology.

body:
In addition to all the interesting answers, it worth mentioning that setting the serial speed to _XXX_ bits/s does not necessary imply _XXX_ bits/s on the hardware.

Clocks -- even quartz based -- are imperfect and subject to drift. In addition, as the serial clock is usually generated through a power-of-two pre-divisor and (integer) counter, all value cannot be accurately obtained given a base clock frequency. With the help of the start/stop bits, asynchronous serial communication may be tolerant to some clock drift. But this has limits.

For example, if your ATmega328PA is running at 1MHz, you can achieve 9600b/s at 0.2% of error. But at 14400b/s the error is -3.5% (actually communicating at 13900b/s). And at 28800b/s, the error is +8.5% (actually communicating at 31200b/s). All those figures are from _ATmega48PA-88PA-168PA-328PA datasheet, p200_.

This is _not_ an issue when two identical devices communicate together (as there are in fact communicating at the _same_ speed). It _might_ be an issue when communicating between different devices.

Increasing the base frequency does not necessary improve significantly the accuracy. For example, running the same ATmega328PA as above at 2MHz does not really give better results as those are mostly due to rounding errors. But running it 1.8432MHz give very accurate bps from 2400b/s up to 57.6kHz.


body:
When I started Arduino, I did not expect that everything must be contained in an infinite loop. I thought I could just write something like: motor start -> motor stop. But in actuality, what I get is motor start -> motor stop -> motor start -> ... forever and ever.

What is commonly done to stop a servo after it is in a desired position? Do I use `servo.write(desired position)` to keep it from turning? Do I detach the output wire?

What are some of the risks involved?

title: What is commonly done to stop a servo after reaching desired position?

Answers: 7

body:
A normal servo doesn't have a "go" function, it only has positional control. That is, whether you run `servo.write(90)` forever or once, the servo will go to 90 and continue to actively keep that position until you write another position. The only way to turn a servo  off is:

    servo.detach();

For a normal DC motor, you will need to turn it on then off and then have kind of state tracking in the loop to never turn it on again, using a variable or `millis()` etc.

Of course, if you want something to only run once, put it in `setup()` (maybe within a loop in setup for simple tasks).

Also, you can simulate ending the program by entering an infinite loop with `while(true){}` or `for(;;){}`.

body:
You do not "stop" a servo.

A servo is always running.  In a general sense, the servo is a control loop that takes as input a position target and applies force to hold at the requested target.  If you want the target to be maintained, then the servo must be running.

A servo motor contains electronics that are internally turning a DC motor on and off as necessary to hold the target position.  If the target does not match the current position, it turns on the motor to turn until the two match.  Once the output shaft reaches what you requested, the electronics inside the servo motor turn the motor "off".  Off meaning the DC motor is drawing little or no current.  The servo control loop is always running comparing the shaft position to a target.

If you powered off the entire servo motor, the position is not under control and could move.  For many applications if you unplugged the wires, the gears and motors apply enough friction that it would not turn.  But in general, you do not count on friction to make things work.

    Do I use...Servo.Write(desired position) to keep it from turning?

Yes.  To tell a servo to stay at one position, you can just keep sending it the same target.

But you do not have to Write() again and again.  If you want, you can keep track of what the last setting was and apply only when you have a change.   For example, you can code like this:

    if(position_target != position_last_set) {
      Servo.Write(position_target);
      position_last_set = position_target;
    }

Regardless of your code, under the hood, Servo is constantly transmitting the position target to the servo motor.

body:
I had the same problem.

I figured out that simply adding `myservo.write(90); delay(4000);` helps to stop motor.

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
                    // twelve servo objects can be created on most boards

    int pos =0;    // variable to store the servo position

    void setup()
    {

      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
    }

    void loop()

    {
      myservo.write(180);
        delay(8000); ////stops motor for 8 seconds
      for(pos = 180; pos>=90; pos-=1)// goes from 180 degrees to 0 degrees
      {
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15); // waits 15ms for the servo to reach the position

      }

        myservo.write(90);
        delay(4000); //stops motor for 4 seconds
      for(pos = 90; pos <= 180; pos +=1) // goes from 0 degrees to 180 degrees
      {                                  // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);      // waits 15ms for the servo to reach the position

      }

    }

body: A servo, by nature, is used to hold a position in the presence of disturbances trying to disturb that position. If you just need to move a mechanism that won't try to (or can't) back-drive the motor, your application ay be better served by a geared motor with a shaft encoder or position switches.

body:
This is a very brief explanation regarding servos.

The type of servo system that you are proposing is a none positional open loop system and is generaly used for accurate movement rate (controlled speed) . The loop in this case is usually a tachogenerator which sends a voltage (which is proportional to the motor speed) to a comparator which compares the tachogenerator voltage to the required adjustable voltage , the output of the comparator then regulates the motor speed, hence the required speed . this type of servo system will continue to run at the constant speed until  A the comparator signal is set to zero or B the motive power is reremoved from the moter ( switched off)   ----Point to point servo control , on the other hand ,, generally uses a position command which is verified with a signal from an encoder at which point the servo will stop until another command is issued from the stack ( EG. another position location or a dwell command (wait) or other )  the most common way to do this is to use gcode which has the ability to give full control of your servo system . If there is no encoding device then accurate servo position control is very difficult if not impossible.

body:
`myservo.detach();` is what you are looking for. Moving it to a location than detaching. This is good when you want to use it to control a servo and not have it continue to take power like when using a battery.  Here is a example.

    #include <Servo.h>
    Servo myservo;  // create servo object to control a servo

    void setup() {
      myservo.attach(9);
      // attaches the servo on pin 9 to the servo object
    }

    void loop() {
      myservo.attach(9);
      // attaches the servo on pin 9 to the servo object
      delay(15);
      myservo.write(1);
      // sets the servo position according to the scaled value
      delay(1000);
      // waits for it to get to the position
      myservo.detach();
      delay(1000);
      myservo.attach(9);
      // attaches the servo on pin 9 to the servo object
      delay(15);
      myservo.write(179);
      // sets the servo position according to the scaled value
      delay(1000); // waits for it to get to the position
      myservo.detach();
      delay(1000);

body:
The word _servo_ has a vague definition and can encompass many types of subcomponents. If you want **no-power position holding** using an electromagnetic motor, then there are four options:

* High viscosity grease
* Dash pot
* Very high gear ratio
* magnetic brake shoe / brake band

EDIT: There are some additional possibilities, but it's sort of an effect of some motor designs:

* Permanent magnet pole holding torque, or detent torque
* Permanent magnet drag torque

The high viscosity grease and dash pot have similar functions; providing a high static friction to resist motion, which then breaks away into movement. (A dash pot is essentially a toothed gear inside a toothed wall container, and which is permanently filled with a high viscosity fluid.)

However both of these will add to the motor load, and when they get hot they tend to become thin and runny and lose holding ability.

A high gear ratio increases the torque required to back-spin the motor. Though note, if any gearbox could have a perfectly frictionless lubricant, no amount of gear reduction could stop back-spinning.

So really this is similar to the thick grease and dash pot, but gear reduction allows just the normal thin lubrication to have enough static breakaway friction, to stop back-spinning.

A magnetic brake gives you active control over the static breakaway friction, and can allow for very high holding ability vs intermittent load spikes on the output shaft. Typically with the power off, a spring engages the brake to hold position with no power.

Note, there are two different kinds of braking: static position holding, and deceleration of a moving mechanism.

The second type both dumps heat into the brake pads and friction plate, and wears down the pads and friction plate. If the brake overheats, the pads usually disintegrate, and the brake now won't hold position.

Unless we're talking about large machinery, usually servo brakes are simple designs without replaceable parts. When the brake fails, you pull the whole thing off and replace it ... including possibly the entire servomotor and gearbox too.

For long service life with magnetic braking, you need to actively decelerate the load using the servo, and then once it has stopped moving, then engage the brake to just do the job of holding position.

Using a magnetic brake for no-power static load holding only, will look like this:

  * Power up motor, get current position, and begin actively holding position.
  * Energize brake to release it
  * Accelerate and move to new position
  * Decelerate motor and hold end position
  * Remove power from brake to engage it
  * Turn off power to motor

The motor is powered up and goes into position holding first, so that the load doesn't suddenly slip in either direction, in the instant between the brake being released and the servomotor then becoming active.

**EDIT #1**: For some permanent magnet motors, even with the power off there is a resistance to rotation because in certain positions, the magnets and the pole pieces more closely attract to each other, known as *detent torque*.

This pole positioning is like a low-energy valley and it takes a bit of force to overcome the magnetic attraction and move the rotor in either direction using an external torque.

You can feel this in some brushless fans and stepper motors, where if you rotate the shaft unpowered, it resists continuous motion, and there seem to be high resistance points that the rotor does not want to cross. When spun, the rotor rapidly slows, and may fall into a back-forth oscillation as it settles into one of the magnetic attractive wells.

This can be used to resist external torques without a brake, but making use if it requires stopping the rotor in one of the magnetic wells rather than a specific position you may want. But if combined with a gearbox, the exact specific stopping position may not matter too critically, and there may be a number of wells next to each other where the rotor can stop that provide an acceptable end-effector alignment.

**EDIT #2**: Permanent magnet drag torque is an effect of shorting all the power wires together. When this is done it takes considerably more force to rotate the shaft than with the stepper coil wires disconnected from each other.

This is because with the coil wires all connected together, when the rotor turns it acts as a generator and current flows through the coils. This current flow creates what is known as counter electromotive force (CEMF), which counters the magnetic field of the permanent magnet.

This CEMF can provide additional resistance against rotation when the servo is unpowered. Although CEMF won't prevent motion, it can help resist continued motion and provide instant deceleration when intermittent load spikes are applied that try to move the unpowered servo.

All of the above is also generally true for linear motor servos. Those don't have gear reduction, but the motion carriage can be lubed with thick grease, be equipped with a dash pot, and have position holding magnetic brakes.


body:
Every time that I open the Serial Monitor, my [Arduino Uno][1], seems to go back to `void setup()`. Is it a normal thing?

  [1]: http://arduino.cc/en/Main/ArduinoBoardUno

title: Why does my Arduino seem to reboot every time that I open Serial Monitor?

Answers: 1

body:
That is a normal feature of Arduinos, not an error. I find it mildly annoying sometimes, but it's nice for interactive programs that want some kind of menu message to be the first thing you see in the terminal.

If you want help disabling the auto reset, your options are detailed in *[Disabling Auto Reset On Serial Connection][1]*.

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


body:
Has anyone ever accidentally or inadvertently connected connected the supply port with the ground port with a wire?

Does Arduino provide internal safety to prevent the circuit board from shorting out?

title: Curious: What would happen if you connect 5V and GND port directly with a wire

Answers: 1

body:
There is some protection.

When powered from the USB port, the UNO has a 0.5 A fuse.  This is a self resetting fuse that will trip when the current is high, and reset when it cools back down.  These fuses are great for peripherals that might be exposed to occasional "oops".  See the [data sheet][1] for more details of the part on the UNO.

When powered from the PWRIN plug, the voltage regulator provides some protection.  The device on the UNO contains over current and over temperature protection, which is common for regulators such as this.  The device will get very hot, and the protection will activate to limit the current (see [datasheet][2] for details).  By design, the regulator chip should protect itself from being destroyed.

So to first order, if you by mistake connect the +5 on the header to GND, all that will happen is Vcc will be reduced to near zero Volts.

The caveat is that a small spark can be generated when you make this short to ground, especially if you have a bunch of capacitors on Vcc.  That spark may cause a voltage transient that could damage a pin.

  [1]: https://www.bourns.com/pdfs/mfmsmf.pdf
  [2]: http://www.onsemi.com/pub_link/Collateral/NCP1117-D.PDF


body:
I'm trying to control a single motor.

If I press 'a', then motor 1 should turn to 0, if I press 's', then motor 1 should turn to 180

    #include <Servo.h>

    char key = 0;
    const unsigned int BAUD_RATE = 9600;

    Servo Servo_0;

    void setup()
    {

      Servo_0.attach(0);
      Servo_0.write(0);

      Serial.begin(BAUD_RATE);

     // Serial.println("      Arduino Serial Servo Control");
     // Serial.println("Press < or > to move, spacebar to center");
     // Serial.println();

    }

    /*
    a - 97
    s - 115
    d - 100
    f - 102
    */

    void loop() {

      if(Serial.available()>0)
      {
          key = Serial.read();
          Serial.print("I received: ");
          Serial.println(key, DEC);

         if(key == byte(97))
         {

           Serial.print("Turning Motor 1 to 0 deg");
           Servo_0.write(0);

         }
         else if(key==byte(115))
         {
           Serial.print("Turning Motor 1 to 180 deg");
           Servo_0.write(180);

         }

         delay(1000);
    }

But what is happening is that the motors are barely turning after I enter the key onto the Arduino monitor interface. Can anyone diagnose as to what might be happening?

title: Keyboard Control Not Working As Intended

Answers: 1

body:
The problem I see is that your servo is attached to pin 0.

Pins 0 and 1 are used by arduino unos and megas for serial communication, so you can't output to a motor and send/receive serial at the same time. Try moving the servo to pin 3 and see what happens.

In response to your comment, any character sent from any terminal (or other piece of hardware) will work; you do not need to use Processing to communicate with an arduino.


body:
I'd like to build a simple GPS system. It should be very little. For the software side, I will build an API, so from my PC/smartphone/whatever else I could ask the GPS system where it is located (I think Google provides this kind of feature).

How can I do this? My main problem is the GPS and the its building. I'd like to build the smallest thing possible, because I have to hide it. My idea is to hide this GPS system in my bike: I'd like to locate my bike if someone stole it. As you can see, internet is a problem.

I'm not asking to design anything. I would only know what I need to build a basic GPS system that has just the feature described. What do I need? Is it possible to do it? Does GPS require Internet connection? I would know if I could make it or not without internet access.

title: Building a gps system

Answers: 1

body:
***"Is it possible to do it?"***

Well... everything is possible :-)

***"Does GPS require Internet connection?"***

GPS doesn't require internet. A GPS receiver (e.g. http://www.modulestek.com/prodts/GPS/Mars740-mini/Mars740-mini_SPEC.pdf) is connected to the reading unit via USB or a RS232 interface. The protocol is very simple. However it only provides latitude and longitude. If you want to have an address, map data is required (for *this* you would need internet - or a large memory).

And of course such a system requires good signals from the GPS satellites.

***"What do I need?"***

First you need a GPS receiver (see above).

Second, you need a microcontroller unit which runs your application and does all the control of the external units.

Third, you need a GSM module (e.g. http://www.exp-tech.de/Shields/Wireless/GSM-GPRS/adafruit-fona-mini-cellular-gsm-breakout-sma.html) to send a message.
Don't forget the antenna for connection to the mobile communication network.

Fourth, you need a power supply. Ideally it has a battery which can be reloaded when driving.

As you may see, if you put all this together you are far from the "smallest thing possible".

Actually any modern smartphone could be enough. Mount it "invisible" under your saddle, connect it to a bike charger, find the proper App and that's it - although it might not be the smallest solution.

I don't know any, but I'm sure there *are* products off the shelf that fulfil your requirements, designed and developed by experienced engineers, and thus smaller and maybe cheaper than what you ever could achieve on your own.


body:
I was playing around with my Arduino Uno R3 board with Sublime Text 2 & 'Stino' as IDE

I am not sure if it is my code is the problem or if I broke something...

I pressed upload while another sketch didn't finish uploading, even the original Arduino IDE can't upload new sketches anymore!

This is my code:

    // singleServo.ino

    #include <Servo.h>

    Servo servo;
    const int button = 2;
    const int led = 13;
    const int buzzerPin = 10;
    const int duration = 180;

    int stateLED = LOW;
    int previous = LOW;

    void setup() {
     pinMode(led, OUTPUT);
     pinMode(button, INPUT);
     pinMode(buzzerPin, OUTPUT);
     Serial.begin(9600);
    }

    void loop() {
     int stateButton;

     stateButton = digitalRead(button);

     if (stateButton == LOW && previous == LOW) {
      if (stateLED == HIGH)
      {
       stateLED = LOW;
       initAction(duration);
      }
      else
      {
       stateLED = HIGH;
      }
     }

     digitalWrite(led, stateLED);
     previous = stateButton;
     servo.detach();
    }

    void initAction(int time_iA){
     tone(buzzerPin, 523, 200);
     delay(200);

     shiftServo(180, time_iA);

     tone(buzzerPin, 262, 200);
    }

    void shiftServo(int angle, int time_sS) {
     servo.attach(9);
     delay(500);
     int position;

     for(position=0; position <= angle; position += 1)
     {
      servo.write(position);
      delay(time_sS / 180);
      Serial.println(servo.read());
     }
     // for(position=angle; position >= 0; position -= 1)
     // {
     //  servo.write(position);
     //  delay(time_sS / 90);
     // }
    }

I am a newbie with all things Arduino - Please help!

EDIT:
After rebooting the system (Ubuntu Linux 14.04) everything was working just fine again!
But I'm going to take the serial functions out too.

title: Arduino Uno 3: Stuck at 'uploading...' sketches

Answers: 4

body:
You have to wait for the first and all other uploads to fail.

If you are not sure, a reboot is the most reliable solution.

Also note that if your sketch sends a lot of data over serial, a manual reset of the board may be needed.

body:
I've got the same problem on my Ubuntu.
Eventually, I was stuck at every uploading, even after unplugging+replugging the device.

Killing all avrdude process, remove the problem.

    sudo killall avrdude

or with new IDEs:

    sudo killall avrdude_bin

body:
I had this happen to me on an UNO R3. I solved the issue by disabling Bluetooth on my laptop. It was causing a conflict on COM5.

I had ruled out the board, cable, and IDE. Finally noticed in Device Manager that COM5 had entries (one being the Arduino and the other being Bluetooth)

Hope that helps someone else that might have this issue in the future.

body:
I had the same problem with arduino uno r3 on win10.
 The solution was simple:
1. open the task manager (Ctrl + Shift + Esc)
2. stop all open COM processes
 and the arduino upload worked again.


body:
I would like to control 16 motors with a servo shield, however, I have found scant to nothing sample code online. The one I was able to find is...strange to say the least

https://github.com/kachok/arduino-libraries/blob/master/Adafruit_PWMServoDriver/examples/servo/servo.pde

    #include <Wire.h>
    #include <Adafruit_PWMServoDriver.h>

    // called this way, it uses the default address 0x40
    Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

    #define SERVOMIN  150 // this is the 'minimum' pulse length count (out of 4096)
    #define SERVOMAX  600 // this is the 'maximum' pulse length count (out of 4096)

    uint8_t servonum = 0;

    void setup() {
      Serial.begin(9600);
      Serial.println("16 channel Servo test!");

      pwm.begin();

      pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
    }

    void loop() {
      // Drive each servo one at a time
      Serial.println(servonum);
      for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++) {
        pwm.setPWM(servonum, 0, pulselen);
      }
      delay(500);
      for (uint16_t pulselen = SERVOMAX; pulselen > SERVOMIN; pulselen--) {
        pwm.setPWM(servonum, 0, pulselen);
      }
      delay(500);

      servonum ++;
      if (servonum > 15) servonum = 0;
    }

Im used to controlling motors using servo.write, but with the shield, it doesn't seem very intuitive as to how I should control the motors. How does Servomin and Servomax map to 0 degree and 180 degree?

Someone please elucidate!

title: Sample code for using adafruit servo shield?

Answers: 2

body:
Adafruit's guide for the shield is here:
https://learn.adafruit.com/adafruit-16-channel-pwm-slash-servo-shield/using-the-adafruit-library

I'm not sure how much the library you linked and the official one differ. They seem to be used the same way, but you should probably stick with the official one.

You are going to have to use setPWM(pin, on, off) since the arduino is not generating the signals like it would with servo.write(), the arduino is sending commands to a chip on the shield that generates the signals for you.

Adafruit recommends calibrating SERVOMIN and SERVOMAX yourself with whatever brand of servo you plan on using, but those default values should be pretty close.

body:
The 2 values SERVOMIN and SERVOMAX define the pulse length, which tells the servo what angle to go to.  The example uses 150 for SERVOMIN and 600 for SERVOMAX.  When running the code, the servos travel 180 deg.  I changed the code to read:

    #define SERVOMIN  262 // this is the 'minimum' pulse length count (out of 4096)
    #define SERVOMAX  488 // this is the 'maximum' pulse length count (out of 4096)

and the servo now moved only 90 deg. centered at the same place as the original code.

the tutorial provided by Adafruit describes a way to define the movement by angle:

    pulselength = map(degrees, 0, 180, SERVOMIN, SERVOMAX);

found here:  https://learn.adafruit.com/adafruit-16-channel-pwm-slash-servo-shield/using-the-adafruit-library

hope this helps


body:
So recently my company threw away some rather large and reasonably old laser printers. One was a LaserJet 9050dn the other was a Epson printer/scanner combination. Being a little industrial I thought let me salvage them and brought them home.

I managed to salvage a couple of stepper motors. However I am having huge trouble is getting them to step properly. So lets get into the details.

Components used:

 - 1x Freetronics eleven (Arduino Uno compatbile)
 - 1X H-Bridge driver shield(Freetronics rated for 40V/2A max).
 - 1X Old scanner power supply which has a output of 24V/2A.

Currently there are two stepper motors I am interested in using. They have the following part numbers:

 - 1X MITSUMI M42SP-4N
 - 1X Minebea-Matshushita 17PM-J212-G2ST

Just to keep this short I am going to focus on the Minebea-Matshushita 17PM-J212-G2ST. I have been unable to find exact matches on these serial numbers when looking for datasheets but I have managed to find the following sheets on the net.

 1. [Minebea-Matshushita 17PM-K][1] datasheets found from Minebea. However I cant match the model exactly.
 2. [Minebea Stepper Motor Information & Specifications][2] also carries some useful information.

So it appears that these are 24V steppers(in both cases). The Minebea-Matshushita 17PM-J212-G2ST appears to have a step angle of 1.8 degrees which should give me 200 steps per revolution. I have not been able to find the current needed to drive this motor but judging by the looks of things it will be between 0.8A and 1.2A.

I then used my multimeter to find the pairs of wires. It has 4 wires coming out (Bipolar motor I guess). The colours of the wires are red, yellow,orange and blue. First pair was red and yellow with red being positive/anode. Second pair orange blue with orange positive/anode side.

I wired my power supply into my h-bridge and started using the [recipe and quickstart][3] found at the freetonics site. This is where the frustration begins. When asking the motor to do one complete revolution(360 degrees) it does more than 360 degrees at times and other times it does less. I tied a cable tie to the motor so I can confirm it.

So I tried the one-step-at a time sketch to see if I can troubleshoot it. Here is what I have noticed. The steps are mostly correct one step at a time clockwise however every now and again it will jump counter clock wise and then clock wise again. I suppose you can call it a jitter.

Interestingly both these motor show the same behaviour pretty good step action just every 25 degrees or so a jitter. So I suspect that this might not be bi-polar motors but uni-polar? [This blog][4] entry points me to believe that this might be the case. However the datasheet in this case points to a M42SP-7.

So my question would be simple how do I figure out if they are bi-polar or uni-polar?

Can someone help me with a proper datasheet?

Any tips would be really appreciated.

Update:

Note that I can get both motors to step clock-wise and counter clock-wise I just cant get them to do a whole 360 degrees without a jitter. Based on the [Wiring Mitsumi stepper ( M42sp-4np) with arduino blog ][4] it appears that the Mitsumi is a uni-polar motor with a 2-2 phase excitation. What stumps me is that the wires are paired thus it must be bi-polar?

So last night I tried 2-2 phase excitation with the MITSUMI M42SP-4N and it appears to be solve the problem with this motor in particular. From early observations the motor now steps without jitter, however it was late so I will need to confirm this.

I was previously using 1-1 phase excitation i.e.

    Step number: 1a 1b 2a 2b
    1            1  0  0  0
    2            0  0  1  0
    3            0  1  0  0
    4            0  0  0  1
    5            1  0  0  0

When using 2-2 phase excitation I get a more steady step however this needs to be confirmed a bit more:

    Step number   1a 1b 2a 2b
    1             1  0  0  1
    2             1  0  1  0
    3             0  1  1  0
    4             0  1 0  1
    5             1  0  0  1

Just some added observations. The headache continues but I am learning a LOT about steppers motors.

Update:

Not a 2-2 phase excitation these are definitely bi-polar. I am currently watching the Minebea-Matshushita 17PM-J212-G2ST do 360 degrees both clock and counter-clockwise. I hooked them up to a 12V/1A power supply both motors are running smoother and cooler and stepping relatively jitter free. I suspect the whole issue is a lack of a proper data-sheet.

Will update as things progress and once solved add pictures and sketches so the next lucky sod wont loose as much hair as me.

Update:

Thanks to Chris who made me look at the sketch in detail again. These motors seem to have a minimum rpm of sorts. I was trying to go for a really slow rpm under 5rpm at this speed these motors show the jitter effect. However when moving the speed to 10rpm and up no jitter.

  [1]: http://www.eminebea.com/en/product/rotary/steppingmotor/hybrid/standard/data/17pm-k.pdf
  [2]: http://www.theprojectasylum.com/electronicsprojects/componentdata/minebeasteppedatacirca1999.html
  [3]: http://www.freetronics.com/pages/hbridge-motor-driver-shield-quickstart-guide#.VA1jNfmvUrW
  [4]: http://josafatisai.blogspot.com.au/2013/04/wiring-mitsumi-stepper-m42sp-4np-with.html

title: Salvaged Stepper Motor Blues

Answers: 1

body:
Keeping this here for future reference. It appears these motors have a minimum RPM of sorts and running them on a lower RPM causes the jitter effect described above.

Like I mentioned in the updates when running at 10RPM or above these motors seem to perform very nicely.

Update: I recently bought a ADAFruit motorshield and I am getting much more stable results with this shield and the stepper motors. I am even running them off 6V and they are working perfectly even at lower rpm.


body:
I have found bunch of information about how to hack an RC car with a PCB; and how to control an Arduino from a receiver. Also how to run a servo from an Arduino, but I'm looking for a way to make an Arduino send signals to a 27 MHz 3 channel receiver, Using three potentiometers to decide servo location.

Is there any information about this somewhere? - I have an old transmitter lying around if needed.

Links, pointers - anything is welcome.

[It does not have to be 27 MHz AM, it is just what I have on the shelve, without investing in new gear]

title: Is it possible to make an Arduino send signals to an RC receiver?

Answers: 3

body:
The easiest way would be to open up the transmitter, desolder the potentiometer used for the stick and solder the cables to Arduino's PWM instead. Then use `analogWrite()` to simulate stick position. If your TX would use that potentiometer with more than 5 V, you'll not able to use full ppm values. A RC or a RCL filter may be needed between PWM output and RC input to "smooth" the PWM into an analog signal. There are a lot of online calculator to find good *R, C and L* to polish your signal.

This assuming your TX is using potentiometer like stick; if it is a really cheap one, it may be using *buttons*. If this is the case, then you connect a transistor in parallel with the button, that way you can keep manual button.

Another way is to program your Arduino to look for ppm signal (normally 50 Hz with high starting value with a period from 500 to 2000 µs) and then look for this signal into the Tx PCB; if found cut the trace of the generator and solder your cable from Arduino. I've seen around a lot of libraries outputting ppm (they are used on drones to mix single ppm channel back to PPM to use only one pin from logic board without having to hack standard RX

body:
Many RC TX have a remote connector where you can input the signal and not having to open them.

In any case, 27 MHz RC are a train of pulses, of variable width, from 2 to 20 ms each, one for each channel, flowed by a 20 ms pause.

This can be recreated in a single output pin.

body:
Consider the methods of US patent 9,996,079 (linked URL):

"Radio frequency device detection and intervention": [US 20180081354 A1][1]

After reverse engineering the badly written descriptive, you should be able to come up with an Arduino board set.

P.S. Try not to copy the whole patent.

  [1]: http://patents.com/us-9996079.html


body:
First things first, I have found some solutions to this problems but they all involved for printing to serial monitor. I am trying to take the information from the sensors and write them to an sd card. Here is my code so far:

    //-----Writes Data to SD Card-----//
    if(!Data) {
        u8g.firstPage();
        do {
           drawFileError();
        } while( u8g.nextPage() );
        while (1);  // don't do anything more:
    }

    dcounter++;
    if (dcounter=1){

        Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
        Data.println(Header);
        Data.print(strutcDate + "  ");
        Data.print(strutcTime + "  ");
        Data.print(strgpsStatus + "  ");
        Data.print(strmodeIndicator + "  ");
        Data.print(strlatitude + "  ");
        Data.print(strlongitude + "  ");
        Data.print(strspeedOverGnd + "  ");
        Data.print(strcourseOverGnd + "  ");
        Data.print(t);
        Data.print("  ");
        Data.print(f);
        Data.print("  ");
        Data.print(h);
        Data.print("  ");
        Data.print(hi);
        Data.print("  ");
        Data.print(press_pKa);
        Data.print("  ");
        Data.println(str);
        Data.close();
    } else{
        Data.print(strutcDate + "  ");
        Data.print(strutcTime + "  ");
        Data.print(strgpsStatus + "  ");
        Data.print(strmodeIndicator + "  ");
        Data.print(strlatitude + "  ");
        Data.print(strlongitude + "  ");
        Data.print(strspeedOverGnd + "  ");
        Data.print(strcourseOverGnd + "  ");
        Data.print(t);
        Data.print("  ");
        Data.print(f);
        Data.print("  ");
        Data.print(h);
        Data.print("  ");
        Data.print(hi);
        Data.print("  ");
        Data.print(press_pKa);
        Data.print("  ");
        Data.println(str);
        Data.close();
    }

two questions: is it possible for me to reduce this chunk of code into something smaller? is there a way to decrease print time?

Edit: Ahh I see, the problem with my code is that the last few values are floats.Any way to shorten those as well, or do i need to do it individually? I do agree about the adding string parts.

title: Optmizing print code when writing to file, and reducing print time

Answers: 3

body:
Maybe this helps with speed. It will however use more memory, so use with caution.

    Data.println(Header);
    Data.println(strutcDate + " " + strutcTime + "  " + strgpsStatus + "  " + strmodeIndicator + "  " + strlatitude + "  " + strlongitude + "  " + strspeedOverGnd + "  " + strcourseOverGnd + "  " + t + "  " + f + "  " + h + "  " + hi + "  " + press_pKa + "  " + str);
    Data.close();

body:
I would analize what I want to write, extrapolate all numeric value, then create a structure that hold numeric value. So at every write I would write the structure (it is a binary write, so use fixed byte size) followed by all others string(or even place string in different file, but may turn out harder to manipulate or fix in case of problem).

Then to read it you'll need to read back the structure, followed by eventual know number of string. If string may be of unknown number,, just put the number of following string into the struct. Outside string, as you can see, you need no special char to signal the end of chunk of data :)

Unrelated: please, remove all println in the if rather than the header as they are equal to the else; then remove the else statement (but not the else body!) That way the if will open file and add header, and then the code will always add the rest of code. It would be a shame if you edit your else branch and forgot the if, or viceversa. Code style matters, trust me

body:
First of all, the only difference between the two parts of the "if" statement is that, the first time, it prints the header. Instead of that code, you could do this:

    //(Include the top part of the code here...)
    dcounter++;
    if (dcounter=1){
        Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
        Data.println(Header);
    }
    Data.print(strutcDate + "  ");
    Data.print(strutcTime + "  ");
    Data.print(strgpsStatus + "  ");
    Data.print(strmodeIndicator + "  ");
    Data.print(strlatitude + "  ");
    Data.print(strlongitude + "  ");
    Data.print(strspeedOverGnd + "  ");
    Data.print(strcourseOverGnd + "  ");
    Data.print(t);
    Data.print("  ");
    Data.print(f);
    Data.print("  ");
    Data.print(h);
    Data.print("  ");
    Data.print(hi);
    Data.print("  ");
    Data.print(press_pKa);
    Data.print("  ");
    Data.println(str);
    Data.close();

Like already mentioned, you can append strings with the `+` operator. This would be the final code then:

    //(Include the top part of the code here...)
    dcounter++;
    if (dcounter=1){
        Data = SD.open("Data.txt", O_CREAT | O_APPEND | O_WRITE);
        Data.println(Header);
    }
    Data.println(strutcDate + " " + strutcTime + "  " + strgpsStatus + "  " + strmodeIndicator + "  " + strlatitude + "  " + strlongitude + "  " + strspeedOverGnd + "  " + strcourseOverGnd + "  " + t + "  " + f + "  " + h + "  " + hi + "  " + press_pKa + "  " + str);
    Data.close();

FYI, it doesn't seem like you should close the stream every iteration at the end since you only open it the first time.


body:
I am trying to read/send CanBus messages using a Arduino Due.

As of now I have used https://github.com/collin80/due_can library to setup my Can Bus interface.

I am using Vector Software CanAylzer to see what CAN message are being received.

This is where I have my issue.
Although the CanAylzer software is being able to detect Can Messages on the line it gives be a Bit error on bit position 119. All the fields of relevance for me ID,Data etc seem to be reported fine.

Here is a snapshot of the CanAylzer Error Frame. Below is my Arduino code . Any help would be awesome.
![enter image description here][1]

Here is the ino code:

    // Arduino Due - CAN Sample 1
    // Brief CAN example for Arduino Due
    // Test the transmission from CAN0 Mailbox 0 to CAN1 Mailbox 0

    #include <Arduino.h>
    #include "variant.h"
    #include "due_can.h"

    #define TEST1_CAN_TRANSFER_ID    0x18FF0017 //random 29 bits
    #define TEST1_CAN0_TX_PRIO       1
    #define CAN_MSG_DUMMY_DATA       0xABC

    // CAN frame max data length
    #define MAX_CAN_FRAME_DATA_LEN   8

    // Message variable to be send
    uint32_t CAN_MSG_1 = 0;

    void setup()
    {

       // start serial port at 115200 bps:

       Serial.begin(115200);
       Serial.println("Program Started");

    }

    void loop(){

       CAN_FRAME frame1, frame2;
       // say what you got:
       Serial.print("Sent Value: ");
       Serial.println(CAN_MSG_1, DEC);

       // Initialize CAN0 and CAN1, baudrate is 250kb/s
       CAN.init(CAN_BPS_250K);
       CAN2.init(CAN_BPS_250K);

       //Initialize the definitions for the frames we'll be sending.
       //This can be done here because the frame never changes
       frame1.id = TEST1_CAN_TRANSFER_ID;
       frame1.length = MAX_CAN_FRAME_DATA_LEN;
    //Priority
       frame1.priority = 0;
    frame1.rtr = 1;
       //Below we set the 8 data bytes in 32 bit (4 byte) chunks
       //Bytes can be set individually with frame1.data.bytes[which] = something
       frame1.data.low = 0xAFAFAFAF;
       frame1.data.high = CAN_MSG_DUMMY_DATA;
       //We are using extended frames so mark that here. Otherwise it will just use
       //the first 11 bits of the ID set
       frame1.extended = 1;

       CAN.sendFrame(frame1);
       while (1) {
       }
    }

###Update###
Ok so here are the printed(via serial port) values of various registers. I don't think it is a problem with the values in the registers. I have cross referenced these with the SAM3X/A (on the due) Micro-controller manual (chapter 41, pertaining to the CAN). The only one I am fishy about is the baudrate one.

    Serial Port Initialized
    ******START OF LOOP ******
    No of Sent frames: 1
    <><><><><><><><><>><><><><>
    CAN_SR:( Status Register)
    Bits 3 | 2 | 1 | 0
         0 | 0 | 0 | 0

    Bits 7 | 6 | 5 | 4
         0 | 0 | 0 | 0

    Bits 11 | 10 | 9 | 8
          0 | 0  | 0 | 0

    Bits 15 | 14 | 13 | 12
         0  | 0  | 0  | 0

    Bits 19 | 18 | 17 | 16
         0  | 1  | 1  | 0

    Bits 23 | 22 | 21 | 20
         1  | 0  | 1  | 0

    Bits 27 | 26 | 25 | 24
         0  | 1  | 0  | 0

    Bits 31 | 30 | 29 | 28
         0  | 1  | 0  | 0

    <><><><><><><><><>><><><><>
    #####END OF LOOP ######

    Serial Port Initialized
    ******START OF LOOP ******
    No of Sent frames: 1
    <><><><><><><><><>><><><><>
    CAN_MR: (Mode Register)
    Bits 3 | 2 | 1 | 0
         0 | 0 | 0 | 1

    Bits 7 | 6 | 5 | 4
         0 | 0 | 0 | 0

    Bits 26 | 25 | 24
         0  | 0  | 0
    <><><><><><><><><>><><><><>
    #####END OF LOOP ######

    ******START OF LOOP ******
    No of Sent frames: 4
    <><><><><><><><><>><><><><>
    CAN_MID7: (Message ID Register Mailbox 7)
    Bits 3 | 2 | 1 | 0
         0 | 1 | 1 | 1

    Bits 7 | 6 | 5 | 4
         0 | 0 | 0 | 1

    Bits 11 | 10 | 9 | 8
         0  | 0  | 0 | 0

    Bits 15 | 14 | 13 | 12
         0  | 0  | 0  | 0

    Bits 19 | 18 | 17 | 16
         1  | 1  | 1  | 1

    Bits 23 | 22 | 21 | 20
         1  | 1  | 1  | 1

    Bits 27 | 26 | 25 | 24
         1  | 0  | 0  | 0

    Bits 31 | 30 | 29 | 28
         0  | 0  | 1  | 1

    Serial Port Initialized
    ******START OF LOOP ******
    No of Sent frames: 1
    <><><><><><><><><>><><><><>
    CAN_ECR: (Error Count Register)
    Bits 3 | 2 | 1 | 0
         0 | 0 | 0 | 0

    Bits 7 | 6 | 5 | 4
         0 | 0 | 0 | 0

    Bits 11 | 10 | 9 | 8
         0  | 0  | 0 | 0

    Bits 15 | 14 | 13 | 12
         0  | 0  | 0  | 0

    Bits 19 | 18 | 17 | 16
         0  | 0  | 0  | 0

    Bits 23 | 22 | 21 | 20
         1  | 0  | 0  | 0

    Bits 27 | 26 | 25 | 24
         0  | 0  | 0  | 0

    Bits 31 | 30 | 29 | 28
         0  | 0  | 0  | 0

    <><><><><><><><><>><><><><>
    #####END OF LOOP ######

Lastly and most importantly in my opinion:

    Serial Port Initialized
    ******START OF LOOP ******
    No of Sent frames: 1
    <><><><><><><><><>><><><><>
    CAN_MSR7: (CAN Message Status Register Mailbox 7)
    Bits 3 | 2 | 1 | 0
         0 | 0 | 0 | 0

    Bits 7 | 6 | 5 | 4
         0 | 0 | 0 | 0

    Bits 11 | 10 | 9 | 8
          0 | 0  | 0 | 0

    Bits 15 | 14 | 13 | 12
         0  | 0  | 0  | 0

    Bits 19 | 18 | 17 | 16
         1  | 0  | 0  | 0

    Bits 23 | 22 | 21 | 20
         0  | 0  | 0  | 0

    Bits 27 | 26 | 25 | 24
         0  | 0  | 0  | 0

    Bits 31 | 30 | 29 | 28
         0  | 0  | 0  | 0

    <><><><><><><><><>><><><><>
    #####END OF LOOP ######

and the Baud rate register

    ******START OF LOOP ******
    No of Sent frames: 1
    <><><><><><><><><>><><><><>
    CAN_BR:
    Bits 3 | 2 | 1 | 0
         0 | 0 | 0 | 1

    Bits 7 | 6 | 5 | 4
         0 | 0 | 0 | 1

    Bits 11 | 10 | 9 | 8
         0 |  0  | 1 |  0

    Bits 15 | 14 | 13 | 12
         0  | 0  | 1  | 0

    Bits 19 | 18 | 17 | 16
         1  | 0  | 0  | 1

    Bits 23 | 22 | 21 | 20
         0  | 0  | 1  | 0

    Bits 27 | 26 | 25 | 24
         0  | 0  | 0  | 0

    Bits 28
         0
    <><><><><><><><><>><><><><>
    #####END OF LOOP ######

You can find what all the register bits details on Atmel's website or leave some way for me to email the documentation to you.

Any Help would be much appreciated!

##Update 2:##
I have attached 2 different Oscilloscope readings and deconstructed the entire binary representation of the Can message manually. Furthermore I calculated the associated CRC's of the two different messages, and then compared them to the ones the hardware created and found them(hardware ones) to be incorrect. I have provided a link to [Google Drive][2] where the results from the Oscilloscope can be found.

PS: the messages I used had in one 7 A's(hex, i.e 28bits) for the ID and 16 A's for the Data field.
The second one had 7 C's for the Id and 16 C's for the Data field.

Both are 2.0B can extended frames.![enter image description here][3]![enter image description here][4]

  [1]: https://i.stack.imgur.com/LMLWi.png
  [2]: https://drive.google.com/folderview?id=0BwRY4KO_k7sUdmN5RWJVZnFHSVE&usp=sharing
  [3]: https://i.stack.imgur.com/eFw36.png
  [4]: https://i.stack.imgur.com/hEVhK.png

title: Aduino Due Can messages

Answers: 0


body:
I've researched how to attach multiple buttons to a single analog input using a resistor network. Instructables has a good lesson on this: http://www.instructables.com/id/How-to-access-5-buttons-through-1-Arduino-input/?ALLSTEPS

My requirement is that I need to attach an interrupt to buttons (ie the analog input) before reading the analog value, so that all the buttons can act as a trigger.

This works for voltages in the higher range, but not in the lower range (the trigger input waits for a RISING edge).

Can any one suggest a circuit that steps a >0V+ to +5V input to a +5V output so that any button push would trigger the input?

Otherwise, does anyone have other suggestions on how to use triggers for each button?

title: Multiple Buttons on Single Analog Pin and Trigger Pin Arduino Uno

Answers: 3

body:
Use the analog comparator in the ATmega328P to trigger an interrupt once the input voltage rises enough to indicate a button press.

Connect the analog network to both the analog input and D6.

If your lowest analog voltage is not greater than 1.2V then apply a voltage greater than 0V but more than 40mV less than your lowest analog voltage to D7. If you have *not* connected the voltage then configure the comparator to use the internal bandgap reference (`ACSR |= _BV(ACBG)`).

Enable the comparator interrupt and capture on a rising edge (`ACSR |= _BV(ACIE) | _BV(ACIS1) | _BV(ACIS0)`).

Disable the digital input on D6 (AIN0), and on D7 (AIN1) if connected to a voltage reference (`DIDR1 |= _BV(AIN0D)`, `DIDR1 |= _BV(AIN1D)`).

Write an ISR that does what you want on comparator trigger (`ISR(ANALOG_COMP_vect) { ... }`).

Now go back and read all that ***three more times*** until you understand it. As always, see the ATmega328P datasheet for details.

body:
Considering the fact that from a *functional point of view*, you just want **to have more digital inputs, I would propose to use a `Parallel-In Serial-Out Expander`**, (e.g. `CD4021B` or `74HC165`).

This IC (i.e. `74HC165`) has 8 digital inputs, that can be 'shifted' and send to your Arduino using just 2 wires. Arduino has a built-in function for this (i.e. `shiftIn`) to read the input and to convert it to a byte.

If 8 inputs is not enough, then you can chain multiple IC to create 16, 24 ... digital inputs.

There is an official [tutorial for the CD4021B][1].

I don't know if this is a requirement, but if you want to register **multiple key-presses at the same time**, then this is a really good strategy.

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

body:
I really do not know your level of experience, so please, ignore this if not applicable;
Most cases of a push button will not need an interrupt. It is a human pushing the button and so precise timing is no where close to needing an interrupt.  You would only need an interrupt if you wanted to actually interrupt some looping code. And since timing (of a human by definition) is not that great, simply checking for a button press in your looping code will always be good enough.
That being said, the common resistor networks you have read about will work adequately.

    psuedo code;
    void loop()
    {
      int btn = analogRead(pin);
      if (btn > pin1Level)
      {
        if (btn > pin5level) DoPin5();
        else if (btn > pin3level) DoPin3();
        else DoPin1();
      }
      doOtherStuff();
    }


body:
Ok, serialEvent "runs after loop()" and it is not an interrupt.
AS far as I know main() has two functions  - setup and "infinite" loop.
So where does serialEvent comes in?

And if I do not want loop()  to run and use only setup than  I cannot use serialEvent.

title: How does serialEvent gets into main()?

Answers: 1

body:
Yes you are correct, the event handlers will not do anything in setup. Main runs "setup()", then loops infinity through "loop()", but gives the serial event handlers a chance to run in between. The actual main that runs on the arduino is this:

    int main(void)
    {
     init();

     initVariant();

    #if defined(USBCON)
     USBDevice.attach();
    #endif

     setup();

     for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
     }

     return 0;
    }

this is found (on linux at least) in arduino/hardware/arduino/avr/cores/arduino/main.cpp

"serialEventRun()" is in HardwareSerial.cpp, but is not very interesting.

To be clear, Serial itself will still work fine in setup(). If you want to use the same event handler function, all you have to do is call "serialEventRun()" yourself periodically.


body:
I have two problems in the code below. This ACS712 sensor is too noisy so I am not getting the count value properly, since I need approximate reading I consider curve is linear, and calculate the slope.

My problems are:

1. When I take a 10 sample average, the first value it reads properly, i.e. 512 is count value, other value taking as 0. I don't why.

2. Once current exceeds 1A, my relay output should go low. Once it goes low it waits for 30s & again it must high the relay high. Since I am checking output in loop, it making high & low without waiting for 30s. Can someone help me how can I do this?

If you used without MStimer, the `newaverage` values print 512 which is my reference, but for other 9 values print `newaverage` as zero.

    #include <MsTimer2.h>

    #define RELAY1  3
    #define RELAY2  4

    int num_readings=10;
    //int total;
    int readings[10];
    int index;
    float CS_Value;
    static float Output_Current;
    float mad;
    float madstd;
    float lowlimit ;
    float highlimit;
    int count;
    int total;
    int reading;
    static int newaverage;
    unsigned long Wait_Time=30000;
    unsigned long Current_Time;
    static int Tripped_Flag=0;

    float standard_deviation(int avg1) {
      total = 0;
      for( int i=0; i<num_readings; i++)
        total = total + pow((avg1 -readings[i]), 2);
      return sqrt(total/num_readings);
    }

    int  average()
    {
      total = 0;
      for( int i=0; i<num_readings; i++)
      {
        total = total + readings[i];
      }
      return total/num_readings;
    }

    void TakeReading()
    {

      reading = analogRead(A0);
      readings[index] = reading;
      index = index + 1;

      if (index >= num_readings)
      {
        index=0;
        int avg = average();
        float std = standard_deviation(avg);
        madstd = mad * std;
        lowlimit = avg - madstd;
        highlimit = avg + madstd;

        total=0;
        count=0;
        for(int i=0; i<num_readings; i++) {
          // Check if the values of the readings are within the limits.
          if(readings[i] >= lowlimit && readings[i] <= highlimit) {
            total = total + readings[i];
            count = count + 1;
          }

        }

        // compute the new average
        newaverage = total/count;
        // send it to the serial port (as ASCII digits)

        Serial.print("Newaverage:");
        Serial.println(newaverage, DEC);
        Output_Current = 0.0336666666667*newaverage - 17.17;
        //return(Output_Current);
      }

    }

    void setup() {
      // sets the serial port to 9600
      Serial.begin(9600);
      pinMode(RELAY1, OUTPUT);
      pinMode(RELAY2, OUTPUT);
      Relay_Intialize();

    }

    void loop()
    {
      MsTimer2::set(50, TakeReading); // 500ms period
      MsTimer2::start();
      //  CS_Value=  TakeReading();
      Serial.print("current is :");
      Serial.println(Output_Current);
      //if (CS_Value>0.95 && Tripped_Flag==0)
      if (Output_Current>0.95 && Tripped_Flag==0)
      {
        Serial.println("Main Activate");
        Serial.print("Tripped_Flag_status:");
        Serial.println(Tripped_Flag);
        Relay_Activate();

      }
      else
      {

        Serial.println("Main Deactivate");
        Serial.print("Tripped_Flag_status:");
        Serial.println(Tripped_Flag);
        Relay_Deactivate();
      }
      Serial.println(",,,,,,,,,,,,,,,,,,,,,,,,,,,,,");
      delay(1000);

    }

    void Relay_Activate()
    {
      for (unsigned long start = millis(); millis() - start < 10000;)
      {
        digitalWrite(RELAY1,LOW);
        digitalWrite(RELAY2,LOW);
        Serial.println("RELAY GOT TRIPPED");
        Tripped_Flag=1;
      }

    }

    void  Relay_Deactivate()
    {
      digitalWrite(RELAY1,HIGH);
      digitalWrite(RELAY2,HIGH);
      Serial.println("RELAY NOT TRIPPED");
      Tripped_Flag=0;

    }

    void Relay_Intialize()
    {
      Serial.println("RELAY GOT INTIALISE....");
      digitalWrite(RELAY1,HIGH);
      digitalWrite(RELAY2,HIGH);
    }

[![Data output when load connected with MS library][1]][1]

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

title: Sample average of analog of current sensor

Answers: 1

body:
I didn't have a look at your item 2, but regarding item 1:

Please consider that in function `TakeReading()`, if the condition is never true, count is 0 when you come to `newaverage = total/count;`!

I don't know what the Arduino does in case 0/0, but -1 may be a proper return value.


body:
I'm building a line follower with arduino, here some part that I'm going to use

- Arduino Uno

- Motor Shield 2A http://www.dfrobot.com/index.php?route=product/product&product_id=69
- LCD Keypad

- 4 Channel Line Tracking Sensor http://www.aliexpress.com/item/4Channel-Infraed-Line-Tracking-Sensor-Module-w-Connector-Line/2021343637.html

I'm using LiPo Batteries 3 Cell 11.1v for power source.

I'm new in here so I didn't know how to stack that shield, if I recall I can stack up Arduino and the LCD Keypad, and Arduino and the Motor Shield, but didnt know how to stack those 2 together and adding another sensor like that line tracking sensor. May I know how to resolve that? thanks.

title: Stacking Arduino Shield (Motor Shield, LCD Keypad, LED Sensor)

Answers: 2

body:
The Motor Shield 2A plugs in on top of the Arduino Uno, and the LCD Keypad plugs in on top of the motor shield. [But see *Edit 1* below]

There is better information about the  4 Channel Line Tracking Sensor at [uctronics.com](http://www.uctronics.com/channel-tracking-sensor-module-line-hunting-sensor-p-1463.html) where you can see that its main board (with the LM339 chip) connects to the Arduino via six lines: Vcc, Gnd, Out1, Out2, Out3, Out4.  That main sensor board does not mount on the stack, but instead can be located whereever is convenient and leaves its four comparator-level pots accessible for adjustment.
Mount the four small boards for the tracking module as convenient and necessary for line following.

For connecting the six lines from the sensor main board to the Uno, you probably will need to solder two headers (rows of pins) to a board in the stack.  Using right-angle headers (see below) will allow the pins to come out of the side of the stack without interfering with other layers of the stack.  One of the headers should let you connect sensor Out1...Out4 digital outputs to four otherwise unused analog or digital pins, and the other header should let you connect Vcc and Gnd.

![6-pin angle header, 0.1" spacing][1]

***Edit 1:*** In the [LCD shield page](http://www.dfrobot.com/wiki/index.php?title=Arduino_LCD_KeyPad_Shield_(SKU:_DFR0009)), section 2 (Diagram) shows Vcc, Gnd, and D0-D3 available at the top right corner (the angled corner).  Those six pins probably are a reasonable place to add a six-pin angled header for the sensor board.

Given that the LCD KeyPad Shield is a [DFRobot.com](http://www.dfrobot.com/wiki/index.php?title=Arduino_LCD_KeyPad_Shield_(SKU:_DFR0009)) model, the [summary pinout](http://www.shieldlist.org/dfrobot/lcd) at shieldlist.org shows that its use of D4,5,6,7 will conflict with use of [those same lines](http://www.shieldlist.org/dfrobot/2a-motor) by the DFRobot 2A Motor Shield.  There are several ways to handle a conflict like this:  **1,** use two Uno's, one per shield; **2,** make one shield or the other use different lines; **3,** share the lines.

**Method 2** could work as follows:  Stack the LCD shield directly on the Uno (or any other compatible Arduino).  Besides a header for the sensor board, add a header for a cable to the motor board, and drive the motor board's D4-7 inputs with some other lines from the Uno, eg A4-7.  [Alternately  one could remove the D4-7 pins on the LCD shield and jumper from A4-7 to the D4-7 lines on the LCD shield.  This would leave the boards in a single stack but would make some serious changes to the LCD board.]

**Method 3** would work as follows:  The LCD shield only pays attention to D4-7 (which from the [DFRobot schematic](http://www.dfrobot.com/wiki/images/a/a7/LCDKeypad_Shield_SCH.png) drive DB4-DB7 on an LCD TC1602 chip) when the TC1602's E line is strobed.  See pages 7 and 8 of Adafruit.com's [copy of TC1602 specs](https://www.adafruit.com/datasheets/TC1602A-01T.pdf), where timing diagrams show about half-microsecond times for writing to or reading from the TC1602.

You would need to run tests with your motors and see if they work ok in spite of the four inputs to the motor shield being random during the occasional half-microseconds that data is being written to the LCD.  You might have to add more diodes or capacitors to  suppress electrical noise due to rapid switching.

[DFRobot's motor shield page](http://www.dfrobot.com/index.php?route=product/product&product_id=69) has links to that board's schematic and to its L298 chip data sheet.  Page 7 of the datasheet says
>An external bridge of diodes are required when inductive loads are driven and when the inputs of the IC are chopped; Shottky diodes would be preferred.

The motor shield schematic shows diodes; although not drawn using [Schottky diode](http://en.wikipedia.org/wiki/Schottky_diode) symbols they might be Schottky anyway (which would give better noise suppression, less heating, etc).  The schematic also shows that JP1, a 16-pin dual row header, has jumpers that control ENA and ENB on the L298.  In a "proper solution" for sharing D4-7 between the LCD and motor shields, you'd drive ENA and ENB low when using D4-7 for LCD i/o, which would allow the attached motors to briefly free run, as opposed to being suddenly commanded to stop or reverse.

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

body:
The most elegant approach would probably be to use shields controlled by the I2C bus. I've found LCD+keypad and [motor shield](https://www.adafruit.com/products/1438) offered by Adafruit for example.

The I2C bus is shared by all slaves connected to it, and you should find microswitches on each shield to set its I2C address.

Regular shields should not interfere with I2C lines, so as last resort you can put one shield controlled "traditional way".


body:
I'm having problems with using Arduino Leonardo PWM outputs (I'm actually using YUN board).

I need 4 PWM outputs that generally have the same base frequency of around 10 to 20 Hz or so.

I'm using timer 1 (A-pin-9,B-pin-10,C-pin-11) and timer 4 (A-pin-13)

I get pins 9,10,and 13 PWM output working decent, but for some reason pin 11 PWM frequency is much much higher.

Pins 9,10,11 should be working off TIMER 1 which all use the same pre-scaler, so I dont know how 9 and 10 can have one frequency, and 11 have a different frequency.

Here is my code can anybody see anything wrong? thanks!

        #define PWM_4A_PIN  13
        #define PWM_1C_PIN  11

        #define PWM_1B_PIN  10
        #define PWM_1A_PIN  9

        void setup() {
         TCCR1B = TCCR1B & 0b11111000 | 0x05;
         TCCR4B = TCCR1B & 0b11110000 | 0x09;
         analogWrite(PWM_4A_PIN,128);
         analogWrite(PWM_1C_PIN,128);
         analogWrite(PWM_1B_PIN,128);
         analogWrite(PWM_1A_PIN,128);
        }

        void loop()
        {
        }

title: Confusing Arduino Leonardo PWM

Answers: 1

body:
> Pins 9,10,11 should be working off TIMER 1 which all use the same pre-scaler, so I dont know how 9 and 10 can have one frequency, and 11 have a different frequency.

Unless D11 is configured as OC0A instead of OC1C, which means that it will work off timer 0.

    TCCR0A &= ~(_BV(COM0A1) | _BV(COM0A0));
    TCCR1A |= _BV(COM1C1) | _BV(COM1C0);
     ...
    OCR1C = ...;


body:
Not a pure Arduino question really. I'm actually using a standalone ATmega168. So far I've been using AVR-ISP programmer (working from AVR Studio) to program the chip. After everything is done, the chip will be covered and I will only have access to the I2C pins. The MISO,MOSI, etc pins will be unreachable.

I was just wondering if there was a way to use the I2C pins to update the program that is burned on the chip. I won't need to burn the bootloader again, but just to update the program if it needs to be.

title: Burning sketch with I2C

Answers: 2

body:
You need to write a I2C bootloader to the AVR. There seems to be a [project that has already created such a bootloader](https://code.google.com/p/raspy-juice/wiki/Bootloader).

Atmel has provided a [TWI/I2C bootloader](http://www.atmel.com/ru/ru/Images/doc8435.pdf) for their XMega processors (not the ATmega168).

Next problem is uploading the code via I2C. You'd need some hardware to convert USB  to I2C. And some software to talk to this hardware. The last part is probably supported by AVR studio, as Atmel has provided an I2C bootloader. Though I'm not sure both of the above bootloaders are using a compatible protocol over the I2C.

body: Take a look at [miniboot](https://github.com/mihaigalos/miniboot). I implemented it as a self-contained bootloader. Instructions about uploading from USB to I2C are also provided. Live long and prosper.


body:
I need a way to rewrite the switch case part in a more efficient way.

    int y , x ;
    byte dataArray[6];

    void setup () {
       pinMode(8,OUTPUT);
       pinMode(11,OUTPUT);
       pinMode(12,OUTPUT);

       Serial.begin(9600);
       dataArray[0] = 0x3 ; //00000011
       dataArray[1] = 0x5 ; //00000101
       dataArray[2] = 0x9 ; //00001001
       dataArray[3] = 0x11; //00010001
       dataArray[4] = 0x21; //00100001
       dataArray[5] = 0x41; //01000001
    }

    void loop () {
       while (Serial.available()>0) {
         y = Serial.read();
         x = Serial.read();
         switch ( x ) {
         case 1:
            digitalWrite(8,LOW);
            shiftOut(11,12,LSBFIRST,0);
            shiftOut(11,12,LSBFIRST,0);
            shiftOut(11,12,LSBFIRST,0);
            shiftOut(11,12,LSBFIRST,0);
            shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,dataArray[y]);
   digitalWrite(8,HIGH);
   delay(10);
   digitalWrite(8,LOW);
         break;

         case 2:
   digitalWrite(8,LOW);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,dataArray[y]);
   shiftOut(11,12,LSBFIRST,0);
   digitalWrite(8,HIGH);
   delay(10);
   digitalWrite(8,LOW);
         break;

   case 3:
   digitalWrite(8,LOW);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,dataArray[y]);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   digitalWrite(8,HIGH);
   delay(10);
   digitalWrite(8,LOW);
         break;

          case 4:
   digitalWrite(8,LOW);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,dataArray[y]);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   digitalWrite(8,HIGH);
   delay(10);
   digitalWrite(8,LOW);
         break;

          case 5:
            digitalWrite(8,LOW);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,dataArray[y]);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   digitalWrite(8,HIGH);
   delay(10);
   digitalWrite(8,LOW);
         break;

          case 6:
            digitalWrite(8,LOW);
   shiftOut(11,12,LSBFIRST,dataArray[y]);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   digitalWrite(8,HIGH);
   delay(10);
   digitalWrite(8,LOW);
         break;

         default:
            digitalWrite(8,LOW);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   shiftOut(11,12,LSBFIRST,0);
   digitalWrite(8,HIGH);
   delay(10);
   digitalWrite(8,LOW);
         break;
         }
       }
     }

title: Serial input parallel output shift registers with arduino

Answers: 1

body:
    unsigned char i;

    digitalWrite(8,LOW);
    for(i=0;i<=6;i++){
        if(x+i==6) shiftOut(11,12,LSBFIRST,dataArray[y]);
        else shiftOut(11,12,LSBFIRST,0);
        }
    digitalWrite(8,HIGH);
    delay(10);
    digitalWrite(8,LOW);


body:
I'm currently trying to code a simple program that would allow me to light up an individual LED on an 8X8 LED board using a double array.

Here are the problems:

All the rows can ON individually UNTIL I turn all 8 rows ON. When I do this the last column turns OFF by itself (see attached pictures).

The columns aren't even working properly either. Every time I assign a column ON, the last column faintly turns ON too (one of the LEDs light in that column is broken so that is expect to be OFF. See picture).

I think those are the reasons why I am not able to singly assign a particular LED to be ON according to assignments in the array. If someone could spot my mistakes, it would greatly be appreciated. Thanks!

    int led2 = 2;
    int led3 = 3;
    int led4 = 4;
    int led5 = 5;
    int led6 = 6;
    int led7 = 7;
    int led8 = 8;
    int led9 = 9;
    int led10 = 10;
    int led11 = 11;
    int led12 = 12;
    int led13 = 13;
    int led16 = 16;
    int led17 = 17;
    int led18 = 18;
    int led19 = 19;

    int rowPins [8] ={led19, led18, led11, led7, led12, led5, led4, led16};//assigning each LED to a row.
    int columnPins [8] ={led13, led17, led9, led10, led2, led8, led3, led6};//assigning each LED to a column

    int image [8][8]=
    {

    {0,0,0,0,0,0,0,0},
    {0,0,0,0,0,0,0,0},
    {0,0,0,0,0,0,0,0},
    {0,0,0,0,0,0,0,0},
    {0,0,0,0,0,0,0,0},
    {0,0,0,0,0,0,0,0},
    {0,0,0,0,0,0,0,0},
    {0,0,0,0,0,0,0,0},

    };

    void setup()
    {
      for (int i = 0; i<8; i++)
      {
          pinMode(rowPins[i], OUTPUT);
          pinMode(columnPins[i], OUTPUT);
      }
    }//end of setup()

    void loop ()
    {
    for (int y=0; y<8; y++)
    {
     for (int x=0; x<8; x++)
     {
       if (image[x][y]==1)
       {
         digitalWrite (columnPins[x], HIGH);
       }
       else
       {
         digitalWrite(columnPins[x], LOW);
       }
     }//end of 2nd for loop

      digitalWrite(rowPins[y], LOW);
      delayMicroseconds(100);
      digitalWrite(rowPins[y], HIGH);
    }//end of first for loop
    }//end of loop

![When all 8 rows are ON the last column turns OFF][1]

![When only 7 rows are ON][2]

![when one column is ON the other is faintly also ON][3]

  [1]: https://i.stack.imgur.com/eax3Z.jpg
  [2]: https://i.stack.imgur.com/G0m3w.jpg
  [3]: https://i.stack.imgur.com/Fc4Kj.jpg

title: 8X8 LED not lightning up according to matrix assignment on a Arduino Nano

Answers: 1

body:
I don't see any program statements in the code as shown to cause the described behavior, and imagine it is some hardware problem.  (I'm assuming you put some non-zero values into the `image[][]` array; it looks to me like nothing should light up when `image[][]` is all-zeroes.)

Hardware problems break into several categories:  A wiring problem (which we can't see without much better pictures); incorrect software setup of HW; temporary misbehavior of the processor; or permanent damage.  For the sake of discussion, suppose temporary misbehavior applies.

Temporary misbehavior can be caused by overheating.  Overheating can be caused by drawing or sinking a lot of current for too long a time.  (If a large current is a fast transient event, it may have little effect.)

Note that most Arduino I/O lines are rated to sink or source at most 40 mA current each.  Ground and Vcc lines have higher limits, like 200 or 100 mA.  For more details see the spec sheet for your processor; also see [ArduinoPinCurrentLimitations](http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations) at arduino.cc, and [Real maximum current for ATmega328?](https://electronics.stackexchange.com/q/17962) on Electronics SE.

If an LED is directly connected to 5V, it is likely to draw several times more current than nominal.  Connecting  an LED directly to an Arduino digital line also will allow it to draw too much current.  Connecting 8 LEDs to a single processor IO line is likely to cause enough overheating to damage the processor permanently.  You may need to add 8 or 16 resistors to your circuit.

Anyhow, instead of trying to debug while using a 100 μs multiplexing delay in your program, and instead of turning on lots of lights at the same time, try turning on one at a time for a brief but visible period each, and see if the array of lights scans ok, via code like the following:

    int rowPins[]    = {19, 18, 11, 7, 12, 5, 4, 16}; //assign row lines
    int columnPins[] = {13, 17, 9, 10,  2, 8, 3,  6}; //assign col lines

    void setup() {
      int i;
      for (i=0; i<8; ++i) {
        pinMode(rowPins[i], OUTPUT);
        digitalWrite(rowPins[i], HIGH);
        pinMode(columnPins[i], OUTPUT);
        digitalWrite(columnPins[i], LOW);
      }
    }
    void loop () {
      int x, y;
      for (y=0; y<8; ++y) {
        digitalWrite(rowPins[y], LOW);
        for (x=0; x<8; ++x)  {
          digitalWrite (columnPins[x], HIGH);
          delay(250);     // wait about .25 seconds
          digitalWrite(columnPins[x], LOW);
        }
        digitalWrite(rowPins[y], HIGH);
      }
    }

If multiple lights are on there may be miswiring on your project board, or the chip might be damaged, or there may be some roundabout leakage path from columns to ground or from rows to Vcc.  If you make the delay longer or add a pushbutton to advance manually, you can check voltages on LEDs and wires, or measure currents in wires, and perhaps deduce what the path is.


body:
I have the following circuit and want to use the Arduino Mega 2560 as an debugger for an other Microcontroller.
![circuit][1]

So I am looking for the code to redirect the UART input from "P17 (RX2)" to the serial USB and the data coming from the serial USB to the output of "P16 (TX2)"

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

title: Code to use an Arduino Mega 2560 to transfer UART <-> USB to debug an other Microcontroller

Answers: 1

body:
A very simple sketch to pass serial through looks like this:

    void setup(){
      Serial1.begin(/*BAUD*/);
      Serial2.begin(/*BAUD*/);
    }

    void loop(){
      if(Serial1.available()){
        Serial2.print((char)Serial1.read());
      }
      if(Serial2.available()){
        Serial1.print((char)Serial2.read());
      }
    }

I would advise both run at the same baud rate, otherwise you may need to do some extra buffering yourself if the arduino starts running out of buffer space. If you want to use the mega's USB connection instead of "Serial1" like your schematic, just switch "Serial1" to "Serial"


body: On the Arduino website it states that the analog pins read voltages from 0 to 5 volts (default) and return a value from 0 to 1023. One can also set the range with analogReference(). However, this is probably assuming the Arduino is running at 5 volts. If one powers the board with, say 4 volts, will the analog reference still be 5 volts default, or changed to the input voltage of 4 volts?

title: Analog Reference and Power Voltage

Answers: 2

body: Your suspicions are correct. Calling `analogReference()` with a value of `DEFAULT` sets the ADC reference to the voltage at AVCC which at least on the Uno R3 is tied directly to VCC and hence has the same voltage as whatever you're supplying there.

body: There is code published that shows how to read the internal voltage, I use that to correct my A/D readings. It is not perfect but close. You can of course select a lower reference voltage by changing the appropriate registers and use a different reference. This is much safer then supplying an external reference.


body:
Im building an electrical system for my EBike.  My bike has 2 power sources, one is the 48 volt battery, the other is a 12 power converter coming off the battery pack.  I need an arduino shield that has 4 switching channels.  2 that can take in the 48 volt and switch it on and off, and two that can take in the 12 volt and switch it on and off.  Something that can take the 12 volt to power the arduino uno would be nice but I can find a chip to do that if necessary.

Since these are lights, normally off would be more more efficient but with the power consumption we are talking about, i can probably run the battery all day to the point of dry and the fets eat all of 50 feet worth of power staying closed.

Does anyone know of anything like that?  I found several shields out there like [this](http://arduino-info.wikispaces.com/Brick-4ChannelPowerFetSwitch) but all of them seem to be setup to take 1 voltage input and switch it between the 4 or 6 fets on the board, not different voltages per fet and since I'm a programmer, not an EE so I have trouble reading the schematics.

Because my grounds have to be tied, its easier to switch the positive on and off than the negative.

title: Selecting a MOSFET Shield

Answers: 1

body:
You can make your own. Buy a protoshield and 4 fets (and a few resistors).

You can also use the shield you linked to, by not using the `+` terminals on the board. Just connect the `+` of the lights directly to the battery and only the `-` of the light to the shield.

The Uno can be powered by up-to 20V, so you can connect it directly to the battery.


body:
In my low power project, I'm using a Arduino Pro Mini (5V, 16 MHz, ATMEGA328) and a low wattage 3W power supply. Everything else on the system other than the Arduino uses a max of 1.98W.

How much power should I budget for the Arduino Pro Mini (without any mods, ie: disconnecting the voltage regulator and LED)?

title: Budgeting Power for 5V Arduino Pro Mini

Answers: 1

body: Arduino mini, and atmega328 in general use less than 10mA with default arduino code. Turning down unused component (ADC and so on), using deep sleep and optimizing pbc would lover this consumption a lot, in the land of uA


body:
In the example of the arduino starter kit the point is to use a potenciometer to control a servo.

The code is

    angle = map(potVal, 0, 1023, 0, 179);

The output in the serial

    potVal: 1023, angle: 179
    potVal: 1015, angle: 177
    potVal: 1023, angle: 179
    potVal: 1016, angle: 177
    potVal: 1023, angle: 179
    potVal: 1023, angle: 179

I noticed that the servo is shaking like trying to go passing over the 179, when it is suppose to use an angle max 180º (0-179)

What could be the problem?

title: Arduino starter kit servo is shaking

Answers: 3

body:
If the problem is due to jittery pot readings, you may want to smooth the `potval` data sequence by code like the following, where `rawreading` stands for what you just read from the potentiometer's input line.

    potval = alpha*potval + (1-alpha)*rawreading;

Set `alpha` to a number (eg 0.8 or 0.9 or 0.95 etc) between 0 and 1.  `alpha` represents the fraction of the old value that you retain, and  `1-alpha` represents the fractional influence of the new raw reading.   `alpha` closer to 1 causes smoother but slower response.

If you prefer integer arithmetic for faster or smaller code, then represent `alpha` as a ratio of integers.  For example:

    potval = (potval*12 + rawreading)/13;

The technique mentioned above is called *[exponential smoothing](http://en.wikipedia.org/wiki/Exponential_smoothing#The_exponential_moving_average)* or  *exponential moving average*.

body:
I like this method the best (personal preference) for smoothing signals:

    //In setup
    int bufferedVal = analogRead(A0);
    int unbufferedVal = analogRead(A0);
    #define _TOLERANCE_ 5

    //The loop
    unbufferedVal = analogRead(A0);
    if(abs(unbufferedVal - bufferedVal) >= _TOLERANCE_ ) {
      bufferedVal = unbufferedVal;
    }

This finds the error using the `abs()` function (absolute value; makes sure it is positive).

Another thing you can do is round it to the tenth placeholder (i.e. 88 -> 90, 83 -> 80) so it always is a good number to work with:

    int val = analogRead(A0);
    val += 5;
    val = val / 10;
    val = val * 10;

The last two lines work because of the lack of precision that integers offer with decimals. If I divide 88 by 10, it doesn't output 8.8; it outputs 8 instead. We then multiply by ten again so it isn't 8 when it really should be 80. The only problem with this is it only rounds down. We can fix this by adding 5 (the halfway point between 10 and 0). That way, it goes: 88 to 93 to 9.3 to 9 to 90.

**NOTE:** I'm not sure if the compiler will notice the redundancy of the last two lines. If it acts weird, try using the `volatile` keyword.

body:
Since the previous answers were all code-related, let me suggest you use a smoothing capacitor. In noisy environments, or where you want to get more consistent readings, place a capacitor across your signal lines (signal to ground). The result is less "spikes" in your readings, and can sometimes cause a slight delay in signal changes, as charge has to build up in the capacitor before the voltage goes up.

http://www.learningaboutelectronics.com/Articles/What-is-a-smoothing-capacitor