Interrupt Programming with Arduino

Setting up interrupt functions on Arduino is quite simple. Search the internet, you’ll find several nice tutorials on the subject. I’m just sharing my own example for style, and to clarify, why do interrupts at all?

Interrupts are immediate, and they allow clean separation of concerns between main (loop) code and special-purpose functions. Like object-oriented programming, they clarify code intent.

The main loop() function typically has delays built in, so while you could test for a button push in the loop, it may take a while before the loop gets to that point in the code, so you’ll see a delay between the push the resulting effect. An interrupt does what it says – it interrupts the main loop and executes all the code in the interrupt function first, before returning back to the main loop.

Setting up an interrupt is super easy: just define a function, then “attach” it as an interrupt with the attachInterrupt() function, with a digitalPinToInterrupt() identifying the appropriate pin (on Arduino Duo and Nano, digital pins 2 and 3 are available for interrupts), and the type of interrupt, RISING, FALLING, or CHANGE. For simple button interrupts, RISING is your best choice. If your interrupt function references any global variables, make sure those variables are defined as volatile.

For this demo, I have set up a simple circuit with two LEDs, red and green, and a button. Typical set up: grounded LEDs with 220 ohm resistors in serial on the anode pin; button is grounded with a 10 kiloohm resistor and its common pin to digital pin 2, with power on the other switch pin.

The program is simple: a green light that blink endlessly. The button push interrupts that loop to turn on the red light. Push it again (it’s a toggle) to turn off the red light. If the red light is on, green remains off.

To those new to C programming, let me explain a few more lines. First, the ternary operator: (toggle == HIGH) ? LOW : HIGH . This says if toggle value is HIGH, then return LOW, else return high, all in a single line of code. Since toggle itself is being assigned (toggle = ) to this operator’s return result, toggle is just becoming the opposite value of whatever it was last. The ternary operator is concise, and saves you a long if then else statement with lots of curly braces.

This line digitalRead(red) == HIGH , also saves you a tedious if then else statement. If digitalRead() is HIGH, it returns true, else it returns false.

byte red = 11;
byte green = 9 ;
byte interrupt_pin = 2 ;
volatile int toggle = LOW ;
void setup() {
  pinMode(red,OUTPUT) ;
  pinMode(green,OUTPUT) ;
  pinMode(interrupt_pin,INPUT) ;
  digitalWrite(green,LOW) ;
  attachInterrupt(digitalPinToInterrupt(interrupt_pin),toggleRed,RISING); 

}

void loop() {
  blinkGreen() ;
}

void blinkGreen() {
  if (!isRed()) {
    digitalWrite(green,HIGH) ;  
  }
  delay(2000) ;
  digitalWrite(green,LOW) ;
  delay(2000) ;
}

void toggleRed() {
   toggle = (toggle == HIGH) ? LOW : HIGH ;
   digitalWrite(red,toggle) ;
   if (isRed()) {
    digitalWrite(green,LOW) ;
   }
}

boolean isRed() {
  return digitalRead(red) == HIGH ; 
}

Object-oriented Programming with the Arduino Microcontroller

A Traffic Light Simulation with pedestrian crosswalks

These days, when I’m not managing teams and projects, I am primary a Python developer. But, recently I took it upon myself to learn Arduino, and it’s been fun going back to old hobbies – building circuits and C!

The Arduino programming language include some C++ elements as well, especially classes, so this has allowed me to introduce object-oriented design concepts as well. Here’s a simple circuit with two interconnected traffic lights, programmed in such a way that neither can be green at the same time. The connected pedestrian crosswalk switches initiate a countdown, then switching one light to red before allowing the other light to turn green. I’ve added an additional safety consideration for broken red lights.

By using a TrafficLight class, I’m able to reuse code as well, instead of repeating code for each traffic light circuit. The method names clearly indicate their functional purpose, so the code is easy to read.

There’s several ways to approach this circuit control, the code here is just for demo purposes, something I hacked out rather quickly. Overall, it was a fun project to develop, and my first Arduino circuit beyond the starter package projects.

The TrafficLight class header

The interest element of this class is interconnectedLight. Notice that it is defined as a TrafficLight class as well. One traffic light refers to another traffic light. This being C++, the syntax is actually a pointer to a class, thus TrafficLight*.

class TrafficLight {
    byte red, yellow, green, switchPin ;
    TrafficLight* interconnectedLight ;
    boolean switchWasPressed = false ;
  public:
    void attach(int switchPin, int red, int yellow, int green) ;
    void interconnect(TrafficLight anotherLight) ;
    void countdownToGreen() ;
    boolean canSwitch() ;
    boolean isSwitchPressed() ;
    void turnLightGreenInitial() ;
  private:
    boolean isGreen() ;
    boolean switchAlreadyPressed() ;
    void turnLightRedInitial() ;
    void flashLights() ;
    boolean isRedFunctioning() ;
    void turnLightRed() ;
    void turnLightGreen() ;
    void greenOn() ;
      
} ;

The TrafficLight method implementations

Modeled after the Servo class in Arduino, the class is initialized with an attach() method, passing in all the pins wired on your circuit. It also sets up all the pinModes and initial settings for the LED lights.

void TrafficLight::attach(int aPin, int aRedPin, int aYellowPin, int aGreenPin) {
  switchPin = aPin ;
  red = aRedPin ;
  yellow = aYellowPin ;
  green = aGreenPin ;
  pinMode(yellow,OUTPUT) ;
  pinMode(green,OUTPUT) ;
  pinMode(red,OUTPUT) ;
  pinMode(switchPin,INPUT) ;
  digitalWrite(red,LOW) ;
  digitalWrite(yellow,LOW) ;
  digitalWrite(green,LOW) ;
}

void TrafficLight::interconnect(TrafficLight anotherLight) {
  interconnectedLight = &anotherLight ;
}

Also make note of the interconnect() method. Passed in is another TrafficLight, and since interconnectedLight is a pointer definition, we use &anotherLight, the “reference” to this object, to get the pointer assignment. For those new to C++, this pointer and address references are perhaps the most tricky syntaxes you’ll have to learn.

turnLightGreen() is perhaps the the most significant method in this class. The main microcontroller calls countdownToGreen() when the appropriate button is pushed; that method then calls turnLightGreen(). Notice what it does: it’s very first step is to turn the other light red. In then double checks that light, is it really red – isRedFunctioning() ? If it does, it then proceeds to turn this light green, after a suitable delay.

Oh, here’s another syntax quirk of C++: see the -> ? That’s the arrow reference, is used when calling a method of another class pointer. It is also used with this. This is not necessary, but makes most code easier to read: this->greenOn() meets means to call the greenOn() method on the class object itself. That is, if light1.turnLightGreen() is called, this is light1.

void TrafficLight::turnLightGreen() {
  interconnectedLight->turnLightRed() ;
  if (interconnectedLight->isRedFunctioning()) {
    delay(1000) ;
    this->greenOn() ;
    crosswalkSounding() ;
  }
  else {
    this->flashLights() ;
  }
  switchWasPressed = false ;
}

Here are the remaining methods. They should all be fairly easy to understand, but if you have any questions, feel free to email me.



void TrafficLight::countdownToGreen() {
  switchWasPressed = true ;
  countdown() ;
  this->turnLightGreen() ;
}

void TrafficLight::turnLightGreenInitial() {
  interconnectedLight->turnLightRedInitial() ;
  if (interconnectedLight->isRedFunctioning()) {
    this->greenOn() ;
  }
  else {
    this->flashLights() ;
  }
}

void TrafficLight::turnLightRedInitial() {
  digitalWrite(green,LOW) ;
  digitalWrite(yellow,LOW) ;
  digitalWrite(red,HIGH) ;
}

void TrafficLight::turnLightRed() {//this should probably be a private method
    digitalWrite(green,LOW) ;
    //if (!isRed()) {  //when recovering from malfunction, the light may already be red
      digitalWrite(yellow,HIGH) ;
      delay(5000) ;
      digitalWrite(yellow,LOW) ;
    //}
    digitalWrite(red,HIGH) ;
}

boolean TrafficLight::isGreen() {
  return digitalRead(green) == HIGH ;
}

boolean TrafficLight::isRedFunctioning() {
  pinMode(red,INPUT_PULLUP) ;
  boolean pullup_high ;
  pullup_high = digitalRead(red) ;//if input_pullup is high, this means the LED is off or missing
  pinMode(red,OUTPUT) ;
  return !pullup_high ;
}

boolean TrafficLight::isSwitchPressed() {
  //int switchState = 0 ;
  //switchState = digitalRead(switchPin) ;
  return digitalRead(switchPin) == HIGH ;
}

boolean TrafficLight::canSwitch() {
  return !this->switchAlreadyPressed() && this->isGreen() ;
}

boolean TrafficLight::switchAlreadyPressed() {
  return switchWasPressed ;
}

void TrafficLight::flashLights() {
  while (!interconnectedLight->isRedFunctioning()) {
    digitalWrite(green,HIGH) ;
    digitalWrite(yellow,HIGH) ;
    digitalWrite(red,HIGH) ;
    delay(500) ;
    digitalWrite(green,LOW) ;
    digitalWrite(yellow,LOW) ;
    digitalWrite(red,LOW) ;
    delay(500) ;
  }
  this->turnLightGreen() ;
}

void TrafficLight::greenOn() {
  digitalWrite(green,HIGH) ;
  digitalWrite(yellow,LOW) ;
  digitalWrite(red,LOW) ;
}

The microcontroller setup and main loop:

The setup() is straightforward: define light1 and light2 as TrafficLights, then “attach” them to their appropriate pins. interconnect light1 to light2 and, vice versa. Then turn on one of the lights. Calling turnLightGreenInitial() will automatically turn light2 to red.

TrafficLight light1 ;
TrafficLight light2 ;
const int piezoPin = 7 ;
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(LED_BUILTIN, LOW) ;
  light1.attach(2,3,4,5) ;    //switch, red, yellow, & green pins
  light2.attach(9,10,11,12) ;
  light1.interconnect(light2) ;
  light2.interconnect(light1)  ;
  light1.turnLightGreenInitial() ;
}

The microcontroller loop() itself if deceptively simple: it’s just checking whether any of the switches are pressed, and if the the light can be switched (i.e., isn’t already green or in the middle of being switched), then go ahead and start the countdown.

void loop() {
      if (light1.isSwitchPressed() && light1.canSwitch()) {
        light2.countdownToGreen() ;
      }
      if (light2.isSwitchPressed() && light2.canSwitch()) {
        light1.countdownToGreen() ;
      }  
}

Here’s an additional few functions, to control the piezo sound. I could have made a Piezo object as well, but there’s not much gain to such for this simple example.

void countdown() {
  for (int i = 0 ; i < 10; i++) {
      tone(piezoPin,1000,50) ;
  delay(1000) ;
  }
}

void crosswalkSounding() {
  for (int i = 0 ; i < 50; i++) {
    tone(piezoPin,250,10) ;
    delay(100) ;
  }
}

Carless In Houston

“What, you don’t have a car?!”  I’m in Houston, Houston’s a car town, everyone in Houston has a car, right?  Well, not everyone.  I had been using public transit for many years, so was already used to it, but it really became pressing 3 years ago when my son moved off to college. Do I buy him a car?  Or wait, why not give him my car, do I really need it?!  I examined my own transportation habits, and realized I could easily do without a car, and in fact even enjoyed being without a car.  Technology and service improvements have made it much easier these days, so give him the car I did, and couldn’t justify the expense of buying another one.

So, these days, I get around in Houston without a car.  Well, almost – my wife still has a car.  It’s a cherished classic car, though, a 1985 Mercedes, we give it a limited range, used mostly on weekends when we venture outside the loop to Chinatown.  (strike that – since September 2017, we have no car). Beyond that, we use alternate transportation.

I am not exclusively a public transit user.  These days, my modes of transportation are:

Each have their utility for different transportation needs. Continue reading Carless In Houston

Jakarta Contrasts

(see  also Indonesia and a “million dollars of problems”)

In 1997, Jakarta was in the throes of economic expansion. Our view from our apartment on the 16th floor of the Ascott presented a remarkable array of skyscrapers and shopping malls. The Japanese-funded malls were spectacular multi-level affairs, each of them rivaling Houston’s Galleria.  The skyscrapers were modern and sleek.  But, my young kids were fascinated by a contrasting view, of the open field directly below – a family living in a tin-roof shack right next to a fetid green canal.  Living without electricity and water, our kids would watch them in the morning, as someone would walk out to an empty spot in the field with bucket in hand to take a sponge bath or relieve themselves.  These folks, though, were at least surrounded by a lot of open air – just another block away was a squatter kampung, a crowded, tangled arrangement of shacks, handmade concrete-brick buildings, and dark alleyways.

Walking down Jalan Thamrin or visiting Blok M, local Indonesians hardly paid us any attention -they were middle-class Indonesians, office and service workers just like any other city.  But, a mile off the beaten path, a visit to an open market or the nearby Textile Museum, suddenly were were noticed by everyone. Hellos (“halo” or “selamat”) and smiles greeted us – the more daring would want to touch our pale skin or take photos with our children.  We often went out with our neighbor Alaude, a young red-hair Dutch woman, and she was even more exotic to the locals.  Much to Connie’s chagrin, they assumed Alaude was my wife and Connie the nanny; they would stop us to get a picture together, or surreptitiously line up a photo of themselves with us in the background.

Continue reading Jakarta Contrasts

Happy Birthday, Walter Grinder!

I didn’t realize that Walter Grinder and I almost share a birthday! Today is his 75th birthday, and numerous students and professors are writing tributes to Walter, so here’s mine.

Walter Grinder’s history is intertwined with history of the Institute for Humane Studies.  Coincidently, IHS was also born in the same year as myself. IHS was instrumental to my college education. Though I was a computer science major in college, I also minored in economics, and it was an econ professor who first recommended me to an IHS summer seminar. So, in 1981 I fly up to Valley Forge for a week-long seminar (all-expenses paid, at that!), where I first met Walter Grinder. He good-naturedly teased me for being the rare student from the south (most IHS students then seemed to come from the West or East coast), and was even more surprised to find I was a Cajun.

Well, this first encounter with IHS led to many – a week-end seminar in the fall, (can’t remember where), and the following spring a week-long seminar in Chicago, where I met the esteemed Voluntaryist George H. Smith, as well as the legal theorist Randy Barnett, among others.  Then, in the summer of 1983, I head to another IHS economics seminar at New York University, along with my friend Gerard Mildner. While there, we were offered a summer-long research fellowship at IHS. It was quite a special honor, as only 8 to 10 students were selected that summer. So, very excitedly, we make our way back to Houston, Gerard and I pack up our belongings in his car, I strapped my bike to the back bumper, and we make for a 2-week long road trip to Stanford University.

Walter Grinder was the anchor of IHS then, steered our young interests in productive ways, and was an ever-present figure in the Menlo Park office. He still good-naturedly teased me for being a Cajun, living on the bayou or such, but one evening, after reading some essay I wrote, he exclaimed, “Kevin, you are like a diamond in the rough”. As a mentor, I was assigned the esteemed, and very friendly, professor Shudha Shenoy. I was recall that Larry White was there that summer as well – not as an undergraduate research fellow, I think, but in some other capacity.

I biked all around Menlo Park and Palo Alto, and my best days were spent in the Stanford University library, 8 million books strong, as well as the Hoover Institution Library. My only regret was the research paper I finally wrote for that summer – looking back at it, I think it was rather uninspiring and mundane.

Wind forward a few years later, after marriage, the birth of our first daughter, and then her passing away, I felt a little lost, and decided to further pursue my 2nd greatest interest (beyond computer science), and enrolled in the PhD economics program at George Mason University. And, lo and behold, IHS had moved there, as well as Walter Grinder. Of course he still remembered me well, and was a key recommendation for me to get a full-scholarship to school.

Walter has made it his lifelong career in investing in and developing human capital, the creative mind. Happy Birthday, Walter!

America’s Foreign Policy Calculus

The United Nations is far from perfect, that I agree. But, it is our channel for international peace and diplomacy, and I am dismayed to see a U.S. President yet again bypass, ignore, and generally disregard this institution. Yes, I’m an idealist – I sincerely believe that War does not have to remain a permanent condition of mankind, that we can eradicate it, and ultimately replace it and all its surrounding institutions with processes of justice, diplomacy, and liberalism. There are steps we can make in this direction, but unfortunately, America’s foreign policy is far from traveling down this path.

Here’s some sweeping assertions about our current situation:

  • There is an America foreign policy regime
  • It is, if you will, a “spontaneous order”, a long-operating result of varied interests and processes.  Eisenhower named it “the military-industrial complex” – “complex” is a good word here; it is not simply a cabal, a small, smoke-filled room of profiteers, king-makers, world conquerors, whatever. It’s not a sinister plot, or conspiracy, but the systemic outcome of lots of players.
  • These players include the military itself, military contractors, intelligence communities, foreign policy think tanks, etc.
  • These players do not all have the same interests, but their interaction still produces a consistent outcome.
  • This complex has had a continuity, and consistency, that outlasts Presidencies.
  • This continuity stretches back to at least the early 1960s, but probably has its roots in WW2, with the permanent establishment of a Department of Defense (previously called Department of War), the CIA, and a few other key institutions.
  • This continuity is fed by an increasing percentage of taxpayer money that is directed its way.
  • An old Constitutional restriction – no appropriation of funds longer than 2 years for the raising of Armies – the that would have perhaps provided some brakes to this self-perpetuation, is largely ignored these days.
  • The general outcome of this regime is to #1, perpetuate itself (a lesson from Public Choice ECON 101, of course).
  • The regime is driven by “realpolitik”, not idealism.  Liberty, democracy, the human condition, are all secondary issues to its preservation of itself and “American Interests”.
  • The regime has a focus, and thus produces analysis and attention to, areas where its interests can be preserved or enhanced, and ignores other areas, no matter how stridently offensive to liberty, democracy, or humanity.  For example, the long-running Congo war has been completely ignored in the U.S. for decades.
  • A secondary factor in this focus is gamesmanship against other world powers that may threaten its dominant position in the world today.  Namely, Russia and China, though to a lesser extent, even Britain and France.
  • Its foreign policy “calculus” first analyzes this question: “if we take an action in this direction, will it enhance our interests?”.  This calculus extends even to regime change – either directly pondering assassination of foreign leaders, or supporting rebel causes that may lead to the toppling of a foreign leader.
  • Being realpolitik, this calculus will of course seek to preserve foreign leaders, no matter how undemocratic or brutal they are, if that means its interests are preserved or enhanced.
  • World events are still unpredictable, so the regime must react to events it doesn’t always control, and refactor its calculus
  • Thus, we’ll see the U.S. supporting certain players, such as Osama bin Ladin, Qaddafi, or Saddam, during certain periods, only to withdraw support later.
  • The regime doesn’t always win.

Robert’s Rules of Order, Diagrammed

In the distant past, I was a certified parliamentarian. On occasion, I still do chair meetings, or all called upon to provide some training on parliamentary procedure. Most recently, last weekend I was asked to prepare some training notes for a group of folks, so I started refreshing myself on Robert’s Rules of Order. That led me to thinking, “how can I visualize all these rules, in a simple flow?” The result is this diagram, below the fold.
Continue reading Robert’s Rules of Order, Diagrammed

Notes on Parking Ordinance Changes in Houston

The City of Houston Planning Committee is considering changes to our parking ordinances. Some notable changes include increasing the parking ratio for restaurants (from 8 to 10 spaces per 1000 square feet) and bars (from 10 to 14 spaces per 1000). These rules come on top of an already increasingly “suburbanized” parking and building rules. In general, not good. I’ll try to make it to the hearings on these changes, and below are some of my talking notes

I speak for myself, but some credentials:
– Inside-the-Loop resident for many years
– office in Rice Village
– board of directors of a non-profit shop in Rice Village
– married to a Montrose-area cafe owner

In summary, what I want to present here is “one size does not fit all”. Houston is a very diverse city, don’t define a cookie-cutter ordinance to meet a very varied problem – instead, more local dialogue and collaboration required.
Continue reading Notes on Parking Ordinance Changes in Houston

Cross-Platform CSS for Translucent DIVs

Had a need recently (in 2011!) to make some translucent (semi-opaque) elements on a Web page. CSS3 supports an “alpha” channel, the “a” in rgba, to provide color opaqueness, but IE 7 and 8 do not support this attribute.  So, most web developers resort to using a translucent background-image.  However, there is a pure CSS way that is compatible with all modern browsers today (IE6 ignored, of course).  This takes advantage, though, of some CSS parsing bugs, so may not satisfy the CSS purists out there, but it works for me 🙂

Demo: solid background inner-box surrounded by a translucent box, overlaying a background-image.

Continue reading Cross-Platform CSS for Translucent DIVs

Texas Employment Statistics

As Rick Perry has joined the Republican Party presidential fray, there will be questions about his prowess at bringing jobs to Texas.  Of course, a governor can only directly “create” jobs by increasing payroll of government employment, but he does have a limited role in creating a more or less positive environment for businesses in the state, an that may have an impact on private employment as well.

The 2008-2011 recession has hit private employment in Texas just has it has in ogther ; however, it is worth noting that federal, state, and local employment figures have continued to rise through this same period.  Rise in state employment figures roughly matches the growth in the state government budget, and of course, the state budget deficit.  Some of these deficits have masked by federal ARRA “stimulus” funds, but that will be the subject of another post.

These stats drawn from the Texas Workforce Commission:

May 2008 – 8,857,500
May 2011 – 8,704,800

2011, though, has seen some job growth – not to pre-recession figures, but growing nonetheless.  These stats may change, though, as often past month figures are re-adjusted:

Jan 2011 – 8,483,200
Feb           – 8,514,400
Mar          – 8,612,000
Apr           – 8,674,200

State Government employment has gone up through the recession, which matches (approximately) the growth in our state budget through this same period:

May 2008 – 364,200
May 2011 – 378,700

May 2011 reflects an interesting decrease, perhaps due to the current budget battles at the state level.  We’ll see if that drop remains:

Jan           – 374,500
Feb           – 385,000
Mar          – 385,300
Apr          – 385,300

Local government employment has also been growing through this period – this is partially state budget-driven, so is worth reflecting:

May 2008 – 1,244,600
May 2011 – 1,303,000