Saturday, November 29, 2014

Debugging Interrupt Service Routines

I have been spending some time writing AVR Interrupt Service Routines of late and have decided to share some debugging techniques that I have found useful.

When writing ISRs, especially those used to service timer interrupts, as the timer period shortens, it becomes necessary to be especially prudent about the amount of code you place in the ISR.

Obviously, the ISR routine cannot execute longer than the timer period or timer interrupts will be missed.  When an ISR is entered, interrupts are disabled so that the ISR itself cannot be interrupted unless interrupts are explicitly re-enabled in the ISR itself.  This is something that should be done very carefully (if at all) after understanding all the ramifications.

It is a mistake to put Serial.print() code in your ISR code as such code takes a very long time to complete when interrupts are disabled.  It may appear to work for a while with very short output messages, but you are fooling yourself as to the usefulness of this output.

So, how does one debug ISR code?  I find it very useful to use an oscilloscope connected to a digital pin and to toggle that pin when events of interest are seen.  For example I might set the pin high when entering the ISR and low when exiting the ISR.  Along with allowing me to see that my interrupt service routine is in fact being called, I can see how often it is called by measuring the time between pin transitions from low to high.  Additionally, I can see how long the ISR itself is taking to run by measuring the time between the pin going high and it going low again.

By way of example, I have set up timer2 on an ATMega2560 to interrupt every 32 microseconds. 

// Setup timer2 with prescaler = 1, PWM mode to phase correct PWM
// Timer will count to maximum and then back down again (effectively a divide by
// 512 since timer2 is an 8 bit counter.  This will generate an interrupt every
// 32 us.  16000000 / 512 = 31250 = 32 us (.000032 seconds)
// See the ATMega datasheet for all the gory details
void timer2Setup()
{ 
  TIMSK2 = 0;
  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20);
  TCCR2B = _BV(CS20);
}

And then enable timer2 when I am ready for the timer to start.

  // Useful macros for setting and resetting bits
  #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
  #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

  sbi (TIMSK2, TOIE2);      // Enable timer 2.

To handle the ISR, I have created a trivial handler that merely sets digital pin 8 high and then sets it back low.

  // Timer 2 interrupt service routine (ISR).
  ISR(TIMER2_OVF_vect)
  {
    digitalWrite(8, HIGH);
    digitalWrite(8, LOW);
  }

Now, looking at this on the scope, we see a positive going pulse on pin 8 every 32us indicating that the ISR is being entered at that rate.


But another very interesting fact is revealed by this scope trace.  The amount of time it takes the ISR to simply toggle a pin high and then low is an amazing 7.6us.  This is a freaking eternity in the relative scheme of things.  Out of 32us I have to perform all of my ISR code, just toggling a pin high then low takes 23% of the available time.



If your ISR code is very short and sweet, this may be a non-issue.  However, everything you can do to shorten ISR code length should be done because the ISR runs with interrupts disabled.  Nothing else can run until you return from your ISR.

A silly example would be an ISR that runs every 32us and takes nearly 100% of the available 32us to complete.  This would mean that precious little time would be available for your main loop to run in your Arduino sketch.  In this particular example, there is no code in the main loop, so it is of no consequence.  However, this is not the norm and you want to minimize the time spent with interrupts disabled as much as possible as a general rule so some time spent on optimizing your ISR code can pay big dividends on overall performance.  Any section of you code can be timed quite accurately using this method allowing experimentation of different techniques to speed up your code or at least understand the effect on performance of any code change.

So, what can we do to optimize this simple two line ISR routine?  Ditch the use of digitalWrite and manipulate the port directly.  The beauty of digitalWrite is that it allows you to abstract the notion of "digital pin 8" from the particular hardware you are running on.  If you are running on a Arduino UNO (or any ATMega328 device) then digital pin 8 is PORTB bit 0 (PB0).  However, if you are running on an ATMega2560 as I am, then this same digital pin 8 is PORTH bit 5.  The digitalWrite implementation hides all of this mess from you very nicely, but at the expense of code speed.

So, let's take the knowledge we have of what processor we are running on and what port and bit the digital pin is assigned to and optimize this code a little.  I am running on an ATMega2560, so digital pin 8 is PH5.  Modifying the code to manipulate the desired bit directly means the code is hardware specific, but we gain a significant speed improvement in the code.  This code is for the ATMega2560.

  // Timer 2 interrupt service routine (ISR).
  ISR(TIMER2_OVF_vect)
  {
    sbi(PORTH,5);
    cbi(PORTH,5);
  }

Now looking at the scope, we see that the setting and resetting of the pin only takes 320ns to execute, a significant savings.



If running on an ATMega328 such as found in the UNO, change the ISR as follows:

  // Timer 2 interrupt service routine (ISR).
  ISR(TIMER2_OVF_vect)
  {
    sbi(PORTB,0);
    cbi(PORTB,0);
  }

Hopefully you will find this technique useful in your general debugging as well as when debugging ISR code in particular.  As always if you need assistance, drop me a line at ko7m at arrl dot net and I will be happy to assist in any way I can.

Wednesday, November 12, 2014

VNA fixture PCB available from OshPark.com

Due to a number of requests to share my VNA fixture design, I have made them available at OshPark.com using the following link.  Boards can be ordered directly at that link in multiples of three very inexpensively (about $11).  Drop me a note at ko7m at arrl dot net should you encounter any difficulty in obtaining them.




The tactile switches used on the board are available at mouser.com at this link.  As always, I would be happy to help you succeed in implementing this board should you so desire.

Tuesday, November 11, 2014

Characterizing Crystals

Still learning how to use the VNA.  Grabbed a handful of Crystals and clipping them to the VNA fixture described in my previous post, I collect the following information:



I am not sure that I am doing things correctly, and certainly am not yet in a position to interpret the results seen above.  More study and experimentation will be required, but it looks like I will certainly have the necessary information to design filters.



More to come...

Monday, November 10, 2014

VNA fixture

In a previous blog post I mentioned purchasing a batch of 20 MHz crystals from China with the intent of building some crystal filters.  I am facing the need to be able to characterize my new collection of eBay crystals.  I have looked at many of the suggested techniques and out of them all, I like the idea of using a vector network analyzer for the task.

A few years ago, I purchased one of these units from SDR-Kits.



I purchased this at a time when support on Windows platforms for the necessary drivers was quite sub-optimal and as a result this device has not seen much use over the years.  However, I have dug it out, dusted it off and upgraded the firmware and USB drivers, which are now nicely supported on all versions of Windows.

Now, I need a nice fixture that can be used to characterize a batch of Crystals. Leveraging the fine work of Eldon (WA0UWH) I have built a fixture that can be used with this VNA for the task at hand.


The idea behind this is to provide a couple places where components can be connected to the fixture and swept with the VNA to be able to visualize its characteristics over a wide frequency range.

The 8 pin header is provided with three ground attach points, one signal attach point and two pins on each side that connect together.  The idea is to be able to create simple networks of discrete components and be able to sweep them or to just sweep individual components.



The buttons provide the ability to short or terminate the VNA with a 50 ohm load.  As part of the calibration process when the fixture is attached, you want to remove the effects of the fixture itself from the measurements so the VNA is calibrated with a short, through, open and load conditions before attaching components to be measured.

The two resistors are 100 ohm 0805 units that are connected in parallel across the SMA when nearest button is depressed providing a 50 ohm load.  The bottom button shorts the SMA connector when depressed.

The bare copper area at the bottom of the board allows for placing surface mount components across the gap.  These can be held in place with a non-conductive clothes pin or a conductive clip as appropriate.  When measuring surface mount crystals for example, a conductive clip will allow grounding of the crystal case as the back side of the board is an open ground plane while holding the connectors firmly against the top side of the board.



Hopefully this little fixture will help expand the usefulness of the VNA in my projects.  I will share my experiences using this characterizing crystals in a separate post.

Friday, November 7, 2014

At the tone...

Fun with Arduinos and scopes in XY display mode...  Looks good on good old analogue and high end digital scopes.  Not so much on my $400 digital model.


Dual channel 8 bit DACs and a bunch of table look-up data, and a cheap RTC if you want accurate time.



Commercial versions of hardware able to produce such a display are available.  

Thursday, November 6, 2014

New Minima-like build

My good friend Wayne NB6M has kindly loaned me his Minima-like build using my controller shield for the Arduino.  His front panel is very similar to his original Minima build, but is now sporting a 20x4 display.  He has removed the reset button from the front panel and added input for paddles in anticipation of me actually finishing the integration of my keyer code to the Minima code base.



Looking at the back of the panel, we can see the Arduino Uno and my controller shield mounted on the back of the display board.  Wayne has used #12 bare copper wire soldered to the front panel to provide attach points for the Uno and shield.  My shield will be modified to provide through-hole plating and solder pads so that it can be soldered in place.

The display board has been converted to i2c with a backpack board and the rotary encoder uses pins freed up by display being converted to i2c.  The current shield design does not incorporate the proposed pins for the encoder from the discussion list, but will be modified in the final run to be compliant.


Wayne is using a pretty conventional IF strip from the Minima, but has chosen to replace the KISS mixer and BFO mixer with ADE-1 devices.  His audio section is from a pre-existing project re-purposed for this project.  The two SMA connectors connect to the VFO and BFO Si570 outputs from my controller shield.  No low pass filter sections yet.  The current configuration makes a pretty nice general coverage receiver.


I have handed off Wayne's other Minima build to Eldon so he will have a working radio to test with during his software development efforts.

Saturday, November 1, 2014

Arduino Yun

I recently was given an Arduino Yun and have been playing around a little with this guy.


It is quite a little improvement over the basic Arduino UNO.  I have only begun to explore the possibilities, but it looks like it will be fun.

Yun is based on the ATMega32u4 microcontroller, but also is distinguished by the presence of an Atheros 9331 processor (the bit under the metal can above) that runs concurrently with the AVR processor a Linux distribution based on OpenWrt called OpenWrt-Yun.

The board has built-in Ethernet and WiFi support, as well as a USB-A port, micro-SD card slot and 20 digital I/O pins of which 7 can be used as PWM outputs and 12 as analog inputs.

The AVR processor can communicate with the Linux distribution to leverage capabilities of that platform such as networking, shell and python scripts.  The AVR side of the house has no need for a separate secondary processor as is found in the UNO to handle USB communications as it is built in.

The Yun device can appear to a connected computer as a mouse and keyboard in addition to a virtual serial / COM port.

A block diagramme can be seen below of the architecture.  The bridge component facilitates communication between the two processors allowing sharing of abilities such as running shell scripts, access to network interfaces , USB host functionality and the SD card.


Out-of-the-box the Yun is WiFi enabled and it acts like an access point.  You can connect your computer to the access point and then configure the Yun network.  I joined it to my home WiFi network, rebooted it and now I can upload scripts to it over WiFi.  Here is a shot of it sitting on top of a 10,000 ma/hr battery that is powering it as a stand alone unit that I can program from my laptop connecting via WiFi.



Here is a screen shot of an ssh session to the Linux side of the device and the normal Arduino IDE side-by-side.



 It will be fun to see what new ideas will result from this enhanced functionality.

Thursday, October 23, 2014

Minima controller shield - Using second Si570 as BFO.


I have implemented changes to the Minima controller code developed by Eldon Brown (WA0UWH) and others to use the second Si570 on my controller shield as the BFO oscillator.  This change allows easy setting of your Minima BFO oscillator frequency to the desired point on your crystal filter passband curve, be that at the -3 dB point or further down the skirt.




The IF edit mode of the controller firmware will allow the adjustment of the BFO frequency.  Separate frequencies are maintained for USB and LSB.

A separate issue is regarding the calibration of both of the Si570 devices on the shield against some frequency standard.  For most folks that have a crystal oscillator for the BFO, the IF edit mode has probably been used to calibrate the dial to some frequency standard and this is fine.  However adjusting the IF frequency offset from the displayed frequency only allows you to match the value that the controller uses to whatever frequency your crystal oscillator BFO is tuned to whereas with the second Si570, you can actually move the BFO frequency in software which is not the same thing as calibrating the dial.




The calibration of the Si570 devices as I see it is a separate matter from setting the desired BFO frequency as you certainly don't want to change where the BFO frequency sits on the IF passband just to calibrate the dial.  So, I anticipate providing a different mechanism that will allow moving the VFO frequency (and BFO frequency for those using a second Si570 as the BFO oscillator) without changing the displayed frequency in order to determine the error offset for each Si570.  This error offset can then be stored in eePROM and applied automatically from that point forward to the appropriate Si570.

More to come on this topic...

Sunday, October 19, 2014

Updated Minima Rotary Encoder Driver


I have implemented support for rotary encoders in the Minima and provided integration of it into Eldon Brown's (WA0UWH) fine work on the Minima controller code.  The encoder works very smoothly and is very resilient to noisy, bouncing contacts on the mechanical encoders typically used.  That said, if you can avoid it, you should stay away from cheap mechanical encoders.  Spend a little more money on the main interface to your radio if you can.

The implementation uses pin-change interrupts for both the A and B inputs from the encoder.  A side effect of this is that you cannot pick completely arbitrary pins for the A and B inputs to the Arduino.  They must both be on the same port (PORTB, PORTC, PORTD).  My minima shield uses digital pins 8 and 9 freed up by replacing the 6 wire LCD with an i2c display.  Another option would be to use PD6 and PD7.  PD7 is currently targeted to be used by the RF386 amplifier.  However, the tuning control pot input A2 could be used freeing up PD6 and PD7 (both on PORTD) for use by the rotary encoder.

When an interrupt is received, the encoder is read and if it has changed, a 3ms debounce timer is reset.  As long as the pins continue to interrupt, the debounce timeout continues to be reset.  When the debounce timer expires, the encoder hasn't changed in the last 3ms and the value is processed.

I have provided integration to Eldon Brown's (WA0UWH) radiono code and completed initial testing.  I have turned it over to him to release with his code if he wishes to do so.

In general there are three basic functions that need to be implemented to support rotary encoders.

  1. Set up pin change interrupts for encoder A and B inputs.
  2. Set up debounce timer
  3. Implement interrupt service routines (ISR) for pin change and timer

The following bunch of noise is to try to minimize the number of changes required in order to change the pins the encoder is connected to.  The implementation represents a balance between providing pin change support for a Minima radio that can be configured as compared to a general purpose (large) library that can be configured in any way desired on any hardware platform.  If you wish to use analogue aliases for encoder pin numbers (A0-A5) you should instead use 14-19 (the digital pin equivalent numbers).

It should be noted that all of this (currently) only works on the ATMega328 such as is found in the Minima, Arduino UNO, etc.  Specifically support for the ATMega2560 is not yet implemented.

// Encoder pins
#define ENC_A_PIN 8  // Change these as desired, but both pins must be on 
#define ENC_B_PIN 9  // the same port (PB, PC, PD)

// Pin change interrupts
// Digital pin     PC Pin     Vector      Ctl Reg Port PCICR Bit Pin Mask Reg
// D0-D7           PCINT16-23 PCINT2_vect PCIR2   PD   PCIE2     PCMSK2
// D8-D13          PCINT0-5   PCINT0_vect PCIR0   PB   PCIE0     PCMSK0
// D14-D19 (A0-A5) PCINT8-13  PCINT1_vect PCIR1   PC   PCIE1     PCMSK1

// Define the interrupt vector, interrupt enable bit, PCINTpin values
#if (ENC_A_PIN) >= 0 && (ENC_A_PIN) <= 7
  #define VECTOR    PCINT2_vect
  #define PCMask    PCMSK2
  #define PCICRbit  (1<<PCIE2)
  #define PCINTpinA (1<<(ENC_A_PIN))
  #define PCINTpinB (1<<(ENC_B_PIN))
#endif
#if (ENC_A_PIN) >= 8 && (ENC_A_PIN) <= 13
  #define VECTOR    PCINT0_vect
  #define PCMask    PCMSK0
  #define PCICRbit  (1<<PCIE0)
  #define PCINTpinA (1<<(ENC_A_PIN-8))
  #define PCINTpinB (1<<(ENC_B_PIN-8))
#endif
#if (ENC_A_PIN) >= 14 && (ENC_A_PIN) <= 19
  #define VECTOR    PCINT1_vect
  #define PCMask    PCMSK1
  #define PCICRbit  (1<<PCIE1)
  #define PCINTpinA (1<<(ENC_A_PIN-14))
  #define PCINTpinB (1<<(ENC_B_PIN-14))
#endif

Ok, so all that noise is defining a bunch of things that change when you change the encoder pin numbers.  Specifically, you need to define the interrupt vector, the pin mask used and the pin change interrupt enable bit used.

The encoder returns a Gray code which I normalize to a 0..3 value.  Specific patterns of values are compared to determine the encoder direction of rotation.

// Encoder patterns for clockwise and anti-clockwise rotation
static const int CCW_DIR[] = {0x01, 0x03, 0x00, 0x02};
static const int  CW_DIR[] = {0x02, 0x00, 0x03, 0x01};

static int      last_code;  // Last stable encoder output
static int  encoder_count;  // tracks incremental rotation CW (+), CCW (-)

// Structure used to track encoder pin state in ISR
typedef struct 
{
  union 
  {
    byte encoder;
    struct 
    {
      int enc_A:1;
      int enc_B:1;
    };
  };
} PINSTATUS_t;

// Returns current encoder pin reading normalized to 0..3 value.
static inline int getEncoderValue(void)
{
  int value = 0;
  
  if (digitalRead(ENC_A_PIN)) value += 1;
  if (digitalRead(ENC_B_PIN)) value += 2;
    
  return value;
}

The pin change interrupt service routine (ISR) now needs to be defined.  We only look at the current value of the encoder pins and compare it to the last value read.  If it has changed, we just reset the 3ms debounce timer.  We are not going to process the encoder value until it has not changed for 3 ms.

// Encoder pin change ISR - If a pin changed, reset debounce timer
ISR(VECTOR)
{
  static PINSTATUS_t last;
  byte prior;

  prior = last.encoder;
  last.enc_A = digitalRead(ENC_A_PIN);  // Get encoder current pin values
  last.enc_B = digitalRead(ENC_B_PIN);
  
  if (prior != last.encoder)
  {
    TCNT1  = 0;
    TIMSK1 |= (1 << OCIE1A);
  } 
}

The 3 ms timer is implemented using timer 1.  I chose this timer because internal libraries for Arduino use timer 0 (the delay() function for example) and I plan to use timer 2 in my CW keyer code going forward.  Timer 1 is a 16 bit timer and is set up to provide an interrupt after 3 ms.

Currently, I decode and debounce 4 edges per detent on the encoder.  I could increment the encoder for each of these events which might make sense for an encoder without detents.  However, getting an increment/decrement of 4 for every click of the encoder detent would be confusing, and not useful, so currently I only return an increment for every 4 encoder edges decoded resulting in incrementing by one per detent click.  This could be used to speed up tuning when moving a long distance, but that is for another day...

// Timer ISR - We get here if the debounce timer times out.  Compare the new
// code with the previous one to see which direction the encoder has turned.
// Update the rotation counter to reflect the change.  The timer and interrupt
// are left disabled.  I can get four counts per detent and effectively divide
// this by 4 to get one tick per detent.
ISR(TIMER1_COMPA_vect)
{
  int new_code = getEncoderValue();
  
  if (new_code != last_code)
  {
    if (new_code == CW_DIR[last_code]) {
      if (0x00 == new_code) encoder_count++;
    } else if (new_code == CCW_DIR[last_code]) {
      if (0x00 == new_code) encoder_count--;
    }
    last_code = new_code;
  }
  TIMSK1 &= ~(1 << OCIE1A);  // Disable Timer
}

The initialization code for the encoder sets up pin change interrupts and Timer 1.  No magic here.

// Initialize the encoder
void initEncoder()
{
  cli();
  
  // Encoder pins
  pinMode(ENC_A_PIN, INPUT_PULLUP);
  pinMode(ENC_B_PIN, INPUT_PULLUP);
  
  // Set pin change interrupt enable and pin mask for encoder pins
  PCMask |= PCINTpinA;    // Set pin mask for A and B inputs
  PCMask |= PCINTpinB;
  PCICR  |= PCICRbit;     // Enable interrupts on correct port
  
  // Set timer 1 for 3 ms debounce timeout
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  // set compare match register 3 ms
  OCR1A = 48000;
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set bits for no prescaler
  TCCR1B |= (1 << CS10); 
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);
  sei();
  
  // Set the initial value from the encoder
  last_code = getEncoderValue();
  encoder_count = 0;
}

All that is left is to read and return a signed value indicating the direction and amount that the encoder has moved.  If this is called in the main loop of your sketch, it will typically return a +/- 1 value depending on the latency of your main loop.  In Eldon's Minima controller, it nicely returns a single increment or decrement per call.  The only magic here is to disable interrupts while reading the multi-byte value of the encoder in order to prevent the value from being changed before all bytes can be read.

// Return encoder count.  Negative - Anti-clockwise, positive - clockwise
int getEncoderDir()
{
  uint8_t oldSREG = SREG;
  cli();
  int val = encoder_count;
  encoder_count = 0;
  SREG = oldSREG;
  return val;
}

As always, your mileage may vary, but I hope you find this code useful.  I am happy to help if anyone has problems with it.  I will not be publishing this separately, but I expect that Eldon will use the integration in his Minima controller and publish it in due course after he has had a chance to review it.

I am happy to help with any problems.  Drop me an email note at ko7m at arrl dot net and I will do my best to help you with any issues.

Wednesday, October 1, 2014

Minima working with rotary encoder

I have gotten Wayne, NB6M's Minima hardware working with a rotary encoder, thanks to the great work by Eldon, WA0UWH.  Eldon has come up with a clever way to implement an encoder on top of his button structure that only requires a single input pin on the ATMega328 to handle all 7 buttons, plus the rotary encoder.  Check out his blog for all the details.

I am sitting here listening to 75 meters tonight to the group that meets around 3.885 MHz on AM.  Most of these guys are running old AM ham gear.


I have replaced the audio section with an LA4425 power amplifier chip.  This is a 5W amplifier that typically is found in a automotive applications.  It requires very few external parts and has sufficient drive to comfortably drive an unpowered speaker.


I have inserted this circuit between the volume control wiper and the speaker.  Here is a shot of the ugly-style build in Wayne's Minima.


I like the end result, but it actually has a little more gain than it needs for this application.  It is nice not needing to use amplified speakers just to hear the radio.  I have not yet screwed down the component.  It runs cool enough in this application, but the additional heat sink couldn't hurt.