text:
Arduino time keeping using millis() is not accurate or correct?
I have been using the Arduino to record some data. In my Arduino sketch I also used the millis() function so I can keep track of the time at which each value I am measuring is taken. However, I noticed that the timing isn't correct. For example 30 seconds in real life only comes out as 10 seconds (made up example).
Am I correct in saying that the Arduino delay function affects the time keeping using millis()? In other words suppose I have a delay of 50ms, does that mean the millis() function stops for that duration as well and then continues and so on for the duration of the connection? I noticed this when I tried plotting some data and finding that the frequency of the peaks in my data was too frequent given the time which had passed by. So I want to know if that is the reasoning for this mismatch of timing and if so, how do I fix this so that I can keep the time each sample occurs?
To give some context here is my sketch:

#include <eHealth.h>

unsigned long time;
// The setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);
}

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

  float ECG = eHealth.getECG();
  time = millis();
  Serial.print(time);
  Serial.print(" ");
  Serial.print(ECG, 5);
  Serial.println("");

  delay(50);
}

Are you using one of the official Uno boards?

Actual timing instead of made-up values (a serial monitor that timestamps the lines is ideal) would probably help figure out what's going on.

The computation of millis() is interrupt driven, so delay() should not affect it.

I have the same problem but only when i integrate it (millis()) into complex code. I guess complexity of the code affects its accuracy in way it goes more and more into delay with the complexity of the code. Is there any way to avoid this? maybe using separated RTC module?

millis() is interrupt driven so delay() won't impact it, at least not on an ATmega based board.
That isn't to say that millis() is totally accurate either. Each tick of the timer is not exactly 1ms, but is 1.024ms. This error gradually accumulates until a correction is made. This can be seen in the implementation of the TIMER0_OVF (timer 0 overflow) interrupt handler.
Another source of inaccuracy is the oscillator/crystal itself, which is not exactly 16MHz. It is pretty close though, and as long as temperature doesn't change too much, is relatively stable.
The above means that you might be about 1ms out when using millis(). This doesn't sound like your problem.
Another potential issue would be what getECG() is doing - it might be very slow.
float eHealthClass::getECG(void)
    {
        float analog0;
        // Read from analogic in.
        analog0=analogRead(0);
        // binary to voltage conversion
        return analog0 = (float)analog0 * 5 / 1023.0;
    }

analogRead() is slow, but not so slow as to impact a loop like this.
Another problem I have seen people have is when they change the clock speed but don't correctly change boards.txt. This means that the constants used in the millis() implementation are wrong and the times are wrong.
If you actually want to read values every 50ms, a much better way of implementing this is to do the following
static long lastUpdate;

if (millis() - lastUpdate > 50)
{
    lastUpdate = millis();
    //Do stuff
}

We'd really need to see the timestamps you are getting. If you actually seeing 30s showing as 10s, then there is something else at work.

Please note that, for the Uno, the clock is not crystal-driven, but just uses a ceramic resonator which is less accurate than a crystal.

@jfpoilpret Ah good to know.  Looking at the schematic, this would be the CSTCE16M0V53-R0 Murata CERALOCK device.

Resonators have a poor initial tolerance (often 0.5-2%) and poor temperature stability, but if you calibrate timing loops when using them, they can be fine as long as temperature doesn't move.

Millis() still works on a timer that ticks every 1.024ms, but they added error compensation, in the form of incrementing whenever an error meter variable gets too high. I think it's Roman Black's algorithm actually.  So timing should be much closer to 1ms exactly.https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/wiring.c

For those still interested, see the comment I have posted on JRobert's answer, I didn't want to reply with my own answer since I don't have one, I have just rephrased the problem.

A more optimized getECG: float eHealthClass::getECG(void) { return analogRead(0) * 5 / 1023.0; }

If interrupts are turned off for any significant fraction eHealth.getECG() call duration, millis()'s count could fall behind. Otherwise, millis() should return much more accurate time than the 3x errors you described.
You said your sampled signal appears higher in frequency than what you expected, which could happen if your sample rate is lower than you intended. Are you a assuming a 20Hz sample rate? Your loop could be taking a fair bit longer than 50ms, which you would see in the printed times, but those should still track the clock time. If you didn't account for that but assumed 50ms/sample, you'd see an apparent speed up of of the data.
If this is not the issue, then the next step would be to toggle an output while you're in loop(), and measure the frequency of the resulting square wave with a frequency meter (some inexpensive DVMs can do this) or a 'scope. Do the same thing with an empty loop(). The first experiment will your real sampling rate or interval; the second will tell you whether millis() (ie., the timer0 frequency) is what you expected.

I have been playing around with it further and have come to realise that the issue is not with the Arduino, the millis() function for the most part works very well, some of the values are not exactly 8ms (delay) apart but from what you have said that is to be expected. The 3x error I described is true of the Python side of things which I using to receive the data. Any idea what that could be a result of, I am using Python's pyserial and it is slow as hell.

I don't know enough about your implementation to give you more than a 1/2@'d guess, but is the Python side slow enough to be dropping samples?

Same here. I can add that if interruptions are turned off, the time measured is "real time". Anyway, I dont understand why this delay, because if the loop take too long, anyway the millis() should return real time values (only with more distance between each value)

What does "same here" refer to? Answers should stand on their own, as StackExchange can re-order things (unlike a forum). So "same here" could mean anything depending on what reply/question your answer appears underneath.

This post would be more appropriate as a comment, although (admittedly) you lack sufficient reputation .

Sorry, I though when you answer something, its obvious it's refering to the main post, otherwise it would be a comment


text:
How does this code line detect if a serial interface is connected?
I am working with some code for remote temperature sensor nodes. They turn the debug interface on and off depending on if anything is conneced to the serial port or not.
The code is on Github here. Line 111 is the line of interest:
if (Serial) debug = 1; else debug=0; //if serial UART to USB is connected show debug O/P.

So, a simple question: On a hardware and software level, how does this work? I can't see anything in HardwareSerial or Stream that would return true/false if anything was connected or not.
Note that I am not confident that it actually works. This simple test indicates it doesn't work as the LED flashes regardless of the presence of a serial adapter or connection:
boolean debug;

const int toggle = 6;

void setup()
{
  if (Serial) debug = 1; else debug = 0;

  pinMode(toggle, OUTPUT);
  digitalWrite(toggle, LOW);

  if (debug)
  {
    Serial.begin(9600);
    Serial.println("Setup");
    digitalWrite(toggle, HIGH);
    delay(1000);
    digitalWrite(toggle, LOW);
  }
}

void loop()
{
  if (debug)
  {
    Serial.println("Loop");
    digitalWrite(toggle, HIGH);
    delay(1000);
    digitalWrite(toggle, LOW);
    delay(1000);
  }
}

Sidenote: For traditional RS232, the only way to really determine if something is connected is to send out data, and see if you get a response. There is no other universal connection detection mechanism. This is why serial devices on windows still sometimes get detected as a mouse. The OS assumes a certain set of characters means there is a mouse present, since it has no other way to corroborate this assumption, it just runs with it.

You're right -- it doesn't work in most cases, and will almost always return true. The one board where it's actually functional is the Leonardo. According to the official documentation:

On the Leonardo, if (Serial) indicates wether or not the USB CDC serial connection is open. For all other instances, including if (Serial1) on the Leonardo, this will always returns true.

Basic serial connections (used by most Arduinos) usually don't care if anything is actually listening. It's not uncommon for embedded devices to send debug info by serial even when nothing is receiving it. This has the advantage that the code's timing and behaviour won't change when debugging, which could cause all sorts of problems if you're trying to diagnose a problem reported in the field.

While it may not be possible to detect whether a device is connected to the Arduino serial connection or not, it is possible to enable the debug messages over the serial connection based on the presence of a device on the serial connection.
Considering that you will be using the debug interface of your sketch only when connected to a computer capable of serial communication, it is possible to incorporate a simple test into the sketch based on which debug mode is enabled or not.
When the sketch starts, you can check to see if any data is available on the Serial connection or not. If there is, then a device is present and debugging can be enabled. On the computer side, everytime you want to start the debugging mode on the Arduino, simply send a byte over the serial connection during the setup phase and sit back.
Here is a sample sketch showing the same:
int debug = 0;

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

  //Wait for four seconds or till data is available on serial,
  //whichever occurs first.
  while(Serial.available()==0 && millis()<4000);

  //On timeout or availability of data, we come here.
  if(Serial.available()>0)
  {
    //If data is available, we enter here.
    int test = Serial.read(); //We then clear the input buffer

    Serial.println("DEBUG"); //Give feedback indicating mode

    debug = 1; //Enable debug
  }
}

void loop()
{
  if(debug==1) Serial.println("ON");
  digitalWrite(13,HIGH);
  delay(1000);
  if(debug==0) Serial.println("OFF");
  //Turn off if serial is not available
  digitalWrite(13,LOW);
  delay(1000);
}

This is pretty much the technique I use on my own code.

Imho, you could also enable serial output as soon as it receives a character. Or use different build modes (in an advanced IDE), or may be even check if the input voltage comes from the USB.

source: Stack Exchange

license: 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/

sort: votes


text:
How to implement multiple LED modes in a sketch with potentiometers?
My hardware is 4 potentiometers connected to Arduino Analog 0-3, the output is an RGB led driver connected to Digital outputs 9,10,11. The output channels provide access to PWM control of those pins. So idea is the color and intensity can be controlled by the Arduino. I wrote a simple Sketch that reads the potentiometers and then outputs PWM to the RGB driver circuitry. This works great! So the hardware is working! Now comes the last potentiometer...
I want to make the last potentiometer a "mode select" control. It would function like this: If the last potentiometer (Pot4) is turned down all the way, then all lights are off. If the level is turned up a little, the Arduino then controls the RGB channels via Pots 1, 2 & 3. If Pot4 is turned up to just past halfway, the sketch enters a "strobe flash pattern" pulsing all channels on and off. And if the mode control Pot4 is turned up all the way, Arduino turns on all RGB channels.
How do I implement? Mode selection via a potentiometer?

Have you looked at how analogRead() works yet?

It seems you already have code for the 3 first pots to drive the RGB LED; it would be good to show it here so that answers can better show where to modify the current code.

Since you already know how to hook up a pot and read it's value, it's quite simple. You already have it hooked up in a voltage divider configuration and are getting a 10 bit (0-1023) value using analogRead(), you just need to decide what to do with it.
Assume potVal has the value of the pot.;
if (potVal < 256) {
    // Pot is one quarter turn or less
} else if (potVal < 512) {
    // Pot is between 256 and 512, so its more than quarter but less than half
} else if (potVal < 768) {
    // Pot is between half and 3/4ths of the way there
} else {
    // Pot is greater than 3/4 of it's full range
}

So I have broken it down into four quadrants for you, but you can do it however you like.

There should be at least a little calibration involved (for instance, if the pot being read involved is a logarithmic audio pot), but these threshold values are the best starting point.

It would be relatively simple to do a threshold test on analogRead() to switch modes (e.g. if the value is above 512 (analogRead() gives values between 0-1023) then you switch modes (probably with a boolean variable that you can then use to decide whether to strobe the LEDs).

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


text:
Can you fry an arduino with nothing plugged in to it?
I only get to work on my arduino every few weeks, so sometimes and get interrupted a lot by small children, so if I completely forget what is on the firmware, then I unplug the pins (because I haven't got anything soldered on there) should I be 100% certain I'm not going to fry my board?

There have been microcontrollers in the past that have functionality that allows you to create internals shorts or setup the clock in a way which means they are unrecoverable, but not recently

Although the controllers on an Arduino are pretty well protected, they can still be damaged by ESD (Electro Static Discharge). The same effect that makes a crispy sound when you pull off your woolen sweater in the winter, or after walking with rubber shoes on a carpet and you touch someone else or a metal and grounded object and you feel a pick. Static electricity can damage the controller. It may get completely broken, or it may function 'most of the time' or lifetime may be shortened.
An Arduino is also easily killed with an piezo gas lighter, just make the spark near the copper traces that feed directly in the controller. This is largely the same effect as above.
Again, the controllers themselves are pretty well protected, don't worry too much about them. But with kids running around (on their rubber shoes) better make sure they don't accidentally draw a spark from their little finger to your Arduino. The protective metallic bag is best, but putting it away in a cupboard or box should do the trick equally well.
As a general rule of thumb, the faster the electronics, the more sensitive it is for ESD. A Due is probably more sensitive than a UNO or a MEGA. But with normal, avoiding static electricity, use you should be OK.

An Arduino is also easily killed with an piezo gas lighter, just make the spark near the copper traces that feed directly in the controller This one is funny: why would someone want to do that? Is that a real-life experience of yours?

@jfpoilpret I don't know it is a fun experiment (for cheap chips that you don't need anyway). You never know with kids. But is was mostly to illustrate what is going on.

Arduinos are far from bulletproof but with nothing connected (apart from a power source of course) I doubt it will come to harm. If in doubt, upload Blink to it.
There are rugged Arduino-compatibles. One of them has a rather obvious name

What would that obvious name be? Ruggedduino? ;) You probably should put that in your answer because it could be called BulletProofDuino and that last sentence would still be applicable.

@AnnonomusPerson: I try to limit the amount of advertising I subject you folk to. (Especially(?) as I don't have any affiliation with the company concerned)

It seems though if a user wants one that you should tell them about it. You can just say I've heard of _____. Not to mention, you're not really affiliated with Arduino, either. :)

@AnnonomusPerson: Answer updated to be less coy.

It's generally a good idea not to try to take input from a pin configured as pinMode(OUTPUT) and vice versa. In addition, I prefer not to take input from tristated pins. Both of these cases are harmless, but it's good practice not to do so, especially since they can cause issues when coupled with some hardware.
In general, Arduinos are protected from software issues. You can't burnout an Arduino with just faulty software.
There are, however, many ways to fry an Arduino via hardware.

100% certain? No. 99.9999[Repeating]%? Yes
Here's a couple problems you could run into:

Using pins 0 and 1 when connected to USB (wouldn't damage it, the USB chip if on a board with a separate USB chip would probably ignore the "corrupted" data.)
You never mentioned your board. If it's a Uno and you modified your USB firmware, there might be some issues reflashing your board if you forget that you flashed it with a keyboard firmware. It won't damage it, but you may think it's bricked if you forget to reflash it.
If you only disconnect a couple pins and leave others in, it may give wierd results and fry the Arduino or whatever is partially attached
If you make any physical modifications to the board

The second to last one is the one you really have to worry about. I have seen previous discussions about destroying a board with a sketch, but nothing has been suggested.
Lastly, there a chance you can damage it with setting the fuses on the chip(s) on the board.


text:
Build Infrared Camera Remote
I wish to build a remote for my Camera i.e Sony NEX 5R. It has a built in IR receiver and has several Sony as well as aftermarket remotes provided for it. Due to my interest in Micro controller design I wish to build one myself rather than use an aftermarket one.
A friend who did the same for his NEX 5 series camera posted a video of the same on Facebook, which inspired me to build my own. I plan to use an Arduino Uno R3 with the following additional components:

IR LED
NPN Transistor(for amplification)
Schmidt Triggers(for rectification)
9 Volt Battery

Ultimately I would like to swap out the Arduino for a standalone ATmega328 or ATtiny2313 but currently I have some issues as of now:

I currently do not have a schematic or a sample code which I can use. I have been trying to search the internet for the same but to no avail.
I am unsure of the protocol used by my camera. I have found it difficult to find documentation on the same.
How can I replace the 9-Volt battery for something smaller?
I would like to use a smaller micro controller but what differences will I encounter when trying to change my code for the smaller micro controller?
For such a project, will I need additional hardware?

Welcome to Arduino.SE. :) If you're looking for general introductions and tutorials, then the official Arduino website is usually the best place to look at first. You're welcome to ask the more specific questions here, but please try to ask each one separately. It helps us keep the site better organised. Thanks!

Ah. Apologies. As you can see I'm quite new here. I shall take care in the future. I will try and clarify my question as it seems it's quite complicated to understand.

Using the Arduino shouldn't be any different than any other microcontroller.
The IRremote library is my go-to library for any IR related stuff.
Power shouldn't be an issue, look at the Moteino from LowPowerLab and check out his coin cell battery tests. It's definitely possible. Not with a full blown Uno, but with a bare chip, yes.
You want to burn the bootloader on the IC first, before you can start writing Arduino code. Check out this tutorial: From Arduino to a Microcontroller on a Breadboard. It's the same process for an ATTiny, you just have to look at the datasheet to see where to plug things into. Specifically, MOSI, MISO, SCK, and Reset pins. The Tiny AVR Programmer is also a good choice. It's meant for the 8 pin micros but it has an ISP header so you can use it for almost any chip.

This may be useful for more information about decoding IR signals:

EEVblog #505 - IR Learning Remote Control Hack
EEVblog #506 - IR Remote Control Arduino Protocol Tutorial

Phew. That's a lot of information. Do you think I will need any additional hardware for the same?

additional hardware for what?

In order to complete the remote i.e have a button which can signal the micro controller to control the LED into transmitting the correct bit pattern which is then detected by the camera at a distance of approximately 1-5 meters. Sorry for the ambiguity.

You could probably do without the Schmidt trigger but that should be enough.

1.) I'm not exactly sure what you mean by this. What I'd recommend is a ATMega328 for the heart of the chip. It's what is in the Uno, so with a exception of uploading code, for this project this will cut down on the size of your project. However, an Uno will work pretty much identical. If you do want to use a chip like this, this design looks pretty complete. You'll probably want to move to a PCB for your final product, but since you have a little electronic experience, I assume you can solder and know about this. Here is another tutorial for barebones.
2.) Again, what do you mean by "standard?" Like protocol? If so, there's no real protocol to use. This may be easy for a begginer. It's the remote and the receiver. If you want to go all geek you can also hack an existing TV remote to do the same task. That library should take care of everything you need (see code later).

A bit of code/wiring:
The circuit will depend on what receiver you choose. Most IR receivers have one pin for 5v, one for GND, and the last one is connected to a digital pin. Again, look at the information on the specific receiver you choose.
Some sample code with the library I listed:
#include <IRremote.h>

int RECV_PIN = 11;        //Using pin 11 for the signal pin
IRrecv irrecv(RECV_PIN);  //Creates a variable that will be used later to inference between library and code
decode_results results;   //Use it to store the value of the keycode

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
}

You'll have to run this sketch to determine the value of the button you'll use on the remote. It should print on the serial window some sort of hexadecimal value IIRC that you'll have to convert into decimal if you want to use it inside the code to compare that to the button you want to use on the remote. The post I mentioned is a great resource: go and look at it.

3.) I don't recommend building a remote. Like I said, you can use existing TV remotes or buy one for this purpose. Start small, figure out how IR remotes work, and then build one later if you desire. A v2 is often required on Arduino.
4.) Don't bother for the receiver. It can be bigger. If you don't know how to to program it, this guide is a good reference. It has some files that you download to add it in the IDE to trick the IDE to think the chip is a board. Note: You'll have to program it with an Uno or similar to upload and to burn the firmware. (I would explain it more in case the site goes down, but you need the files there so it'll be pointless anyway.)
Also a quick tip: don't be afraid to ask your friend for some help. You don't need to rely on him, but if you get stuck ask him.
I don't know how to connect the Arduino to the camera, but you seem to know how to do that.

Thank you for your answer. The receiver is in the camera. Hence the confusion. Unfortunately my friend is in India and I'm currently living in the US so coordinating for us is largely impossible. I asked him once and was able to procure materials and necessary documentation. I am writing this post for the both of us as he would like to improve his design as well which currently uses ATmega328 with 9 Volt battery.

Also, I have some experience with electronics but not a lot with Micro controller so I can build an IC and to some extent maybe design it too but I do need somewhere where I can start.

@AdityaSomani You should've mentioned that. That's really outside the scope of the question, and I don't know enough about your camera. Unless you can find some data online, you'll need to have an actual remote available to reverse engineer the signals. There's no universal camera shoot protocol.

Oh I see. I'll try and find a data sheet for the camera or talk to my friend about the same. Thanks. Sorry again for the confusion.

@AdityaSomani That's okay!

Well, for your project you can simply buy/rebuild a TV-B-Gone made by Mitch, which he uses as a basic project to teach soldering all over the world.
You can "hack" the TV-B-Gone by adding a TSOP4838 that can work as an IR receiver (or use another device as a code recorder).

And as you can see here the TV B Gone features an ATTiny85. A really small and nice beast.
Here you'll find the source code for the TV B Gone. I'm not sure what format they use for their code database though.


text:
Adjust resistance of a circuit
I need to emulate a component that measures an input mechanically and varies resistance from 0 to infinity (a more detailed set of specs list it at 20-1,000ohms, though I'll have to actually check its true values myself once I have physical access to it).
My aim is to replace this troublesome mechanical component with a current (read as available and serviceable) component, and convert the signal from the new component into an emulated signal (varying resistance) from the old component.
I am not certain as to the resolution required (how big the steps can be), though it may be able to handle 50ohm 'leaps', just judging by the range of mechanical movement and my past experience with replacing similar mechanical systems with ready-made kits for conversions.  I'd like to smooth the curve a whole lot more than 50ohm leaps though.
I have barely an idea where to begin on this.  I thought maybe a resistor ladder and a set of transistors triggered by the arduino to connect into the different points in the line, though I suspect there has to be a better way to achieve a much better result (and I don't think I have enough outputs for that anyway).
Is there a digital component that can vary its resistance using a PWM signal or maybe an analog signal from an arduino?
FYI, I greatly appreciate your input.
EDIT
The controller provides a constant voltage to the component, and the controller then looks at the ground (the voltage over a static resistor) I presume. It is an actual load.
I may be able to provide a variable voltage to the controller on its ground pin, though I have never seen that done on them before. I think that may be the trick, though the controller may(??) dislike it? I can try that.. The next best thing (only 2nd because it requires more components) would be the digital pot.
Anyone ever forged a return signal on a circuit thats supposed to supply its own constant voltage to a resistor type sensor?

The idea of using a servo to move a potentiometer came up, and that doesn't work because it cannot keep up (its too slow).

How is the resistance being used? is it an actual load?

Does your system really need a variable resistor, or is the variable resistor only used to generate a variable voltage. If the latter, you could just use a digital DAC.

What about a digital potentiometer
Digital Pot
Many types available, generally controlled via a serial interface e.g SPI

A JFET can act as a voltage-controlled resistor. It will need additional components if you require precision (a shunt resistor and a couple of op amps come to mind), but it should do. JFETs are rarer than they used to be, but still should be available for a few decades.


text:
Arduino IDE #ifdef
I use my Arduino IDE to either upload my sketch to a Arduino or ATTiny or ATmega328. As you know each device can have a different pinout. Does the Arduino compiler support ifdef, depending on the board I am connected to?
For example
#ifdef Attiny85
       a=0; b=1; c=2;
#else
       // arduino
       a=9; b=10; c=11;
#endif

Yes. Here is the syntax:
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
    //Code here
#endif

You can also do something like this for the Mega:
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    //Code here
#endif

Assuming the implementation for the ATtiny is correct, your code should be like this:
#if defined (__AVR_ATtiny85__)
       a=0; b=1; c=2;
#else
       //Arduino
       a=9; b=10; c=11
#endif

In Arduino.h, __AVR_ATtiny85__ is used (capital T). Not sure if it makes any difference though.

alternatively using 1.5.+ IDE you can test against the board type you are building. See Arduino-IDE-1.5---3rd-party-Hardware-specification. Example "#if defined(ARDUINO_AVR_UNO)" or ARDUINO_AVR_MEGA2560 or ARDUINO_AVR_LEONARDO, etc...


text:
A waterproof Chlorine Sensor
Does anyone know where I can find a Chlorine Sensor to use with the Arduino? It would need to be water proof. I've googled, but I couldn't find anything.
EDIT
Requirements: relatively inexpensive (under $100us), works with Arduino, waterproof and used to detect chlorine in water.

A quick Google search turns up tons of them. Do you need to sense Chlorine gas in air? Dissolved in water? Do you need to measure concentration or merely detect the presence? How have you tried to find one so far?

actually for water (swimming pool) - I have searched but could not find any that look suitable

Define "suitable".  What are your requirements?

suitable = relatively inexpensive (under $100us), works with Arduino

Your best bet would probably be to interface with a colorimeter.  There is a tutorial for an open source colorimeter here:
http://www.appropedia.org/Open-source_colorimeter
IORodeo also sells a shield:
http://www.iorodeo.com/colorimeter
Vernier sells a colorimeter that may be suitable for your project & Sparkfun sells a shield to interface with Vernier sensors.
If a colorimeter doesn't work you would have to use an electrode, which is pretty expensive and has a shelf life.

Maybe measure conductivity instead?  I think, in freshwater pools, one of the active parts of working chlorine is an OCL ion - which I guess is conductive.

Conductivity does not give a correct answer. As active chlorine decays from NaClO to NaCl, it is just as conductive when active or inactive. As you add chlorine to your pool it stays active for a while but remains conductive, so during season your conductivity increases all the time not depending if there is active chlorine or not.

That is why in test stripes often a colour for "salinity" or "alkali" . This shows all the added chlorine has become too much salt. If you ignore this, you will swim in an salty ocean sooner or later. And you have to change all the water from pool and replace it with fresh water.

The chlorine is an oxidizer.  You should be able to look at redox potential and determine the amount of active chlorine in the water.  There are a number of methods for determining the redox potential and several commercially available units that will give you that number.


text:
Arduino Controlling through C#
i would like to measure some signals from arduino and send it to a pc using USART and display the results in a c# winform application. Does anyone have such a project example ?
Besides, i want to send the data in live time mode, each values should be directly transmitted and then the second measurement ( sample rate 100 kHz )
Thanks a lot

Are you sure you can support that sample rate with your communications?

The maximum sampling rate for analog signals is 10 kHz at default 10 bit resolution. Digital should be ok. The USB bus is nominally 12 MBit/s. Assuming 1-byte data size, you would probably have to send the data in 64 byte bursts(max packet size) if you want a chance of having eneough bandwidth since there is also overhead. Whether possible would depend on the Leonardo USB implementation and possibly also hardware/software on the PC.

User2973, you should post your comment as an answer, and then the OP should accept it. (Excellent, through treatment of the question. Voted.)

ok, if we assume with 5 KHz samle rate, do you can any suggestion for c# PC program to control the board ?

This question was never specific enough for the rules of this site, and has clearly been abandoned for over a year.  Voting to close.

Am I missing the point here or wouldn't the C# just have to open a Serial connection to the board and read and write to that to control the program running on the Arduino?
Yes the board is connected by USB, but that's only so it can open a serial connection.
To be honest I don't think you will be able to sample at that speed, you might be better looking at ICs that directly interface with GPIO and RS232/USB.


text:
How can I get a unique address for all my Arduino boards while in RS485?
My attempt is to know how to identify the board I'll be sending parameters to in a serial connection like rs485.  I'm asking because I will have about 11 or so mcu's as "Rx slaves" while my pc is the Master "Tx". I want to know how my code block is being sent to a specific board will be received by just that board and not all the other boards connected to that Rx port COM?
If I send 'LT2|LP3|LM5|LR4|LI6' and I want that to be for one specific Arduino, I don't want all the other 10 arduinos to take those parameters in this serial Rx line.
@Federico Fissore you mentioned in another post "Some boards, when connected to a computer, publish their serial number. My Arduino Uno R3 says"
[16818.451423] usb 3-2: SerialNumber: 85235353137351E02242

how and where can i find this info?

You can't; it's locked up in the other chip.

@ Ignacio Vazquez-Abram dam! ok thanks thought i can just use that to add to my const unique address before i Tx to serial

The simplest thing would be to burn a serial number into each chip's EEPROM, and interrogate that at startup.

@Nick Gammon i dont think that could have sounded more advance for me then anything thus far lol any links on how to go about that ? im just not getting the big picture thanks!

Related to your other thread: I'm looking for a way to Serially communicate with a multi mesh Arduino Slave Network

what was that link for ? @NickGammon

You seem to be also asking this question in another thread. In other words, cross-posting. In the other thread you said if send 'LT2|LP3|LM5|LR4|LI6' and i want that to be for one specific arduino i dont want all the arduinos to take those parameters. Isn't that basically your question here? Asking the same question in multiple threads dilutes the answers, and some people may not notice that there is a similar answer (to one they are about to spend 10 minutes typing) in this other thread. It would be courteous to either not cross-post, or to point out your other thread yourself.

i dont feel like im asking the same question nick how ever if you wan to help i think is you who should stick to one thread, cuz even if i was asking the same question which im not but  lets say i was "would you say your answers are correct?" i mean i am getting different answers aren't i ? this would imply that i am asking 2 completely different question

i mean that the answers being given by both threads aren't consistent and therefor someone is not being honest or knowledgeable about what they are saying for a answer "so think about that for a second and find my logic before you think about going back and forward with a discussion that has nothing to do with the main question in this pg, okay?!
at he end of the day if i was to ask a second question within the same subject i would have to refer to my past exp in this website where i was told that if i have another question to ask START A NEW THREAD

I dont think that could have sounded more advanced for me then anything thus far. Any links on how to go about that?

First, run a sketch like this for each board:
#include <EEPROM.h>

const int SERIAL_NUMBER_ADDRESS = 1023;
const byte SERIAL_NUMBER = 42;
void setup ()
  {
  // don't do it if it has been done before
  if (EEPROM.read(SERIAL_NUMBER_ADDRESS) != SERIAL_NUMBER)
    EEPROM.write(SERIAL_NUMBER_ADDRESS, SERIAL_NUMBER);
  }  // end of setup

void loop () { }

The serial number address can be any address in range for that chip - a Uno has 1024 bytes. I chose 1023 to leave the other addresses free, but it could be 0. Anything you don't need for any other purpose.
Then write a different serial number to each board (eg. 42, 43, 44, 45). Obviously you change the sketch each time you upload to a different board.

Once you have done this (once per board) now each board "knows" its serial number. You can detect this in your main sketch:
#include <EEPROM.h>

const int SERIAL_NUMBER_ADDRESS = 1023;
byte serialNumber;
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  serialNumber = EEPROM.read(SERIAL_NUMBER_ADDRESS);
  Serial.print (F("Serial number of this board is: "));
  Serial.println (int (serialNumber));
  }  // end of setup

void loop () { }

Output for me in this case was:
Serial number of this board is: 42

Also I have a post about RS485 on my forum.

Just assign every node a variable like "const int ID = 5" and so on and then before sending the instructions send a line terminator, the ID, line terminator and the data you need to send to the nodes. Every device listens but they all wait their ID to accept the commands. For example:
Serial.write('\n');
Serial.print(ID);
Serial.write('\n');
Serial.print(|LT2|LP3|LM5|LR4|LI6);
Serial.write('\n');

NOTE: This is the easiest way. Most likely not the most reliable or optimized.

Comments are not for extended discussion; this conversation has been moved to chat. (cc @Frank'sDesig'Nature)

why not just use a usb tower and connect all my arduino's to that tower usb style just like when they plug into my pc and connect the other end of the usb tower into my pc ? doesn't that sound more easy and less complex?
this way i can just use the # of the com port as the address?

@Frank Yes that would work.


text:
Arduino Zero D0/D1 set output high
I am trying to use D0/D1 as normal IO pins but DigitalWrite does not work as on an Arduino UNO.
I know the SAMD21G has SERCOM but I can't seem to find an example of not using D0/D1 as an UART port.
EDIT ** Code I have tried:
#define MYMASK 0x00000C00
void setup() {
  REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
  REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
  delay(1000);
  REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)
}

void loop() {
}

You can do this by simply calling the right registers:
Example 1, using a MASK
D0/D1 are mapped to to PA10 & PA11 on the M0
/* The following ports where selected
    PORT_PA11
    PORT_PA10
    */
#define MYMASK 0x00000C00

int main (void)
{
    system_init();

    REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
    REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
    //REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)

    while(1){

    }
}

Here is another simple example:
/* The following ports where selected
    PORT_PA11
    PORT_PA10
    */
#define MYMASK 0x00000C00
#define LED1 PORT_PA10
#define LED2 PORT_PA11
int main (void)
{
    system_init();

    REG_PORT_DIRSET0 = LED1 | LED2; // Direction set to OUTPUT
    REG_PORT_OUTSET0 = LED1 | LED2; // set state of pin(s) to TRUE (HIGH)
    //REG_PORT_OUTCLR0 = LED1 | LED2; // set state of pin(s) to FALSE (LOW)
    while(1){

    }
}

In the Arduino IDE you can do something like:
#define MYMASK 0x00000C00
void setup() {
  REG_PORT_DIRSET0 = MYMASK; // Direction set to OUTPUT
}

void loop() {
   REG_PORT_OUTSET0 = MYMASK; // set state of pin(s) to TRUE (HIGH)
   delay(1000);
   REG_PORT_OUTCLR0 = MYMASK; // set state of pin(s) to FALSE (LOW)
   delay(1000);
}

Thanks for the quick reply... I tried the the above trough Arduino but without any luck. I wonder if Arduino overwrites the registers in the background.

Can't tell unless you post your code.

Have added the Arduino Code...

@BertusKruger - I just tried the code on my Arduino M0 which has D0/D1 mapped to PA11 & PA12. You have set the ports to low before the loop. See my revised code.

edit - D0/D1 are mapped to PA10 & PA11

Thanks @PhillyNJ . I can confirm that that worked for me. How did you derive the mask and where can I read more about the registers? I would like to do the same with the SPI and I2C pins...

@BertusKruger HTH - please don't forget to mark as answered :) - You can read all about the GPIO registers in the Datasheet or my tutorial which  I posted here https://community.atmel.com/forum/samd21samr21-xplained-pro-gpio-tutorial for peer review. Let me know how it goes.

Thanks. I figured out the mask but could not see any mention of REG_PORT_DIRSET0 in the datasheet. I now noticed the DS talks about DIRSET. Still need to find the link... I am building a SAMD21 board from scratch and is now busy on a test jig testing each pin... :)

Thanks for the tutorial link. Haha I found my answer... :)  https://github.com/arduino/ArduinoCore-samd/blob/master/bootloaders/sofia/Bootloader_D21_Sofia_V2.1/src/ASF/sam0/utils/cmsis/samd21/include/instance/port.h


text:
Internet of Things at home only
My question isn't specific to Arduino but can concern Raspberry Pi and all Internet of Things homemake projects.
As I'm preparing a personal projet with sensors, data storage and visualisation/reporting web page (not yet Android app) I'm looking about Internet of Things platform.
It seems all that I can find are cloud related system. I would prefer a home localized solution but I'm not able to find one (and maybe open source) where datas don't go outside home.
The goal is to be able to :
    send datas from my Arduino to a home storage server
store these data into database for later query (may be MySql)
trigger some computation or aggregation job over datas
prepare some graphs
generate some html page from template
option: allow Android client to connect and get datas/graphs
Before starting thinking how to create my own (non standardized) system is anyone can give me some advice ? some name of such existing system ?
Thanks
Thomas

I recently worked extensively on a Home Automation Project and here's what I would recommend based off of that:

Use Arduino for hardware interfacing.
Use Raspberry Pi for hosting your server.
Write your server using Node.js (or Python if you wish).
Use Express, Socket.io (or Python simple server). Google these.
Use Serial (USB) for communication between Arduino and Raspberry Pi
Use RF/BLE if you want to go wireless.
Use Redis or MySQL for database.
Use a graph JS API for charting.
To build an android app, send http requests (or a Socket.io link), for communication.

This is a simple to implement, but you'll need to put some time. Good luck.
All of the above steps are abstracted from each other. This means that if you want to incorporate additional features, you can change any stage without affecting the whole.

Setting up a basic webserver on the Raspberry Pi is fairly straightforward, and as long as you have a firewall and aren't port-forwarding the data will be restricted to your home network.  You can also setup the firewall on the Pi to allow only local access fairly easily.  I did a similar project, and here was my process.

Get the Arduino to output the data in a standard way.  I used CSV format, but as long as it easy to parse you should be fine.
Get the Arduino to make the data available.  I ended up using the webserver sketch to generate a page with all of my values, but you could just as easily have it send data instead.
Insert the data into a database.  I had a cron job that every x minutes would pull the webpage, parse the data, and insert it into the database.
Make the webpage.  There are a ton of open source graphing projects, and I chose a PHP based one as that is the language I am most comfortable with.  Javascript, Python, and CSS can also do it if you prefer.
Since I used PHP it was fairly easy to setup a template system.  Basically it had some standard include statements, then worked off of $_GET variables to call a variety of graphs.


text:
Is there a Serial write buffer limit and does the Arduino reset if it is hit?
I have an Arduino Mega 2560 that is resetting every 32 seconds if the serial monitor is not attached. Just before it resets, there is a flash of TX, then it goes. If ther serial monitor is attached it runs forever. Clearly I can't use the serial monitor to debug this so am clutching at straws as to what is happening.
Update:
Having eliminated all code and uploaded an empty sketch, no includes etc., the board still exhibits the reset. However, I have an Adafruit Ultimate GPS attached to the GND, 5V, TX1 and RX1 pins. When I remove it the resets stop. But with it attached and the serial monitor attached to the board, the resets also stop, even with an empty sketch. Spooky.
So, is it possible the GPS unit is filling a receive buffer, even if the serial port isn't set up to receive? I still have a problem that while I'm clearing and logging the GPS data, the resets are still at a regular 32 seconds, thus the reason I'm working on it still.
Note: The flash of TX no longer shows up with the empty sketch.

Show us your code.

When you detach the serial monitor do you also remove the USB cable and power it from a different power source, or does it remain connected to the computer?

It remains attached to the USB power of the computer, though in service it is designed to run on the Vin pin or 9V DC jack

What is the power consumption of the additional GPS module? It may be off limits for arduino power supp.

The GPS module draws 25 mA and I am pulling from the 5 V supply. The module is designed to take 3.0 - 5.5 V supply.

Not that it turned out to be relevant, but the answer to the original question is that Arduino serial output calls block until there is room in the buffer.

It turns out this problem had a very different cause, once I was able to eliminate the other variables. Having disconnected literally every component from the board and uploaded an empty sketch:
void setup() {}

void loop() {}

the board would still periodically reset itself.
I eliminated:

flushing the receive buffers,
eliminating all receives by disconnecting pins,
speeding up/slowing down the serial port/s,
speeding up/slowing down the GPS reporting rate,
auxiliary hardware,
code,
includes,
defines,
laptop power supply noise,
board revision in Arduino IDE,
Arduino IDE version,
USB port on laptop,
trying this hack to prevent the RESET pin from going low,
another Mega 2560 and a Due

None of the above influenced the issue.
The thing I did not think to check was whether the board would work with another power supply alone. This was a result of hunting for another power fault in service and with the laptop plugged in, finding a periodic, random reset.
Ultimately, I plugged the board into a monitor USB output, then a car charger power supply and finally found the issue was eliminated. Even plugging into another computer solved the issue. It appears that either the Arduino driver in Windows or the Arduino IDE software itself, would periodically poll the port, causing the board to reset. While the serial monitor was running, I assume the driver or IDE felt no need to poll the port, thereby leaving the board un-reset.

It is probably not the Arduino IDE but some other rogue piece of software, like a GSM modem manager (a modern Arduino sort of looks like one) or a driver for old serial mice.  Having the Serial monitor open likely means that the serial device is claimed and unavailable to the undesired program.

Is that in any way an indicator of nefarious software running, or just annoying? I imagine something in the HP Workstation special tools could be trying to do that.

authors: Владимир Беленьков


text:
Initialising timer interrupt crashes Mega 2560
Below is the entirety of my prototype code, the cycling of pin 13 is what I use to confirm the board is restarting. The board resets continually on this implementation of initialising the interrupt. There is no code implemented for the interrupt, simply initialising the interrupt and specifically enabling the Output Compare Interrupt by setting its bit high is enough to cause the crash. The evidence of the crash is the onboard LED cycling as instructed in the setup() routine.
I have tried setting OCR3A in one and two operations, I have tried initialising TIMSK3 and not, I have tried intialising TCNT3 to zero and non-zero values, and setting the prescaler with the bit shift and the discrete value, nothing seems to work..
What is going on?
void FlashLED() {
  digitalWrite(13, !digitalRead(13));
  delay(100);
  digitalWrite(13, !digitalRead(13));
  delay(100);
  digitalWrite(13, !digitalRead(13));
  delay(100);
  digitalWrite(13, !digitalRead(13));
  delay(100);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
  FlashLED();

  // Initialise timer 3 and interrupt
  noInterrupts();
  TCCR3A = 0;
  TCCR3B = 0;
  TIMSK3 = 0;
  TCNT3 = 0;

  // Initialise OCR3A in two operations, as OCR3A = 62500; Serial.print(OCR3A); yields 36 (low byte only)
  unsigned int count = 62500;
  OCR3AH = count >> 8;
  OCR3AL = count;
  TCCR3B |= 1 << WGM32; // CTC Mode
  //TCCR3B |= 4; // Prescaler 256
  TCCR3B |= 1 << CS32; // Prescaler 256

  TIMSK3 |= 1 << OCIE3A; // Output Compare Interrupt Enable
  interrupts();
}

void loop() {
  // put your main code here, to run repeatedly:

}

Update:
I had also been trying with an empty ISR handler and discounted its effect:
ISR(Timer3_COMPA_vect) {

}

However, as the astute viewer would notice, the signature is incorrect in its capitalisation. The correct handler is
ISR(TIMER3_COMPA_vect) {

}

This has resolved the issue.

You have enabled the timer and also its interrupts but you have no interrupt handler.  The interrupt has to go somewhere and as it is it's going who-knows-where.  Add an ISR and I believe that will resolve your issue.

How irritating. I have for hours been working with an empty ISR handler, the whole problem has been incorrect capitalisation!! The Oscar Liang tutorial routinely mixes the case of the ISR, so it never occurred to me to change it: https://oscarliang.com/arduino-timer-and-interrupt-tutorial/ Feel free to submit ans answer that I will accept, since your prompt got me home.

Glad to be of assistance.

Unrelated; You should be able to use OCR3A = count to set both the H and L register with only one line of code.

That is what I was doing initially, but using Serial.print(OCR3A); returned 36, indicating that only the low byte was being written. I don't know how my code could possibly be behaving differently to anyone else's.

You have enabled the timer and also its interrupts but you have no interrupt handler. The interrupt has to go somewhere and as it is it's going who-knows-where. Add an ISR and I believe that will resolve your issue.
Yes, the capitalization is important!

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


text:
Is there a VESC firmware implementation that runs on Arduino?
I am looking to use an Arduino in a motor control application, and have found that the VESC^ project has done some good work in this. I would like to have some fine-grain control over the motor drive, but using the VESC foundation looks great.
Research so far on Arduino and VESC discusses using an Arduino to interface with VESC hardware, however I'd be more interested in having the VESC firmware running on the Arduino, with output driving a power stage.
Is there a reason why this is not possible? (where the most powerful Arduino being insufficient on processing, not enough memory, etc.)
^VESC is an open Electronic Speed Control infrastructure for motor control that in completeness includes hardware, firmware and parameterisation/control sotfware. VESC Project website.

It might help if you define VESC.

@PMF Description added.


text:
Erratic behaviour using a DUE with the Microchip 24FC64 EEPROM chip?
I am attempting to read and write from/to an EEPROM chip, and have got access to this 64 kbit device.
It appears I can write to the device and read from it, but there appears to be some strangeness around addressing the written data for later writing.
I am using this page as a reference for my code, and getting some strange results. For starters, the 64 kbit is in fact 8k, and I was able to write to the 10000 the byte and read from it (though I suspect it rolled over on the memory address).
The strangeness was when I attempted to write two adjacent bytes to two adjacent addresses. The subsequent read of the two addresses read the second byte both times. It was as if the location pointer was stuck on the last read.
when I reset my code, I can read the previously written addresses, confirming they are not just stuck in memory.
Similarly when I write an array of bytes to an address, I can read back the bytes, but if I change the read pointer to read again, the bytes are returned all the same, until the pointer goes a significant distance away from the read address (over say 50 bytes). At this point the return data is all 255.
Finally if I read many bytes, requesting say 50, the most I get back is 32 bytes.
Say I write:
[60, 61, 62, 63, 64, 65] to position 8000 in memory

if I attempt to read from the address or addresses near it or anywhere else, I either get the exact bytes I wrote at whatever position I request, or I get nothing (all 255).
I have managed to read old data from other locations from previous compiles, so the data is for sure in the chip, just accessing it seems uncertain.
Some read results:
7000: [255, 255, ..., 255]
7500: [255, 255, ..., 255]
7980: [60, 61, 62, 63, 64, 65, 255, 255, ..., 255]
8040: [60, 61, 62, 63, 64, 65, 255, 255, ..., 255]
7960: [60, 61, 62, 63, 64, 65, 255, 255, ..., 255]
8060: [60, 61, 62, 63, 64, 65, 255, 255, ..., 255]
7940: [60, 61, 62, 63, 64, 65, 255, 255, ..., 255]
8500: [255, 255, ..., 255]
8150: [60, 61, 62, 63, 64, 65, 255, 255, ..., 255]

Code:
  const int memoryI2CAddress = 0x50;

  void Initialise() {
    Wire.begin();
    Test();
  }

  void Test() {
    unsigned int baseAddress = 8000;
    byte data[6] = {64, 65, 66, 66, 65, 61};
    Wire.beginTransmission(memoryI2CAddress);
    Wire.write((byte)(baseAddress >> 8));
    Wire.write((byte)(baseAddress && 0xFF));
    Wire.write(data, 6);
    Wire.endTransmission();
    delay(10);

    ReadTest(7000);
    ReadTest(7500);
    ReadTest(7980);
    ReadTest(8040);
    ReadTest(7960);
    ReadTest(8060);
    ReadTest(7940);
    ReadTest(8000);
    ReadTest(8500);
    ReadTest(8150);
  }

  void ReadTest(unsigned int baseAddress) {
    Serial.println(baseAddress);
    Wire.beginTransmission(memoryI2CAddress);
    Wire.write((byte)(baseAddress >> 8));
    Wire.write((byte)(baseAddress && 0xFF));
    Wire.endTransmission();

    int count = Wire.requestFrom(memoryI2CAddress, 50);
    Serial.print(count);
    while (Wire.available()) { Serial.println(Wire.read()); }
  }

Update:
The data addressing seems to be sensitive to the first address byte and not the second. When inverting the order of the most and least significant bytes and comparing to the MSB change with the address, I can reliably return the byte at the correct address. This appears to explain why I either get the same data for some addresses and not others, where the MSByte is or is not changing.
So why is the system insensitive to the least significant byte in the address?

Good catch, was a typo in my description.

8000 in my description is in decimal, under the 8192 limit

I'm not sure I understand what your question is. But, what I'm wondering when reading it is whether or not you read section 6 of your linked datasheet.

I have read 6 and 8, but admit I'm not totally au fait with it and am wondering what the Wire library will be doing on my behalf. What have you spotted explicitly? Primarily I'm not getting an expected behaviour in reading and writing to specific addresses of one or several bytes, either the write is not writing to the correct address, and/or the read is not reading from the correct address.

Sadly the simple answer is in how the least significant byte was being calculated, and the boolean operator generating it.
Wire.write((byte)(baseAddress && 0xFF));

should have been
Wire.write((byte)(baseAddress & 0xFF));

Tough lesson to check my assumptions!


text:
Is there a definitive reference for the Arduino DUE?
I am looking for a reference document or documentation system that concretely relates at minimum:

Screen printed pin name/number
SAM3X8E pin number
Register number
Channel number
Port name

In my case I am looking to change the PWM characteristics of pins 2 and 3 (as named on the physical board). Various forum posts discuss setting registers, register pin mappings, but nothing seems to quite tie up.
On the Arduino as printed, Pins 2 to 13 are listed as PWM pins, 12 in total. By this page, pins 2 and 3 map to PB25 and PC28 respectively on the SAM3X8E chip. Presumably this suggests Pin 2 is on the 'B' port, and 3 is on the 'C' port. Referencing this page, the sample code goes through 'all 8' PWM ports and pins, which by the register naming scheme PIO_ASBR_Pxx, suggests the pins numbered 16 to 19 are on the B Port, and 21 to 24 are on the 'C' port. Later the PWM ports are again iterated over with the PWM->PWM_CH_NUM[i] where i runs from 0 to PWMCH_NUM_NUMBER - 1, which is suggested as 8 in total.
'Pin 2' on the board then seems to have a mapping to a named pin on the Atmel chip of PB25, somewhere between 21 and 24 on the register name and between 0 and 7 on the channel index. Surely there is a place that attempts to harmonise all of these disparate naming conventions.
Further Information:
For instance, PWM/Digital Pin 2 maps to PB25 on the chip, as per the schematic provided by Majenko. PB25 is not a member of the PWM pins as per the chip datasheet. How am I to understand this?
When referencing the name PIO_ASBR_19, this is the 20th bit in the PIO_ASBR register, but how does this bit map onto the port/pin mapping? Then while the datasheet discusses the 'PIO_ASBR' register, since that can relate to at most 32 pins, the datasheet does not expand on how to map the excess pins.

The name -> pin -> port/bit mapping can be got from the schematic. The PWM mappings of channel -> pin can be got from the SAM3X8E datasheet.

in Arduino store: https://content.arduino.cc/assets/Pinout-Due_latest.pdf

Forgive my simplicity, but it looks like both references, the schematic and the pinout, simply relate the screen printed pin names with the P[A|B|C|D][dd] notation. When I review the (enormous) chip datasheet, I cannot find the majority of the register definitions required to map back to the pin notation. Could you help me interpret that document?

PC7 is Port C bit 7. There's nothing much to interpret. For special peripherals like PWM you just look them up in the port multiplexing table (section 9.3).

@Juraj I can see there is a lot of information, but it still seems to fail to identify 1) What PWM ID (i=0..7) Pin 2 corresponds to, which bit the pin is in any register (16..19, 21..24).

@Majenko: Pin 2 is PB25, that doesn't help in identifying its PWM ID or position in a register.

I see there pins labeled PWML1, PWMH0 . Is it the PWM ID?

Pin 2 is PB25. That's bit 25 in the Port B registers. In the matrix table PB25 has alternate function TIOA0.

@Juraj Perhaps it is, it definitely does not correspond to the 12 pins printed on the board, and I can see Pin 2 and 3 are not members of this set.

I think your confusion may come from the fact that there's two ways of generating PWM: using the "Fast PWM" module and using a timer.

@Majenko you will note from my second link with the example code, PB25 is not one of the registers addressed when enabling the high speed PWM. They are 16..19 on port B and 21..24 on port C, which by the pin mapping I linked, are D47..44 and D9..6 respectively, again different to the datasheet Juraj provided.

Also you may be right, the Arduino strikes me as a bit of a mess when it comes to anything slightly advanced. I might ask a simpler question then, which is how I can get a higher frequency of PWM switching on Pins 2 and 3.

I have always held the opinion that the Due, in general, is one of the worst Arduino boards ever made. I would never recommend it for anything.

The full pinout is available on arduino.cc in Store and in the Getting started section.

For instance, PWM/Digital Pin 2 maps to PB25 on the chip. PB25 is not a member of the PWM pins as per the chip datasheet. How am I to understand this?

The Arduino core uses timers to do PWM on pins without native PWM support.
In analogWrite source code you can see sections for DAC, PWM and TIMER PWM pins.
The information about pins for Arduino core is in variant.cpp.


text:
On initialising PWM with registers on my Due, why does unrelated duty cycle input influence my output?
I am finding that setting duty cycle on PWM channels 4 or 5 has an influence on whether channel 6 generates output. The following is a design of experiments view of my tests and results, where the outputs are measured on pins associated with PWM channels, high or low. PWM channels 4 and 7 appear not to have a high channel. The configuration allows for 2100 ticks per cycle, so 1050 is 50% and 1575 is 75%.
Why does duty cycle on PWM channels 4 or 5 affect the output of channel 6?
Why does setting a duty on channels 4 or 5 not yield output on those channels?
       Channels included in     Channels included in    Channels given duty cycle                     Measuered PWM Output on Pins/channels
Test   ASBR, PDR                CMR, CPRD               CDTYUPD                                       D6 (PWML7)    D7 (PWML6)    D8 (PWML5)    D9 (PWML4)    D44 (PWMH5)    D45 (PWMH6)
------|------------------------|-----------------------|--------------------------------------------||-------------|-------------|-------------|-------------|--------------|-----------
A      C24, C23, C22, C21       4, 5, 6, 7                       4: 1050, 5: 1050, 6: 1050, 7: 1575   75%           50%           0%            0%            0%             0%
B      C24, C23                 4, 5, 6, 7                       4: 1050, 5: 1050, 6: 1050, 7: 1575   75%           50%           0%            0%            0%             0%
C      C24, C23, C22, C21             6, 7                       4: 1050, 5: 1050, 6: 1050, 7: 1575   75%           50%           0%            0%            0%             0%
D      C24, C23                       6, 7                       4: 1050, 5: 1050, 6: 1050, 7: 1575   75%           50%           0%            0%            0%             0%
E      C24, C23, C22, C21       4, 5, 6, 7                                         6: 1050, 7: 1575   75%           0%            0%            0%            0%             0%
F      C24, C23                 4, 5, 6, 7                                         6: 1050, 7: 1575   75%           0%            0%            0%            0%             0%
G      C24, C23, C22, C21             6, 7                                         6: 1050, 7: 1575   75%           0%            0%            0%            0%             0%
H      C24, C23                       6, 7                                         6: 1050, 7: 1575   75%           0%            0%            0%            0%             0%
I      C24, C23                       6, 7                       4: 1050,          6: 1050, 7: 1575   75%           50%           0%            0%            0%             0%
J      C24, C23                       6, 7                                5: 1050, 6: 1050, 7: 1575   75%           50%           0%            0%            0%             0%
K      C24, C23                       6, 7              3: 1050,                   6: 1050, 7: 1575   75%           0%            0%            0%            0%             0%

Further Information:
Output to PWM7 is not necessary, so have simplified problem. Also the duty value set on channels 4 or 5 can be anything, so long as it is set.
void O_() {
  REG_PMC_PCER1 |= PMC_PCER1_PID36;
  REG_PIOC_ABSR |= PIO_ABSR_P23;
  REG_PIOC_PDR |= PIO_PDR_P23;
  REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1);
  PWM->PWM_CH_NUM[6].PWM_CMR =  PWM_CMR_CPRE_CLKA;
  PWM->PWM_CH_NUM[6].PWM_CPRD = 2100;
  REG_PWM_ENA = PWM_ENA_CHID6;
  PWM->PWM_CH_NUM[4].PWM_CDTYUPD = 0; // Eliminating this line prevents output on channel 6 for some reason
  PWM->PWM_CH_NUM[6].PWM_CDTYUPD = 1050;
}

Original DOE source code:
void setup() {
  // put your setup code here, to run once:
  L_();
}

void A_() {
  REG_PMC_PCER1 |= PMC_PCER1_PID36;
  REG_PIOC_ABSR |= PIO_ABSR_P24 | PIO_ABSR_P23 | PIO_ABSR_P22 | PIO_ABSR_P21;
  REG_PIOC_PDR |= PIO_PDR_P24 | PIO_PDR_P23 | PIO_PDR_P22 | PIO_PDR_P21;
  REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1);
  for (uint8_t i = 4; i < PWMCH_NUM_NUMBER; i++)
  {
    PWM->PWM_CH_NUM[i].PWM_CMR =  PWM_CMR_CPRE_CLKA;
    PWM->PWM_CH_NUM[i].PWM_CPRD = 2100;
  }
  REG_PWM_ENA = PWM_ENA_CHID7 | PWM_ENA_CHID6;

  PWM->PWM_CH_NUM[4].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[5].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[6].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[7].PWM_CDTYUPD = 1575;
}

void B_() {
  REG_PMC_PCER1 |= PMC_PCER1_PID36;
  REG_PIOC_ABSR |= PIO_ABSR_P24 | PIO_ABSR_P23;
  REG_PIOC_PDR |= PIO_PDR_P24 | PIO_PDR_P23;
  REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1);
  for (uint8_t i = 4; i < PWMCH_NUM_NUMBER; i++)
  {
    PWM->PWM_CH_NUM[i].PWM_CMR =  PWM_CMR_CPRE_CLKA;
    PWM->PWM_CH_NUM[i].PWM_CPRD = 2100;
  }
  REG_PWM_ENA = PWM_ENA_CHID7 | PWM_ENA_CHID6;

  PWM->PWM_CH_NUM[4].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[5].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[6].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[7].PWM_CDTYUPD = 1575;
}

void C_() {
  REG_PMC_PCER1 |= PMC_PCER1_PID36;
  REG_PIOC_ABSR |= PIO_ABSR_P24 | PIO_ABSR_P23 | PIO_ABSR_P22 | PIO_ABSR_P21;
  REG_PIOC_PDR |= PIO_PDR_P24 | PIO_PDR_P23 | PIO_PDR_P22 | PIO_PDR_P21;
  REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1);
  for (uint8_t i = 6; i < PWMCH_NUM_NUMBER; i++)
  {
    PWM->PWM_CH_NUM[i].PWM_CMR =  PWM_CMR_CPRE_CLKA;
    PWM->PWM_CH_NUM[i].PWM_CPRD = 2100;
  }
  REG_PWM_ENA = PWM_ENA_CHID7 | PWM_ENA_CHID6;

  PWM->PWM_CH_NUM[4].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[5].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[6].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[7].PWM_CDTYUPD = 1575;
}

void D_() {
  REG_PMC_PCER1 |= PMC_PCER1_PID36;
  REG_PIOC_ABSR |= PIO_ABSR_P24 | PIO_ABSR_P23;
  REG_PIOC_PDR |= PIO_PDR_P24 | PIO_PDR_P23;
  REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1);
  for (uint8_t i = 6; i < PWMCH_NUM_NUMBER; i++)
  {
    PWM->PWM_CH_NUM[i].PWM_CMR =  PWM_CMR_CPRE_CLKA;
    PWM->PWM_CH_NUM[i].PWM_CPRD = 2100;
  }
  REG_PWM_ENA = PWM_ENA_CHID7 | PWM_ENA_CHID6;

  PWM->PWM_CH_NUM[4].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[5].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[6].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[7].PWM_CDTYUPD = 1575;
}

void E_() {
  REG_PMC_PCER1 |= PMC_PCER1_PID36;
  REG_PIOC_ABSR |= PIO_ABSR_P24 | PIO_ABSR_P23 | PIO_ABSR_P22 | PIO_ABSR_P21;
  REG_PIOC_PDR |= PIO_PDR_P24 | PIO_PDR_P23 | PIO_PDR_P22 | PIO_PDR_P21;
  REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1);
  for (uint8_t i = 4; i < PWMCH_NUM_NUMBER; i++)
  {
    PWM->PWM_CH_NUM[i].PWM_CMR =  PWM_CMR_CPRE_CLKA;
    PWM->PWM_CH_NUM[i].PWM_CPRD = 2100;
  }
  REG_PWM_ENA = PWM_ENA_CHID7 | PWM_ENA_CHID6;

  PWM->PWM_CH_NUM[6].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[7].PWM_CDTYUPD = 1575;
}

void F_() {
  REG_PMC_PCER1 |= PMC_PCER1_PID36;
  REG_PIOC_ABSR |= PIO_ABSR_P24 | PIO_ABSR_P23;
  REG_PIOC_PDR |= PIO_PDR_P24 | PIO_PDR_P23;
  REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1);
  for (uint8_t i = 4; i < PWMCH_NUM_NUMBER; i++)
  {
    PWM->PWM_CH_NUM[i].PWM_CMR =  PWM_CMR_CPRE_CLKA;
    PWM->PWM_CH_NUM[i].PWM_CPRD = 2100;
  }
  REG_PWM_ENA = PWM_ENA_CHID7 | PWM_ENA_CHID6;

  PWM->PWM_CH_NUM[6].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[7].PWM_CDTYUPD = 1575;
}

void G_() {
  REG_PMC_PCER1 |= PMC_PCER1_PID36;
  REG_PIOC_ABSR |= PIO_ABSR_P24 | PIO_ABSR_P23 | PIO_ABSR_P22 | PIO_ABSR_P21;
  REG_PIOC_PDR |= PIO_PDR_P24 | PIO_PDR_P23 | PIO_PDR_P22 | PIO_PDR_P21;
  REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1);
  for (uint8_t i = 6; i < PWMCH_NUM_NUMBER; i++)
  {
    PWM->PWM_CH_NUM[i].PWM_CMR =  PWM_CMR_CPRE_CLKA;
    PWM->PWM_CH_NUM[i].PWM_CPRD = 2100;
  }
  REG_PWM_ENA = PWM_ENA_CHID7 | PWM_ENA_CHID6;

  PWM->PWM_CH_NUM[6].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[7].PWM_CDTYUPD = 1575;
}

void H_() {
  REG_PMC_PCER1 |= PMC_PCER1_PID36;
  REG_PIOC_ABSR |= PIO_ABSR_P24 | PIO_ABSR_P23;
  REG_PIOC_PDR |= PIO_PDR_P24 | PIO_PDR_P23;
  REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1);
  for (uint8_t i = 6; i < PWMCH_NUM_NUMBER; i++)
  {
    PWM->PWM_CH_NUM[i].PWM_CMR =  PWM_CMR_CPRE_CLKA;
    PWM->PWM_CH_NUM[i].PWM_CPRD = 2100;
  }
  REG_PWM_ENA = PWM_ENA_CHID7 | PWM_ENA_CHID6;

  PWM->PWM_CH_NUM[6].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[7].PWM_CDTYUPD = 1575;
}

void I_() {
  REG_PMC_PCER1 |= PMC_PCER1_PID36;
  REG_PIOC_ABSR |= PIO_ABSR_P24 | PIO_ABSR_P23;
  REG_PIOC_PDR |= PIO_PDR_P24 | PIO_PDR_P23;
  REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1);
  for (uint8_t i = 6; i < PWMCH_NUM_NUMBER; i++)
  {
    PWM->PWM_CH_NUM[i].PWM_CMR =  PWM_CMR_CPRE_CLKA;
    PWM->PWM_CH_NUM[i].PWM_CPRD = 2100;
  }
  REG_PWM_ENA = PWM_ENA_CHID7 | PWM_ENA_CHID6;

  PWM->PWM_CH_NUM[4].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[6].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[7].PWM_CDTYUPD = 1575;
}

void J_() {
  REG_PMC_PCER1 |= PMC_PCER1_PID36;
  REG_PIOC_ABSR |= PIO_ABSR_P24 | PIO_ABSR_P23;
  REG_PIOC_PDR |= PIO_PDR_P24 | PIO_PDR_P23;
  REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1);
  for (uint8_t i = 6; i < PWMCH_NUM_NUMBER; i++)
  {
    PWM->PWM_CH_NUM[i].PWM_CMR =  PWM_CMR_CPRE_CLKA;
    PWM->PWM_CH_NUM[i].PWM_CPRD = 2100;
  }
  REG_PWM_ENA = PWM_ENA_CHID7 | PWM_ENA_CHID6;

  PWM->PWM_CH_NUM[5].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[6].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[7].PWM_CDTYUPD = 1575;
}

void K_() {
  REG_PMC_PCER1 |= PMC_PCER1_PID36;
  REG_PIOC_ABSR |= PIO_ABSR_P24 | PIO_ABSR_P23;
  REG_PIOC_PDR |= PIO_PDR_P24 | PIO_PDR_P23;
  REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1);
  for (uint8_t i = 6; i < PWMCH_NUM_NUMBER; i++)
  {
    PWM->PWM_CH_NUM[i].PWM_CMR =  PWM_CMR_CPRE_CLKA;
    PWM->PWM_CH_NUM[i].PWM_CPRD = 2100;
  }
  REG_PWM_ENA = PWM_ENA_CHID7 | PWM_ENA_CHID6;

  PWM->PWM_CH_NUM[3].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[6].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[7].PWM_CDTYUPD = 1575;
}

void L_() {
  REG_PMC_PCER1 |= PMC_PCER1_PID36;
  REG_PIOC_ABSR |= PIO_ABSR_P24 | PIO_ABSR_P23 | PIO_ABSR_P22 | PIO_ABSR_P21;
  REG_PIOC_PDR |= PIO_PDR_P24 | PIO_PDR_P23 | PIO_PDR_P22 | PIO_PDR_P21;
  REG_PWM_CLK = PWM_CLK_PREA(0) | PWM_CLK_DIVA(1);
  for (uint8_t i = 4; i < PWMCH_NUM_NUMBER; i++)
  {
    PWM->PWM_CH_NUM[i].PWM_CMR =  PWM_CMR_CPRE_CLKA;
    PWM->PWM_CH_NUM[i].PWM_CPRD = 2100;
  }
  REG_PWM_ENA = PWM_ENA_CHID7 | PWM_ENA_CHID6;

  PWM->PWM_CH_NUM[4].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[5].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[6].PWM_CDTYUPD = 1050;
  PWM->PWM_CH_NUM[7].PWM_CDTYUPD = 1575;
}

void loop() {
  // put your main code here, to run repeatedly:

}


text:
Should a delay be expected to cause deadlock?
I have made a simple program using the int main() {} function. It has a delay in it. It is evident the code before the delay is running, but the delay never seems to time out and let the next instructions through. Is this by design?
If I rename the method and call it exactly once from the loop() {} function though, it does work.
Edit:
The code borrowed the 'main()' function and I suppose redefined it:
int main() {
    Forward();
    delay(3000);
    Reverse();
}

void Forward() {
    //...
}

void Reverse() {
    //...
}

I can see this redefinition of main() could cause some serious issues based on the answer below.

We would need to see the code in question in order to give a full answer.

main() suggest this isn't normal Arduino.

Arduino programs don't use main, they use loop

What value for delay are you using? delay(999999999999999999999999999999999999999999999999); will cause a fairly large problem (if the variable even is that big). | @Cyber It must be another language/bare C. It's weird that it compiled...

First, no, delay can't deadlock, because there are no threads to deadlock on the Arduino. Second, you wouldn't be able to build a sketch containing a redefinition of main (and you don't sound experienced enough to bypass the IDE). Show the simplest code that reproduces the problem. I'm guessing the problem will be very obvious to readers here.

If you don't use Arduino standard main() then you cannot expect using Arduino functions like delay() because these rely on timer initialization performed by main().

@jippie look at my answer below, you'll see the code of delay() depends on micros() which itself is based on Timer0. At least the code is so in Arduino 1.05 libraries. You must be talking about delayMicroseconds() which is a different beast.

@jfpoilpret Why would they do that? The standard and highly optimized delay (both ms and us) routines are in the standard AVR libraries :-s /usr/lib/avr/include/util/delay.h

@jippie Why? I have no idea; they must have a good reason I guess ;-)

@jfpoilpret I think it must have changed over software releases. The delay.h version can only be passed a static parameter, whereas 'your' Arduino.h version can be passed a changing parameter. I remember from when I was a young boy that you couldn't pass a variable to delay();. With this code you obviously can.

@annon this code won't compile as delay() expects an unsigned long which is "only" 32 bits. Also the OP mentioned that it worked in setup(), I guess this was with the same duration.

You don't seem to use standard Arduino stuff since you defined your own main() which is normally avoided when programming Arduino.
If you take a look at Arduino provided main() (in hardware/cores/arduino/main.cpp), you'll see how it is defined:
#include <Arduino.h>

int main(void)
{
    init();

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

    setup();

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

    return 0;
}

Did you notice the init() function call at the beginning?
Its code is defined in hardware/cores/arduino/wiring.c; what it does is setup all timers used by Arduino functions, in particular a timer that is needed by delay().
In the same wiring.c file, you can also find the definition of delay():
void delay(unsigned long ms)
{
    uint16_t start = (uint16_t)micros();

    while (ms > 0) {
        if (((uint16_t)micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

This will turn into an infinite loop if micros() always return the same value, and it does so if init() has never been called before.
This is what happens with your code.

This means delay(); won't work with interrupts disabled.

@jippie yes, that's why you should never call it from an ISR or a function that has disabled interrupts.

Cheers jfpoilpret, I was actually surprised when I borrowed the name main and found it was recognised same as with general c programs so I ran with it, since, I only wanted this instruction run once anyway. Your answer has given a good hint as to the architecture and I'll be able to work from there. Apologies for taking such a hack approach..!

@JCollins no need to apologize, hacking is part of learning and experience eventually :-) Glad you can proceed from here.


text:
How can I2C be made to work through a level shifter?
I am attempting to use a bi-directional level shifter for an IMU to shift the SDA and SCL lines in an I2C implementation, however cannot get the level shifter working with the Arduino at all. It feels like the bi-directionality is confusing the master<>slave relationship and pulling the high and low levels to some average, preventing communications.
At idle, with no connection, the SDA and SCL lines on the Adruino are are 5 V, however when connected to two channels of the level shifter, the voltages drop to 2.5 V on the high side and 1.7 V on the low side of the shifter. The low side of the shifter is completely open so shouldn't be controlling the voltage at all, I've even tried a 10 kOhm and 1.5 kOhm pullup resistor between the low and high sides and their respective voltages, 3.3 and 5 V, but that hasn't worked either.
The level shifter works fine interfacing the MEGA to an SD card over the SPI pins, so I don't understand quite why the level shifting would stop working with the I2C.
The fault manifests as the Arduino hanging on a Wire.endTransmission(); call, which would seem to suggest the MEGA is failing to oscillate its SDA and SCL pins as it wishes. The problem occurs when either of the SDA or SCL pins are connected to the shifter high-side.
I also know that the Sparkfun datasheet for the IMU states that for I2C a level shifter is not necessary, but in debugging another problem, this is being attempted as a solution.
Level shifter: Adafruit 8-channel Bi-directional Logic Level Converter
IMU: Sparkfun LSM9DS1 breakout
Arduino: MEGA 2560 v3

For I2C you need a special kind of logic translator. This one isn't suitable.

This device can only translate push-pull CMOS logic outputs. If for open-drain signal translation, please refer to TI TXS010X products.

Personally I use the PCA9306DCUR since it is specifically designed for I2C operation.

I always use the I2C level shifters with mosfets. 30 cents at AliExpress (search for: i2c level). Adafruit: https://www.adafruit.com/product/757  Sparkfun: https://www.sparkfun.com/products/12009

@Jot they take up too much room for my liking. One of the variants of the PCA9306 is smaller than just one of those SOT23 MOSFETs. It's about the size of one pin and needs a microscope to work with it ;)


text:
Why does command line BOSSA not recognize Arduino Due?
Running Ubuntu 12.04.4 LTS (64 bit) I try to upload my code to the Arduino Due through the Native port. I have tried both the bossac that ships with the Arduino IDE (which is a modified version of BOSSA), and the master BOSSA branch.
Running this command:
sudo ./bossac -p /dev/ttyACM0

I get this error:
No device found on /dev/ttyACM0

However, it works perfectly inside the Arduino IDE.
What can the problem be?

from the IDE's menu you can activate the verbose upload (and compile) mode, that will print all the command executed; Probabibly what you miss is the necessity to open the serial at 1200baud, that will trigger the reboot and consequent bootloader's start ont DUE chip, and bossac need to find the bootloader. see autoReset
edit: i've now a pc with a physical Serial, so i've tryed to upload in verbose mode:
Sketch uses 10,380 bytes (1%) of program storage space. Maximum is 524,288 bytes.
Forcing reset using 1200bps open/close on port /dev/ttyS0
/home/xxx/arduino-1.5.6-r2/hardware/tools/bossac -i -d --port=ttyS0 -U false -e -w -v -b /tmp/build8035422101690460839.tmp/sketch_apr14a.cpp.bin -R

as you can see he is resetting the board by opening the serial at 1200, forcing the bootloader to start. You have to do the same on your script befor launching bossac. How this can be done depends on your OS
Please note that the reset is triggered by the 8u2 chip used as USB to serial adapter on the arduino board, so bypassing it by connecting through tx/rx pin (like using your own conversor, like in my example with hardware serial) won't work unless you do a manual reset at the right time

I can't see what it's doing because there are too many lines outputted. The first lines where it's calling BOSSA are being clipped away.

I found a way. Press the upload-button while in the middle of uploading. It will fail, and will not output too many lines anymore. I'm going to try it out now.

you can also try with a non-due (or a physical serial port with nothing attached)

I believe the problem was either the command line arguments, or that the board needed to be reset before connecting to it. I can't connect to it through the master bossash.exe, so it seems they've changed something on the Due rendering the master BOSSA useless. I don't quite know yet, but I'll try to leave a comment later when I've figured it all out.

edited my answer, as expected the reset opening theserial port with a baudrate of 1200 is a foundamental passage. Also please note that the bootload probably as a little timeout, so you have to script the execution of reset + upload to make it in the time slot.

Does it reset when connecting with 1200 because of some code written by Arduino? If I were to program the Due without the Arduino library, would this method stop working? Is the Arduino Bootloader which runs automatically saved to a different memory than the code we normally flash to the chip?

no special code needed, just opening the serial at 1200baud is fine, and yes, bootloader live in a special area, like in the UNO! Util you get that reset working, you can program using wathever you want

Hmm, how does it know the serial is opened at 1200 baud? Isn't this a number both parts have to know on before hand?

automatic baudrate discovering is possible. Btw you are forgetting that this is a virtual serial over USB, some trick may apply. see /hardware/arduino/sam/cores/arduino/USB/CDC.cpp

Okay, I'm able to upload it now. The problem is just that after the upload, the Arduino doesn't restart, and it isn't possible to connect to it without rebooting the computer.

rebooting the computer?? just disconnect/reconnect the USB does not work? do you close the serial connection?

My mistake. Rebooting the computer worked only once. Now even the Arduino IDE does not recognize it using the native port. It finds the Due on the programming port, but cannot upload code with it. Yes, I have closed the connection.

that's another kind of issue, i think. Developer usb works but not user? How are you compiling code? Des the pc detect the usb?

The PC doesn't detect the USB when connected directly to the SAM (native), but is recognized when connected to the programming port. All using the Arduino IDE, it cannot upload code through the programming USB. Might there be something wrong with the Arduino Due? When connecting RESET to GND, nothing happens.

let us continue this discussion in chat

Sorry, but this answer is fundamentally mistaken.  Opening the port at 1200 baud specifically cannot do anything for a true serial port as listed here.  That's only "magic" with a USB serial device, where the baud rate is a parameter communicated to the hardware.  But on many configurations, merely opening a (real or USB) serial port will change the state of control lines which can be wired to trigger a reset.

@ChrisStratton my answer stand as he is opening a ttyACM0 witch IS acm driver (virtual serial over usb), and the usb driver on the due has been scecifically written to use that as a reboot request. Strange but true: see the "programming" at http://arduino.cc/en/Main/arduinoBoardDue

I'm aware of the special casing - but it does not apply here.  Your answer is erroneous, as in your answer you are, by both description and quoted command, access a true serial port /dev/ttyS0, rather than a USB one.  What you are proposing will not work for a true serial port.

I see. This is because that output is from arduino ide, and because i didn't had a Due i told the ide to use the hw port. I now i get what you say, and I'll point this out

Your description and example command still references a hardware serial port where that trick will not work.

Fixed, i think. Feel free to edit if you dont like it

Easiest way I've found to do this purely from the terminal:
stty -f /dev/cu.usbmodemfa121 1200;stty stop /dev/cu.usbmodemfa121;./bossac -i -d --port=tty.usbmodemfa121 -U false -e -w -v -b Blink.cpp.bin -R

Swap out the serial device for whatever /dev you are using; in Linux you may have to sudo to get direct access to the device.
This is assuming you are in the directory where bossac lives and your .bin file is there too. Adjust to suit your needs.
If using the native USB port you should change -U to true

The Arduino CLI uses a slightly different version of bossa from the one that is on master:
https://github.com/shumatech/BOSSA/tree/arduino
On Linux, I was able to do the following:
$ git clone git@github.com:shumatech/BOSSA.git
$ cd BOSSA
$ make bin/bossac -j4
$ stty -F /dev/ttyACM0 1200
$ ./bin/bossac --port=/dev/ttyACM0 --force_usb_port=true -e -w -v -b /path/to/my/firmware.bin -R

(I got the answer from this Arduino forum thread.)


text:
How to compile code for the Arduino Due?
I have set up Eclipse to compile for the Arduino Due using all the tools shipped with the Arduino IDE 1.5.6-r2. It compiles without errors, but when uploaded, the Arduino does nothing, and isn't recognized on the computer. It then has to be reset manually using the erase and reset buttons.
There is one static library (ArduinoDueCore) consisting of the Arduino library (core), and other code (Atmel found in lib). The other Eclipse project is the TestProject. It contains one file blinking an LED on pin 13. All the files from the Arduino library are there.
This is the output from Eclipse compiling the library itself: (excerpt of only one of each type of command)
18:31:36 **** Build of configuration Release for project ArduinoDueCore ****
make all
Building file: ../src/lib/variants/arduino_due_x/variant.cpp
Invoking: ARM Sourcery Linux GCC C++ Compiler
arm-none-eabi-g++ -DUSB_PRODUCT="Arduino Due" -DARDUINO=156 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/lib/variants/arduino_due_x/variant.o.lst" -fno-exceptions -fno-rtti -w -c -g -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -MMD -MP -MF"src/lib/variants/arduino_due_x/variant.d" -MT"src/lib/variants/arduino_due_x/variant.d" -mcpu=cortex-m3 -mthumb -o "src/lib/variants/arduino_due_x/variant.o" "../src/lib/variants/arduino_due_x/variant.cpp"
Finished building: ../src/lib/variants/arduino_due_x/variant.cpp

Building file: ../src/lib/libsam/source/adc.c
Invoking: ARM Sourcery Linux GCC C Compiler
arm-none-eabi-gcc -DARDUINO=156 -DARM_MATH_CM3 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PRODUCT="Arduino Due" -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/lib/libsam/source/adc.o.lst" -w -c -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -std=c99 -MMD -MP -MF"src/lib/libsam/source/adc.d" -MT"src/lib/libsam/source/adc.d" -mcpu=cortex-m3 -mthumb -o "src/lib/libsam/source/adc.o" "../src/lib/libsam/source/adc.c"
Finished building: ../src/lib/libsam/source/adc.c

Building file: ../src/core/USB/HID.cpp
Invoking: ARM Sourcery Linux GCC C++ Compiler
arm-none-eabi-g++ -DUSB_PRODUCT="Arduino Due" -DARDUINO=156 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/core/USB/HID.o.lst" -fno-exceptions -fno-rtti -w -c -g -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -MMD -MP -MF"src/core/USB/HID.d" -MT"src/core/USB/HID.d" -mcpu=cortex-m3 -mthumb -o "src/core/USB/HID.o" "../src/core/USB/HID.cpp"
Finished building: ../src/core/USB/HID.cpp

Building file: ../src/core/cortex_handlers.c
Invoking: ARM Sourcery Linux GCC C Compiler
arm-none-eabi-gcc -DARDUINO=156 -DARM_MATH_CM3 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PRODUCT="Arduino Due" -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/core/cortex_handlers.o.lst" -w -c -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -std=c99 -MMD -MP -MF"src/core/cortex_handlers.d" -MT"src/core/cortex_handlers.d" -mcpu=cortex-m3 -mthumb -o "src/core/cortex_handlers.o" "../src/core/cortex_handlers.c"
Finished building: ../src/core/cortex_handlers.c

18:31:39 Build Finished (took 2s.811ms)

Here is the project itself:
18:33:42 **** Build of configuration Release for project TestProject ****
make all
Building file: ../src/TestProject.cpp
Invoking: ARM Sourcery Linux GCC C++ Compiler
arm-none-eabi-g++ -DARDUINO=156 -DUSB_PRODUCT="Arduino Due" -DARDUINO_SAM_DUE -D__SAM3X8E__ -DARDUINO_ARCH_SAM -Dprintf=iprintf -DF_CPU=84000000L -DUSB_MANUFACTURER="Unknown" -DUSB_VID=0x2341 -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/TestProject/src" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -Os -ffunction-sections -fdata-sections -Wall -fno-exceptions -fno-rtti -c -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -g -w -MMD -MP -MF"src/TestProject.d" -MT"src/TestProject.d" -mcpu=cortex-m3 -mthumb -o "src/TestProject.o" "../src/TestProject.cpp"
Finished building: ../src/TestProject.cpp

Building target: TestProject.elf
Invoking: ARM Sourcery Linux GCC C++ Linker
arm-none-eabi-g++ -T"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x/linker_scripts/gcc/flash.ld" -L"/home/kim/workspace_juno/ArduinoDueCore/Release" -Wl,-Map,TestProject.map -lm -lgcc  -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--gc-sections -mcpu=cortex-m3 -mthumb -o "TestProject.elf" -Wl,--start-group  ./src/TestProject.o   -lArduinoDueCore -Wl,--end-group
Finished building target: TestProject.elf

make --no-print-directory post-build
/home/kim/arduino-1.5.6-r2/hardware/tools/g++_arm_none_eabi/bin/arm-none-eabi-objcopy -O binary TestProject.elf TestProject.bin

Invoking: ARM Sourcery Linux GNU Create Listing
arm-none-eabi-objdump -h -S TestProject.elf > "TestProject.lst"
Finished building: TestProject.lst

Invoking: ARM Sourcery Linux GNU Print Size
arm-none-eabi-size  --format=berkeley TestProject.elf
   text    data     bss     dec     hex filename
  10396      24    1188   11608    2d58 TestProject.elf
Finished building: TestProject.siz

18:33:43 Build Finished (took 308ms)

Here is the upload command: (removed readWord, go, write and writeWord lines)
-i -d --port=ttyACM0 -U true -e -w -v -b ${project_loc}/Release/${project_name}.bin -R

Set binary mode
chipId=0x285e0a60
Connected at 921600 baud
Erase flash
Write 10420 bytes to flash

[                              ] 0% (0/41 pages)
[=======                       ] 24% (10/41 pages)
[==============                ] 48% (20/41 pages)
[=====================         ] 73% (30/41 pages)
[============================= ] 97% (40/41 pages)
[==============================] 100% (41/41 pages)
Verify 10420 bytes of flash

[                              ] 0% (0/41 pages)
[=======                       ] 24% (10/41 pages)
[==============                ] 48% (20/41 pages)
[=====================         ] 73% (30/41 pages)
[============================= ] 97% (40/41 pages)
[==============================] 100% (41/41 pages)
Verify successful
Set boot flash true
Device       : ATSAM3X8
Chip ID      : 285e0a60
version()=v1.1 Dec 15 2010 19:25:04
Version      : v1.1 Dec 15 2010 19:25:04
Address      : 524288
Pages        : 2048
Page Size    : 256 bytes
Total Size   : 512KB
Planes       : 2
Lock Regions : 32
Locked       : none
Security     : false
Boot Flash   : true
CPU reset.

TestProject.cpp:
#include "Arduino.h"

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

void loop() {
    digitalWrite(13, HIGH);
    delay(50);
    digitalWrite(13, LOW);
    delay(950);
}

Can you tell if it works when you build and upload the program from Arduino IDE instead of Eclipse?

@jfpoilpret It works from the Arduino IDE.

Only the #include "Arduino.h" line is unnecessary.

How did you setup eclipse for Arduino, do you use http://eclipse.baeyens.it/ plugin?

@jfpoilpret I'm using GNU ARM Eclipse plugin version 0.5.4 (http://sourceforge.net/projects/gnuarmeclipse/files/Current%20Releases/0.5.4/) It is set up with the Sourcery Lite toolchain. All the build settings are reflected in the terminal output.

I used this guide as a starting point, and added preprocessor variables to make it compile successfully.
http://forum.arduino.cc/index.php/topic,135403.0.html
By following the guide, it worked using Arduino 1.5.1, however it did not support all of the Arduino API...

Then the next important question is "where is main() defined?"

@jfpoilpret It is defined inside of the Arduino Library. It resides inside ArduinoDueCore->src->core->main.cpp.

OK; in your situation, I would try to compare the output (console and files) of Arduino IDE 1.5 and Eclipse, in order to spot any difference; each found difference is a potential reason of failure. Then analysing each difference can help you find the root cause for it. Sorry, I can't help more, I don't have a DUE available.

@jfpoilpret That is what I've tried. All the differences I know how to "fix" are "fixed". The problem is that the Arduino IDE uses a precompiled library (I believe) for some operations. I know very little about C/C++, as I've mostly interpreted languages. I'll try and see if I can make the Arduino IDE compile everything itself by deleting the compiled library (l*\.a?)

If I were you, I would rather try http://eclipse.baeyens.it/ (I already use it for UNO boards). It works well, and there is a version for Arduino IDE 1.5 also; that may be your best option?

@jfpoilpret Does it work for Arduino 1.5.6-r2? The problem with 1.5.1 was that the API wasn't fully developed for the ARM series.

It is not mentioned; the latest mentioned supported IDE is 1.5.5; I guess that does not mean it won't work with 1.5.6, but you'll have to check it by yourself I think.

@jfpoilpret The reason why I wanted to do it "myself" is because I want to learn how to use the Atmel ARM series step by step. But I suppose Arduino have modified everything so much that it's not like communicating with the real chip anymore. The master branch BOSSA doesn't work on the native port, which I thought was connected directly to the chip... I'll learn how to program it using a book instead.

@jfpoilpret Now I've set up Baeyens.it. It only works half way. Yes, it uploads the code, but it only starts running after pressing the RESET button manually. Additionally it needs to be erased and reset to listen for new code. The RXTX-library doesn't work, and even triggers a Linux system error. I'll just stick to the Arduino IDE!

Using 1.5.6-r2 with Eclipse cause the Due to hung in Default_Handler function after entering main and polling a few times for the next SysTick gettin passed.
Some weak symbol declarations are done twice (i.e. the SysTick_Handler function definitions). They appear to overwrite each others weak alias depending on the link time usage of the objects. All declarations (not only the failing SysTick_Hanlder) from cortex_handler.c are getting overwritten by weak symbol redeclaration inside startup_sam3xa.c.
This commit seems to already address a weak symbol definition problem.
https://github.com/arduino/Arduino/commit/65f00a69c74ca0def8d7f1d7597327945a04a33f
For now, to fix it. Just comment out the part in startup_sam3xa.c with the weak symbol declaration regarding the vectors. Lines 53 to 129.
It should also work to just remove the file completely.
The startup handler code and vector map should be provided by gcc arm built-in libraries instead.