text:
Best way to determine if a 5 gallon water jug is getting empty
I have an espresso machine that gets its water from one of those 5 gallon blue water bottles (I would plumb it, but our water here is WAAAAY too hard).
If I ever accidentally let the bottle run out of water, the rotary pump in the espresso machine will be ruined, which would be a costly mistake.
I know that I can install some sort of magnetic float sensor inside the water bottle, but since I have to change it out once every few weeks, having another thing inside the bottle would make changing it out harder, and microbial contamination more likely.  The pump that pumps water out of the bottle forms a tight seal at the lid, and anything running under it or through it would compromise that seal.
Is there something I could use to detect if the water level is low from the outside of the bottle?  Like a laser sensor?

I believe water absorbs infrared light, so you could experiment with an infrared LED / phototransistor. There are special components too and possibly break outs. I believe it is how rain sensors work in a car.

A pressure sensitive base (i.e. springs and a switch) might be something to consider as well. The accuracy may not be excellent, but as long as you accounted for that in your tolerances it could work.

You might be able to use the difference in specific heat at a point on the bottle with and without water to the level of that point. A resister dissipating a level of energy detectable to the touch that is in thermal contact with a temperature sensor and all of that in thermal contact with the appropriate point on the bottle.

Using a Force Sensor to Measure a Quantity of Water
To satisfy your requirement of having the sensor on the exterior of the water container, I would recommend using a force sensor to weigh the bottle at set intervals. A force sensor, such as the FlexiForce A401, is a type of resistor that changes resistance in response to the amount of force applied. While not as accurate as a scale, it should provide enough accuracy (+-3% according to the datasheet) for the application described.
The basic procedure would be to hook up the force sensor to the Arduino and first measure the resistance with an empty bottle, then measure again with a full bottle. This will give you an idea of the force that your specific platform is actually applying to the sensor, and you can then fine tune the voltage (as per the datasheet) for your installation.
A basic tutorial using a similar force sensor with an Arduino can be found here.
Other Possibilities

Optical Liquid Level Sensors
Ultrasonic Level Monitoring
Thermistors and Heating Coils at various levels to Measure the Thermal Mass (i.e. water) near the Sensor

It's basically using the tare weight of the empty water container (or nearly empty, anyway) to trigger the alarm.
I would suggest that the hoses from the espresso machine plus a minimum safe amount of water be in the bottle when getting the baseline sensor measurement.

Another option is to measure the current going into the pump; when it runs dry, the current goes up, which generates the heat that fries the pump.
Or measure the temperature on the pump, but measuring the current will detect the beginning of the pump's meltdown, while the temperature may only detect the middle or end of the meltdown.  :-(
Or install a current limiter or breaker inline with the pump, just in case everything else fails.  :-)

Interesting. This would require modifying the espresso maker somewhat to implement, correct? Would a fuse be an acceptable method?

Whenever light follows a path that takes it from one material to the next, it makes a sharp turn. However, the angle of deviation is different based on the characteristics of the materials.
You can use this principle.
Set a LED on the level that you want to be your lowest. When the water is full, its light will follow a certain path across the container and reach its light sensor. When the water gets bellow the level, it will miss it (or you could set up a second sensor if you really wanted to).
Based on this info, you can know when the water gets too low. Just take appropriate action.
Watch out on the recommendation to measure the water used. This could be dangerous. You may have a leakage (either now or later) or somebody might tip the machine and spill some water. In either case your water level would be lower than the level you calculate, which would certainly result in your espresso machine be ruined.

I think you want a "liquid level switch", possibly also known as a "fluid switch" ... I realize this may not satisfy your requirements, but this is one way to solve the problem for >$10. I would probably hack something together that would put this sensor inline to the bottle. it's probably too hacky, but you could have a disc of plywood the same diameter as the water bottle, with a pipe fitting in the middle where you could mount the switch, so that the water bottle routes water through it so that when it runs low, it would trigger the switch before it runs to the pump.

Yeah, that needs to be in the water, which is what I don't want.

you can use a metal detector like setup using the fact that electronic permittivity of water is different than that of air
have a coil with AC next to the bottle and an unpowered coil inside it
then by measuring the current and/or voltage generated by the second coil you can sense the difference between with water next to it and without

Lasers
If your blue water bottles are like mine, they are transparent.
Here's what I would try first:
I would get a cheap laser, and shine the light horizontally through the bottle.
I would aim the laser through a short chord -- not pointed directly through the middle of the bottle; perhaps 1/8 turn to the left of center.
    -------
L../.......\..........S1
  /         \
 |     o     |        S2
  \         /
   \       /
    -------
top-down view

When the bottle is empty, the laser beam will shoot pretty much straight through the bottle -- I would put one photo-sensor S1 there.
When the bottle is not quite empty, the laser beam will bend (refract) -- for redundancy, I would put another photo-sensor S2 there.
As long as the Arduino sees the laser hitting S2 alone, there's still some water in the bottle, at least up to the level of the laser -- turn on the green light.
Anything else -- light detecting only at S1, or nothing detected at either sensor, or light detected at both sensors (yes, it can happen) -- something doesn't seem right, better have the Arduino turn off the green light and turn on the red light.
I would start with the simplest thing that could possibly work.
If I'm lucky, it might work.
If not, there's lots of little tricks involved in getting the light where you want it to go.
There's also lots of tricks for blocking sunlight, etc. from going where you don't want it to go.
Little black tubes, red plastic filters,
pulsing the laser at a few kHz,
collimating lenses,
lock-in amplifiers, etc.
There seem to be lots of tutorials that describe how to detect a laser using Arduino -- see

"Laser Harp"
"Laser Timing Gate"
"Arduino Laser Tripwire"
"Arduino Forum: laser detection"
"Arduino security with frickin’ laser"
"Arduino self-calibrating laser trip wire"
"The Arduino Controlled Laser Security System"
"Raspberry Pi & Arduino: laser pointer communication"
etc.

(This would probably work just as well with a medium-power LED or "infrared LED" and some careful optical focusing and alignment. But -- lasers!)

Im definitely going to try this one, because I feel like it'll be a solution where I can change the bottle out without removing any sensor gear.  The laser and the sensor just need to be mounted bear the bottle, not actually on it.

Honestly - you're overthinking this.
A dipstick or a float would be all you need.  Once the water level drops below your minimum, the float moves down with the water level and pulls a switch or allows a LDR to see through a hole.  Then do something like turn on a light.
Less is more.

Again, I dont want it in the water.

It seems to me that if you have pumped out 4.9 gallons you know the jug is close to empty. If an inline flow meter between the pump and the espessso maker is out due to water contact, then maybe you know that an espresso shot takes x amount of water, and once one has called for y shots (and calculated x times y) one is in the danger zone of running out of water?

Would work if all shots were equal, and then only if water was only used to make shots (not steam milk or clean glasses, or make americanos)

An espresso shot or even an Americano would seem a fixed amount (digital in this context), but yeah, steaming milk and cleaning in particular could vary (analog in this context). jlbnjmn's suggestion of essentially weighing the jug periodically is looking good, unless you can find a jippe suggested sensor that would maybe shine through the bottle near the bottom and then have some sort of reading change when it was no longer shining through water.

Nah, they are only semi-fixed per bean, and only assuming you don't change your recipe. The amount needed for a shot of espresso is not known beforehand as it can change per bean, per mood, per desired output weight or volume.

Try a non contact water sensor: https://www.dfrobot.com/product-1493.html I use them and they work very well. You stick it on the outside of the jug, If it falls off the jug will show empty protecting your pump. The ones I use are similar and have an open collector, so no micro is required.  I think I paid about $6 a year or so ago. They make adjustable ones. Nice point nothing touches the water or can contaminate it.


text:
Expected Unqualified-ID Before 'do'(and 'while')
I am getting the error "error: expected unqualified-id before 'do'" multiple times for every do{
}while(); loop I have... Any help?
Pastebin:http://pastebin.com/DubuAEUs

Perhaps you should cut down the amount of data you have (say, 3 pokemon and 7 moves) until you have working code.

I cut down the code as you said... Much easier to work with... Thanks!

From the code you posted, I would highly advise you to follow a C or C++ tutorial, as it seems quite obvious to me that you are new to C/C++ programming. There are a bunch of these on Internet.

The do whiles are outside setup or loop.

This question appears to be off-topic because it is a general C/C++ programming problem. It is not specific to Arduino at all.

Moderators, please remove this question as the code in pastebin as expired so this question is pointless now.

The do whiles are outside of the setup() or loop(), so they won't work.
I would suggest doing a simple C/C++ tutorial like this one to get up to speed with how things work.

source: Stack Exchange

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

sort: votes


text:
Programming an Arduino using Python, rather than C/C++
I am not very skilled with the C Language and I was wondering if there is a way in which python could be used to program an Arduino. This would most likely require a different IDE in order to be able to debug the scripts them self.

There are couple alternatives for programming Arduino, one of them is BitLash and there is a basic interpreter. There are couple options when you search the Internet, but learning C/C++ will pay off in the end.

Thanks, I am actually getting a bit better at C, just not as good as I am with Python.

related, more general question: "Arduino programming options other than C++"

Is a raspberry PI an option?

It's going to be extremely difficult to get any kind of Python script running directly on the Arduino. The reason is that it's an interpreted language, so you would need the interpreter on-board in addition to the plain text script. There's probably not going to be enough memory for all of that.
Your best bet would probably be finding a way to compile a Python script to native machine code (which is how C/C++ works). I believe there are projects around to do something like that for other platforms, but (as far as I know) none which does it successfully for Arduino yet.
You might find some more useful information on this question at Stack Overflow: Is there a way to "compile" Python code onto an Arduino (Uno).

Yes, it is (somewhat) possible to program the Arduino using Python. One such project on Github is the Python Arduino Prototyping API v2. It provides very basic functionality such as digital I/O and analog I/O.
This can be used for very simple projects.

*This project is a bit of a hack at "programming" the board using the serial connection. It passes the commands over the serial connection to a sketch running on the board which then "executes" the Python command.

So the board has to be plugged into a computer in order to actually run the code?

@JVarhol Oddly, yes.

Well, that pretty crappy. It would be easier to use a Raspberry Pi.

There is a project which brings a Python virtual machine to micro-controllers, including the Arduino Mega.
Here's a quote from the Ardunio Mega README, which gives a feel for what this could be like (though, I've not tested this!):

The following is an example session using ipm::
ipm> import avr, sys
ipm> avr.ddrA(0xff)
ipm> avr.portA(0)       # Pins 22-29 all at 0 V
ipm> avr.portA(0xa5)
ipm> sys.heap()
(2622, 7424)

I have used pyserial with great success in controlling the pins on the arduino.  Your workstation (laptop, etc) runs a python script that then communicates in real time to the arduino.
It's not quite the same as running the script directly on the arduino but I was doing quite a bit more than I thought the arduino could handle (some music analysis, hitting a REST api, etc).

Yes,its possible with the recent new ArduinoPro H7 which has abilities to upload a written programme in Python and JavaScript and its a dual core,32bit.

Java Script? really? did you try it?

Another option to consider is the Arduino Yun. In addition to the AVR chip which most Arduinos have, it also includes a MIPS chip running Linux. Since it's linux, you can easily run python code, and any pure-python package can be easily installed.
However, all the interesting input/output capability is on the AVR chip, not on the MIPS chip. Projects such as Autobahn and LininoIO solve this problem by running a special program on the AVR chip which performs I/O operations under instruction from the MIPS chip.

Yes. Python can be used to program an Arduino, simply by importing pyfirmata, which can interface the arduino with Python.

True. But that isn't what the OP is asking for.

I disagree. Using firmata is effectively "programming an Arduino" using python. In fact I was surprised to see nobody else suggested it. From a beginner's point of view it's pretty much the same. I'm thinking of using it to help teach my son programming as python is a bit easier than C.

We know this is an open issue in Arduino programming and in the embedded world in general.
There are various solutions available on the market like MicroPython but most of them are dedicated to specific boards and don't allow to keep the system real-time.
We are working on a solution!
VIPER is a Python Virtual Machine for Arduino DUE and all ARM 32 bit architectures that runs on top of a real-time operating system.
This means that you can develop Python scripts that can be exexuted by Arduino DUE, UDOO, Spark (all boards) and also on the new ST nucleo boards.
Moreover if you need high performances and you re skilled in C you can develop real-time modules for VIPER that can be called and managed by the Python scripts.
You can see VIPER in action here http://bit.ly/kickviper

It’s not an open issue. python is a horrible indentation language.

You could learn from C (AVR) how sensors work but it needs much more time.
Arduino IDE Code and Python Code for Arduino use C Code functions to make things simple.
Python and Arduino IDE if use Firmata they use serial communication and you think you code self.

You gotta use pyfirmata because that's the only way to make your son a PRO engineer who makes robots. Also, python can do more advanced stuff so use pyfirmata.

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

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


text:
How do I erase the memory of the Arduino Uno?
I'm just a tinkerer learning Arduino with my son and I was surprised that when I plugged the USB cord back in to the Arduino the program was still running and I thought to myself, "it's a good thing I didn't just blow anything up."
So, what's the normal way people call it a day with these things?  Do you usually load up the bare-bones do nothing sketch or just unplug everything?

What do you mean by "when I plugged the USB cord back in to the Arduino the program was still running", what behavior did you observe and what behavior did you expect? Was anything connected to the Arduino?

@jippie yeah, I had a bunch of LED's plugged in and they all lit up. For some reason I thought the programs were loaded into memory and would be gone on reboot, but since that doesn't exist....

The programs are loaded into flash memory, not RAM, so they are kept even after powerdown.

When booted, the Arduino will run whatever program was put on it last. Solution: Don't turn it on if you don't want it to run.
When out of the box, the Arduino usually runs the Blink program. So you can just load that and call it a day if you want to "reset" it.
Or have a loop program with a sleep command.
If you've been messing with the USB bootloader via the icsp pins, this isn't enough though, you'll need to reinstall the bootloader. But if you've been uploading programs via usb or directly using a programmer, there is no issue with uploading Blink or some other dummy program to reset it.

is it possible to have it run a self-destructive program with nothing plugged in to the voltage terminals?

@PeterTurner when there's no power to it? No. But you can add a program that misuses the pins, and if you leave it on some damage can be called (not much unless the pins are connected)

If safety is a major concern, then you should almost always load a stop* sketch onto the board before calling it a day. This would be a good idea, for example, when your board is semi-permanently a part of a larger system. You could do so by:

Upload the Bare Minimum sketch found in File ->  Examples -> Basic in the arduino-ide
Upload a sketch with a large delay in loop.

#include <limits.h>

void setup()
{}

void loop()
{
  delay(ULONG_MAX);
}

Upload a sketch with a call to exit() from setup() (Thanks @Peter!)

void setup()
{
   exit(0);
}

void loop()
{}

*Stop is simply figurative. The board doesnt really stop running.

Could you get a similar (and more permanent) effect by calling exit() from within setup() or loop()?

@PeterR.Bloomfield Can't believe I forgot about that!

Why bother with either the exit or the delay? Just have void setup () { } void loop () { } - in any case internally the processor is just looping around "doing nothing useful".

My biggest concern when this happens is I've usually wired the Arduino for my new project and I'm plugging in the USB for the initial download of the new sketch. I worry, having no idea what the previous program is going to try, being connected to totally different hardware.
So far nothing bad has happened and I don't think I'll adopt burning BLINK each time I put one of my Arduinos back in the bin. It's probably just a matter of time though.

The major thing that can go wrong is if you put your Arduino aside for a couple of weeks, forget what sketch (code) is loaded onto it, then get back to work on it, plug in hardware (like a switch, LED or motor) and have it unexpectedly light up / turn on, because the previous code addressed the pin it was connected to.

Solution 1. Load the new code first.
A simple and safe technique is to load the new code that you are working on today before you plug any hardware in. Now you know what the code does, what pins it uses, and you then plug the hardware in afterwards (preferably turning the Arduino off first by unplugging it).
Then when you reconnect power, it runs the sketch you uploaded, you have your hardware connected and all should be well.

Solution 2. Load a "do nothing" sketch.
You can upload this short sketch:
int main () { }

It "does nothing". All pins will remain as inputs, so you can safely then attach your hardware, and then start coding your new project.

Safety first
A good rule is to not plug or unplug hardware (eg. LEDs, switches, motors) with the power applied. If you get distracted and plug into the wrong socket on the board you might immediately damage either what you are connected, or the Arduino, or both.
With the power off, you can then do a last-minute check that everything is connected to the right place, you have your polarities correct, and so on.
Also make sure you don't have static electricity on your body, particularly if you are wearing a jumper or something fluffy, or are sitting on carpet.
Personally I always reach over and touch some metal part nearby to "ground" myself, before reaching for the Arduino. An example is the metal case of a PC, a headphone socket, or something like that.
If, after connecting power to the Arduino (eg. by the USB cable) you do not immediately see the power LED come on, disconnect the power immediately! You may have shorted something out, and the less time you do that for, the better.

In the Arduino IDE, go to examples, select Eeprom, select eeprom clear and then upload the sketch.
When it is the LED on pin 13 will turn on, you are done.
NB. This may take some time depending on the size of the EEPROM in the Arduino.

So what is the point? Running something that does not touch I/O (but clears the EEPROM at every power on)?

Have you actually tried this? Pin 13 does not appear to be set up as output (Arduino IDE 1.6.5)

If the arduino board is connected to any other device then unplug everything and just connect the arduino with the computer using the usb cable and try to upload new sketch i hope it will help.

Welcome to Arduino SE! Is there any reason this answer is better than the other provided answers? Thanks!


text:
Why are the files not being created correctly?
I have been through http://arduino.cc/en/Hacking/LibraryTutorial but I can't do it. Whenever I create a new sketch and try to save it as .cpp or .h from the Save As button in the Arduino IDE, it gets saved as _cpp and _h. I am not able to create a library this way. How do I create a new library? What am I missing here?

Welcome to [Arduino.se]! Could you tell us what you were trying, where you got stuck, what is it that is not clear, and what is the error message you are getting? Stack Exchange works best for Q&A, and not tutorials. See How to Ask.

Well I have created 2 programs with the code .h and .cpp but it keeps changing .h and .cpp to _h and _cpp.

You said that the .cpp and .h files get renamed to _cpp and _h. Could you tell us how you are creating the files? Using the new file button on the right side of the Arduino IDE? Some other way?

A sketch and a library are two different things. For your first experiments, you will probably not need to create any library of your own. Just write your sketch with Arduino IDE and save it the usual way.

When you save a file using the Save As button from the Arduino IDE, it saves the current file as a sketch i.e. as an .ino file.
To create a .cpp and .h files for working on a new library, you need to create the files alongside a sketch. For this, you can use the Tab button on the top right (circled in red).

Click on it, and select New Tab. You will get a bar at the bottom of the screen asking for a file name. Enter the name with extension (test.cpp) and press Enter.

Your file has now been added to the current directory.

Similarly, follow the same steps for creating the .h file.
Once your library is complete and ready to ship, you can move the .cpp and .h files to a separate directory and then add it under libraries.

do i copy the same code in .h and .cpp and what do i do after this because the tutorial i have been following is unclear

@user121855 That deserves a separate question. That will involve a purely code-related answer, while this was more about the file structure.

my other question is here http://arduino.stackexchange.com/questions/550/how-do-i-create-a-library-after-i-create-a-h-and-cpp-file


text:
SimpleAudioPlayer + sleep function
I have tested the SimpleAudioPlayer example.
https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer
This works fine, but when I add a sleep(1000) at the end of the loop() function, the music sounds dismembered (second run).
void loop()
{
    // ... source from the example

    myFile.close();
    Serial.println("End of file. Thank you for listening!");

    sleep(1000);
}

Does anyone have any idea on how to resolve this?

sleep() is something different. You are probably want to use delay(1000) instead.
sleep() comes from libsam and is not very well documented for use within the Arduino environment. There is probably a conflicting timer or interrupt between sleep() and the Audio.h library. So sticking with delay() is probably your best option.


text:
Self-diagnose components in the circuit
How can I tackle self-diagnosis problem within my Arduino project?
For example, I have a temperature sensor and humidity sensor. How can I know if they work or not on Arduino start or inside the sketch loop?

You could get your program to output messages to the serial pin on your board, Tx. For example:
Serial.begin(9600) //baud rate of 9600

Serial.print("Debug Message");

You can use this to print out string and integers. Here is the link to further information on the Arduino website - https://www.arduino.cc/en/reference/serial
If you are already using the Serial pins then you could use the SoftwareSerial Library - https://www.arduino.cc/en/Reference/softwareSerial
This library allows you to make two other pins on your board Tx and Rx. For example:
SoftwareSerial mySerial(12,13) //Makes pin 12 Rx and pin 13 Tx

mySerial.begin(9600) //baud rate of 9600

mySerial.println("Debug Message");

To read the output from any of the pins on your arduino - use a USB to TTL serial cable. Plug it into your computer and use a program like PuTTY to connect to the serial cable and read the messages coming from the Arduino.

If you can define "it works" in code (e.g. the temperature is between X and Y degrees, and changes no faster than 2 degrees per second), and all you need is a "Yes" or a "No", then you can write this into code, then the easiest way is to use an LED. Make sure you blink it, rather than having it on steadily, so you can tell if it's frozen.
Make sure you try unplugging your sensor, to understand what it does when it fails; this is one thing you specifically want to test for.
If you specifically do not want to do this in your main loop, you can do an interrupt-driven version, but that adds a lot of complexity. I suggest you do it in your main loop if you can.
You can use the current time to blink the light regularly:
if (everything_is_working()) {
  if (millis()%10000<1000) {
     <turn led on>
  } else {
     <turn led off>
  }
}

The two numbers let you control the flashes. I've used 10,000 and 1,000; this means that out of every 10,000 millis (10 seconds), the led is on 1,000 millis (1 second). Depending on your preference, you can adjust these to your liking. You can also add an else clause which blinks a different pattern depending on what is wrong - 9 seconds on out of 10 for a problem with the humidity sensor, and 5 seconds out of 10 for the temperature sensor having issues.
If your sketch isn't running, the led will stay in it's current state - either on, or off, indefinitely. If your project has no power, the light will obviously be off.
If you want more data, you can either make more complex blink codes - short-long-short-long, for example - or add multiple lights, or even a three-colour LED, with different colours indicating different problems.

Another approach can be handy if you want to do detailed debugging (like outputting numbers) but your serial port is already in use for something, like a GPS. You can use a second Arduino as a "debugging interface" using SPI or I2C. For example, using SPI:

Or via I2C:

In these examples the "debugging" Uno also supplies power to the "main" Uno via the 5 V / Gnd pins.
I have a description about this method on Debugging using SPI/I2C and a second processor. Code is available at: http://gammon.com.au/Arduino/SPI_Debugging.zip and http://gammon.com.au/Arduino/I2C_Debugging.zip .
To demonstrate the idea, on the "main" Uno this is an example of sending debugging info via SPI:
// make true to debug, false to not
#define DEBUG true

#include <SPI.h>

// conditional debugging
#if DEBUG

  #define beginDebug()  do { SPI.begin (); SPI.setClockDivider(SPI_CLOCK_DIV8); } while (0)
  #define Trace(x)      SPIdebug.print   (x)
  #define Trace2(x,y)   SPIdebug.print   (x,y)
  #define Traceln(x)    SPIdebug.println (x)
  #define Traceln2(x,y) SPIdebug.println (x,y)
  #define TraceFunc()   do { SPIdebug.print (F("In function: ")); SPIdebug.println (__PRETTY_FUNCTION__); } while (0)

  class tSPIdebug : public Print
  {
  public:
    virtual size_t write (const byte c)
      {
      digitalWrite(SS, LOW);
      SPI.transfer (c);
      digitalWrite(SS, HIGH);
      return 1;
      }  // end of tSPIdebug::write
  }; // end of tSPIdebug

  // an instance of the SPIdebug object
  tSPIdebug SPIdebug;

#else
  #define beginDebug()  ((void) 0)
  #define Trace(x)      ((void) 0)
  #define Trace2(x,y)   ((void) 0)
  #define Traceln(x)    ((void) 0)
  #define Traceln2(x,y) ((void) 0)
  #define TraceFunc()   ((void) 0)
#endif // DEBUG

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced device-under-test debugging!"));
  TraceFunc ();  // show current function name

}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

If DEBUG is true then the debugging prints are activated. Otherwise they turn into "no code".
The receiving end looks like this:
volatile char buf [1000];
volatile int inpoint, outpoint;

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

  Serial.println ();
  Serial.println (F("Commencing debugging session ..."));
  Serial.println ();

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // now turn on interrupts
  SPCR |= bit (SPIE);

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register
int next = inpoint + 1;  // next insert point

  // wrap-around at end of buffer
  if (next >= sizeof buf)
    next = 0;

  if (next == outpoint)  // caught up with removal point?
    return;  // give up

  // insert at insertion point
  buf [inpoint] = c;
  inpoint = next;  // advance to next

}  // end of interrupt routine SPI_STC_vect

void loop (void)
{
  // insertion and removal point the same, nothing there
  noInterrupts ();  // atomic test of a 16-bit variable
  if (outpoint == inpoint)
    {
    interrupts ();
    return;
    }
  interrupts ();

  // display anything found in the circular buffer
  Serial.print (buf [outpoint]);

  noInterrupts ();
  if (++outpoint >= sizeof buf)
    outpoint = 0;  // wrap around
  interrupts ();

}  // end of loop

There is a 1000 byte buffer which will cope with bursts of incoming data, which is then sent out the serial port on the debugging Uno (that is, to your serial monitor).
The linked library above includes code for SPI and I2C debugging interfaces.

Having said that, the simplest thing is just to do serial debugging prints inside your code on the main device, if that is practical.
Remember to use the F() macro, or your debugging code might take up so much RAM it causes a crash.
eg.
Serial.println (F("Temperature sensor working."));


text:
Power saving of atmega 2560
Is arduino code Consume More power other than "Avr Studio" Code?
Please tell some key points for power saving.
Processor on $ off Methodology.

Processor on $ off Methodology. - not sure what you mean by that.

There is nothing about the Arduino code that would inherently consume more power than using a different compiler, so no, it doesn't. What the code does you can change in either development environment.
Read Power saving techniques for microprocessors for a considerable number of tips about saving power.
Also see related threads about this question such as What are (or how do I use) the power saving options of the Arduino to extend battery life?

authors: Электро хобби ТВ


text:
run two motors in turns without using delay()

I googled solutions and tried, but I still cannot get it working.
I've tried BlinkwithoutDelay.
I feel it is very confusing to track timing of two motors (i.e., step, direction, speed) for the following routine loop:

step 1: run motorA_forward() for 10 seconds;
step 2: run motorAB_stop() for 1 seconds;
step 3: run motorB_backward() for 3 seconds
step 4: run motorAB_stop() for 1 seconds
step 5: run motorA_backward() for 10 seconds
step 6: run motorAB_stop() for 1 seconds

Please help me on this!! I really appreciate your time and comments.
Thank you.
The following is my working code.
// ----------LIBRARIES--------------

#include <Wire.h>
#include <LIDARLite.h>
LIDARLite myLidarLite;

// ----------CONSTANTS--------------

const int motorA_pin_1 = 8;           // the pin numbers for the motors
const int motorA_pin_2 = 11;
const int motorA_pin_speed = 9;
const int motorB_pin_1 = 12;
const int motorB_pin_2 = 13;
const int motorB_pin_speed = 10;

//------------VARIABLES--------------

byte motorA_state_1 = LOW;             // used to record whether the motots are on or off
byte motorA_state_2 = LOW;             // LOW = off
byte motorB_state_1 = LOW;
byte motorB_state_2 = LOW;

int currentMillis               = 0;     // stores the value of millis() in each iteration of loop()
int motorA_Forward_Interval     = 5000;  // will store last time the motor was moved
int motorA_Backward_Interval    = 5000; // will store last time the motor was moved
int motorA_Stop_Interval        = 2000;  // will store last time the motor was moved
int motorB_Stop_Interval        = 2000;  // will store last time the motor was moved
int motorAB_BreakTime_Interval  = 2000;

unsigned long motorA_Forward_Timer      = 0;     // will store last time motorA start was updated
unsigned long motorA_Backward_Timer     = 0;     // will store last time motorA start was updated
unsigned long motorB_Forward_Timer      = 0;     // will store last time motorA start was updated
unsigned long motorB_Backward_Timer     = 0;     // will store last time motorA start was updated
unsigned long BreakTime_timer   = 0;     // will store last time motorA/B break time was updated

//------------INITIALIZATION--------------

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

  pinMode(motorA_pin_1,OUTPUT);         // set the motor pins as output:
  pinMode(motorA_pin_2,OUTPUT);
  pinMode(motorA_pin_speed,OUTPUT);
  pinMode(motorB_pin_1,OUTPUT);
  pinMode(motorB_pin_2,OUTPUT);
  pinMode(motorB_pin_speed,OUTPUT);

}

//------------LOOPING----------------------
// Notice that none of the action happens in loop() apart from reading millis()
// It just calls the functions that have the action code

void loop()
{
    Serial.println(myLidarLite.distance());

    unsigned long currentMillis = millis();

    motorA_forward();  // for 10 seconds
    motorAB_stop();    // for 1 seconds
    motorB_backward(); // for 3 seconds
    motorAB_stop();    // for 1 seconds
    motorA_backward(); // for 10 seconds
    motorAB_stop();    // for 1 seconds

}

//------------SUBROUTINE----------------------

void motorA_forward()
{
  if(currentMillis - motorA_Forward_Timer <= motorA_Forward_Interval)
  {
    motorA_state_1 = HIGH;   // Turn motor A on - backward
    motorA_state_2 = LOW;  //
    motorB_state_1 = LOW;   // Turn motor B off
    motorB_state_2 = LOW;   //

    analogWrite(motorA_pin_speed,255);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,255);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    motorA_Forward_Timer = currentMillis;
  }
}

void motorA_backward()
{
    if(currentMillis - motorA_Backward_Timer <= motorA_Backward_Interval)
  {
    motorA_state_1 = LOW;   // Turn motor A on - backward
    motorA_state_2 = HIGH;  //
    motorB_state_1 = LOW;   // Turn motor B off
    motorB_state_2 = LOW;   //

    analogWrite(motorA_pin_speed,255);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,255);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    motorA_Backward_Timer += currentMillis;
  }
}

void motorB_forward()
{
    motorA_state_1 = LOW;   // Turn motor A off
    motorA_state_2 = LOW;   //
    motorB_state_1 = HIGH;  // Turn motor B on - forward
    motorB_state_2 = LOW;   //

    analogWrite(motorA_pin_speed,255);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,255);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    motorB_Forward_Timer = currentMillis;
}

void motorB_backward()
{
    motorA_state_1 = LOW;   // Turn motor A off
    motorA_state_2 = LOW;   //
    motorB_state_1 = LOW;   // Turn motor B on - backward
    motorB_state_2 = HIGH;  //

    analogWrite(motorA_pin_speed,255);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,255);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    motorB_Backward_Timer = currentMillis;
}

void motorAB_stop()
{
    motorA_state_1 = LOW;   // Turn motor A off
    motorA_state_2 = LOW;   //
    motorB_state_1 = LOW;   // Turn motor B off
    motorB_state_2 = LOW;  //

    analogWrite(motorA_pin_speed,0);
    digitalWrite(motorA_pin_1,motorA_state_1);
    digitalWrite(motorA_pin_2,motorA_state_2);
    analogWrite(motorB_pin_speed,0);
    digitalWrite(motorB_pin_1,motorB_state_1);
    digitalWrite(motorB_pin_2,motorB_state_2);

    BreakTime_timer = currentMillis;
}

int currentMillis               = 0;     // stores the value of millis() in each iteration of loop()
...

void loop()
{
    Serial.println(myLidarLite.distance());
    unsigned long currentMillis = millis();

You have two currentMillis variables. The global one never changes. You change a different one inside loop.

Remove the data definition. eg.
void loop()
{
    Serial.println(myLidarLite.distance());
    currentMillis = millis();  // change the global variable

Also make the global one unsigned long:
unsigned long currentMillis               = 0;     // stores the value of millis() in each iteration of loop()

This is a classic example where Object Oriented Programming (OOP) can make your life so much easier.
The principle behind OOP is to define a Class which contains all the actions you want to perform on something - in this case a motor.  The Class contains all the instructions on how to do things like set the motor speed, the direction, start it, stop it, etc.
From that Class you then create Objects.  The beauty is there is only one Class which has the abstract concept of "Motor Control", but that Class is used to create one Object for each motor you want to control.
A Class, and hence the Objects derived from it, are all completely self contained, which makes it so much easier to manage.  All the variables associated with a single motor are wrapped up inside the Class and you don't need to worry about unique names for them all on a per-motor basis.
For example, you might define a class like this:
class Motor {
    private:
        int _speedPin;
        int _directionPin1;
        int _directionPin2;

    public:
        Motor(int sp, int dp1, int dp2) {
            _speedPin = sp;
            _directionPin1 = dp1;
            _directionPin2 = dp2;
        }
        void begin() {
            analogWrite(_speedPin, 0);
            pinMode(_directionPin1, OUTPUT);
            pinMode(_directionPin2, OUTPUT);
            digitalWrite(_directionPin1, LOW);
            digitalWrite(_directionPin2, LOW);
        }
        void forward() {
            digitalWrite(_directionPin1, HIGH);
            digitalWrite(_directionPin2, LOW);
        }
        void reverse() {
            digitalWrite(_directionPin1, LOW);
            digitalWrite(_directionPin2, HIGH);
        }
        void speed(int speed) {
            analogWrite(_speedPin, speed);
        }
        void stop() {
            analogWrite(_speedPin, 0);
            digitalWrite(_directionPin1, LOW);
            digitalWrite(_directionPin2, LOW);
        }
};

Everything you need to control a motor is in there.  Then you could use that to create two motor objects:
Motor leftMotor(3, 4, 5);
Motor rightMotor(6, 7, 8);

You provide the pins that control the motor to the constructor of the object - that is pin 3 is the speed pin of the first motor, and pins 4 and 5 are the direction control pins, etc.
You can now control the motors very simply.  Configure the pins by calling the begin function defined in the class above:
void setup() {
    leftMotor.begin();
    rightMotor.begin();
}

And now you can use similar decision making as normal to decide when to do what.  The main difference is that your motor control code now looks as simple as:
leftMotor.forward();
rightMotor.reverse();

or
leftMotor.stop();
rightMotor.forward();
rightMotor.speed(30);

You then end up with a program that is much cleaner and easier to follow.  And adding a third or forth motor is as simple as defining more Motor objects with their pins.
This video is a good introduction to what OOP is and how it differs from the "traditional" approach:

https://www.youtube.com/watch?v=MTfWr7o7Q4U


text:
Atmega328p - Going low power 1.8V using 4Mhz oscillator - Bootloader flash
I would like to use an Atmega328p micro-controller with a 4 Mhz oscillator in order get some low power consumptions. I am using an Arduino board to flash the bootloader into the Atmega.
EDIT
In order to compile the optiboot bootloader I had to install the avr-libc package and clone the repo
sudo apt-get install avr-libc
git clone https://github.com/Optiboot/optiboot.git

and edited the Makefile in /optiboot/bootloaders/optiboot/Makefile by adding a new entry called atmega328_4
HELPTEXT += "target atmega328     - ATmega328p 4Mhz\n"
atmega328_4: TARGET = atmega328
atmega328_4: MCU_TARGET = atmega328p
atmega328_4: CFLAGS += $(COMMON_OPTIONS)
atmega328_4: AVR_FREQ ?= 4000000L
ifndef BIGBOOT
atmega328_4: LDSECTIONS  = -Wl,--section-start=.text=0x7e00 -Wl,--section-start=.version=0x7ffe
else
# bigboot version is 1k long; starts earlier
atmega328_4: LDSECTIONS  = -Wl,--section-start=.text=0x7c00 -Wl,--section-start=.version=0x7ffe
endif
atmega328_4: $(PROGRAM)_atmega328_4.hex
atmega328_4: $(PROGRAM)_atmega328_4.lst

atmega328_4_isp: atmega328
atmega328_4_isp: TARGET = atmega328
atmega328_4_isp: MCU_TARGET = atmega328p
ifndef BIGBOOT
# 512 byte boot, SPIEN
atmega328_4_isp: HFUSE ?= D9
else
# 1k byte boot, SPIEN
atmega328_4_isp: HFUSE ?= D9
endif
# Low power xtal 46MHz) 16KCK/14CK+65ms
atmega328_4_isp: LFUSE ?= 7D
# 2.7V brownout
atmega328_4_isp: EFUSE ?= FE
atmega328_4_isp: isp

I saved the file, run the make command and got the following error:
userk@norepinephrine:~/development/git/optiboot/optiboot/bootloaders/optiboot$ make atmega328_4
avr-gcc (GCC) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

BAUD RATE CHECK: Desired: 115200, Real: 125000, UBRRL = 3, Difference=8.5%
avr-gcc -g -Wall -Os -fno-split-wide-types -mrelax -mmcu=atmega328p -DF_CPU=4000000L  -DBAUD_RATE=115200 -DLED_START_FLASHES=3           -c -o optiboot.o optiboot.c
optiboot.c:348:6: error: #error BAUD_RATE off by greater than 5%
     #error BAUD_RATE off by greater than 5%
      ^
optiboot.c:359:2: error: #error Unachievable baud rate (too fast) BAUD_RATE
 #error Unachievable baud rate (too fast) BAUD_RATE
  ^
<builtin>: recipe for target 'optiboot.o' failed
make: *** [optiboot.o] Error 1

So I changed the -DBAUD_RATE parameter to 19200 and rerun the make command
BAUD_RATE_CMD = -DBAUD_RATE=19200

Then 2 new files were created: optiboot_atmega328_4.elf and optiboot_atmega328_4.hex
Then I copied these files into the arduino configuration folder located
 at: /home/userk/.arduino15/packages/arduino/hardware/avr/1.6.21/bootloaders/optiboot
TIDE
I am using a custom board configuration file board.txt
##############################################################

nz.name=Arduino Noize

nz.vid.0=0x2341
nz.pid.0=0x0043
nz.vid.1=0x2341
nz.pid.1=0x0001
nz.vid.2=0x2A03
nz.pid.2=0x0043
nz.vid.3=0x2341
nz.pid.3=0x0243

nz.upload.tool=avrdude
nz.upload.protocol=arduino
nz.upload.maximum_size=32256
nz.upload.maximum_data_size=2048
nz.upload.speed=19200

nz.bootloader.tool=avrdude
nz.bootloader.low_fuses=0x7D
nz.bootloader.high_fuses=0xD9
nz.bootloader.extended_fuses=0xFE
nz.bootloader.unlock_bits=0x3F
nz.bootloader.lock_bits=0x0F
nz.bootloader.file=optiboot/optiboot_atmega328_4.hex

nz.build.mcu=atmega328p
nz.build.f_cpu=4000000L
nz.build.board=AVR_UNO
nz.build.core=arduino
nz.build.variant=standard

Flashing the Bootloader
I have followed these steps:

Uploaded the ArduinoISP sketch onto the Arduino UNO board.
Wired up the Arduino board and microcontroller as shown in the diagram below

Select "Arduino Noize" from the Tools > Board menu.
Select "Arduino as ISP" from Tools > Programmer
Run Tools > Burn Bootloader

At this point I got a success message from IDE. So the bootloader has been correctly flashed into the Atmega328p
The Problem
When I try to upload a sample sketch (blink) using the wiring below I get a timeout from the IDE.

I have double checked the connections but the sketch doesn't upload.
Do you have any advice?

How did you compile the optiboot bootloader? You need to tell the bootloader at what speed it's running.

Thanks, I am updating the post with the optiboot's Makefile

So you compiled optiboot with a baudrate of 19200, but specify 9600 in your boards.txt.

Sorry I didn't update the question after the addition of the optiboot configuration. Now it is updated. I still have the same timeout problem.

As Gerben notes in the comments, the bootloader has to know how fast the board is running. It uses this to work out the baud rate settings for the serial communication.
If you haven't compiled the bootloader yourself with the right clock settings you will probably find that it is operating at a quarter of the speed you expect it to. Dividing your upload baud rate by four in your board settings may make it work, but you really should compile the bootloader to match the board properly.

Thanks, I have edited the question with the information related to the optiboot bootloader compilation

As mentioned before, you need to compile the Optiboot bootloader with the correct clock frequency. Here's a guide that shows you how to do that, as well as adding an option to the Arduino IDE menu to select the right clock speed without having to add your own board definition.
Optiboot - ATmega328P at custom frequency

Good tutorial, I am trying to follow the provided steps but the example is for 12Mhz clock. Please see my edits

The principle is exactly the same for clock speeds other than 12 MHz. I think that you selected the incorrect baud rate for uploading. Either change nc.upload.speed in your boards file to 115200 baud, or recompile the bootloader with a baud rate of 19200.

nz.bootloader.low_fuses=0x7D
nz.bootloader.high_fuses=0xD9
nz.bootloader.extended_fuses=0xFE

Extended fuse byte. bits 2,1,0 determine the brown out level (bits 7-3 not used)
110 = 1.7 to 2.0V, 1.8 typical
Low fuse byte bits 3,2,1 determine the clock source
110 = low power crystal oscillator in 3-8 MHz range.
So those settings look okay.

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


text:
Wrong characters received with Bluetooth Mate Gold using Software Serial
I have a Bluetooth device from Sparkfun which I would like to use with the Arduino Mega. If I connect the module via the hardware serial pin everything works fine but when I use other pins like 12 and 13 with SoftwareSerial, the communication doesn't work as expected.
THE CODE
#include <SoftwareSerial.h>

int bluetoothTx = 12;
int bluetoothRx = 13;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(115200);
  bluetooth.print("$$$");
  delay(100);
  bluetooth.println("U,9600,N");
  bluetooth.begin(9600);
}

void loop()
{
  //Read from bluetooth and write to usb serial
  if(bluetooth.available())
  {
    char toSend = (char)bluetooth.read();
    Serial.print(" Receiving: ");
    Serial.println(toSend);
  }

  //Read from usb serial to bluetooth
  if(Serial.available())
  {
    char modeS = Serial.read();
    Serial.print(" Writing Blu: ");
    Serial.println(modeS);
    bluetooth.print(modeS);
  }
}

I'm using an Android App (BlueTerm) to test the communication.
Here is what I get when sending a letter from Android to Arduino.
 Receiving: ÿ
 Receiving: ÿ
 Receiving: ÿ
 Receiving: ÿ
 Writing Blu: d
 Writing Blu: d
 Writing Blu: d

I'm not able to receive anything from the Arduino.
I've tried decreasing the baudrate but nothing changed. Do you have any advice?
Update
I have tried without the following lines but nothing changed... It seems that the module can be used only with the hardware serial pins 0 and 1... It's a shame
bluetooth.print("$$$");
delay(100);
bluetooth.println("U,9600,N");
bluetooth.begin(9600);

What character are you sending from the Android App that is being received as 'ÿ'?  Are you just echoing back the 'd'?

Every letter I send from the Android app is received as 'ÿ'. Then from Arduino serial monitor I press three times d and send.

Just making sure, because 'ÿ' is the same as 'd' if you use 2 bytes per character and reverse the bit ordering. Seemed really strange if that was the case.

Is it possible that since Software Serial doesn't work well with baudrates over 38600 then the lines used to change the rate: bluetooth.print("$$$");   delay(100);   bluetooth.println("U,9600,N");   bluetooth.begin(9600); are not received by the module? If that was the case then I would have sent bytes @ 9600 to the module which has a default listening rate of 115200.

That was my next thought.  115200 is really pushing it for Software Serial.


text:
What happens if an interrupt is triggered while sending data via serial?
I would like to use an inertial sensor to measure acceleration and send the results to an Android app using a serial communication with a bluetooth Mate Gold module. The sensor provides a data ready interrupt which notifies Arduino-Mega that a new value is stored in a register of the module. The output data rate can be modified during the configuration of the sensor.
I want the information to be sent at a 10 Hz rate to the bluetooth module.
Is an interrupt at 400Hz capable of compromising the integrity of a 50 bytes long message sent at 10 Hz with a baudrate of 9600?
If yes, which approach would you recommend to correctly send the data?
Edit:
I'm using the following formula to compute the amount of time required to send N chars.
bytes x bits_per_character / bits_per_second
N x (8+2) / 9600 = N/960 secs

For N = 52:
52/960 = 0.054 secs = 54 ms

So theoretically, I can send a 54 char-long message at 18Hz with a baudrate of 9600.
Edit2
I can use the hardware serial or the Software Serial interface.

Have you done the math?

Hi Ignacio, is the math correct?

I think it would depend on how long the interrupt to get data takes to execute. If I were you I'd just write enough code to test it and see.

What do you mean by compromising the integrity of the message? Is there is a delay between the transmission of two bytes of the message? What do you do in your interrupt?

The arduino has hardware serial. So it sort of runs in the background, independent of the main processor.

@fuenfundachtzig the interrupt routines asks a I2C connected sensor.

@Gerben do we have the same property using SoftwareSerial?

I think Software serial might break if interrupts occur during transfer (especially if interrupts take a bit of time)

This could be a problem. Do you have any advice? I sould probably use pin 0 and 1 of the board

SoftwareSerial disables servicing interrupts during transmission of every byte, although interrupts are allowed between consecutive bytes. Looks like you should be safe, but you will have some latency in responding to the sensor interrupt.

Ok that's a good news! So if I send, let's say, 10 chars, the values of the sensor won't be updated for 1/96th of second. (Loosing 4 updates of the sensor considering 400hz interrupt's rate) And this will occur every time the serial communicates with the bluetooth module. I think I have the answer. I will try to implement it and measure latencies.

Actually, the fact that readings are slowed down is a really bad behavior. Especially when dealing with integrations. What about timer interrupts? Does the serial disable them?

Please edit the question to discuss what board you are using and what serial port you intend to use.  The answer depends greatly on whether you have a hardware serial port or SoftwareSerial as interface to the BT module.  Also would benefit to mention the BT module.  On some modules you would be able to up the baud rate to 57.6k or 115.2k, which will change the question?

@narutov6: No, if you send 10 chars, interrupts will be blocked for 1/960 s, while you send the 1st char. If some interrupts trigger during this time, they will be put on hold, and serviced right after the 1st char is gone. Then interrupts will be blocked again for 1/960 s while you send the 2nd char and so on.

Actually I was wrong: at 9600 bps, interrupts are blocked during 9/9600 s ≈ 938 µs (plus a few cycles). They are enabled right after the stop bit has been written, which means they can be serviced during the stop bit period.

If you are on the ardruino platform, and are using the hardware serial port, you basically don't have to do anything.
The Serial library interface already uses a outgoing data-buffer (it's varies between versions, 1.5.5 has it set to 64 bytes. The arduino people keep changing it's size for no reason), where the call to Serial.print() or Serial.write() only places the bytes in question into the outgoing buffer, and the buffer is then emptied asynchronously in the background by the TX-ready (UDRE) interrupt (which is then disabled when the buffer is emptied).
Basically, all you have to do is ensure that you're not placing data into the transmit buffer from both an interrupt and the main loop(), because it's then possible for the message from the interrupt to be inserted into the middle of the message from the main loop thread.
This can be easily enough done by either guarding the call to Serial.print() with cli() sei() interrupt guards in the main loop() section (or the useless arduino analog: noInterrupts() and interrupts(), which are just named proxies for cli() sei(), which exists for no good reason), or simply not printing from an interrupt (which is a good idea anyways, string formatting can be slow).

As of 1.5.5, the transmit buffer in HardwareSerial.h is 64 bytes so his 54 character messages will fit.

@jdr5ca - Good to know. The only arduino package I have installed is 1.0.5, where it's 512 bytes(!).

That is fixed back to 64 in my 1.0.5-r2 install.  Two buffers per serial port is 1k!  With 3 ports on the Mega, that would suck up 3k of RAM = doh!

@jdr5ca - Yeah, it's possible I was hacking one some bits, and that value is not original. I removed the text.

cli() and sei() disables/enables all interrupts, correct? I have got problems with servo controlling (jittering) because of that. A decoupling queue to avoid corrupted serial communication was the only solution in my case.

See http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html for the specifics of sei() and cli(). The arduino serial transmit already involves a decoupled queue, so I'm not sure what's going on in your application.

"noInterrupts() and interrupts(), which are just named proxies for cli() sei(), which exists for no good reason": avr-libc and arduino are two different project, and the arduino library uses the avr-libc. Th existence of cli() sei() in the arduino environment is not because of intention, but the crosstalk of "include" directives.

Arduino is a bunch of libraries on top of avr-libc. There are no good reasons for it to re-implement underlying functions exclusively for the sake of changing their name.

You want to send a 50 byte (or 52 byte?) sequence every 100 ms (10 Hz).
For hardware serial, that will go into a buffer which is emptied via serial interrupts; it should be emptied well before the next 100 ms tic (as you have calculated).
You will get about 40 sensor interrupts during that 100 ms.  With hardware serial, that need not be a problem - so long as you don't send bytes from within a sensor interrupt.  If your sensor interrupt just accumulates results and the main loop (non-interrupt) uses those results to periodically send the 50 byte message, you should be good.
Suppose you were averaging each of the sensor readings.  In the sensor interrupt you might add 1 to the count and add the reading to a sum value.  In the main loop, test if it has it has been 100 msec since the last send, and if so turn off interrupts, divide the sum by the count and store that average in a new variable, zero the sum and count, turn on interrupts.  Then use the computed average to format and send the 50 byte package.
That's just an example.  The main thing is to make the sensor interrupt quick and simple; and to format and send the packet in the main loop (inhibiting interrupts temporarily while fetching and clearing the variables which get updated during the sensor interrupt).
Be sure to use "volatile" for the variables used by both the sensor interrupt and the main loop.
The serial should take care of itself if you use hardware serial, and might even be OK for software serial.  In the latter case, a sensor interrupt in the middle of sending the bits of a single character/byte would mess up the bit timing, but software serial should inhibit interrupts during that time - so your sensor interrupt might be delayed up to a millisecond.

What you are looking for is a way to safely interleave transmitting characters while at same time responding to the interrupts.  You can wrap the sending of bytes with
noInterrupts();
swSerial.write("somethinglongyaddayadda"); // takes 50-60 ms
interrupts();

That will protect the write() operation from being interrupted and ruined by you sensor interrupt handler.  But as you note, that will block the ability to process the the sensor every 2.5 ms.  During the noInterrupts() period you would miss readings.
To achieve the interleave of both operations, you should transmit the message one character at a time.  Implement a transmit queue to hold the outbound string.  When it has characters, send them 1 at a time, wrapping each interrupt protection:
...inside loop...
if(txQueue is not empty) {
  // do not need noInterrupts() or cli() as these are inside write();
  swSerial.write(one character from Q); // takes ~1 ms
  txPointerHead += 1;
}
// at this point the interrupts are enabled
// and the sensor will be processed if available
// if the interrupt occurred in the middle of the above,
// the level is still set and the interrupt handler will be invoked

The 1 ms is ideal and not accounting for overhead, but it is unlikely the 1 character write time could stretch out to 2.5 ms.  As long as the write time stays under 2.5 ms, you will never drop a sensor reading.
Note that this interleave means that the characters will have larger inter-character delay.  The serial ports will not care about that.  But if the processing of the sensor data takes too much time, you will not be able to keep up with your 10 messages per second goal.
Some options I see to improve:

Use a higher baud rate.  The baudrate of the serial port is not related to the bluetooth data rate, so you might as well use the 115.2k.  That will reduce the blocking time.  The baud rate doesn't even need to be the same on both ends.  The BT module isn't a simple modem; it is packetizing characters wrapping them in encryption and transmitting.  The receiver unbundles the packets and pushes out its serial port at the receivers baud rate.
Use hardware serial.  Using a hardware serial port greatly reduces the time because all write() does is put one character into a register.  The time for that is microsecond domain.  After the byte is put in the transmit register, the UART handles the clocking of the bits so the microcontroller is free to do other tasks.

Assuming you're on the arduino platform, the Serial library already does all this for you. It uses an internal 128-byte outgoing ring buffer, and the buffer is emptied by the transmit-ready interrupt of the USART.

True point that SoftwareSerial turns off interrupts character by character, so the calls are redundant.  SoftwareSerial uses the Print::write(uint8_t*,size_t) which is a synchronous call that does not return until all the characters are written.  There is no transmit queue which would allow an asynchronous call (at least in my 1.5.5).  So if he does not want the main loop blocked for the 50 ms periods during the transmit of the entire string,  this was my approach to keep the loop() running.


text:
How to update a variable in an ISR using Timers
I'm trying to check the frequency of Timer3 using a counter. The value of the counter, declared as volatile, is incremented in the ISR and every second the sum is shown in the main loop and the value reset to zero.
The timer has been set up correctly. (If I choose a 3Hz timer I can see the led blinking)
The problem
The counter isn't incremented. Here is the output:
Setup Completed
tick: 1
tick: 0
tick: 0
tick: 0

CODE
volatile int cont = 0;

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

  pinMode(13, OUTPUT);

  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3B = 20; // 800Hz 5; // 3 Hz
  // turn on CTC mode:
  TCCR3B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  Serial.println("Setup completed");
}

void loop()
{
  if (millis() % 1000 == 0)
  {
    Serial.print(" tick: ");
    Serial.println(cont);
    cont = 0;
  }
}

ISR(TIMER3_COMPB_vect)
{
  //digitalWrite(13, digitalRead(13) ^ 1);
  cont++;
}

EDIT
This timer is used to read an anlog value from an accelerometer and store it in an array of float. But at the moment I'm stuck on this update issue.
SOLUTION 1
Thanks to Gerben
volatile int cont = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);

  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3A = 20; // 20; //800Hz 5; // 3 Hz
  // turn on CTC mode:
  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();
  Serial.println("Setup completed");
}

void loop()
{
  delay(1000);
  Serial.println(cont);
  cont = 0;
}

ISR(TIMER3_COMPB_vect)
{
  cont++;
}

SOLUTION 2
Thanks to BrettM
volatile int cont = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);

  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3B =  20; //800Hz 5; // 3 Hz
  // turn on CTC mode:
  //TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();
  Serial.println("Setup completed");
}

void loop()
{
  Serial.println(cont);
  cont = 0;
  delay(1000);

}

ISR(TIMER3_COMPB_vect)
{
  TCNT3 = 0;
  cont++;
}

And if you uncomment the digitalWrite line you see the LED blink about once per second (every 0.66s)?

Yes, If I uncomment digitalWrite and set OCR3B = 5; the led blinks at approximately that frequency.

Then it's a mistery. Have you tried commenting out the cont = 0; inside the loop? What happens then?

Also, the output you provided doesn't match the code, as each line should be "tick: 0" instead of just "0".

Yes I've updated the text with the output I get. Now there is a 1! XD

Try increasing the frequency. I think your if statement may be clearing the counter more often than the interrupt is called, somehow. But then you should see more ones in the output. Also let if run for longer (say 1 minute) and paste the results. Also, when you update the question, leave the old output so your question makes sense (without the edit history).

I've set OCR3B to 20 (800 Hz, prescaler 1024 -> 800Hz right?) and commented the line cont = 0 in the if statement. The output in the EDIT2

Can't see the EDIT2. Did you really save it?

Yes, I've tried printing the value every 5, 20 and 50 sec. The count's value doesn't change.

I suspect that the interrupt routine is being called only once and then it is disabled. I've read somewhere that the interrupts are disabled when an interrupt code is running, and in some cases you have to re-enable it, but I'm really not sure if that's the case. Hopefully someone more knowledgeable will come to our rescue...

In CTC mode the top is OCR3A, not OCR3B!
After that TIMSK3 |= (1 << OCIE3B); should also be changed to TIMSK3 |= (1 << OCIE3A);, and ISR(TIMER3_COMPB_vect) to ISR(TIMER3_COMPA_vect)
For 3Hz, OCR3A should be 5208, not 20.
Technically TCCR3B |= (1 << WGM12); should be TCCR3B |= (1 << WGM32);

With your configuration the counter is not updated and every second the "Setup completed" sentence, (written in the setup() function!) is shown. Really weird behaviour.

Solved using TIMSK3 |= (1 << OCIE3B);. Thank you Gerben! Please modify your answer and I'll accept it as solution.

I forgot the mention you also need the change the ISR vector. ISR(TIMER3_COMPB_vect) should be ISR(TIMER3_COMPA_vect). If an ISR isn't defined, the AVR will reset itself, like you were experiencing. Glad you got it working.

It seems my answer to this question was previously incomplete, thanks for pointing out that CTC mode only works with OCR3A Gerben. I apologize for not testing an answer before I post it.
Given the information only in this question Gerben's answer is complete, but since your other question implies that you cannot use OCR3A due to the Servo library I'll add a bit. (I've also edited that answer)
you can emulate the behavior of CTC mode by setting TCNT3 to 0 in your interrupt routine. Remember to remove the line that turns on CTC mode in your code.
I've tested your code with this ISR:
ISR(TIMER3_COMPB_vect)
{
  TCNT3 = 0;
  cont++;
}

and this configuration of the timer registers
OCR3B = 5208; // 800Hz 5; // 3 Hz
// Set CS10 and CS12 bits for 1024 prescaler:
TCCR3B |= (1 << CS30) | (1 << CS32);
// enable timer compare interrupt:
TIMSK3 |= (1 << OCIE3B);

This might be a bit less accurate at high frequencies than CTC, I'm not sure, but at 3Hz it worked perfectly. Notice that 5208 was the correct OCR value, not 20 (again thanks to Gerben).

I've tried your code but the counter isn't incremented. I've added the TCNT3=0; in the ISR() and removed
//TCCR3B |= (1 << WGM32); in the setup() as you said. I've also tried commenting out the cont=0; line but nothing changed

Make sure the code matches what is posted in the question in every other way. Try changing your loop to just println(cont); delay(1000);. Also you are still including the bits with cli() and TCCR3A etc correct?

Ok thanks. At 800 Hz is still accurate!


text:
How to use a Pololu 5v AVR ISP Programmer to program an AVR at 3.3v
I have a Pololu 5v AVR ISP which I have successfully used to program several Arduinos (a Mega, an Uno and a Pro Mini 5v). I now have a new Arduino compatible clone which is basically a clone of the pro mini 3.3V.
I am wondering if anyone else has used this programmer to program a 3.3V board without issues. I've seen a forum post on pololu's forum which discusses modifications required - but I don't really understand what is necessary.
I've also found the software tool mentioned in the above forum post here and I have downloaded it and built it.
When I run the aforementioned tool I get these options:
PgmCmd: Configuration and status utility for the Pololu USB AVR Programmer.
Version: 1.0.1.0
Options:
 -l, --list             list available devices
 -d, --device SERIALNUM (optional) select device with given serial number
 -s, --status           display complete device status
     --freq NUM         sets the ISP frequency (in units of kHz)
     --linea ID
       or --lineb ID    set serial control signal associated with line A or B.
                        Valid IDs are: none, cd, dsr, ri, dtr, rts.
                        Warning: dtr and rts are outputs: -f option is required
     --swminor HEXNUM   AVR ISP software version minor (in hex, e.g. A)
     --swmajor HEXNUM   AVR ISP software version major (in hex)
     --hw HEXNUM        AVR ISP software hardware version (in hex)
     --vddmin NUM       set minimum allowed target vdd (units of mV)
     --vddmaxrange NUM  set maximum allowed target vdd range (units of mV)
     --restoredefaults  restore factory settings
     --bootloader       put device in to bootloader (firmware upgrade) mode

I then ran the --status option with the serial number of my programmer and got this:
Serial number:                  00048632
Firmware version:               1.07
Settings:
  ISP Frequency:                200 kHz
  Line A Identity:              None
  Line B Identity:              None
  AVR ISP hardware version:     F
  AVR ISP software version:     2.A
  Target VDD allowed minimum:   4384 mV
  Target VDD allowed max range: 512 mV
Last programming:
  Error: None
  Measured Target VDD Minimum:  N/A
  Measured Target VDD Range:    N/A
SLO-scope:
  State:                        Off
  Line A output:                Off
  Line B output:                Off

From this I deduced that my programmer is currently set at between about 4.38V and 4.89V which I presume corresponds to the 5V approximate voltage of the normal Arduino chips.
Given that the utility program allows me to set both the target minimum Vdd and the target Vdd max range should I therefore set it to something like a minimum of 2704 with a max range of 512 which should put the signal voltages at up to ~3.2V.
Is that all I have to do to get this to work?

Instead of modifying your programmer to wok with 3v you can also consider buying a USBasp programmer that has a jumper to select between 5v/3v. The cost is less than $3 from ebay.

I tried the usbasp method. I bought a cheap one off ebay. When it arrived it didn't work until I gave it a firmware upgrade - fortunately I had the other programmer to do that with. Then having had it's firmware upgrade I tested it out on my arduino with mega2560 and my arduino bt with a 328p. I simply tried the blink sketch - on the bt it worked but not on the 2560. Turns out cheap chinese programmers don't always set the fuses correctly and I had to reload the arduino bootloader using my other programmer. I decided not to risk using the usbasp on my 3.3v things.

That is actually unfortunate to hear. I have a USBasp clone (Baite EvUSBasp specifically) and have had success with it for the most part, but I've not tried it at 3.3V.

fair enough. i guess it's just a pot luck thing on which manufacturers clone you get.

Since AVR ISP is simply a modified form of SPI, the most universal way to handle this is to use a 3/1 level translator such as the MAX3392E. Once you provide it with 5V on VCC and 3V3 on VL it will translate the MOSI, SCK, and nRESET signals to 3V3 and the MISO signal to 5V.

Thx. I now have 2 more questions - why does MISO stay at 5V? and I'm not sure I can easily get hold of the part you mention but I do have several of these: https://www.sparkfun.com/products/retired/8745
Could I use the tx (bi directional despite name) lines of those instead?

I should probably add I come from a Software background rather than hardware and have only really used the serial and I2C interfaces of the Arduinos for communication so haven't come across SPI before.

"MISO" stands for "Master In, Slave Out". It's the signal going from the slave (the device) to the master (the programmer). That translator should work provided that 1) you have 4 bits total, and 2) you fix the 3V3 side as described in the comments.

Thanks for this - eventually though I went with @alexan_e's solution of purchasing a cheap programmer from ebay. I didn't realize they were quite so cheap.

I've come back to this solution because cheap ebay programmers are cheap rubbish.


text:
How to power Arduino externally for long term?
For a robotic project, I need to keep an Arduino powered up for a long time in an outdoor environment. What can I use to power the board?
If battery is the only solution, can the device tell me remotely that battery is getting low?
It needs to be powered for at least few days ( at least). The unit monitors an outdoor sensor that is shaded from sun but still exposed to wind and moisture. The unit does not move.

This is very vague. How long do you need your system up? Are the circuits unprotected? Is it in a sunny environment (allowing for the possibility of a solar panel)? For the second part of the question: How far will the robot be? What communication interfaces do you have in mind? Do you have existing interfaces in your robot? Lastly, have you done any research starting from a basic Google search? The more detailed the question, the better the answers you will get.

Yes, this needs a lot more detail. Is it a mobile robot, static, how much power does it consume, what kind of voltage do the motors need, what kind of life do you need. Etc.

And robot definition is vague too... a robotic arm could be a robot.

Power requirements? 1W? 10W? Other than the Arduino and "sensor", do you have other components?

There are several options for Arduino power in an external environment.

Wall wart: Connects to a wall socket, provides a great long-term source of power
Rechargeable battery: Doesn't last long, but they can be recharged and monitored with a low cost board
Alkaline Battery: Last longer, there are some monitoring systems available.
Solar: Only works when the sun is out, unless you combine it with a rechargable battery (example)
Nuclear power: NOT RECOMMENDED!!!

Nuclear power is the best option. The OP should totally go nuclear.

Don't forget about hydrogen fuel cells, hydroelectric, or even wind energy.  Geothermal might be an option depending on what/where the device is. Gasoline engines/generators are an option as well.  Most renewable sources should be coupled with a battery to store excess energy when the source ceases for a time period.  (I'm being totally serious, with the possible exception of hydrogen fuel cells.)

Come one, go for the fusion power (The sun have been using it successfully for a long time now). I think that with fusion on a robot it will go near eternally.

@Faux_Clef - Fusion power is nuclear power.

@FakeName: yes, nuclear as in fusion of atomic nucleus into new elements ie. the sun. Nuclear power is also fission, the kind used in nuclear reactors/power stations.

@Faux_Clef - Fission and fusion are both types of nuclear power.

Depending on the project, an RTG might very well be a reasonable option; if you can get your hands on one.

Nuclear isn't really a joke - you could use a nuclear battery... http://en.wikipedia.org/wiki/Atomic_battery


text:
Convert a Bitstring into an integer value
I have got a String filled up with 0 and 1 and would like to get an Integer out of it:
String bitString = "";
int Number;
int tmp;

bitString = "";
  for (i=1;i<=10;i++)
  {
    tmp= analogRead (A0);
    bitString +=  tmp % 2;
    delay(50);
  }
// now bitString contains for example "10100110"
// Number = bitstring to int <-------------
// In the end I want that the variable Number contains the integer 166

What is the question? What do you expect this code to do and what is it doing? What else have you tried?

@Craig I eddited the question. For example If the bitString contains a "10100110" I want the programm to save it as the decimal 166 in the int variable.

Do you need the string? You could create the integer representation directly.

@Craig i would also like to print out the bitstring

If you only need the string for printing you can store value in an integer and then use the Serial.print(number,BIN) function to format the output as a binary value.  Appending integers to strings is a potentially costly operation both in performance and memory usage.
int Number = 0;
int tmp;

for (int i=9;i>=0;i--) {
  tmp = analogRead (A0);
  Number += (tmp % 2) << i;
  delay(50);
}
Serial.print(Number, BIN);

Yes your solution looks more efficient! and does the work

Check out strtoul()
It should work something like this:
unsigned long result = strtoul(bitstring.c_str(), NULL, 2);
Now you have a long variable which can be converted into an int if needed.

@kimliv Did you add .c_str() to the end of bitstring as Peter pointed out above? c_str() should return a const char*.

it is working that way!


text:
Issues programming Arduino Uno with Sparkfun's MAX3232 breakout board
I'm having an issue programming the Arduino Uno with Sparkfun's MAX3232 breakout board attached.  Sometimes the Arduino IDE won't see the Uno plugged in.  I'm thinking of  connecting a switch to the GND or the 3V - 5.5V pin so I don't have to disconnect the breakout board when programming.  Are there any better solutions?
Sparkfun link: https://www.sparkfun.com/products/11189

Switching off power to the MAX2323 might work. I assume you understand the MAX2323 is connected to exactly the same pins as the host PC, via USB, and that is the problem source. Yes? Would you post a link to the MAX2323 you are using? Is there a schematic diagram? I would like to see the schematic diagram so that I could see if the MAX2323 might still present a load to the Tx Rx lines when it is powered off. For serial communication, the Tx and Rx lines may be pulled up by resistors, and you would like them to be defeated or disconnected too. We should probably look at the MAX2323 data too

Hi gbulmer.  I meant the MAX3232 breakout, but I think you probably figured that out.  I've included a link to sparkfun's breakout board to the original question as well.

Thank you for the schematic. The breakout has no resistors on Tx or Rx to cause any problems. It looks like switching off power would work, and it is an okay solution. To be more sure, we need to look at the datasheet for MAX3232. I would expect it to be designed well enough that it won't be harmed by having lines driven while it is off, or that it could pull-up a signal line while off, but it is worth a check. I apologise, but I am off till tomorrow. Good night from the UK.

Good night, thanks for the help and tips!

PS - My alternatives were: use an enable/disable on the RS232 converter (there isn't one, so that is dead), disconnect MAX2323 Tx (as that interferes with the Host PC's signal), or disconnect both (if necessary).

Off to bed for real now :-)

@NickAlexeev this should not have been migrated, as it is an EESE appropriate question primarily hinging on understanding of the MAX232 IC, not the "Arduino-ness"

Switching the power off to the MAX3232 appears to be okay.
There are no components connected to the Rx and Tx lines on the breakout board to complicate it.
Unfortunately the break out does not give access to pin 1, EN which is "Enable Control", or pin 18 SHDN "Shutdown Control". AFAICT they could have been used to turn off the receiver and transmitters of the MAX3232. That would have been ideal. Maybe contact Sparkfun and suggest the improvement to put them on pads for folks to use, and offer to beta test it :-)
The datasheet for the MAX3232 says that it is able to withstand a continuous short on the Tx line, so it sounds pretty tolerant to minor abuse. Also, the diagrams dont show any pull-ups on the MOS/TTL Tx line. So I would expect it t be okay if you shut the power off, but continued to wiggle the Tx Rx pins.
An alternative would be to disconnect the Tx pin from the Arduino, so that the MAX3232 wouldn't interfere with the host PC's USB comms. It sounds like the thing on the RS232 connection will ignore data it receive while the Arduino is being programmed. If that is not true, then it would need to be disconnected too.
At the moment, switching off power looks like a reasonable approach.
Disconnecting Tx and Rx also looks reasonable, and slightly better than powering the MAX3232 off.
Do you know how you want to do that?
NB: The MAX232 datasheet shows that part should not be driven by a high when the chip is unpowered. However the MAX3232 datasheet does not carry that warning. My preference would be to use the MAX3232 signals 'EN' and 'SHDN'. However those are not available on the breakout. I'd recommend having the part powered, and disconnecting Tx and Rx from the Arduino.

Hey, you're still awake!  Thanks for interpreting the datasheet for me, I'm not very good at that.  I'm thinking of just a simple switch at either the GND or power.  I can also have switches at the RX and TX lines like you suggested earlier.  I think I'll do more testing with the things you suggested.

@ChrisStratton - Is MAX232 a typo? The question is about MAX3232. If it is a typo, that is an extremely important point, and I will correct my answer. I looked for that information, but may have missed it.

Sorry, I did indeed look up the wrong part, and the specs on the MAX3232 appear to be different without the MAX232's input-above-Vcc restriction.  It would be interesting to use an ammeter to see what if any current the chip draws through the TIN pin when unpowered.

@ChrisStratton - I amended my answer to show a WARNING pending clarification. I will remove that warning.

@ChrisStratton - I have amended my answer. I have removed that warning, but kept a note to reduce the chances of the same concern being re-raised.


text:
Digital pins on Arduino function as both positive and negative terminals?
I'm learning the arduino platform and working on a circuit that connects the two pins of a piezo buzzer -- one to ground and the other to a digital pin of the arduino board. In this configuration, is the arduino's digital pin acting as the positive terminal of the circuit?
The arduino docs seem to suggest it is:

They (the digital pins) can provide a substantial amount of current to other >circuits. Atmega pins can source (provide positive current) or sink (provide >negative current) up to 40 mA (milliamps) of current to other devices/circuits.

Can the digital pins act as both positive and negative terminals in circuits? Does this question even make sense? What resources are out there that can help me better understand the underlying electronics of the arduino and microcontrollers in general?

The answer to your question is basically yes, you can use ATmega I/O pins as +/- power supply terminals for other circuits. But there's a limit to what you can power that way (20mA per pin and 100mA total per ATmega). In practice this means you can only power the simplest circuits (single LEDs per pin, and not many LEDs in total, for example). As a general rule, you should really look for other ways to power anything else.
Also, there's a problem with the citation you gave. That 40mA figure is the absolute maximum current per pin, but that should be avoided. Safest is to use about 20mA of maximum current per pin. Also, the ATmega pins should not have more than 200mA flowing through Vcc and GND (also an absolute maximum that should also be avoided).
Usually, you should either power other stuff off of the regulated +5V that also feeds the ATmega (up to the regulator capacity that depends on the Arduino board - 500mA for the Arduino Uno - 1A for LM7805 regulators - and so on). You could also use the unregulated power in some cases. Then you should use digital pins on the ATmega to switch transistors on and off which in turn will switch your load. Sometimes you can use transistors to switch relays, that in turn will switch even larger loads.

Step one: read the data sheet for the microcontroller.  In there is a nice diagram that shows you exactly how the IO pins work.
The pins can work in 2 modes: input, and output.  You're interested in output mode.
The drive state of a CMOS output pin consists of two MOSFETs, one connecting the pin to Vcc and the other connecting it to GND.  Only one of the MOSFETs is ever turned on at a time, so the output pin is either connected to Vcc through one MOSFET, or connected to GND through the other.
When it's connected to Vcc it's said to be sourcing current, since it's at a positive potential compared to ground and current can flow out of the pin to light an LED (say), and when it's connected to GND it's said to be sinking current because current can flow into the pin to get to ground.
As an example of how it all works, consider how you would connect up and power a capacitative humidity sensor.
These sensors require a square wave at around 1KHz to operate.  The humidity defines the impedance, and as part of an impedance divider (like a resistor divider) the output voltage is relative to the humidity.
Now, they don't just want any square wave, but require a square wave that reverses polarity around a virtual ground point, and that means reversing the polarity of the power across the sensor at 1KHz.  How can you do that with an Arduino? The answer is simple:
Connect the sensor to two IO pins rather than 1 IO pin and GND.
Both pins are set as output, and one is set HIGH with the other set LOW.  So the voltage across it is 5V.
Now you switch the outputs over, so the one that was HIGH is now LOW, and the one that was LOW is now HIGH.  The power across the sensor has been reversed!  It's now (effectively) -5V (compared to what it was before).

Yep, that's what I said ;)  But remember you only have limited current available, or the MOSFETs will overheat and the IO pin will die.  40mA absolute maximum, 20mA recommended maximum.

"...if it is in input mode it is functioning as a connection to GND?". No, that's not correct. You misread Majenko's explanation. In output mode, the pin can be either driven high (to Vcc) or low (to GND). In input mode, it's typically high-impedance (neither high or low) so it can read an external voltage.

And I mis-read Jog's comment.  Yes, in input mode the pin is connected to a completely different part of the circuit.  Take a look at Figure 13-2 in the data sheet. The IO pin is split 3 ways - one to the input circuit (bottom), one to the output circuit (middle) and one to the pullup circuit (top).

Step one, for someone beginning an electronics hobby by trying stuff on an Arduino, definitely isn't to read the ATmega data sheet :)

Considering the question was posted on the EE SE then yes, step one is definitely read the DS.  For anyone, regardless of expertise, who wants to understand how the internals work, then step one is, guess what? read the DS!

To summarize other people's answers:
Arduinos have a whole bunch of GPIO, or general purpose I/O, pins. They can be configured as digital inputs or digital outputs. Certain pins can also be configured as analog inputs or PWM outputs.
For a simple digital pin, if it is an input, it has nearly infinite impedance. (It looks like an open connection.)
If it's an output, it acts like a current source (connected to +5V) if it's HIGH, and acts like a current sink (connected to ground) if it's LOW.
Arduino I/O pins (on most boards, check your board's specs) have a hard limit of 40mA of current flowing through them, but you should generally keep the current below 20 mA.
Is a ground connection the same as a negative connection? Sort of. Some circuits include ground, one or more positive voltage sources, and one or more negative voltage sources. Audio (analog) circuits, for example, often need ground, +12, and -12 volts.
Arduinos don't deal with negative voltages, and applying a voltage that's less than ground to any pin will likely destroy it.
Think in terms of positive voltage and ground, not positive and negative. It's less ambiguous.
Don't think of Arduino pins as being power sources. Remember that they are LOGIC pins, and only put our very small amounts of current. Trying to source or sink too much current from an Arduino pin may destroy it.
If you need to source or sink more than 20mA, use a transistor as a switch to handle the higher current load.
In addition to all that, you need to watch the total current that you pass through all your logic pins, and also the total current you draw from the power supply. Check the specs on your board and make sure you stay within the limits.

When a GPIO pin is set to output mode, you can either drive it "high" (ie: VCC), or "low" (GND). They can not, however, drive a negative voltage (ie: -VCC). If you want to create a negative voltage, you'd need some external GPIO expander chip sourced off some negative voltage supply, or you'd need to create a negative voltage rail source via a buck-boost converter or similar to generate it from Vcc.
Fortunately for you, Arduino already has a pieze-electric buzzer library, and wiring it up is dead simple. The relevant GPIO pin is connected to the buzzer's positive terminal, and the buzzers negative terminal is grounded.

Great, so then in this particular example, the piezo is being powered by the connection to digital pin 8 correct? And we could reliably assume that circuit current is definitely less than 40 mA and probably lower than 20 mA before we measure it? Also, technically speaking, could we say that electrons are in fact flowing from the board's GND to digital pin 8?

@Jog I don't know how a piezo-electric buzzer alters current flow, so let's just assume it's limited to Vcc / R at the most. Forget about the flow of electrons, just accept that the "conventional current" is flowing from the output of GPIO pin 8, through the resistor and buzzer, into the ground, as part of a closed circuit. If you need more current than the Arduino can supply, just have the Arduino connects to the gate of a power MOSFET (ie: http://www.hobbytronics.co.uk/image/data/tutorial/arduino-tutorial/power_mosfet.jpg).

@Jog a piezo will naturally pull more than 40 mA due to ohm's law with its resistance; that's why there is the resistor (that little yellow/tan thing there on the + line).

First of all, the Arduino doesn't supply negative voltage. It flows from positive to ground, the reference point that determines voltage.
Anyway, I'm not quite sure of the exact details of the inner-workings of the ATmega chip, but I assume it goes something like this:

A CPU cycle modifies a CPU register (or similar memory/latch somewhere)
To the output of that "register," a circuit is connected that:

Shorts the pin to 5V if HIGH
Shorts the pin to GND if LOW

I suppose the latch could be directly connected to the pin, but I think that the current draw might be too high for the latch circuit, so an external transistor is used.
That above isn't anything that's really technically correct (as these details aren't always released), but its intended purpose is to show you how it basically works from a logic point of view.
You can then manipulate the pin's connection using either of these two pieces of code:
//HIGH (== 5V)
pinMode(5, OUTPUT);
digitalWrite(5, HIGH);

//LOW (== GND; 0V)
pinMode(4, OUTPUT);
digitalWrite(4, LOW);


text:
Two 300RPM 12V DC motors connected to arduino motor shield r3 power supply
I have two 300RPM 12V DC motors connected to arduino motor shield r3 that is mounted on arduino uno board.
Problem is my motors  runs very slow some times not even running.
After googling I found I need to use external power supply. I did  supplied 9 volt dc power to arduino motor shield r3.
But still motor is running very slow what could be the issue.
My other questions.
When supplying power to arduino motor shield r3  via external power supply pins do I need still need to provide separate power to arduino uno board via power jack.
Can I use 9 volt dc for arduino uno board and another 9 volt batter to arduino motor shield r3.
Is single 9 volt batter enough for running two 300RPM 12 dc motor.
My circuit.

My program
          void setup() {

          //Setup Channel A
          pinMode(12, OUTPUT); //Initiates Motor Channel A pin
          pinMode(9, OUTPUT); //Initiates Brake Channel A pin

          //Setup Channel B
          pinMode(13, OUTPUT); //Initiates Motor Channel A pin
          pinMode(8, OUTPUT);  //Initiates Brake Channel A pin

        }

        void loop(){

          //Motor A forward @ full speed
          digitalWrite(12, HIGH); //Establishes forward direction of Channel A
          digitalWrite(9, LOW);   //Disengage the Brake for Channel A
          analogWrite(3, 255);   //Spins the motor on Channel A at full speed

          //Motor B backward @ half speed
          digitalWrite(13, LOW);  //Establishes backward direction of Channel B
          digitalWrite(8, LOW);   //Disengage the Brake for Channel B
          analogWrite(11, 123);    //Spins the motor on Channel B at half speed

          delay(3000);

          digitalWrite(9, HIGH);  //Engage the Brake for Channel A
          digitalWrite(9, HIGH);  //Engage the Brake for Channel B

          delay(1000);

          //Motor A forward @ full speed
          digitalWrite(12, LOW);  //Establishes backward direction of Channel A
          digitalWrite(9, LOW);   //Disengage the Brake for Channel A
          analogWrite(3, 123);    //Spins the motor on Channel A at half speed

          //Motor B forward @ full speed
          digitalWrite(13, HIGH); //Establishes forward direction of Channel B
          digitalWrite(8, LOW);   //Disengage the Brake for Channel B
          analogWrite(11, 255);   //Spins the motor on Channel B at full speed

          delay(3000);

          digitalWrite(9, HIGH);  //Engage the Brake for Channel A
          digitalWrite(9, HIGH);  //Engage the Brake for Channel B

          delay(1000);

        }

9v "transistor" batteries are rarely suited for motors, and generally a poor choice for the arduino itself. Even with a lower impedance 9v supply, your 12v motors would probably perform poorly with only 9v in and the motor shield itself loosing at least another volt.

@ChrisStratton What is the solution. What battery or should I have do to make run at decent speed. Any suggestions..

Disconnect the motors and battery from the motor shield. Then do these tests: 1. When you connect your 9V battery to one motor, does it run much more quickly, and well enough? 2. When you connect both motors to the battery do they run okay? If either answer is no, then the current approach is not going to work. Even if it is okay, the Arduino motor board will reduce the battery voltage, making things worse.

The external power of the shield is connected to the VIN pin, so it will power the Arduino via that. (vin goes to the voltage regulator that will provide the 5v the arduino needs).
You can connect two batteries in parallel to provide mode current.
But since they are 12v motors, they would need 12v to run at maximum power. 9v is a lot less than that.

would you please give a word here : http://arduino.stackexchange.com/questions/9145/which-battery-should-i-use-to-power-arduinomotor-shield-two-motors


text:
Arduino Uno and Agilent ADNS-3080 not reading from SPI
I am trying to interface with a mouse sensor and am not able to get data back.
datasheet link
I have it still soldered to the original PCB but have cut the traces to pins 1-4,6,7 (NCS [SS], MISO, SCLK, MOSI, RESET, NPD [power down {set to 3.3v}])
PLEASE LET ME KNOW IF ANYTHING SEEMS WRONG HERE.
According to the Datasheet, by default the sensor is setup with the pull-up resistors enabled [pg. 29] which enables the open-drain, allowing me to directly connect NCS,MISO,SCLK,MOSI directly to the 5v microcontroller [pg. 15]. This also requires the SPI speed set to 500khz [pg. 10]. RESET is in a (10k)(10k+10k) resistor bridge.
SPI should be set to Mode3 as SCLK is normally high and data should be captured on the rising edge of the clock pulse [pg. 16]
Here is my code:
#include <SPI.h>
const int MOUSEVERSION = 0x00; //mouse version
const int CSmouse = 10;
const int mouseReset = 2;
char val;

void setup() {
  Serial.begin(9600);
  SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE3));
  pinMode(CSmouse, OUTPUT);
  pinMode(mouseReset, OUTPUT);
  digitalWrite(CSmouse, HIGH);
  //pull reset pin high for a half second to make sure mouse is ready to go after powering on [pg. 22]
  digitalWrite(mouseReset, HIGH);
  Serial.println("setup");
  delay(500); //half a second
  digitalWrite(mouseReset, LOW);
  Serial.println("end setup");
}

void loop() {
  Serial.println("Start loop");
  digitalWrite(CSmouse, LOW); //CS enable
  SPI.transfer(MOUSEVERSION); //0x00 = read register Product_ID, should reply 0x17
  delayMicroseconds(75);
  Serial.println(SPI.transfer(0)); //actually just gives 0
  delay(500);
}

You have SPI.beginTransaction but no SPI.begin().
SPI.begin() is needed to initialize the SPI hardware.
More details about SPI at SPI - Serial Peripheral Interface - for Arduino.

Thank you! I was under the impression that beginTransaction() superseded begin() since setClockDivider() and the like were depreciated.  That is what I get for assuming.