Friday, September 04, 2015

Arduino Due: toggle open drain GPIO pin

I wanted a pin on my Arduino Due to switch between pulling down toward ground and turning off (going high impedance).

I tried using pinMode(x, INPUT);, but there's a bug in the arduino libraries that sets the output high when I switch back to pinMode(x, OUTPUT).  That's no good!

So I read up in the datasheet and found the register that enables open drain mode.  The pinout was also handy so I could see that pin 53 (according to Arduino) is port B, pin 14 according to the ARM chip.

Here's the code snippet.

 // Sketch for Arduino Due that enables open drain mode for pin B14  
 void setup() {  
  pinMode(53, OUTPUT);  
  digitalWrite(53, 0);  
  // Enable open drain mode on pin 14 of port B using the Multi-Driver Enable Register  
  REG_PIOB_MDER = 1 << 14;  
  // To switch it back to a normal output:  
  // REG_PIOB_MDDR = 1 << 14;  
 }  
 void loop() {  
  // Turn on B14 (should be about equivalent to digitalWrite(53, 1))  
  REG_PIOB_SODR = 1 << 14;  
  // Pause 1ms so it's easy to see on the scope  
  delay(1);  
  // Turn off B14  
  REG_PIOB_CODR = 1 << 14;  
  // Pause 2ms  
  delay(2);   
 }  

No comments: