2009-06-24

A GPS logger with speedometer

To be able to contribute to the visionary OpenStreetMap project, I built myself a simple GPS logger. I added a speedometer as well, because I like to keep track of my speed when running or biking.



I had a Globalsat EM-411 GPS module already, a leftover from one of my numerous unfinished projects. The EM-411 only does one thing, and that is to output NMEA0183 encoded messages using 4800bps RS-232 with TTL levels. No initialization or control messages necessary.

I used a 5V Arduino Pro Mini as microcontroller, because it is very easy to program with the simple IDE and Java-like language.

A 512Kbit EEPROM with I2C interface is used to store the GPS data. I could not get hold of a PDIP8 version, but I managed to solder a SO8 directly to a DIL socket for easier prototyping. There are a couple of useful references on how to control a I2C EEPROM from the Arduino. Make sure you connect it to ANALOG pins 4 & 5, which I did not do until after many hours of reading and debugging.

The speed is displayed using two seven segment displays. The decimal dots are used to show memory usage. Due to a minor thinking error, I used one with common anode and one with common kathode, but if you decide to use identical displays, this can easily be compensated for in the display() routine.

A push button trigger a memory dump to the serial port on the Arduino, which I connect to a PC using a TTL-232R cable from FTDI. The button can also be used to clear the memory, if pressed during power on.

With a three second log interval, the device can log for about an hour before the memory is full, and that is also the amount of time a 9V, 200mAh rechargeable battery will power it before going empty.

When a $GPGGA message is received from the EM-411, it is stored in the EEPROM unaltered. The memory dump to PC is therefore just a plain playback of NMEA0183 messages. Using this approach, any NMEA0183 compatible software on the PC can read the logs without any conversions. I use GPSBabel to convert between NMEA0183 and GPX, the format required by OpenStreetMap.

When a $GPRMC message is received from the EM-411, the speed in knots is extracted and converted to km/h before being displayed.




#include <Wire.h>
#include <EEPROM.h>

#define LOGDELAY 3000
#define BUFLEN 100
#define PHASEDELAY 10


byte buttonPin = 4;
byte commonPin[2] = {3, 2};
byte segmentPin[8] = {9, 8, 7, 6, 13, 12, 11, 10};

byte matrix[70] = {1, 1, 1, 0, 1, 1, 1,
1, 0, 0, 0, 0, 0, 1,
1, 1, 0, 1, 1, 1, 0,
1, 1, 0, 1, 0, 1, 1,
1, 0, 1, 1, 0, 0, 1,
0, 1, 1, 1, 0, 1, 1,
0, 1, 1, 1, 1, 1, 1,
1, 1, 0, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 0, 1, 1};

int deviceaddress = 0x50;

byte GGA[6] = {'$', 'G', 'P', 'G', 'G', 'A'};
byte RMC[6] = {'$', 'G', 'P', 'R', 'M', 'C'};

byte phase = 0;
long nextphase = 0;
int data = 0;
int state = 0;

unsigned int abase = 0;
unsigned int logend = 0;

byte packet[BUFLEN];
byte length = 0;
byte cache[BUFLEN];
byte cachelength = 0;
byte cachepos = 0;

long time = 0;
long nextlog = 0;

void setup()
{
Serial.begin(4800);
Wire.begin();

pinMode(commonPin[0], OUTPUT);
pinMode(commonPin[1], OUTPUT);
for (byte i = 0; i < 8; i++)
{
pinMode(segmentPin[i], OUTPUT);
}

pinMode(buttonPin, INPUT);
digitalWrite(buttonPin, HIGH); // Pull up

// Read memory pointers
abase = EEPROM.read(0);
abase <<= 8;
abase += EEPROM.read(1);
if (abase < 2 || abase > 510)
{
abase = 2;
EEPROM.write(0, abase >> 8);
EEPROM.write(1, abase & 0xFF);
}
logend = EEPROM.read(abase);
logend <<= 8;
logend += EEPROM.read(abase+1);

// Clear log if button pressed
if (digitalRead(buttonPin) == 0)
{
abase++;
if (abase > 510)
{
abase = 2;
}
EEPROM.write(0, abase >> 8);
EEPROM.write(1, abase & 0xFF);
logend = 0;
EEPROM.write(abase, logend >> 8);
EEPROM.write(abase+1, logend & 0xFF);

while (digitalRead(buttonPin) == 0);
}
}

void loop()
{
time = millis();

// Display driver
if (time > nextphase) {
display();
nextphase = time + PHASEDELAY;
}

// Dump log to serial port
if (digitalRead(buttonPin) == 0)
{
unsigned int address;
for (address = 0; address < logend; address++)
{
Serial.print(i2c_eeprom_read_byte(deviceaddress, address), BYTE);
}
if (digitalRead(buttonPin) == 0)
{
for (; address < 65535; address++)
{
Serial.print(i2c_eeprom_read_byte(deviceaddress, address), BYTE);
}
while (digitalRead(buttonPin) == 0);
}
}

// Serial receive
if (Serial.available() > 0)
{
int serialByte = Serial.read();
packet[length++] = serialByte;
if (serialByte == 10 || length >= BUFLEN)
{
parsePacket();
length = 0;
}
}

// EEPROM write
if (cachepos > 0)
{
i2c_eeprom_write_byte(deviceaddress, logend+cachepos, cache[cachepos]);
cachepos++;

if (cachepos == cachelength)
{
logend += cachelength;
EEPROM.write(abase, logend >> 8);
EEPROM.write(abase+1, logend & 0xFF);
cachepos = 0;
cachelength = 0;
}
}
}

void parsePacket()
{
if (isGGA() && time > nextlog && cachepos == 0 && length > 50)
{
nextlog = time + LOGDELAY;

if (logend > 65535-length)
{
state = 3;
return;
}
else if (logend > 32768)
{
state = 2;
}
else
{
state = 1;
}

byte pos;
for (pos = 0; pos < length; pos++)
{
cache[pos] = packet[pos];
}
cachelength = length;
i2c_eeprom_write_byte(deviceaddress, logend+cachepos, cache[cachepos]);
cachepos++;
}
else if (isRMC())
{
byte pos = find(0, ',', 7);
float speed = parseFloat(pos);
data = speed * 1.852 + 0.5;
}
}

int parseInt(byte pos)
{
int result = 0;
while (packet[pos] >= '0' && packet[pos] <= '9')
{
result = result*10 + packet[pos] - '0';
pos++;
}
return result;
}

float parseFloat(byte pos)
{
float result = parseInt(pos);
pos = find(pos, '.', 1);
float decimals = parseInt(pos);
byte end = find(pos, ',', 1);
pos++;
while (pos < end)
{
decimals /= 10;
pos++;
}
return result + decimals;
}

byte find(byte pos, char sign, byte ncomma)
{
while (ncomma > 0)
{
if (packet[pos] == sign)
{
ncomma--;
}
pos++;
}
return pos;
}

boolean isGGA()
{
for (byte i = 0; i < 6; i++)
{
if (GGA[i] != packet[i])
{
return false;
}
}
return true;
}

boolean isRMC()
{
for (byte i = 0; i < 6; i++)
{
if (RMC[i] != packet[i])
{
return false;
}
}
return true;
}

void display()
{
byte digit = 0;

digitalWrite(commonPin[0], 0);
digitalWrite(commonPin[1], 1);

if (phase == 0)
{
if (state & 0x02)
{
digitalWrite(segmentPin[7], 1);
}
else
{
digitalWrite(segmentPin[7], 0);
}

digit = (data % 100) / 10;
}
else
{
if (state & 0x01)
{
digitalWrite(segmentPin[7], 0);
}
else
{
digitalWrite(segmentPin[7], 1);
}

digit = data % 10;
}
for (byte i = 0; i < 7; i++)
{
digitalWrite(segmentPin[i], (phase ^ matrix[digit * 7 + i]) & 1);
}

if (phase == 0)
{
digitalWrite(commonPin[1], 0);
phase = 1;
}
else
{
digitalWrite(commonPin[0], 1);
phase = 0;
}
}

void i2c_eeprom_write_byte( int deviceaddress, unsigned int eeaddress, byte data ) {
Wire.beginTransmission(deviceaddress);
Wire.send((int)(eeaddress >> 8)); // MSB
Wire.send((int)(eeaddress & 0xFF)); // LSB
Wire.send((int)data);
Wire.endTransmission();
delay(10);
}

// WARNING: address is a page address, 6-bit end will wrap around
// also, data can be maximum of about 30 bytes, because the Wire library has a buffer of 32 bytes
void i2c_eeprom_write_page( int deviceaddress, unsigned int eeaddresspage, byte* data, byte length ) {
Wire.beginTransmission(deviceaddress);
Wire.send((int)(eeaddresspage >> 8)); // MSB
Wire.send((int)(eeaddresspage & 0xFF)); // LSB
byte c;
for ( c = 0; c < length; c++)
Wire.send(data[c]);
Wire.endTransmission();
delay(10);
}

byte i2c_eeprom_read_byte( int deviceaddress, unsigned int eeaddress ) {
byte rdata = 0x0F;
Wire.beginTransmission(deviceaddress);
Wire.send((int)(eeaddress >> 8)); // MSB
Wire.send((int)(eeaddress & 0xFF)); // LSB
Wire.endTransmission();
Wire.requestFrom(deviceaddress,1);
if (Wire.available()) rdata = Wire.receive();
return rdata;
}

// maybe let's not read more than 30 or 32 bytes at a time!
void i2c_eeprom_read_buffer( int deviceaddress, unsigned int eeaddress, byte *buffer, int length ) {
Wire.beginTransmission(deviceaddress);
Wire.send((int)(eeaddress >> 8)); // MSB
Wire.send((int)(eeaddress & 0xFF)); // LSB
Wire.endTransmission();
Wire.requestFrom(deviceaddress,length);
int c = 0;
for ( c = 0; c < length; c++ )
if (Wire.available()) buffer[c] = Wire.receive();
}


From the code we can deduce that the two displays should be connected in parallel to digital I/O 6, 7, 8, 9, 10, 11, 12 and 13. Digital 2 and 3 are display select signals, connected to the anode and kathode on the displays. The push button is connected to digital 4, with the internal pull up resistor enabled. EM-411 TX (pin 3) is connected to Arduino RxD.

2008-12-27

Lockhart's Lament

Lockhart seems to agree with Dijkstra, that problem solving can be taught. But my mind fixed on something else in the paper. The much criticised geometry proofs mentioned on page 21 looks very much like programming. Why not use Haskell notation? Or even better, Coq? The proofs could be type checked and evaluated automatically. The students would learn to program at the same time they were learning geometry. They are learning to program now as well, they just don't know it, and would probably have difficulties to apply their newly gained knowledge in programming, due to the special notation used.

The programming approach would also allow the students to create theorems of their own to be used in future proofs, building a library of geometry as they go.

Even though I agree with Lockhart that problem solving should be emphasized instead of mechanical application of rules, by not using a formal system, he relies too much on human intuition in the proofs created. The informal proof on page 21-22 is elegant, but relies on the intuitive understanding of rotation and that rectangles have diagonals of equal length alternatively that rectangles have corners with right angles (both can not be the definition of a rectangle).

2008-12-15

Connect to Internet with a Bluetooth 3G Phone

There are many tutorials available that describe how to connect to Internet using a 3G phone with bluetooth, but none of them worked for me. I had to use a combination of several sources. This is what worked.

I want to connect to Internet with my Asus Eee PC 901 using my SonyEricsson W880i. The operator I use is Tele2 in Sweden. I have installed Ubuntu Eee on the netbook.

First I used Blueman to configure the bluetooth connection using this tutorial. This should result in a /etc/bluetooth/rfcomm.conf looking something like this:

rfcomm0 {
bind yes;
device AA:BB:CC:DD:EE:FF;
channel 2;
comment "W880i";
}

The device is the mac address of your phone and the channel is the same as your phone's Dial-up Networking channel. You can find out your channel using Properties in Blueman. The Serial Port channel also worked for me.

Then I wrote the following in /etc/wvdial.conf, found in this tutorial.

[Dialer defaults]
Modem = /dev/rfcomm0

[Dialer tele2]
Modem = /dev/rfcomm0
Baud = 115200
Init2 = AT+CGDCONT=1,"IP","internet.tele2.se"
Phone = *99#
Username = *
Password = *
New PPPD = yes
Auto DNS = 1

I start the network with the following command.

wvdial tele2

2008-11-06

Language and Abstraction

'Hell, one of the lessons of Structure and Interpretation of Computer Programs is that a "language" is a natural way of abstraction...', says ivdkleyn on Reddit. I agree and make an even stronger statement. Language is the only way of abstraction.

2008-10-27

Reading Fielding - Software Architecture

In the first chapter of his dissertation Architectural Styles and
the Design of Network-based Software Architectures
, Roy T. Fielding defines software architecture.

A software architecture is an abstraction of the run-time elements of a software system during some phase of its operation.
A software architecture is defined by a configuration of architectural elements...

From this I draw the conclusion that a software architecture is a configuration of abstract run-time elements. Abstraction is the process of removing irrelevant details. A software system can be abstracted in many ways, depending on what you want to show. This means that a software system has many architectures. I must object to this definition. To say that a building has many architectures just sounds strange. Perhaps what is meant is that the design of a building is influenced by many architectural concepts. Despite this, the building only has one architecture, its own.

My definition of software architecture adheres more to the traditional meaning of architecture as the documentation for a specific software system as a whole. Fielding makes software architecture synonymous with configuration, which is just one of many abstractions of the whole system. This also have consequences for his understanding of the term architectural view. In Fielding's definition, it is the configuration that can be viewed from different angles, when it should have been the architecture as a whole, with the configuration as one view.

More interesting is Fielding's definition of architectural style.

An architectural style is a coordinated set of architectural constraints that restricts the roles/features of architectural elements and the allowed relationships among those elements within any architecture that conforms to that style.

Styles exist to make it easier "to directly compare architectures for different types of systems". This is a good definition that I can agree with, except that I would have written "to directly compare architectures for different systems", to be more true to my definition of software architecture. But this is a minor complaint. It is worth noting that Fielding does not use the term pattern due to its altered meaning within OOP as compared to Alexander's original definition.

When I look at the definitions as a whole, I get the feeling that Fielding, in his desire to define architectural style, has pulled the definitions of software architecture, configuration and style together, almost making them the same. It would have been better to differentiate them more, making each of them clearer as a consequence.

Lets proceed with connectors.

A connector is an abstract mechanism that mediates communication, coordination, or cooperation among components.
Internally, a connector may consist of a subsystem of components that transform the data for transfer, perform the transfer, and then reverse the transformation for delivery.

I don't use connectors when I describe my own architectures. I think it is better to connect components directly with a use relation. If transformations are necessary, they are better handled by an additional component, implementing languages for the communicating components to use.

Finally I want to say something about data. Lets see how Fielding defines them.

A datum is an element of information that is transferred from a component, or received by a component, via a connector.

I agree with Fielding that data is important. But I choose to include them in the definition and design of languages, subsequently used and implemented by components. I get a feeling that he likes the notion of data being transmitted over connectors because this closely mimics his own main interest, the design of network-based software architectures.

P.S.
Yes, behind every component and connector there can be a large architecture that has been abstracted away. In this sense Fielding is correct when he talks about "the many architectures within a system". But this definition is not useful when analyzing the architecture of a system, precisely because all the uninteresting architectures have been abstracted away.
D.S.

P.P.S.
In one of his blog posts, Fielding says "Compare that to the Atom architecture within my blog, which consists of just the externally observable behavioral abstraction." In my view, externally observable behavior is a language or interface, not an architecture. Perhaps this is not what he meant, but it is easy to draw that conclusion.
D.S.

2008-10-04

Robotics - Motor Driver

As a hobby project, I build an autonomous LEGO robot controlled by an Arduino Nano with assorted sensors and actuators.

I use two electrical motors powered by a 7,2V racing accumulator pack. To control the direction of and power to the motors, I use two Allegro UND2916B motor drivers in parallel, one soldered on top of the other. See the image below for the complete circuit layout.


Unfortunately, there is an error in the schema. To correct it, the Arduino Nano connections should be shifted one step down, so D8 connects to D7 instead, D7 to D6, and so on.

I do not use the PWM capabilities in the 2916. Instead I use the PWM outputs on the Arduino.

In the Arduino Development Environment, I define the meaning of the different signals.
byte leftDirectionPin = 7;
byte leftSpeedPin = 6;
byte rightSpeedPin = 5;
byte rightDirectionPin = 4;

2008-09-28

Robotics - Telemetry

As a hobby project, I build an autonomous LEGO robot controlled by an Arduino Nano with assorted sensors and actuators.

Using a simple radio link between the robot and a PC, I can monitor the current state of the software running on the Arduino.

The radio link is based on the circuits TX433 and RX433 from Velleman. The receiver is connected to the PC with a TTL-232R cable from FTDI. See the image below for the complete circuit layout.



To transmit data from the Arduino, I open the serial link and write tagged data to it.
Serial.begin(4800);

Serial.print("acc:");
Serial.println((long)fwdAcc);
Serial.print("speed:");
Serial.println((long)fwdSpeed);

The various tags and values are collected and displayed by a Processing application on the PC.
import processing.serial.*;

String tty = "/dev/ttyUSB0";
Hashtable data;
Serial port;
PFont font;

void setup() {
size(300, 600);

data = new Hashtable();
port = new Serial(this, tty, 4800);
font = loadFont("Dialog.plain-14.vlw");
textFont(font);
fill(0, 0, 0);
}

void draw() {
background(255);

while (port.available() > 0) {
String line = port.readStringUntil(10);
int pos = 0;
if (line != null &&
(pos = line.indexOf(":")) > 0 &&
pos < 30) {
data.put(line.substring(0, pos+1), line.substring(pos+1));
data.put("time:", "" + hour() + "." + minute() + "." + second());
}
}

int y = 20;
for (Enumeration e = data.keys() ; e.hasMoreElements() ;) {
String key = e.nextElement().toString();
String value = data.get(key).toString();
text(key, 4, y);
text(value, 104, y);
y += 20;
}
}

You need to create the font Dialog.plain-14 in Processing GUI for the program to work. The end result looks something like this.



The time parameter is there to show when the last message was received.

Debugging with Popper