Friday, November 27, 2015

The third wave of Open Source

I was 6 years old when Richard Stallman founded the Free Software Foundation in 1983. I was completely unaware of that historic moment, and, obviously, I couldn't have cared less anyway.

I was 14 when Linus Torvalds started to work on the Linux kernel. I was just finishing up the elementary school, very difficult time for a kid, I wouldn't have cared much even if I had known. It was a pre-internet era for most Hungarians, I could not have learnt about it anyway.

It took two more years to come across with the free software movement first. For me and for my friends, struggling with the upcoming adulthood, it was such an appealing idea. We were extremely hyped, started every kind of open source projects, and also got involved in many others. I still remember, as if it was yesterday, downloading fresh Linux distributions during many nights (to exploit cheap minutes) on a 33.6K modem.

Later on Linux got more and more attention, but for most people it was just a marginal movement, a kind of adult playground, unusable for real applications. I think, the next milestone could be 1997, when Eric Raymond published his essay, The Cathedral and the Bazaar, what inspired Netscape to release Netscape Communicator as a free software. Then companies started to use Linux, first, only for less critical systems, then, as they learnt how reliable it is, for replacing of the expensive Windows NTs. Those were nasty times, many people considered open source as a threat, and they took it very personally, it felt like a battle of generations.

But the open source movement was unstoppable, and it is mainstream now, the battle is over, the victory is total.

This was the first wave of open source. The second wave is open source hardware.

I couldn't say the exact date it started, but 2005, when Arduino was introduced, was a big milestone in any rate. Arduino is a microcontroller, a tiny computer which is capable of  interacting with the physical world by reading sensors and controlling every kind of actuators (e.g. motors). And it is inexpensive (I mean really inexpensive, some versions can be bought online as cheap as 2$ or less) and mostly because it is open source. There are so many great projects built on Arduinos, 3D printers, every kind of robots, and  so on. And there are many other great open hardware projects e.g. my personal favorite, poppy, which is a state of the art humanoid robotic platform.

Open hardware is not as fundamental part of our life as open software is, it is just forming before our very eyes. Still, being one of the, if not the main, factors behind the maker movement, it already left a mark on the world.

50 years ago nobody wanted to create a scanning electron microscope or a fusion reactor at home. Obviously, there are many reasons behind it, but at least one of them is conceptual complexity. Even a simple robotics project is incredibly demanding, one has to understand software (general purpose + embedded), hardware (electronics, mechanics), not to mention the special, project specific knowledge. A quick glimpse on the required skills and knowledge enough to put off most people as the complexity is just intimidating.

Dealing with complexity is where we are doing better I believe. The knowledge level rises in the world? Maybe. Was it triggered by the open source movement? Probably the other way around. But the open source movement certainly has a kind of reinforcement effect, it boosts the development by making the necessary resources freely and/or easily available.  

Last week I came across the recent Open Source Insulin project. This makes me shivering with excitement. Is it already the third wave?


Saturday, November 21, 2015

Robot car v1

This was my first independent robotics project. After I finished the delta robot, I felt confident enough to create something from scratch instead of following instructions. I was very hyped and I thought a robot car wouldn't be much different than a delta robot. Motors, electronics, software the same, the main difference is simply that a car has a chassis instead of a frame...

Basic design

I made a shopping list: chassis, motors, wheels, electronics, ... As these are mostly dependent parts, without any experience, I was afra
id of buying parts that may not work together. It looked a better idea to buy first the most fundamental part of a car, the chassis, and, make better-informed decisions on the remaining parts with that in my hand.

I went on the internet to look up robot chassis, and I found this immediately:

I loved it as it was very cheap (< 10$ that time) and included the motors and wheels. Its quality was questionable (judging by the price), but being inexperienced, I did not have any expectations either. It seemed a good idea to learn what really matters in a robot, for such a small price.

When I finally received it, it was immediately clear that there is not much space for the electronics. By the picture, I thought that some stuff can be put on the undercarriage, but actually the motors used up most of the space there.

As for the electronics, I needed at least a microcontroller, motor drivers (I learnt this from the delta robot) and something to control the robot (bluetooth?), not speaking about the battery holder. For various reasons I already had an Arduino Mega and an Arduino Nano at home; to limit the cost, it seemed reasonable to use one of them.

I considered the pros and cons. The Mega is quite big (-1), but can be used with a motor shield, so the motor drivers do not use additional space (+1) + it has many IO pins (+1). The Nano, however, very tiny (+1), but shields cannot be placed on it (-1). It also has a way less IO pins (-1).  The Mega looked a clear winner. On the other hand, motor shields are quite expensive, and I do not need too many IO pins for my simple robot. Not speaking about, how cute the Nano is... Thus, I ended up using the Nano and two small sized, very cheap L298N based dual motor drivers. It was powered by 4 AA batteries.


During the development, the robot was controlled via the Nano's USB serial interface. For the final version, however,  I wanted something wireless. My first candidates were bluetooth, xbee and wifi. All of these have cheap receivers, in addition, bluetooth and wifi are very ubiquitous, any mobile phone can be used as a client (xbee does not have this advantage, so I ruled it out instantly). Compared to bluetooth, wifi is not very practical either as it needs a network (bluetooth can connect to another device directly).

However, bluetooth has a big disadvantage regarding kid friendliness: it cannot be used without a e.g. mobile phone, what my 6 years old kids certainly do not have (a second disadvantage is that it requires some client software to be developed). So I kept looking. I wanted something that has an easy-to-use  remote controller like thingy, e.g. a 2.4ghz RC transmitter used for remote controlled helicopters (however it would be hunting rabbits with an elephant gun, and a way to expensive). I found an infrared remote controller, incredibly cheap, but it is not quite user friendly and I was afraid it may have connection problems (that would have certainly spoiled the fun of the kids). I was thinking that something like a play station remote controller would be great... why not actually? I checked it, and turned out that it is available for Arduino and inexpensive. Just perfect.

Additional parts

If something is built for kids, the basic functionality is certainly not enough. The first three requests were the following: eyes, siren, lights (I'm not sure in the order though).  For the eyes, I mixed business with pleasure: the ubiquitous HC-SR04 ultrasonic sensor made the robot very cute (3D print a mount, many model available for free). The siren was the easiest, it turned out that a small speaker or piezo buzzer can be directly controlled by an Arduino. Finally the lights. Of course, lights meant something that police cars have, not an ordinary headlight. After contemplating on this task a bit, I ended up mounting RGB leds into ping pong balls. The kids loved it.


There are many tutorials available online on how to program the individual parts, but the integration  of the software components may not be entirely straightforward. The main problem is that many tasks should run (semi) parallel, e.g. reading the controller / the ultrasonic sensor, changing the tone played by the speaker / the color and intensity of the lights, controlling the speed of the motors. On normal processors, the common technique is to utilize threads; they give the feeling of real concurrency even on a single processor. But for threads, one needs an advanced microprocessor, and a scheduler (that is usually part of an operating system). On a microcontroller, these features are not available. One can use green threads though: they emulate multithreading without relying on any processor support. On Arduino, e.g. the mthread library can be used for this purpose. 

The firmware of my robot is available at github. It probably cannot be applied directly to any projects, but it may be a good source of code snippets and ideas.

List of parts and cost

Just to give a basic idea how much such a project cost (not much). I provide the "Chinese" price based on a simple search at aliexpress at the time of writing the post. Unfortunately the prices are increasing, it is already more that I used to pay a few months ago (especially the chassis), some sellers are getting greedy there...

You may need some common things that are not listed here, e.g. jumper wires and tools, but it is not bad at the end at all. Especially considering how much it may inspire the kids to work on their own inventions.

Part Price
Arduino Nano < 2$
L298N x 2 < 2$ x 2
Chassis + motors + wheels ~ 20$
PS2 controller + receiver ~ 15$
Piezo buzzer < 1$
RGB led x 2 < 1$ x 2
HC-SR04 < 1$

< 46$

Problems (and future work)

  1. Power distribution: I already wrote about it here. Serious problem that could be alleviated by replacing the 4 AA battery holder with a 6 AA one. This is only a temporary solution though, for the second version of the robot, I certainly want to use proper batteries.  
  2. Chassis: It is a very impractical chassis. a) There is no much room on the undercarriage, so most parts had to be installed on the top where space is also limited. b) Because the electronics was not safely concealed in the chassis, it is extremely not kid friendly. Can you imagine how much your kids has to resist the temptation of tampering with the myriad of jumper cables? c) Mounting holes, how made you? None of them fitted any of the holes on my electronics. Furthermore, because it is made of acrylic, you cannot make new holes without risking of a crack. Acrylic is just not practical for prototyping. d) Acrylic is not kid friendly, very fragile. This robot lived for a week only.
  3. Microcontroller: using the Arduino Nano was a poor decision. I actually ran out of IO pins in no time, especially the PWM ones. A second problem was quite unexpected, it occurred because of the number of available timers on the chip. The Nano has 3 timers, one of them is used by delay() and millis() functions, so only two of them are free. However, I needed timers for playing music, controlling the ultrasonic sensor and providing  a clock signal for the PS2 receiver.  It was a heroic struggle to support all of these. In contrast, the Mega has 6 timers...
  4. Wiring: I need to find a way to make wiring nicer, at first I thought it was cute with the many jumper cables going all over, but it was actually just a messy hack what rendered the robot extremely unreliable.
  5. Kinder friendliness: The kids wanted to use the robot in their own creative way e.g. installing their own LEGO creations on the top, attaching additional cars to the chassis and so on. With this robot it was just not possible; the next version must be designed to fulfill these expectations. 


Monday, November 16, 2015

Monadic templating in C#

I have two blog posts at the PDF about the framework I developed for my cross-compiler project. It is basically a monadic approach to generate, from a some structured data (abstract syntax tree in my case), some textual output (e.g. source code). The framework hides the complexity of state management and allows nice templating using string interpolation. It is for C#.

Part I, Part II

Wednesday, November 11, 2015

How (not) to power a robot

After I finished the delta robot, I felt confident enough to create something from scratch instead of following instructions. I inquired my kids whatever they wanted and they opted for building a train. I really do not understand children's obsession for trains... Anyway, being a really bad person, I convinced them that cars are cooler (actually I believe that trains are cooler, but tracks make them impractical).

It was a 4 wheels robot car basically built from some cheap Chinese 6V DC motors, two L298N dual motor controllers and an Arduino Nano. The whole stuff was powered by 4 AA batteries. The relevant part of the electronics was quite straightforward: the batteries were directly connected to the L298N; the L298N has regulated 5V output, that was used to power the Arduino. This configuration, however, simple as it is, has many things wrong with it.

1. problem: low voltage


While being built, the robot was always connected to my laptop with a USB cable. When the wireless controller arrived, I worked half a night to integrate it and develop the software, I was extremely excited being that close to an actual test drive. And finally it worked on the bench pad, ready to test! USB cable was removed, the car was switched on... nothing happened. USB cable was plugged in again, car was switched on, worked perfectly. USB cable disconnected again... nothing happened.

It was immediately clear what was happening. The battery did not have enough power to drive the voltage regulator (what is rather amazing that I did not realize this problem beforehand). The 4 AA batteries produce 6V (another mistake), it may not be enough for regulated 5V, I guessed. The specification confirmed my suspicion; Input voltage (VMS) must be between 7V and 18V for regulated output.

The simplest (cheapest) solution seemed to replace 4*AA battery holder with a 6*AA one. That supposed to supply 9V (wrong again) what is more than enough . So I replaced the battery holder and the robot started to work. For 10 minutes... then the microcontroller started to reset regularly; then more and more often, until it reset every time the motors were switched on.

I measured the voltage of the battery, and it was less than 7V. How come? This was the point when I learnt that  rechargeable AA batteries supply only 1.2V instead of 1.5V. I did not know that... It is embarrassing, but explains a lot; the batteries supplied 7.2V instead of  9V; in addition, they were quite worn-out, voltage dropped soon, and the inrush current took it below the critical level when the motors were switched on.

2. problem: low power


So I switched to non-rechargeable batteries, and finally, it looked solving the problem. For like half an hour. Then the microcontroller started to reset when the motors changed direction or were switched on. 


This time, I faced with two problems. The first one is the discharging curve of the AA batteries. The motors use approx. 200mA under load, the microcontroller around 40mA, plus there are some other active elements in the car e.g. a wireless receiver and ultrasonic sensor, but it is still below 1A, the batteries should have held much longer. It was a problem with the batteries:

Under such a load, the supplied voltage drops a great deal very soon in these batteries (especially that I did not buy the most expensive ones), and you enjoy the low voltage problem again.

3. problem: inrush current


Inrush current in my robot car (starting and reversing
the motors)
When a motor is turned on (or when the robot hits an obstruction and stalls the motor) the motor pulls much higher currents than it does in normal operation. This high current may pull down the battery power rail enough to reset all the digital electronics in the system (the electrical noise generated by DC brush motors may also cause the electronics resetting).

There are some common solutions for this problem:
  • use two power rails + batteries; one for the motors and for the electronics and communicate by the means of optocouplers
  • add capacitors directly across the battery; large electrolytic capacitors can eliminate the current spikes, small ceramic ones can reduce the RF noise [1,2]
  • use an integrated load switch


4. problem: power distribution


There is one more final problem. As it can be seen on the wiring diagram above, the batteries are connected to the motor driver, and the voltage regulator of the motor driver powers the microcontroller. This is very unlucky. Copying from here:

The common section of wire will act as the small resistor and when the motor turns on and draws a large surge current, the electronics will see a large current drop.

The solution is simple, just connect everything directly to the battery (called star power distribution) if possible. In my case, there was nothing to avoid me connecting the Arduino directly to the battery as it has its own voltage regulator.




Most of these problems can be solved using a battery that supplies enough voltage and current that inrush current goes unnoticed. This can vary from system to system, in my case a 3 cells LiPo battery (11.1V) solved the problem. LiPo batteries are great for robotics purpose. They come in many different capacities and voltages (LiPo cells have a nominal voltage of 3.7V, a battery usually contains 1-5 cells, that is 3.7V-18.5V), and have phenomenal peak discharge rate (even up to 100x of their nominal capacity, but 20x-30x discharge rate is very common).

However, a powerful battery does not solve all of yours problem. Even if inrush current does not make your robot resetting by the voltage drop, it still can damage connectors and terminals and generates noise on the power rail that might confuse or even destroy delicate electronics. Some filtering capacitors (or an integrated load switch) are really helpful to limit the peak current and reduce electromagnetic noise.


Wednesday, November 4, 2015

What is Pulse Width Modulation (and what is not)?

Pulse Width Modulation (PWM) is an extremely confusing subject. Mainly, because it is often explained as a way to provide analog output by microcontrollers (there are also many excellent sources though). This tutorial at Arduino says in the second paragraph that
Pulse Width Modulation, or PWM, is a technique for getting analog results with digital means.
Which is very confusing at the least, especially that it follows:
Digital control is used to create a square wave, a signal switched between on and off.
It turns out that the PWM signals for various analog values are these:

This used to confuse me for a very long time. By analog signal, I rather imagine something like this:

What is PWM for then? It can be used when some kind of physical mechanism is involved that averages out the PWM signal. The brightness of a LED can be controlled for example (humans cannot perceive high frequency changes). With some effort, it can be done with a nice result (I mean without apparent flickering). It also can be used to control the speed of a DC motor, where the mechanical inertia of the rotor acts as an averaging mechanism. Probably there are other direct usages as well.

Still, the question remains, how to produce "real" analog output?

The answer is that one still needs to apply a small piece of electronics, a digital to analog converter (D/A), to the PWM signal. In this case, the simplest version of a passive analog low pass filter can do the job:

It is well explained in details in this article.

Intuition says that this works as one expects the capacitor in parallel to smooth the signal. Still, it is a general "low-pass filter", how come it applies to this task? It may be immediately clear for an electric engineer, but I had a hard time understanding it until I found this article. It uses a completely different approach for the explanation, based on the Fourier analysis of PWM signals. If you understand the language of Fourier analysis, I recommend reading it, the theory is simple and beautiful (and quite obvious to be honest, seemingly it was too long ago when I studied this).  In a nutshell, filtering is used to get the DC coefficient (what is the mean value) by removing all the higher harmonics.

Certainly there are many reasons behind that PWMs are widely adopted in almost all microcontrollers. One of these may be efficiency and its direct consequence, straightforward heat management. The transistors involved in generating PWM signals are either fully on or fully off (power loss is very low), thus do not dissipate much heat (no need for huge heat sinks). Another common argument in favor of PWM is that it always provides full voltage for a variable amount of time, thus, e.g. in the case of a motor drive, it can efficiently provide full torque from zero speed to full speed.


3D printer as a beginners DIY project

I wanted a 3D printer. After some hesitation I decided to build a Rostock Mini. I had two main reasons for that:

  • delta robots looks very high-tech and elegant
  • Rostock Mini is just awesome

Later on it became a Rostock Mini Pro; that is build with universal joints used for model helicopters (the original Rostock Mini uses 3D printed u-joints) what I found much nicer.

If you've never build something complicated like a delta robot, even a single look at the part list is frightening and extremely demotivating. It really looked like rocket science (conceptual complexity can be very high if one knows nothing about a subject), so I decided that I do not try to understand it at once, but take a bottom-up approach, and break it into small subsystems. As a consequence, I concentrated the delta robot for a while, and forgot the 3D printing parts. Many people builds this 3D printer at home, it is easy to find detailed information on how to build one, I rather highlight the most important things I learned from this first project.

The first lesson to learn is that on a low budget, parts are coming from China. It is cheap and shipping is free most of the time. The downside is that it usually takes 2-3 weeks to deliver (the quality is also very erratic, slightly biased towards the low end). However, I found it a great fun to wait for the parcels and put the parts together week by week (literally), I was not in a hurry.

Second lesson, you need tools. Probably one has a screwdriver, but not necessarily a soldering station, a thread cutter, a multimeter, a Dremel, .... You will get these in no time.

Third lesson. 3D printers suck. A lot. Some parts of the Rostock Mini must be 3D printed, and I found out there is a printer at the university I work for. It is a BigBuilder Dual Feed, which is not a low end printer  (but not very expensive either). Still, it is painful to calibrate it (regularly): to level the bed (the head is supposed to be 0.2mm from the bed, you have to adjust it manually by turning some screws); to find the proper printing parameters; to replace the adhesive tape on the bed; ... and so on. The quality of the result is also at least questionable some times. This article is speaking from my heart:

The way it's advertised, you'd think you could set up your 3D printer, hit print, leave for the day, and return home later to an item made out of thin air that you can use immediately. It's like Christmas morning, right? 
Unfortunately, that's not exactly the case. You may come back to a tangled mess of plastic, or an extruder printing with no plastic coming out at all. It might be jammed, paused, beeping, or flashing lights. It may have never started at all.

I learnt to hate it even if I find it very useful when I need a custom object (and I still use it to print parts for my other projects).

Anyway, this made me not to finish the 3D printer. The delta robot is finished, fully functional and was a lot of fun to build. One has never been happier than me when my stepper motor had moved the first time. My kids spent hours controlling the robot from a simple application, and explained to everyone how it is supposed to work.

One can also learn a great deal from it:  the basic building parts of the mechanics, bearings, pulleys, belts, screws, nuts and so on; materials; electronics basics and prototyping; the types of electric motors used in robotics; microcontrollers; firmwares, developing embedded software; kinematics; just a few things off the top of my head.


Featured Post

Juicy-footprint: An SMD Footprint designer DSL

  Introduction    Juicy-footprint is a domain specific language written in/for Java and Scala to design/reconstruct SMD footprint...

Popular Posts