EnglishSvenska

Infrared experiments to control the television from a website

Where is the remote? Wouldn't it be good if you could switch channels on the television from a website. A wanted to see if it is possible. It didn't.. Note to self; buy more powerful IR transmitters.

HIL testing in Arduino

I am trying out Hardware-in-the loop simulation on a new Arduino project for a client. Test driven development is unfortunately not very big in the Arduino community (yet) so I decided to implement something by myself. The setup is simple:

  1. One Arduino is running the application software.
  2. Another Arduino connects to inputs and outputs on the first Arduino. This Arduino will include all the test code.

2015-05-14 16.08.09

A test case could for example be, when the user presses a button a LED should light up. The second Arduino will output a signal to the button input on the first Arduino, and then check if the LED pin output is high. Example code is shown below.

void loop() {
// Simulate that user presses button
digitalWrite(BUTTON_PIN, 1);
// check that the LED lights up
assert(LED_PIN, 1);
delay(500)
// check that some actuator starts running
assert(ACTUATOR_PIN, 1);
// Simulate that user releases button
digitalWrite(BUTTON_PIN, 0);
// Led and actuator should turn off
assert(LED_PIN, 1);
assert(ACTUATOR_PIN, 1);
// stop execution
while (1) {}
}
bool assert(uint8_t pin, bool expectedState) {
bool state = digitalRead(pin);
if (state != expectedState) {
Serial.print("## FAILURE: pin ");
Serial.print(pin);
Serial.print(" == ");
Serial.print(state);
Serial.print(" != ");
Serial.print(expectedState);
Serial.println();
return false;
}
else {
Serial.print("## OK: pin ");
Serial.print(pin);
Serial.print(" == ");
Serial.print(state);
Serial.println();
return true;
}
}

Why the hassle?

It might seem unnecessary, (and it is for simple problems), but it does increase code quality and decreases the risk of bugs being introduced when writing new features to the code.

Making it better

I would like to write my test code in Python on a laptop and control an Arduino (via Firmata for example). Then I would have proper tools for testing and generating test reports. For now the Arduino solution is sufficient though.

Tagged with:

Formula Student Baltic Open 2014

Sensommaren och hösten kunde ha blivit utan praktiskt ingenjörsjobb om det inte vore för att jag blev övertalad att bygga räserbil. Målet var Baltic Open i Estland och dit skulle vi ta CFS13 och CFS13e (alltså både den bensin- och eldrivna bilen).

Tagged with: ,

Självbalanserande ARM (uppdaterad och bättre)

Simplicity is the ultimate sophistication. I den förra versionen av den självbalanserande roboten använde jag totalt 3 mikroprocessorer men har nu designat och programmerat om den på en större ARM mikroprocessor. Med mer kräm i processorn ges en mängd fördelar:

  • Färre komponenter
  • Enklare kretsschema
  • Robust mekanisk design på grund av färre kablar
  • Ingen kommunikation mellan processorer är nödvändig vilket ger en mycket enklare kod
  • Ett litet RTOS sköter trådhanteringen (vilket inte gick på AVR)

Så bygger man en likadan (eller bättre)

Komponenter

Mekanisk design

Läs de äldsta inläggen på projektsidan för att se foton från hur man bygger ihop den. Det enda som behöver tillverkas är de tre plattorna för vilka det finns CAD och ritningar.

Kretsschema

Många har frågat om kretsschema så jag gjorde ett i Altium Designer.

Mjukvara

All kod ligger på Github.

Reglerteknik

Kort använder jag kaskadåterkopplade PID-regulatorer. Den yttre loopen reglerar hastigheten på roboten vilket mäts på tachometrar på motorerna. Den intre loopen reglerar robotens vinkel vilket mäts med en IMU. Den yttre loopen har långsam dynamik och den intre loopen är mycket snabbare. Rent teoretiskt ska det gå att göra en självbalanserande robot med endast den inre loopen men man får väldigt lätt ett beteende av att roboten långsamt rör sig framåt eller bakåt över golvet eftersom återkopplingen från hjulens hastighet saknas.

För att få ytterliggare bättre prestanda används gain scheduling på den inre loopen vilket innebär att regulatorparamterarna ändras beroende på robotens vinkel. En liten vinkel nära jämviksläget innebär konservativa regulatorparametrar där endast små justeringar görs för att hålla roboten stående. Är vinkeln stor är roboten nära att ramla och de aggressiva paramterinställningarna aktiveras med syfte att göra allt för att återfå stabilitet.

Information flow

Information flow

Cascade PID implementation theory

Cascade PID implementation theory

Ändra parametrar

Troligtvis kommer alla parametrar inte fungera utan att de justeras något. I koden finns en struct som kan sättas i setConfiguration(). Smartare är dock är att använda en seriell terminal för att ändra parametrar samtidigt som koden körs. På så sätt behöver man inte programmera om processorn varje gång man vill ändra en parameter. Öppna Serial Monitor i Arduino. Testa att skriva "print configuration" till Arduinon. Om allt fungerar som det ska kommer den svara med att skriva ut alla parametrar. Alla variabler i structen Configuration kan sättas från terminalen. Skriv bara "set" följt av variabelnamn och värde. Exempelvis "set speedPIDKp 1.5". För att aktivera debug skriver du "set debugLevel 2". Om du vill debugga IMU skriver du därefter "set angleRawDebug 1". För att stänga av en debug-variabel skiver du exempelvis "set angleRawDebug 0".

Att hitta rätt regulatorparametrar

Använd en realtidsplotter när du ställer in dina regulatorparametrar så går det enklare.

Tagged with: , , , ,

Ska jag ta med paraplyet?

Att bo i Göteborg innebär att man många morgnar ställer sig själv frågan "behövs ett paraply idag?". För att överlämna fler små beslut till datorer programmerade jag en mikroprocessor som svarar med att tända en lysdiod om paraply rekommenderas.

Spark Core as Umbrella reminder

Idéen är väldigt enkel. Mikroprocessorn läser väderprognosen från yr.no för de kommande 10 timmarna (vilket är ungefär den tiden jag väntas vara hemifrån). Om någon av dessa timmar innehåller regn (högre än några få mm) så tänder den lysdioden. Släckt lysdiod innebär givetvis inget regn.

Hur det fungerar

Hårdvara

  • Spark Core
  • Breadboard
  • Lysdiod
  • Resistor
  • Usb-kabel för strömförsörjning

Väderprognos med php och yr.no

Jag kör ett php-skript som hämtar kommande prognos från yr.no. Den är publicerad på http://sebastiannilsson.com/will-it-rain/ och är relativt enkel att använda.

  1. Leta reda på den stad som du vill ha prognos för och kopiera urlen. Exempelvis för Göteborg är den http://www.yr.no/sted/Sverige/V%C3%A4stra_G%C3%B6taland/G%C3%B6teborg/ eller för Kolbäck http://www.yr.no/sted/Sverige/V%C3%A4stmanland/Kolb%C3%A4ck/
  2. Gå till http://sebastiannilsson.com/will-it-rain/index.php?debug=1&threshold=0.2&yr_url=<URL HÄR>

Exempel: Prognosen för Göteborg med ett gränsvärde för regn vid 0.5 mm ser ut såhär:
http://sebastiannilsson.com/will-it-rain/index.php?debug=1&threshold=0.5&yr_url=http://www.yr.no/sted/Sverige/V%C3%A4stra_G%C3%B6taland/G%C3%B6teborg/

Kod för skriptet som visar hur man använder yr.no som ett väder-API.

Kod på mikroprocessorn

Spark Core är en mikroprocessor som ansluter till Wifi. Man laddar över kod till den över deras molntjänst.

  1. Skaffa en Spark Core eller liknande och koppla upp den mot wifi.
  2. Kopiera in min kod för Spark Core. Det enda som behövs ändras är variabeln för url.
  3. Ladda upp
Tagged with:

Realtime data plotter

Debugging sensors on a microprocessor can be a hassle and the most used approach is to output the sensor values to a serial monitor. Realtime plotting is a better and more visual way of doing the same thing.

RealtimePlotterProcessing

  • Real-time plotter of your data while it is still being processed by your application
  • Plots live data from serial port. Microprocessor choice does not matter as long as it can send serial data to your computer.
  • 6 channels of data (and this can be increased if necessary)
  • Live bar charts
  • Live line graphs
  • You just send the data you want to debug with a space as delimiter like this "value1 value2 value3 value4 value5 value6". Floats or integers does not matter.
  • Open source
  • Robust. It will not crash because of corrupt data stream or similar.
  • Multi platform Java. Tested on OSX and Windows 8 (and should work on Linux as well).

I created this software to debug an Arduino Due on my self-balancing robot. To tune the controls of the robot I needed fast feedback to know if I was making progress or not. The video below demonstrates typical use of the realtime plotter:

Download

Download
You can also follow the project at Github. If you make improvements to the source code, please share it by making a pull request at Github.

How to install and use

Since I have an Arduino I will use it as example but any micro processor can be used.

  1. Get ProcessingIDE to run the code. It is a neat and useful IDE for doing graphical stuff.
  2. Download controlP5 gui library and unzip it into your Processing libraries folder
  3. Connect the Arduino to the usb or serial port of your computer.
  4. Upload the example code (RealtimePlotterArduinoCode) to the Arduino
  5. Check serial monitor (at 115200) and check that it outputs data in the format "value1 value2 value3 value4 value5 value6".
  6. Close the serial monitor (since only one resource can use the serial port at the same time).
  7. Open the Processing sketch and edit the serial port name to correspond to the actual port ("COM3", "COM5", "/dev/tty.usbmodem1411" or whatever you have)
  8. Run the sketch

Advanced use

The realtime plotter can be expanded to also send commands to the microprocessor. The usual approach when programming microprocessors is to set some parameters in the beginning of the code, upload them to the processor, see the result, change the parameters again, upload, and so on until satisfactory performance is achieved. This iterative process takes a lot of time and a better approach is to send updated parameters to the microprocessor from your computer via serial data. For example I needed to tune some parameters on my robot and created a command panel that runs in parallell with the realtime plotter. For each change in parameters I immediately am able to see the result on the plotting screen. Example code of this is located in /RealtimePlotterWithControlPanel.

RealtimePlotterProcessingWithControlPanel

Notes

I decided to send and receive the data as ascii characters instead of binaries. The greatest disadvantage is performance and ease of use is the main advantage.

In some sense the realtime data plotter can also be used as a very slow and limited digital oscilloscope. I would not recommend using it for any high frequency applications though.

Some comments about earlier approaches and the used libraries

I have tried many different ways of doing this. My first approach was Matlab but I had problems with it locking the serial port. It was a hassle to get it working and getting everything configured takes to much time. My second approach was Python and graphing libraries but this was still not very satisfactory. The Processing language together with a graph library and ControlP5 made the whole thing much easier.

 

Arduino-bibliotek för motordrivare L29x

l298n arduino library
Jag håller på att bygga om min självbalanserande robot och behövde då ett smidigt sätt att styra motordrivaren L298n. Eftersom jag styr roboten med PID-regulatorer ville jag att mitt bibliotek ska ta flyttal som både är negativa och positiva. Resultatet blev ett motordrivar-bibliotek som är väldigt enkelt att använda:

/* This example shows how to set motor speed in percentage where a negative
value will run the motor backwards.
This is very usuful in control applications. For example the output
from a PID controller is most often a float and can be integrated with
this library easily. 
*/
#include <L29x.h>
L29x motorLeft(9, 22, 23); // enable (PWM), motor pin 1, motor pin 2
L29x motorRight(8, 24, 29); // enable (PWM), motor pin 1, motor pin 2
void setup() {
// put your setup code here, to run once:
}
void loop() {
motorLeft.setSpeedPercentage(-12.34);
motorRight.setSpeedPercentage(-10);      
delay(3000);
motorLeft.setSpeedPercentage(100);
motorRight.setSpeedPercentage(90);      
delay(3000);
}
Tagged with:

Generating an interface for robust manual control using Supervisory Control Theory


This is a project at Chalmers consisting of implementing a control system generated from Supervisory Control Theory.

Problem description

"Operation sequencing and resource safety is a non-trivial task within modern manufacturing systems. Typically, this task is handled manually which is time-consuming and error-prone. Whether a particular system works correctly is determined by how long it has been able to function without severe error. Obviously this situation is not sustainable and can be greatly improved by using software tools and mathematics to guarantee correct functionality. Such "model-based formal methods" is one main part of the research within the Automation group at Chalmers. This project aims at implementing a proof-of- concept of existing methods."

Present at IFAC 2014

Our paper was good enough to be presented by our examiner, Martin Fabian, at IFAC 2014. http://www.ifac2014.org/

Our solution

1. Create a model of the sequence:

Sequence to manufacture a full car

Sequence to manufacture a full car

2. Express it as automatas:

Representation of operations as automata

Representation of operations as automata

3. Extract guards to forbid bad behaviors e.g. deadlocks and forbidden states:

Guard extraction from non-blocking supervisor

Guard extraction from non-blocking supervisor

4. The HMI is implemented in HTML5 and AngularJS that communicates to the OPC server of the PLC:

The HMI with only executable operations being shown

The HMI with only executable operations being shown

overview

Overview of the system and the implementation

 

Download the article Robust Manual Control of a Manufacturing System using Supervisory Control Theory in collaboration with Martin Fabian.

Download the source code from Bitbucket

Tagged with:

Selfbalancing Lego robot

As a part of the Embedded Control Systems course we( Brian Bonafelia, Nicklas Gustafsson, Per Nyman och jag) got a task of programming a self balancing robot in Lego Mindstorms (NXT). The benefit of using Lego from a control theoretical point of view is that it has quite bad mechanics, and there demonstrates the strengths of control theory; to compensate bad mechanics with sophisticated software. Focus in the course if mainly not on Lego building but more on creating the mathematical model and programming control theory algorithms corresponding to said model. Now the result with a short video:

Video with more talk and more details:

Downlosad the report "Self-balancing two-wheeled robot"

 

Vehicle electronics Chalmers Formula Student 2013

The project where I spend most of my time right now is Chalmers formula student where I am Project engineer in the Vehicle electronics subgroup. This post is a summary of the design of the over-all wiring. If I find the time I will also post some more information about other subsystems.

2.1.Technical Background

The overall wiring provides electrical power to the components and transfers signal data from sensors to the processing nodes. The overall schematics refer to the design of this electrical system. The schematics are necessary when connecting the electrical system on the car. It is also very useful for troubleshooting and repair of the system.

2.2.The over-all wiring

2.2.1.Design choice/ selection

Our target goals are presented in the table below:

Adjustability Value Comment

Time to disconnect electronics from engine

15 min

Time to check and change fuses

2 minutes

1 min to check. 1 min to change.

Time to check and change relay

2 minutes

Time to check battery and change battery

11 minutes

1 min to check battery with multimeter. 10 minutes to change it.

Time to reprogram ECU 5 minutes

The ECU should be easy accessible. As long as the software is working it should be quick.

Time to download data from DAQ

5 minutes

Memory card out from DAQ, into computer, download data and memory card back to DAQ

Reliability

Mean minimum distance between major electronics failure (after debugging and testing)

150 km

Reliable enough to do at least five competitions

Water and dust protection level

IP54

2.2.1.1.Schematics

The approach when designing the over-all wiring was to start with a low complexity model where the most important subsystems were represented. Understanding the interactions between subsystems is important to get efficient and minimal wiring and therefore the solution model is a good starting point. Designing the vehicle schematics is an iterative process where information is added for most of the new design decisions. The schematics include component specification, choice of connector, pin configurations, connections to the processing nodes, sensors, engine control unit with wiring, generator, fuel pump and power supply.

2.2.2.Packaging of circuit boards, connectors and cables

Protection level IP45 is chosen from pre-study to get sufficient protection from water, dirt and dust. Our assumption when choosing the protection level was that water is a bigger issue than dust since water implies a greater risk for electric failure. IP45 will give protection from dust and dirt above 1mm and protection from ingress of water from a water jet. Going for IP65 increases the protection to be completely protected from dust and protection from water up to more powerful water yet.1 Upgrading the protection level to IP65 to get a safety factor was not too difficult since boxes from Multicomp together with Buccaneer connectors satisfy this specification.

To avoid disturbances cables carrying signals are separated from cables carrying high currents and shielded cables are used in high disturbance zones near the engine.

Connectors for sensors have to have a high water and dust protection level since they will be unprotected by any other component. To get a low maintenance time when dismounting a subsystem from the electronics they have to be easy to connect and disconnect. They should also not be too expensive. TE connectivity Superseal 1.5 series (Figure ) with IP67 will meet this requirement.2

Figure : TE Connectivity Superseal 1.5 Series3

Connectors for the processing nodes was set to have the same requirements as for the sensor connectors but with a constraint that the female connector has to be mounted at the side of the box containing the processing nodes. Circular connectors were chosen since they make the manufacturing of the processing nodes easier compared to using rectangular connectors. It is also much easier to find circular connectors with sufficient water and dust protection. Buccaneer 400 series (Figure ) which have IP68 classification are chosen.

Figure : Buccaneer 400 series4

A hole on each side in the monocoque is used for wiring the sensors near the front wheels to the front processing node. Delron Inserts 102 series (thru-bolt) will be inserted into the hole for water and dust protection.

 

2.2.3.Discussion of design selection/ Limitations

Alternative solutions for the overall wiring were discussed and benchmarked. The main reasons for rejected design alternatives were reduced reliability or increased complexity.

2.2.3.1.Alternative connection between sensors and inside monocoque

Instead of drilling a hole at each side of the monocoque to transfer a cable for the sensors at the wheels a connector could have been used. We had discussions about using connectors from Deutsch which would be lightweight and robust. The main disadvantage was the wiring inside the monocoque. With a connector the bend of the wires connected to the connector must not get in the way of the driver’s legs. The driver department should be as clean as possible to avoid the driver hitting any protruding parts. Adding a connector would increase this risk and therefore the solution was rejected.

2.2.3.2.Two nodes and the alternatives

The reason for choosing a two node system was to reduce wiring and divide logging and processing on two processors. A two node system with a CAN bus is much easier to expand than a single node system. Adding more sensors can be done by connecting them to free inputs on either of the two nodes or by adding a new node since a CAN bus is used. One design alternative that was considered was to have small nodes by each wheel with a CAN bus connecting them. This could decrease wiring even further since the distance from each sensor to a close by node would be smaller. The main reason for not choosing this design was to limit the number of developed components. Our recommendation though to next year’s CFS would be to consider this approach.

2.2.3.3.Alternative connection of the ECU

An alternative to the current solution of connecting the ECU to the rear node via RS232 would be to connect it to the CAN bus5. Since the rear node in this case would not need to handle the communication to the ECU and instead get the data from the already implemented CAN bus communication the processing would be reduced. The same would be true reducing the programming code when using CAN instead of RS232 since the CAN code has to be implemented either way. The disadvantages are added components since the ECU does not have a CAN interface but a RS232 interface. A purchase of a CAN adapter would be needed with increased cost as result. The programming code for communication to the ECU was implemented last year and will hopefully reduce the development time this year which makes the advantages of the CAN interface less important.

2.2.3.4.Alternative 1 for connecting the DASH3

Using a serial adapter between the DASH3 and the DAQ would make the dashboard able to read sensor values from the data logger. This solution was most importantly not chosen since it would increase the number of components and the complexity of writing to the dashboard did not seem too great to overcome since the dashboard protocol is open6. Even though Race Technology in an email wrote that the logging capacity would not be decreased by much since the update frequency to the dashboard does not have to be more than a couple of times per second, we were not sure if it would be a limiting factor or not. The safe option was to not use the serial adapter and instead send the data from the front node. The disadvantage of this solution is more development time since routines needs to be programmed for communication between the node and the dashboard. With the serial adapter this is already done by Race Technology.

2.2.3.5.Alternative 2 for connecting the DASH3

Connecting the DASH3 to the CAN bus would be done with a CAN adapter. The distance from the DASH3 to the front node is so close that any weight saving due to wiring would not be a factor. The main advantage would be an assumed reduced development time since the sensor data to display on the dashboard would already be present on the CAN bus. Only configuration of the DASH3 would be necessary.

2.2.3.6.Alternatives to the circular connectors in the processing nodes

An alternative to the circular connectors in the processing nodes would be rectangular connectors. If the processing nodes are better protected from water and dust this would be a good option since it makes connecting sensors somewhat easier. A disadvantage with circular connectors is that they require soldering or the use of clamp tool. Adding sensors to a rectangular terminal block would be a matter of just connecting wires to the connector block. This connector is for example used on the DAQ (Figure ) which we use for data logging.

Figure : Race Technology DL1 MK3 DAQ

2.2.3.7.Alternative driver interaction design by combining switches

To minimize the amount of switches on the dashboard it is possible to combine the switches for ignition, fuel pump and start engine into a switch with multiple states; Off, Ignition, ignition+fuel pump and start engine (with momentary action). The main disadvantage is lost control of forcing the fuel pump to be either on or off. The states of this switch would be:

  1. Off

  2. Ignition

  3. Ignition and fuel pump

  4. Starter motor. This state would be momentary stable and return to state 3 when released.

The reason this solution was neglected was loss of control of the fuel pump. With a dedicated switch for fuel pump three states can be selected:

  1. No fuel pump

  2. Fuel pump controlled by ECU

  3. Fuel pump forced on

2.2.4.Simulations/ Tests/ Experiments

The first approach for the schematic design was to do it by hand on paper (Figure ) and then convert this to 2D CAD software. For developing the vehicle schematics a comparison between alternative software was done. A brief summary of the software comparison test:

  1. ExpressSCH seemed quite good at first but adding components was a hassle.

  2. FastEl did simple tasks complex and lacked user friendliness.

  3. Eagle CAD has two main features: board design and schematics design. Designed for manufacturing PCBs and therefore a lot of features would be left unused when only designing schematics

  4. TinyCAD is a simple and fast program without any advanced features.

TinyCAD was chosen since it got the job done and was fast to work with compared to the other alternatives.

Figure : Iteration 2 of schematics on paper

2.2.5.Over-all schematics

Click on the image and then download it as a png. The schematics file is very big and the image below is just a thumbnail.

Direct link to schematics image

Tagged with: ,