Arduino Megasquirt Library

This driver provides access to the MegaSquirt ECU with a level of abstraction above the MegaSquirt serial interface, enabling users with no knowledge of the MegaSquirt commands to access the register data easily without caring about the underlying communication required.

The MegaSquirt is a low cost engine control unit with support for fueling, ignition and idle control.

Wiring

The MegaSquirt is connected to the Arduino using the RS232 output on the MegaSquirt, a MAX232 chip, and the Serial interface on the arduino board.

Synopsis

 
#include >MegaSquirt.h<
void setup(){
 MegaSquirt::begin();
 
 byte status;
 String signature;
 status=MegaSquirt::signature(&signature);
 switch (status){
  case MS_COMM_SUCCESS:
   Serial.print("MegaSquirt Signature: ");
   Serial.println(signature);
   break;
  case MS_ERR_COMM_TIMEOUT:
   Serial.println(" FAILURE: Communication Timeout");
   break;
  case MS_ERR_COMM_OVERFLOW:
   Serial.println(" FAILURE: Communication Overflow");
   break;
  default:
   Serial.println(" FAILURE: Unknown Error"); 
 }

String revision;
 status=MegaSquirt::revision(&revision);

 uint16_t uptime;
 status=MegaSquirt::seconds(&uptime);

 MegaSquirtData registers;
 byte regTable[MS_TABLE_LENGTH];
 status=MegaSquirt::getData(regTable);

 registers.loadDAta(regTable);

 Serial.println(registers.lambda1()/10,DEC )
}

Download

You can download the ZIP file to import into the IDE here, or you can fork your own.

Mesh refinement with SnappyHexMesh

Mesh refinement is probably one of the hardest components of OpenFOAM, for me this mainly revolves around snappyhexmesh and blockmesh, with one or more STL files exported from SolidWorks as the input.

The first thing to get right is the position in the the blockmesh, you can do this using a transform, or by changing the coordinates in the blockmeshdict.  Then check the refinement box is suitably sized, this one was too small so I made it larger using the refinementbox settings:

refinementBox
      {
          type searchableBox;
          min (-1.0 -1.4 0.0);
          max ( 8.0  1.4 2.5);
      }

Next up is to look at the basic refinement and improve that, currently, the basic mesh looks like this:

Using feature edge detection should align the cells better with the edges of the features.  First we run surfaceFeatureExtract on the STL file, then update snappyhexmesh to use edge detection.

   features
   (
       {
           file "seven.eMesh";
           level 10;
       }
   );

I also turn on feature snapping

nFeatureSnapIter 5;

This makes the edges much cleaner, but the mesh is still too course.

Adding more layers of refinement around the car should improve the mesh some more, to do this we use the addLayersControls settings below:

nSurfaceLayers 3;
expansionRatio 1.3;
finalLayerThickness 0.7;
minThickness 0.25;

Next I make the bounding box slightly finer using blockmesh

blocks
(
     hex (0 1 2 3 4 5 6 7) (80 32 32) simpleGrading (1 1 1)
);

At this point I also need to turn up the max cells a little, and add another refinement level

maxGlobalCells 12000000;
refinementSurfaces
{
     seven
     {
     // Surface-wise min and max refinement level
     level (5 6);
     }
}

 As you would expect, mesh size increases dramatically, as does the time to create the mesh.  The result is improved, however the quality of the mesh is still poor in places, this will need further effort.

OpenFOAM rotating boundary conditions using rotatingWallVelocity

So far my model has used only a single STL file with no patches, and did not take into account the rotation of the wheels and tyres.  I figured out the OpenFOAM part from this thread on CFD-Online, and used paraview and solidworks to modify the model.

I’m working with a large assembly, with each component as its own part which makes getting things in the right format fairly easy.  The first thing to do is save the whole assembly as individual STL files.

As this created a few hundred files, all with spaces in the name, I opened them in paraview and used the Append Geometry filter to create a single object for the front axle, rear axle, and everything else.  For each of the new geometries, i added an Extract Surface filter.

As I managed to get my solid model in a strange location in Cartesian space, I performed a translation to rotate and move them to the middle of the bounding box.  I could have also moved the bounding box in blockmeshdict.  I then saved the three surfaces as chassis.stl, faxle.stl, and raxle.stl. Use the ascii file format.

Paraview calls the solids ascii (I’m assuming binary if you use the binary file format) since these dictate the name of the patch that snappy will create, it makes sense to rename these based on their file names.  These then need to be concatenated into a single file.  I used some sed foo to do this.

This then gives me three patches, seven_chassis, seven_faxle and seven raxle.  These need to be defined in the initial condition for U.

Originally there was just a single definition:

"seven_*"
    {
         type            fixedValue;    
         value           uniform (0 0 0);
    }

However, we now need to define the three patches explicitly.  The first is easy, as its the everything else part.

"seven_chassis"
    {
         type            fixedValue;    
         value           uniform (0 0 0);
    }

However, for the rotating boundary, we need to know a few more things.  The first is the origin of the rotation, I created a point in the center of the axle and manually applied the appropriate transformation to get the center of rotation.  As I’m assuming that there is zero toe and zero camber, this is trivial.  In the future I may wish to improve on the model in which case I will have four patches, and I’ll add some sketches to the model to work out the correct axis.

The axis of rotation in my model is the y axis, which again is trivial in this case.

Lastly I needed to work out the speed the wheels are rotating at.  I am modelling the car at a speed 40ms−1, and Omega, the boundary condition is measured in rads/second.

First we calculate the distance travelled in one revolution of the wheel.  I have 13 rims with 205×60 profile tyres. This gives a circumference of 1.8146Meters giving 22.04 revolutions per second.  1 Revolution is 2pi radians, giving 138.5rads/sec.

"seven_faxle"
      {
          type            rotatingWallVelocity;
          origin          ( 0.839 0 0.2775 );
          axis            ( 0 1 0 );
          omega           138.5;
      }
      "seven_raxle"
      {
          type            rotatingWallVelocity;
          origin          ( 2.753 0 0.2775 );
          axis            ( 0 1 0 );
          omega           138.5;
      }

Loguino Data Aquisition for Arduino

I’ve been interested in capturing data from the seven since the moment I could drive it. I’ve looked at commercial data loggers, and there are plenty of good options, I use the ETB Digidash on the Fury, and it’s very competent, not least in the analysis software.

For the seven though, I didn’t feel there was a good fit for a number of reasons:

  • not many data logging tools support reading data from the megasquirt ECU, which is critical to get any information about the engine at runtime.
  • Many data loggers are geared towards providing an in car display system, but I already have a working dashboard that I like.
  • Usually they are limited to a number of channels, each channel having a predefined function or purpose.
So I decided one day to make my own, my first step was the bifferboard, this is a 486pc on a chip, it was easy to program since it runs linux, but it wasn’t the right tool for the job.  I’d hear lots of good things about Arduino, an embedded platform, and once I got my head around the API, it was clear this was the perfect solution, and shortly thereafter loguino was born.
Loguino itself is a generic logging platform, it functions a little bit like log4perl/java/etc in that you have a logging class that accepts log messages, and logger outputs that take those messages and do something meaningful with them.  Most of the time this is simply write the message to a disk, or output it over the serial line, but it could be used to control shift lights or any other task too.
Data is generated by pollers, pollers are polled periodically and generate messages which are picked up by the loggers.  The first task was to write one for the megasquirt, this allows me to pull engine data directly into the logging tool. The next step was gps speed and positioning, and then support for accelerometers and gyroscopes.
I chose a very simple logging format, rather than use columns, I decided to use key value pairs, this means the tool can be completely agnostic about formatting, time, and everything else.  My view is that once data is downloaded of the loguino, it will go into a database and be queried.  Having seen google chart, and flot, I decided there was no real need to use excel or write complex software, instead it should be a case of adding and removing series, and scaling them.  This spawned metriflot, a data visualization package, and was a great way for me to learn some Ajax and django.
Having tested loguino over the summer, I’ll be doing a permanent install over the winter with wheel speed sensors, brake temperature, pressure, and all sorts of other sensors, and generally tidying up the packaging.  Next year I’ll be able to concentrate on the analysis where I want to have more intelligent data trending, for example:
  • Is the engine temperature hot because of the outside temperature, speed, or a fault?
  • Is the oil pump failing or was i just not driving hard enough?
There is a lot of potential here, as well as a good chance for me to learn more about electronics and data analysis, and hopefully it will benefit others too.
Loguino was released under the GPL license, and is hosted on google code.

CFD for the Seven

I’ve long had an interest in CFD, and now that OpenFOAM is getting pretty mature, I decided to have a go at modeling the seven.  I drew the car using Solidworks, I focussed more on the shape of the car, rather than accuracy of the chassis etc and the result is a fairly simple parametric model.

Lotus seven replica modeled using open foam, visualized using paraview
SimpleFOAM was used to create the data, then ParaView to visualize the result.

As I only have a couple of macs at home, I used RDP to connect to an amazon EC2 instance to do the actual drawing.  This works surprisingly well, and has the added advantage of not having another windows system to deal with.

To perform the actual CFD, I use openFOAM running on my mac mini to do the preprocessing, then ship this off to a linux instance on ec2 to do the actual calculation.

Looking at this thread, it would appear that its worth spending some time tweaking the solver to converge sooner, since my main issue right now is the time for a run, and the memory requirement for meshing, it would make sense to optimize this, so i’ve written a workflow and some optimization logic.  The end result should be a model that can tune itself within certain parameters, not only for the solver, but also for the model itself, with Solidworks reading in parameters at run time and generating a new STL file for each combination.

Post finals, I’ll tidy it up and publish the optimizer.

Rear wheel bearings

I decided to replace the rear wheel bearings on the seven as they were making a bit of noise. To make life easier i knocked up a stand for the rear of the car which means I can stick it on the stand rather than using floor standing axle stands or a trolley jack to support the car. This proved very useful.

Made a small stand to support the car on the lift.

The theory is you remove the hub, and undo the bolts that hold the bearing in place, and use a slide hammer to yank out the half shaft. Not having a slide hammer compounded this, but the first one came out with a few stern blows with two hammers on a back to front hub (providing me with something substantial to hit.)

Removing the rear half shaft

The other took many hours of smacking with hammers, chisels, heat and general swearing before it gave up. I cut a groove into the bearing itself, and then used a cold chisel to break it off, this worked pretty well. The new bearings are now ready to fit, and will get pressed into place by my local garage.

And corroded on, so it was easiest to cut a groove and use a cold chisel

Seven Trip to spain

Not much driving weather this year, however I did manage to get a trip to spain with some friends, they were flying from all over the place, so I drove down through france on my own. The weather was forecast to be wet (Imagine my surprise) so I decided to take it easy over a few days as it can be pretty miserable driving when the water is coming in through the drain holes.

The rain held off long enough for a broodje kaas, and a well deserved pee.

The first day was mainly getting through the Netherlands and Belgium, which is miserable at best, but the rain was just damp rather than biblical, so quite good fun. Northern france got a bit wetter, but started to dry up by the time I got to Dijon. I had a bit of a moment when there was a horrible metalic noise, I thought at first the alternator had come off again, which was surprising as its threadlocked, and lockwired, but alas it was only the number plate which had come off at one side. I just undid it and threw it in the boot where it will stay for the time being.

I went through about half a litre of oil on the way to dijon, so apparently I still have a major oil leak out the sump. Grumble.

The next day was towards the Tarn, the morning was very wet, and very slow, but the roads were nice, and fairly quiet, in the afternoon it turned to random showers, and the scenery changed into some nice twisty mountain roads, i went over numerous cols, and found I far prefer the Yokohama A048 tyres over the Toyos, it just feels more planted.

The sun came out just in time for Mende, so I spent a few hours going up and down Cols and mountain roads, the car is really on form, traffic is minimal and i’m enjoying every second. I stop for some groceries, and go out for another our or so before stopping for the night in a camping.

The next day I followed to Tarn gorge, before heading up the side, and over the Millau bridge. At this point I noticed that the alternator output was lower than it should, and the ignition light was flickering. Having had an alternator fail a year ago I know all about the tell tales signs, but the ammeter was flickering all over the place. I also know that David ashurst has been plagued with ignition light flickering recently and that its caused by an electrical connection in the lucas plug. I pulled over and cleaned it up, and squashed the connector a little to provide a better connection, and the problem was solved.

Traffic was obnoxiously bad so I just followed the coast down to spain and then cutting off a pininsula and coming over an amazing bit of road into calonge.

38186_416027916490_602051490_5352970_7439480_n

The week was spent driving shorted distances over some great stretches of road in the costas, with a different passenger for every trip. The car was in great form for the most part, with a crack in one of the vaccum connectors forming and causing an air leak which was a bit of a pain for the rest of the day until I got back home and resolved it.

38342_416025036490_602051490_5352758_5182573_n

The way back I went pretty much dead straight home, doing around 130kph most of the way up the peage, everything was fine till belgium when I noticed a small water leak when refuelling, there was a pinhole in one of the hoses, so I just cut it off and shuffled it up a little which got me home. I also noticed the fuel consumption was up for the last tank, which turns out was a fuel leak in the tank (again) so I’ll add that to the list of jobs to do which is currently:

  • Adjust the position of the gear box so it doesn’t vibrate against the crossmember on hard left turns.
  • Fix the fuel leaks from the tank
  • Replace the rear wheel bearings which are getting a little noisy
  • Make the speedo work again.

Trip to Zeeland

It was sunny so I went for a drive in the seven with tuner studio running to see if I could improve things, I couldn’t but the drive was lovely.

SDC10193

Basically, there is not enough variation in MAP pressure, and the rate of change is very steep off idle with no change at higher rpm. This means that the VE table is pretty flat.

Subsequently, I changed over to TPS based fueling, the result is a much more responsive drive, throttle response is like lightning in comparison, and it feels and sounds like its set up properly. The AFR is much closer to the AFR target. I’ve only ran auto tune for about an hour or so on what was a relatively quiet drive, so the edges are not tuned yet, but for the most part its pretty close. Its certainly very drivable

Whilst I was trying to get Alpha-N working I hit a few idiosyncrasies in the tuning software. There are three fueling options for mega squirt: Speed Density; (MAP Based) Pure Alpha-N; (TPS Based) and Blended.

For now I’m using Pure Alpha-N, however when I set the fueling algorithm to Alpha-N in either tuner studio, or mega tune it was still using MAP for fueling. For whatever reason it was using the blended algorithm. This seems to be not a bug, but slightly misleading name, Pure Alpha-N is essentially blended, but starting with Alpha-N rather than MAP. Therefore I set the Threshold to 9k in the Alpha-N blending dialog.

In addition, I had ego correction active at idle, this results in an idle which falls and rises all the time, setting EGO correction to be active above 1200 worked a treat.

Seven engine rebuild (again)

Well after a disastrous start to the year, it was time for a new engine. The root cause of the failure was the lubrication system possibly caused by a blocked oil cooler.

I got a short block from Jem Engines, its a 711 crossflow bored out to 1700cc, with fully balanced internals. The engine is fitted with ARP con rod and fly wheel bolts. I reused the Kent 244 cam, and Burton stage 3 head.

The first thing to do before building anything was to thoroughly clean the head, as the bearing failure had likely resulted in a lot of crud going around the engine, I stripped it completely and used pipe cleaners to go through each oil passage, and cleaned it with gunk degreaser and compressed air.

Afterwards I painted it black (it was blue) to match the block. I used Hammerite and so far it seems to be doing the trick.

IMG_1406

Next was time to do the ARP bolts, Eric gave me some ARP Lube, so I torqued them up to 40 ft lbs.

SDC10137

I can build a cross flow in a couple of hours from memory alone now, I could even remember the number of degrees to set the cam to, although this didn’t stop me from making a hash of it the first time and having to re-time the engine after everything was built up.

SDC10141

I used a competition gasket set from Burton, Eric recons the best way to get a dry seal on the sump is to evo-stick the gasket to the block, then use a little blob of silicon around the rubber seals on the end, and tighten it up gently.

SDC10144

I tried this, the result was an enormous oil slick on the garage floor after the first drive so I’m back to experimenting with silicon… The engine was back in the car in less than 4 hours, ready to start, or so I thought.

SDC10145

It fired up first time, but made a noise that left me clutching my wallet.

It turned out that the oil pipe was ever so slightly grazing the con rod bolt, this thankfully was easily fixed with a gentle tap from the hammer and it finally ran smoothly. Getting the sump off in-car is a real pain, however if I loosen off the engine mounts and replace the gearbox->engine bolts with longer ones, I can use a crow bar to separate the engine from the box about an inch which is enough to get to the rearmost sump bolts.

Houston, we have a problem (Twice.)

Despite being thrashed incessantly for 4 weeks through morocco resulting in only self inflicted trauma, the seven has now left me stranded by the side of the road twice in 3 weeks. The first through a head-gasket problem, the second due to something big going bang.

The end result is that the block, crank, rods and head are back at Jem Engines, where they will be cleaned, bored/ground/skimmed and balanced, before being sent back for the final build. In preparation for the six hour at Mallory I thought I should try to put as many miles on it as possible, sadly following the two dry days in March, there hasn’t been much dry weather in Holland since which meant getting out in the car has been difficult at best and not possible the rest of the time.

The rocker cover was full of sludge.

The weather in Western Germany, and Luxembourg was due to be not-wet, so off I set, laptop running auto-tune in the passenger seat, following the Waal/Rhine over the border, then heading cross country towards Trier, the TomTom provides a lovely route, (Set max speed to 40kph) about 4 hours into the drive, somewhere near Aachen, I came into a small town and as I slowed down into traffic, and up to a red light, i noticed the engine was stumbling a little, queue comedy smoke screen as the revs fell to idle and i had to nurse it to keep it from cutting out.

The block got the same treatment

I could feel my hand rushing towards my wallet as I thought of all the possibilities, but when i realized it was just a head-gasket, my next thought was to get it to Holland so I could be recovered directly home. I was about 60km from the dutch border, so I hopped on the Autobahn direction Maastricht and hoped for the best, about 5km later the temperature shot up, so i pulled off, cooled down and poured in 3 liters of water, queue more comedy smoke at idle, but was fine for another 38km where i had to do the same again (Thankfully, i was feeling thirsty earlier.) I made it about 10km over the border before it was out of water again, and managed to pull into a service area to call the ANWB.

The end result looking quite shiny

I then spent 4 hours waiting on the ANWB, who got lost, then sent a guy that couldn’t tow it, who got his mate with a beaver tail that didn’t fit the car….. In the end it made it on a flat bed, after my ordeal by the side of the road, I was only just able to cope with 3 hours of dutch country music in the truck home.

I put on the manifolds whilst i waited on the bolts to stretch out

The gasket had failed, and was repaired the next day. The following week I was due to take it to the UK and park it up at Paul’s house in preparation for Mallory meaning i could fly in in Thursday night, get in the car Friday, and all would be fine. I set off, everything was going well, then on the M2 I noticed oil pressure was a little lower than normal, I assumed it was just the thinner oil I’d used post-head gasket, but pulled over to check there was still some in it, there was, so off I set again. I got to my favorite spot on the M25 when there was a funny noise, the engine changed pitch, and overheated whilst i did a 4 lane dash, at this point i noticed i barely had any oil pressure and had that sinking feeling.

I ditched the car, and spent a long time on the phone to the ANWB to try to get recovered, in the mean time i noticed that i was getting enormous blow back out the crank case breather, this was going to be expensive.

The car was then recovered and despite every mechanic trying to tell me it was the fuel pump, or a wiring fault, despite me explaining that this thing called an immobilizer was cutting the connection because they hadn’t wiggled the fob…. Its back in Holland now, there is a lot of metal floating in the sump, so it looks like a bearing had failed either as a result of low oil pressure, or possibly the root cause. I’ll continue stripping it down and hopefully figure it all out soon.