keskiviikko 28. joulukuuta 2016

Travelling ...


I know, my writing pace has slowed down significantly. Like I previously said, I've been way too busy with mundane day-to-day stuff to make anything interesting, meaning that I just don't have that much to say. I'd rather not write completely pointless texts, so I choose to lessen my pace. Now, whether this qualifies as pointless text, that's up to you...


I might have said this before, but it is my firm opinion that travelling sucks.

Sorry, let me rephrase that, it's the travelling, being "on the road", part that sucks. I've never been the kind of person that enjoys the journey itself. However, being there part varies from being a chore to being simply glorious - and everything in between.

That's me in the hammock there, in a small village of Kep in Cambodia, 2007. Getting there involved total of around 40 hours of travelling - but this isn't really being fair since this was extended trip and we stopped in many many locations, before and after this specific point.
 
Longest single trip at that point (during that excursion and from point A to point B) had been about 24 hours. Mostly via planes and airports. Cheap air travel doesn't usually be via quickest possible route. That is the part that sucks - cheapest or not. Be it via planes, trains or automobiles, it all sucks equally. Getting from point A to point B takes often so long time, and while there might be some interesting stops on the way, more than often there is not, or you are now aware of them. Or can't be bothered to stop there. Or are just too tired to.

Recently I took a short business trip; just 14 hours total, just to be in a few meetings with total of maybe two hours. All the rest was travelling around or waiting. Can you guess already why I am not a fan of business travel? But really, sometimes you have to do things that aren't the most fun.

Again, I may be repeating myself from earlier post but maybe 20 years ago I read an opinion piece in a local newspaper, saying that business travel should be taxable benefit. Really, that person travelling for work should be taxed for being able to enjoy benefits of travelling for business.

Listen here, bud. You might want to try that for a while first, your opinion is very likely to change.

But, nevertheless, when everything goes better than expected and you find yourself having an extra day with no work to do (having finished early) - well, that one day might be worth all the trouble.

Assuming, of course, that you aren't in middle of nowhere, with nothing but (unfinished) factory and few personnel barracks around you...



tiistai 20. joulukuuta 2016

Completely useless firmware


Not much blog activity lately, sorry about that, I just am swamped with work right now (uninteresting for readers) so I don't have anything new to post.

But I have to vent some frustration here.

Previously I dabbled with USB HID system with STM32F429 MCU, working fine, sources and all published earlier. I've since tried to get same code working with STM32F469, with no success. Couldn't figure out what was wrong (and I might have burned out one test board in process, oops - 5v tolerant like isn't very tolerant if rest of the board is unpowered...), so I wanted to try newer version of their library, maybe code for older processor isn't working because something in newer MCU had changed.

I want peripheral library to be essentially "drag and drop". Get source file (or directory for more complex subsystems like USB) and drop it in my project directory, change few lines at top of header and done.

This library from STMicro isn't like that. USB  system had been splintered in tiny pieces, thrown liberally around in dozen or so directories with pretty much no logic whatsoever (one file each, of course) in different places of messy directory structure, and with configuration thrown around, piece by piece, in those files. Very opposite of user friendly.

It's almost like they want to force people to use Expensive (with huge capital E) development systems for tasks that should be trivial...


perjantai 25. marraskuuta 2016

C: sizeof(pointer) is ...?


Pointers in C are one of the biggest traps for programmers, novices and experienced alike. If you are working with modern PCs they are fairly simple to use - a linear 32- or 64-bit address, handily the same size of native word size of architecture so you "can" cast it to integer and do other things with it (but you really shouldn't, unless you really, really know what you are doing).

Too often people seem to make assumption that sizeof(int*) == sizeof (int). For many architectures this is so - but not for all, and not even for all x86-based architectures. Because of this you really shouldn't do that casting thing I mentioned above (for example, for backwards compatibility 64-bit linux [amd64 ABI] has 32-bit int.)

And when you get to older architectures it gets even weirder.

Let's take original 16-bit x86 for example. It was, of course, 16-bit architecture, but with 1MB of memory total. Memory was addressed with segment:offset system; both being 16-bit values, the pointer total was 32 bits (I won't go into the actual addressing details here as it's irrelevant for the discussion.)
But wait, there's more! This was the "far" pointer, that could point to any address of the system (no memory protection back then.)  Then there was also "near" pointer that could only access memory within a segment with only the 16-bit offset value. And then there was apparently "huge" pointer which I've never encountered myself.

So here even sizeof(int*) isn't necessarily sizeof(int*), if those happen to be "near" and "far" respectively. Confusing already?

How about embedded world then?

I used to work with C51-based devices. This is old architecture, introduced back in early 80s, but is still going strong as modern variants. Different variants are easily and cheaply available from several manufacturers, and many (old-school) programmers are familiar with it, so they are very popular in embedded world.
These devices are 8-bit MCUs (int typically is 16-bit) and have four different memory access modes (and three completely separate memories);
  • DATA, directly accessible RAM, 128 bytes.  
  • IDATA, indirectly accessible RAM, 256 bytes total. This overlaps DATA for first 128 bytes.
  • XDATA, external RAM, up to 64kbytes. These days this is not really external but built in the chip itself. Being external there is no overlap with DATA or IDATA.
  • CODE, being code memory, I've used devices with up to 8kbytes of flash built in.
So here pointer must identify which memory is accessed *and* up to 16-bit address within it. So commonly pointer is three bytes; one byte to specify which memory is accessed, and two to specify offset (and yes, other compilers may have used other methods, this is one I am familiar with.)

Separate memory spaces for code and data is known as Harvard architecture, and it is common even these days; many Atmel chips use it - and my extension, many Arduino devices. I am not familar with those (aside the code/data separation) and how C compilers there handle pointers, but I wouldn't be surprised if similar methods as with C51 would apply.

C is full of traps, especially when you start mixing several architectures in same project, and it's kinda okay to play fast and loose iff you know damn well what you are doing. If you don't (even I don't, not always), one should play safe. Don't assume you know sizes, and don't do any wild castings. It'll come back to bite you.

I should know, I've been there, many, many times over the years.






maanantai 14. marraskuuta 2016

Voltage detector - with a leak within


Some time ago I bought a cheap contactless voltage tester. This is a device that indicates presence of high voltages (AC mains mainly) near the probe with a sound and is powered with two AAA batteries.

I do not need it often, but like so many devices, when I do need it it is really useful for diagnosing power faults (for example: this device seems to be receiving mains voltage so fault very likely is inside it.)  And just as a reminder: even if these don't indicate voltage presence, you should always treat mains wiring as it were powered!

Now, this specific device unfortunately does not have any kind of power switch for detection (it has a flashlight at the other end which does have button, yes, but that does not turn the voltage detection off). And since it takes only one time forgetting to remote the batteries, the end result is inevitable:


No, despite colors this device has nothing to do with Fluke.

Surprisingly, it still worked when in this condition, both detection and LED flashlight. The physical damage to the battery from trying to remove it forcefully - other battery is still deep inside and I don't even bother trying to get it out. I only noticed the situation since there was this white crap around the battery cap.

As my personal tool-buying rules say, I've bought cheap, found it useful, so now it is time to get a better one. And this time it absolutely must have a physical power switch.




torstai 10. marraskuuta 2016

Intermission: Culture and politics


Now that a bit of time has passed, I'll open up my previous short post a bit. Just politics here so if you don't want to read about that, move on.


Back in 80s, when I was growing up, USA seemed like a heaven based on everything I heard from there. Cheap soda, cheaper gas, advanced technology, rich people, good food, space exploration, world leader, etc etc.

As time as passed the reality has crept in (and maybe I've grown older and maybe a bit more world-wiser too), piece by piece, and the more I hear about conditions in the USA the less I nowadays want to live there. Two big things being political system and medical care. Both of which are so important for people and so horribly broken and there is (at the moment) no hope of either being ever fixed.

These days I've given up of even visiting the country as a tourist since border control seems to have taken openly hostile attitude towards anyone (their own citizen included) entering the country. As long as the situation remains like this I take my tourism money elsewhere. Like Colombia (not very likely, but they certainly are at the moment way above USA on my mental list of countries I'd like to visit some time.)

But back to today's main topic. Let's get real now - when electing the president, if your only real choices are "completely horrible person A" and "totally horrible person B", something is seriously fucked up somewhere. And this election was exactly like that. But hey, "Don't blame me, I voted for Kodos." Right?

I do hope that Trump will turn out to be something else than what he has presented himself to be during the campaign. But I won't be holding my breath in the meantime. 


maanantai 31. lokakuuta 2016

Function generator repair


I have TTi TG330 function generator that I use every now and then. It is fairly nice device, capable to frequencies from 0.003 Hz to 3 MHz in sinusoidal, trapezoid or square waveforms, including sweeps and 120MHz counter. I do not need it every day or even every week but when I do, it is worth every single cent of its price.

Unfortunately it broke a while back. Turning it on did absolutely nothing. I checked the main fuse but no, it was okay. So time to take it apart and see what is going on then.


Its a bit difficult to tell from the picture but the top cover has turned slightly yellowish near rear. Generator is fairly warm during use so that isn't exactly surprising.



Covers are held by simple plastic locking tabs instead of screws. Take these off from corners and cover comes handily off.

The insides. Note that generator is shown here upside down; the board seen on bottom is actually towards the top of the cover in normal orientation. I'm not exactly happy about that large and heavy transformer hanging in there during normal use.


All the capacitors seem to be okay, so it was time to start probing the board. It did not take long to find out that fuses, circled in picture below (marked FS1 and FS2) both seem to be blown. Weird, considering that main fuse (earlier in power supply chain) was intact.

These fuses are on secondary side of transformer so there should not be any (very) high voltages there, but one still must be very very careful when probing around these devices. Even when powered off there might be dangerous voltages around.


I could not find schematic for this model, but I did find schematic for model 550 which, while different, suggested that these fuses might be 500mA (if my memory serves, this was few weeks back now). Not something I had handy, but a quick trip to Sp-Elektroniikka (local parts store) I was able to acquire suitable SMD replacements. The space is a bit cramped but I was still able to replace these fuses with little trouble.

Since the original fuses were both blown I was a bit suspicious if this would work; if there is some issue further down the chain, new fuses might blow again immediately.

They didn't, and generator seems to be working fine again.

So I put it back together and it is serving me well again. No idea why those fuses have blown, but as long as it doesn't happen again I am happy. Although I do not keep the generator on 24/7 anymore.


keskiviikko 26. lokakuuta 2016

Testing linear regulators


Recently I was testing few different regulators and how they behave when you inject higher voltage (at low-ish current) to their outputs than what they are supposed to regulate. As it turns out (and as I kinda expected), many regulators are not very happy about this.

Testing them was kinda fun though. Let's take this 5-pin, 2.9x2.5mm sized one, very cheap 5v micropower (30mA max) regulator IFX20001;


That board is with standard 0.1" (2.54mm) grid. That should tell you about the scale here.

This one requires fairly large output capacitors to be stable (over 3.3uF), so I used 2 2.2uF caps in parallel. Those output caps are almost larger than the regulator itself! And of course I added small  (100nF) input cap.
Positive supply wire goes to left, ground to right and output downwards.

Unfortunately injected voltage goes straight to output with this chip (even if limited to well below 10mA) so this chip doesn't work too well for me here.

Another one I tried came in 8-pin 0.65mm pitch package. That does not fit very well on this prototyping board, but fortunately I keep old unpopulated project boards handy for just this kind of purpose. There is usually a part of them that can be used for just this kind of hacks;


I think this was originally for LED driver chip that I found out I don't really need so it was taken out from newer board revisions.

Here leftmost red wire is supply, center one is output and rightmost is voltage injection test lead, through 2k4 resistor. Resistors on left are feedback (with wire on top of chip being feedback wire), capacitor on left output capacitor (same 2.2uF as I used above, I do have full reel of them!) and wires on top are ground.

Neither of these chips was too happy to have higher voltage injected to their outputs, latter behaving a bit better. So if there is a risk of that, there needs to be diode in series to make sure nothing bad happens. Unfortunately I need output voltage to be 5v or slightly above so otherwise nice and smaller IFX, with its fixed 5v output voltage, does not work here. Ah well, so I spec the adjustable, larger and slightly more expensive other one.

Spec for what? Sorry fellas, but that is something I am not willing to share at this time.



sunnuntai 23. lokakuuta 2016

Bluetooth headphones, once again


Some time ago I wrote some thoughts on bluetooth headphones for phones.

I've gained a bit more experience since so I think it's time for an update.

I actually use several bluetooth headphones and/or hands free-sets;

- Ancient Jabra BT620s. Old (one might say "ancient", technology-wise) but still work nicely. These I use mostly in office when I am anticipating a long call or when I want to use both hands when in phone.
On minus side, they're fairly large yet they offer almost no external noise reduction, so I can't really use them when biking, lawn mowing or anything. The worst part of them is stupidly bright flashing blue light that apparently can't be turned off. Since that makes me feel like I'm having big flashing "look at me!" sign on my head, I very rarely use them in public. They do look a bit stupid even without the light, but then again, I am not a fan of this kind of "on the ear" headphone design anyway.
Battery life is pretty good, I don't think I've even ran out, but then again, due to the appreance issues I don't really use them that much.

-Car 1 handsfree (2011 model, factory option Blaupunkt radio). This actually works damn well. Only problem is annoyingly loud "connect"/"disconnect" sounds when getting in or out of the car, but that is just minor issue for otherwise well working system. Damn steering wheel in that car has more issues than the bluetooth setup! (fortunately it's just radio/phone buttons on steering wheel sometimes refuse to work until car has been power cycled, and not main functions of steering wheel)

-Car 2 handsfree (Pioneer aftermarket set.)  For phone use it's okay, main shortcoming being mostly the microphone that doesn't seem to be very sensitive. When trying to listen audio (podcasts, music etc - non-phone usage) from phone sometimes doesn't come through, and only way to fix this is to power cycle entire car (turning just radio off with power button isn't enough). Kinda weird that hands free doesn't seem to be affected by this issue.

-Previously mentioned Procaster BT-01 unit. In general it works quite well, and the main issue I have with it is that when the "battery empty" indication sounds, there really is maybe a minute left, making that warning pretty much useless. Since I'm primarily using them along with hearing protectors when doing noisy work, I'm seriously considering next hearing protectors to be ones with built-in bluetooth.

-Philips SHB5900 earbuds. In essence, earbuds connected by wire (that goes behind your neck) that has control and battery bulges in it. For what should be quality brand these are real disappointment. Battery/control pods are large and heavy enough so that they get caught on shirt collar, or pull earbuds off just with their weight so I have to be constantly re-seating the buds in my ears (granted, this happens more or less with all earbuds so my ears might not be best for them).
The bluetooth connectivity is pretty bad too. For some reason whenever I look directly left the audio completely drops out. Looking right isn't an issue. Where the phone is (right pocket, left pocket, backbag) doesn't seem to matter. Pretty annoying when biking.


Now, in general, the battery usage is the main issue. Smaller units (BT-01 and SHB5900) have some 4 hours battery life, some units even less. Depending on your usage that might not even last a full day (I certainly run out of battery way too often when doing some light work outside.)  While charging is relatively fast, it's still annoying if you have to do it constantly. Not that many people listen anything for entire day but some certainly do. And if you forget to charge the battery, next time you might have maybe hour left. This has happened to me many times, especially with BT-01, due to its longer nominal (possibly 6-ish hours) life. "I used it for just two hours, no need to charge" .. except that I didn't charge it last time either, and now there's less than hour left.

The second issue is actual connectivity. Philips is supposed to be one of the better brands but in this regard it sucks with audio constantly being interrupted momentarily. BT-01 seems to have somewhat better radio but even it staggers occasionally. Jabra - surprisingly, considering its age - seems to be best in this regard, I have only very rarely noticed any breaks in audio.
Car units don't seem to have this problem (maybe because phone and radio don't really move related to each other so link is more stable).


Then there is the audio quality with all kinds of codec combinations which I can pretty much ignore. When using these I'm pretty much never in situation that could be described "quiet listening" so slight degradation in audio quality is absolutely no issue. And I'm listening mostly podcasts and such anyway where quality loss isn't that noticeable.

On plus side, lack of wire is a good thing, especially when working. Until you run out of battery. Sometimes several times a day.

All in all, my verdict:
If you are what I'd call a serious listener (or even audiophile), there is no usable wireless headphone set. Quality loss and interruptions in audio are absolute no no.

For a physical worker - get rid of wires, now, and get a headphone set with big battery. Lack of wires that just get on your way is definite improvement.

For light use - occasional listening - wireless earphones are okay, but then there is the issue of keeping them charged. Forget once and suddenly you can't listen anything the next time. Depending on your habits the trade-off might be worth the risk.

And just to poke at this specific beehive;

Should you get a device that lacks headphone plug? That's easy: absolutely not. I feel that the cost introduced by headphone batteries, connectivity issues and audio quality is far too great for losing option of using any commonly available wired set. Wireless as an option is great. As an only option? Just no. (and no, converters/dongles in this context only add one fragile extra component to the mix. Connectors are already the weakest link (both proverbially and literally) and you want to add two more to the chain? Come on now.)

maanantai 17. lokakuuta 2016

Led-lamp post mortem


It was to happen sooner or later. First LED lamp we've used pretty much died. Not completely, but it started to turn on and off randomly (not exactly flickering as it kept on or off for longer periods) which was annoying enough so I took it off and replaced with a new one.

Here it is. No-name brand, but I've taken a habit of writing date and place of purchase on the lamps (well, LED and CFLs, you can see tails of text on glass at left) when I put them in use. The date on this was march 2013, so I got about three and half years of life out of it. Of course it's out of warranty by now.

I have no exact figure but I guess this might have been used maybe four hours a day in average, which would put it around 5000 hours or so total. Not exactly a great figure for a LED lamp, actually. However the actual figure might be double that, too, I really don't know for sure as I haven't really kept record of lighting usage at home.

 
Being a curious person with some time on his hands I decided to see what's inside.

First problem is of course how to open it. After some unsuccessful attempts with a knife (round objects like this and knife is kinda dangerous combination, one slip-up and there will be blood...) I put it in vice grip and just grabbed the glass (with thick gloves on, naturally) and twisted. Something gave - and it turned out to be transformer coil and plastic mounts inside. 


Although the glass and heat sink look and feel like plastic, they actually are glass (as I found out when I tried to twist it off - I survived that breakage without damage) and aluminum. The heat sink is anodized so just probing it with multimeter doesn't work (and your fingers should be safe when it's on, but I wouldn't touch it anyway when on), but if you scratch the oxidation layer off the bare metal is exposed)


The main board, with transformer placed in its usual position again. The "isolation slot" there is pretty much for show only, it doesn't really isolate anything; you can see leads going to led under the transformer coil there. Any high voltage isolation here happens purely inside the coil, and since I have no means to judge the construction I can't really say anything about that.

Although it is difficult to see from picture, the flux residue on board is pretty bad. There's nothing obvious that would explain its failure though. Caps haven't leaked or swollen either.

The chip in the middle is LNK613, which happens to be purpose-made CV/CC controller. Rest of the board (and LED board) are pretty much exactly the same as the example given in chip datasheet (no surprise there), and I didn't feel like analyzing it in detail so nothing more about that.


Led board (metallic for heat dissipation) has resistor, capacitor, diode and the LED itself. So simply the parts needed to be on the secondary side of transformer by example circuit.

So this is what you might find inside a four-year old LED bulb. Not the cheapest construction I've seen so far, but not the best either. At the moment I'm waiting one of the dimmable LED bulbs to burn out so I could see what they've eaten... Although I don't expect much more than this, maybe with just a slightly different chip in the center.




keskiviikko 12. lokakuuta 2016

About RF module selection (again)


Last time I mentioned working with WF121 WiFi module. This module is manufactured by BlueGiga (now owned by Silicon Labs) and costs around $17 at digi-key if you need just one. One might ask why I am using this module, instead of say, ESP8266-based module that costs maybe $7 at same vendor?

I've discussed about this in past posts already, but this is worth repeating, this time with a bit more concrete example, especially now with new related legislation (EU directives) in effect.

The short answer is: Declaration of Conformity. To sell your devices in Europe you have to be able to present one. And some categories - like devices dealing with RF - require fairly strict examination before that can be (honestly) produced. As you might guess that examination costs a lot.

I am making a specialized, relatively low volume product in Europe I plan to actually sell. The original R&TTE (Radio & Teleterminal Equipment directive, 1999/5/EC) already places quite strict requirements on radio equipment, and new RED (Radio Equipment Directive, 2014/53/EC) makes those even stricter.

Let's say the one device I make sells, say, 1000 units over its product lifetime.

If I use pre-certified module, I don't have to re-certify my design (RF functionality) as long as I use the module as-is, antenna and all included, so total cost of the module is $17 (actually less, after proper sourcing and volume discounts are in.)


If use use ESP8266 module that is not pre-certified (so far I haven't seen even single module that were certified in Europe, but feel free to correct me if you know one), I actually have to certify my entire design as radio equipment myself. This is not cheap process - let's say I get lucky and the cost of RF certification is about 20k€ ($22.3k with today's rate), but it might be even more.

Suddenly that cheap module costs $7 + ($22300 / 1000) = $29.30 !

Not so cheap anymore.

And that is why I pay a bit more for certified RF modules.While for example EMC/EMI examination is still needed, that is very cheap compared to RF stuff. And those I have to do anyway.

One might get away for a while for selling devices that only claim to have been certified, but especially with new marking rules of RED, you only need one person who checks your claims and you are in deep s**t. Trust me, you do not want to risk it.


On the other hand, if you are building a hobby project you do not intent to sell (or considering the ambiguity of the phrase used in directive, "bring to market", even freely give away in some cases), feel free to use the cheap modules, hobby use doesn't carry such requirements. But you still need to be sure that the $3 module from china isn't actually (un)intentional emitter (aka jammer) - people are not happy if you happen to mess with their frequencies and hobby use doesn't give you free pass there if you get caught.





maanantai 10. lokakuuta 2016

Embedded debugging fun


Sometimes I forget how difficult crash tracking and fixing can be. And for once I would be really happy to have a step-by-step debugger handy. Unfortunately, for this platform I don't.

So I have this simple struct:

struct struct_wf_settings {
    unsigned short magic;        // A3F0: structure valid
    unsigned char mode;          // 1=sta, 2=ap, other=undefined
    unsigned char ssid[4][32];   // ap:first is name; sta:associated SSIDs
    unsigned char ssidPw[4][32]; // passwords
    unsigned char bssid[4][6];   // MACs
};

As you can guess, this is to control external WLAN module, in this case WF121. 

I have written code is written so that it compiles for several different devices, including WiFi module evaluation board (PC as host via USB port) and embedded board I'm using (with ARM processor as host). It works perfectly when ran or PC, but on embedded side it fails in following part (some irrelevant code omitted for simplicity, some debug stuff added).

... 
if (addNewAp) {
  // checking pointer to struct; it is valid.
  debugWriteInt("wfSet=", (unsigned int)wfSettings); 
 
  // n is slot; 0-3. In this case 0 as this is first to be added (yes, that too was verified)
  // print address to ssidPw used. This is correct.
  debugWriteInt("ssid p adx=", (unsigned int)wfSettings->ssidPw[n]); 
 
  // store ssid (kept in temporary buffer, typed char[66])
  cmemcpy(wfSettings->ssid[n], wfConnectTempBuff, 32); 
  
  // store password; also in same temp buffer 
  cmemcpy(wfSettings->ssidPw[n], wfConnectTempBuff+33, 32);
 
  // store bssid from event sent by module
  cmemcpy(wfSettings->bssid[n], buff+6, 6);
 
  // signal change to main 
  wfEvent(WFE_SETTING_CHANGE, 0,0);
}
... 

This is part of "Access Point connected" event handler, where we're figuring out where we actually just connected. At this point we've figured out that this AP wasn't previously known, so we add it to our table of APs we can use in future.

This crashes on second cmemcpy (ssidPw). After some checking I found out that it fails because the target address is invalid. Except it's kinda-sorta correct - the lowest 24 bits of target address is exactly correct, but the highest bits of (32-bit) address are now 0x61, causing processor to segfault when trying to access (nonexistent) memory area.

What the f***?

I'm using custom "standard" library here, and cmemcpy (so named to avoid namespace clash) is simple while-loop that does nothing but copy source from target byte by byte. Nothing fancy, exotic or optimized in such a way that could do anything insidious, and there is nothing overflowing, and it already has been used for several years without any issues (and yes, I know I should also be using sizeof() on call, but copy size isn't the issue here)

Note that second debugWriteInt; it prints out address of ssidPw slot I want to use. Address there is correct. Just a few lines later it isn't anymore.

I even tried to dig through disassembly but since I am not sufficiently familiar with ARM assembly this was a bit of a dead end. Nothing very obviously wrong though, and specifically no mysterious 0x61000000 added to r0 anywhere. A reference to [sp, #20] kinda stumped me; I'm guessing it refers to n variable but it was "a bit" difficult to figure out so I gave up (oh, did I mention that this is compiled with -O2 ?)

Unless this is a compiler bug (and quick googling suggested that there have been somewhat similar issues in GCC 4.7-branch, although on x86), I'm at a loss here. I'm a bit apprehensive on upgrading the compiler as it might cause other issues elsewhere. The devil you know, you know...

Eventually I just moved the first cmemcpy to end of sequence, and not the code works correctly. Not the first time code rearrangement fixed things. But I can't shake the feeling that there is a ticking time bomb there still... So it works correctly, for now.

And I don't like it.




keskiviikko 5. lokakuuta 2016

Dead (cheap) monitor


Several years ago we got a cheap LG LCD monitor for one of the PCs. Now it died - wouldn't turn on no more. As this specific PC is pretty critical for our operations I immediately went and bought a new (also cheap-ish) monitor and just moved the old one to a corner, pending examination - either repair (not worth the trouble, really, considering the price and hours we already got out of it) or waste disposal (more likely).

Then, one day I had finished whatever I was doing and had some time until a customer dropped by. The time was long enough so I didn't feel like just browsing the net, but short enough that I didn't have time to start anything serious either. So I picked this monitor up to see if I could do something. I expected the reason to be the usual - dead capacitors.

The construction was typical; bezel was attached with nothing but clips, and I wasn't really that careful with them so unsurprisingly bezel was scratched at points. But it came off easily. It turned out that panel and electronics inside weren't attached to rear cover either - all the plastic just dropped off.


But wait, there's more! The main electronics cover wasn't attached to anything either - after taking covers off it, too, just lifted out! Well, after taking out backlight wires. Damn, this really is the cheapest construction I've seen yet. 



Insides of the electronics cover. Left is power board, and that tiny, about credit card-sized board is the actual driver board. I was expecting a paperback book-sized board so this came as a surprise.

There wasn't anything obviously broken either. The fuse (grey tube next to power connector) was ok and all the caps seemed fine so I was thinking what to do next when I ran out of time - the customer I was expecting arrived. Which also is the reason I don't have more (better) photos of it.

Considering the current value of this monitor (maybe few tens of euros in working condition) I decided it was not worth further troubleshooting and just quickly re-assembled it (carelessly, so all the parts aren't sitting right) until I could dispose it properly.







sunnuntai 2. lokakuuta 2016

Blown to high heavens


I just came up with this gif video which reminded me of something I heard once. No idea if this ever happened but it is a kinda fun and a bit educational story nevertheless.

Some road workers around here had their asphalt machine repaired. Specifically, the burner of the tank that holds the bitumen material before it is mixed to become asphalt. This is a pretty big tank, almost 10 qubic meters (or about 350cubic ft) in volume, typically full of very hot asphalt material. As you can guess, keeping this stuff hot takes a lot of energy and the burner that keeps is hot is quite powerful.

Now, this time, after the burner repair, someone decided to do a test run. With the tank completely empty.

Not a good idea. Just a few moments after the burner was turned on the tank lid brew off. No, it didn't blow open, it blew off. With nothing in the tank to absorb the massive amount of heat from the burner the air inside immediately became extremely hot, and thus, as physical laws dictate, grew in volume. With a lid on and closed the volume couldn't grow so pressure increased. And very shortly the pressure grew too large and the lid of the container very literally took off towards the sky.

They never found the place where the lid landed.



Or so the story says, at least.




torstai 29. syyskuuta 2016

Let's update some computers


Damn the windows update is a pain these days.

Some days ago I started update on a bit older windows 7 laptop that isn't used much these days. I started that around 9 AM, and according to notification the update scan finished around 10 PM. 13 friggin' hours just to check for updates! And that was just for three missed months of updates. Can't but wonder how many weeks a fresh install would take...

Well, at least that I wasn't using that laptop for anything during that time. Unlike a new windows 10 laptop I was using recently which suddenly started doing anniversary update install. In middle of game I just left there for a moment when I was doing something else. Fuck you very much, Microsoft. That is completely unacceptable default behavior.

Not only did it take ages to install that update, but of course it screwed up several settings I had to spend time to fix, but afterwards some idiot has chosen to force numerous unnecessary and unskippable "look what we just did, nyah nyah!" screens on the user. Talk about annoying crap.

Oh, and same happened to our office laptop too. In middle of work day, without any warning when we had work to do. In addition of usual fuck-ups update did, it also re-activated the PCMCIA slot of the laptop. Which was very deliberately disabled as it has some kind of conflict with network devices (both ethernet and WLAN). Didn't take long to fix but I would have had better things to do with my time. Did I remember say "fuck you Microsoft" already?

Day after day Linux systems start to look more and more inviting. At least "apt-get update && apt-get upgrade" doesn't take but a minute or so - and that's assuming that system isn't equipped with aptitude or such that does that for you with a single click.

Now, if only I figured out how to make applications that run also on windows (for my clients, I don't really expect them to switch to Linux anytime soon) from the linux computer...



sunnuntai 25. syyskuuta 2016

Almost lego


One fun part of traveling at tourist destinations is browsing through all the low-quality forgeries there is for sale. Although surprisingly sometimes stuff is fairly high quality - I still have few T-shirts I bought 10 years ago from Vietnam that are still in great condition (and damn comfortable too!), despite being worn weekly. Although those weren't really brand forgeries but with the usual "Good morning Vietnam" (etc) slogans.

But on latest vacation I spotted, among others, these. These were just the most offending ones; very close to actual Lego logo, down to the font, but still different, albeit just barely. Although I'm quite certain they don't really have license to star wars...


No, I didn't get any. Although it would've been a bit interesting to see how bad the part quality would've been.






sunnuntai 18. syyskuuta 2016

A short break


I've tried to keep up pace of two posts a week, but unfortunately I've been too busy with what you could call "real work" to be able to make more interesting posts. Even now I'm a bit short of good topics so you have to live with filler pieces like this.

And last two weeks were really dry. For that I do have an excuse; I was on vacation at Crete. And once again, the only bad part of traveling is the actual traveling - especially with small kids. At least this time it was relatively short flight...

 




tiistai 6. syyskuuta 2016

One simple tool that is constantly needed


It's Saturday evening when I sit at my summer cottage which is equipped with all comforts of a modern home; running (municipal) water, electric grid connection, fast (wireless) internet (although I could have 100/100 fiber installed here if I wanted (30km from nearest town and 100km from nearest city!) but it just isn't worth it for now.)  Isn't modern living just wonderful?

Yet there is one simple(ish) tool I seem to miss every time I come here but never remember to bring: A simple multimeter. Like with any older house there is always something that needs fixing here. Leaking pipe fitting or roof, failed electrical connection at outside buildings, fire alarm battery and whatnot. For most mechanical and wooden things I have tools (nothing fancy, just enough to do basic repairs), but every time I happen to need a multimeter I remember - again - that once again I forgot or dismissed the idea of getting one there.

Maybe one of these days I manage to get one here permanently. After all, cheapest usable ones cost just few tens of euros (the very cheapest ones have essentially no protections and could kill you - I don't touch them and suggest that you don't either). Not a very big investment for a tool I find myself needing again and again.

keskiviikko 31. elokuuta 2016

Export restrictions


For some reason I keep hitting this wall these days. Some time ago I encountered dual use-restrictions when ordering a common MCU, and now I ran into same issue when trying to order a equally common Bluetooth module. In case of Bluetooth this is (my educated guess) because it uses frequency hopping, which actually would be valid reason - if the module wouldn't be fully integrated consumer level device.

Like so many "anti-communist" and "anti-terror" things originating from US (and UK), this would be friggin' hilarious if it weren't actually making my life so much more difficult, forcing me to try to find local sources for such components. And at the same time these same countries (semi-)publicly ship advanced weapons systems to nations known for practicing terrorism. Talk about hypocrisy...

Oh well, US has been out of my list for "places I plan to visit someday" for years now (to be more exact, ever since surrendering to terrorism, in form of Patriot act and other similar anti-freedom legislations during last 15 or so years.)  This is very unfortunate, but as long as their government keeps being hostile to everyone (their own citizensconsumers included), I'll visit damn North Korea first - at least they seems more hospitable place to visit.

Not that NK is very high on my "places to visit first" list either, mind you.



sunnuntai 28. elokuuta 2016

A small problem with bike


So this is how you refill the infamous blinker fluid...


That blinker was pretty much ruined by water. Replacements were a bit difficult to find, at least without risking having blinkers with grossly different shades of orange, so eventually I just ordered completely new set. Now I'm just waiting them to arrive so I could replace them.

And of course that broken blinker means that I couldn't even drive for few weeks (without risking fines for missing lights or my life for cars missing my intents, that is.)




torstai 25. elokuuta 2016

A Linux laptop


Some time ago I had to dig a bit deeper into Bluetooth protocol to figure out the issue with another device not being to connect to ours (problem ended up being their SDP driver that failed if device didn't provide UUID16, so substandard implementation there, shame on them.)  Kali linux, being essentially a custom-made tool for all kinds of analyzing and testing of this kind, proved to be very useful as it comes loaded with tools to see in detail what happens with Bluetooth connections.

I had to use my laptop to run Kali from a live CD and doing that I came to conclusion that I would need a dedicated Linux computer from now on - live images, while very handy, are just way too slow and bothersome for normal use (and a brief experiment with virtualized system indicated that it was just too unreliable - USB Bluetooth modules just didn't work properly)

So I decided to go and get a cheap-ish laptop I could install Linux to for future use. However, when I started to go through list of cheap laptops available I ran into a problem: essentially every single one of them were listed of having issues either with WIFI or Bluetooth drivers, or worst, both. Considering that Bluetooth was pretty high on my "need to do that" list, this was unacceptable.

So I shelved the idea for some time.

Later, however, I took a look at the laptop I originally ran the Kali in - both WLAN and Bluetooth ran fine with it (laptop was old(ish) Asus X550 series, by the way.)  So... Why wouldn't I install Linux to that?

So, I walked in a shop, got another Laptop for Windows use, moved everything over and installed Linux Mint Cinnammon to older laptop. And now I have nicely working laptop for Linux and newer one for doing legacy stuff in Windows. As a bonus, Linux laptop actually has full disk encryption I can trust, unlike windows one that wants to upload my encryption keys to their servers...



sunnuntai 21. elokuuta 2016

Banks and passwords


The situation with banks and their outright horrible password policies never ceases to amaze me, especially when those policies control such a huge amount of money or even worse - peoples' identities. Granted, the situation here isn't as bad as some horror stories I have heard from the other side of the pond (read: mainly from US, where username-and-bad-password without any second factor of authentication seems to be way too common), but it's still annoying here too.

Take my bank, for example (no, I won't name it). They have user name (random string of letters and numbers they assign for you) and password you can choose yourself. And on top of that, there is one-time password from printed list that they send to me. In general, pretty safe system, as that one-time password prevents you from doing anything with just user/pass combination (including, somewhat unfortunately, many credit card purchases from local web shops - I don't carry that list with me so that's a bit of an annoyance, especially when making travel arrangements for work)

But back to passwords. My chosen password originally had 9 characters. The password page says that maximum length is 8 characters but either that isn't enforced or the policy changed since I picked it. Change might've been when they did major system overhaul at one point due to SEPA - which is damn great, I can send money to anyone within SEPA-area with literally zero cost!
 
This same overhaul brought ability to use paytrail for online shopping. It essentially allows you to pay directly from your bank account with direct transfer, which is pretty nice since not all people have credit cards. Here things went wrong however.

To pay with paytrail you have to provide enter your banking credentials along with one-time code during checkout process. And for some f'ed up reason this will fail horribly if your password has more than 8 characters. And not in a good way - my payment ended in some kind of limbo where I couldn't tell what had happened, except that payment failed. At bank's end all was good; on recipient end however I used significant discount code that was used up although payment eventually wasn't successful. It took some time to straighten things out. But I wasn't exactly happy about this, and figuring out why things failed took a while longer as password problem wasn't exactly apparent - payment just failed with no apparent reason. And I could use the same password to log in to bank itself with no problems.

Eventually someone could point out the reason and I changed the password to 8 characters, no problems since, but really now, this is friggin' 2016. 8-character password is nothing to most password cracking tools. I'd expect the banking system to allow longer passwords - even if the account is protected by the one-time code on top of that.

As a tangential side note, banking situation in US is simply astonishing to me. People are still using checks? Oh, I vaguely do remember my parents using those, back in 80s. Damn things have been antiques for some three decades now. For just about anything that doesn't need face-to-face interaction national bank transfers have been so easy and free (yes, completely free) for ages now (and now, with SEPA, that's for most of Europe.)  Absolutely no one expects for example rent to be paid with anything else than bank transfers. Cashier's checks however I have used a few times, for things like buying a house or a  car (carrying massive amount in cash doesn't feel exactly safe, never mind the funny feeling of having suitcase full of cash), but personal checks... Come on now, this is 21st century, not medieval times!



sunnuntai 14. elokuuta 2016

Blueprints, blueprints everywhere...


I've been playing a bit with Unreal Engine 4 lately, and while I appreciate the idea of Blueprints (which, in context, for those that unfamiliar with UE4, are essentially visual programs, with lines connecting them in sequence, different lines connecting inputs to parameters and to outputs and so on - google them yourself if you are interested), they - at least to me - seem to become horribly complex mess very quickly as program complexity grows.

You can of course use C++ with UE4 too, but it seems to me that that side is horrible neglected nowadays - documentation is out of date (supposedly latest document pages suggesting using already deprecated functions), there either are no examples at all, or they are too few and often too simple for anything past "hello world!"-equivalent and so on.

But then, after wasting a few days (well, evenings) building something that should be just about the simplest thing in existence I start to see why this might be the case. The C++ build environment seems to fragile as hell. Even with vast prior experience with C++ things just don't make sense (granted, that's usual first impression when encountering new, huge code base), and even most innocent looking change will blow up the code (with all the macros and UE4's own preprocessor magic) in unexpected ways, as well as making any compiler error listing full of stuff cause by said preprocessor magic. Combine this with the fact that almost all the examples are worthless videos (give me properly explained text with code snippets any day!) where I can tell the "tutor" obviously doesn't really have a clue what he is doing ... Well, it gets frustrating very quickly.

Just recently Epic announced that UE4 apparently has something like 1,5 million developers. I have no idea how they calculate that number, but I suspect that vast majority of these developers never really do anything with it - people in schools, or who want to play with it for a while and so on. I am quite certain that huge number of those never get past the first hurdle of starting with C++ code.

No wonder people won't even try and go to blueprints.

With all that said, I don't plan giving up. Persistence manages. Eventually. And after grasping the ... quirks ... of the environment it very likely will get easier and I can start focusing on the real code.




torstai 11. elokuuta 2016

Some thoughts on world wars


I've been listening to Dan Carlin's WWI podcasts lately (Hardcore history; Blueprint for Armageddon) and it is quite fascinating. I get that he is no historian so those proverbial grains of salt are needed, but I'm even less historian (I've grown fond of historical topics only recently) so I am just accepting that his interpretation is fairly close to real events.

What has grown to bother me is how the initial setup of the war is described. There had not been a war between major powers since Napoleon's era - 100 years or so. There had been smaller conflicts - Russo-Japanese war (I'm typing these out from oral memory so there might be transliteration errors involved here) and Krimm war for example - but there had not been any wars between major powers for a long time.

Over that time killing power of technology had increased a lot - way, way more than people (including generals and other leaders) really expected. Machine guns and artillery were now a serious powers, but since they had not been used against opponents with similar capabilities their power was severely underestimated and the end result is that military leaders were forced to learn what was new as they went on - often by sacrificing thousands or tens of thousands of men for nothing but a lesson of 'that didn't work.'

Now, my speculation starts. Fast forward to this day. There has not been a major war between major powers since WWII. There has been many smaller conflicts, but most have been local or quite one-sided and wars generally are limited in nature. And technology has progressed massively.

Since no major wars have been fought lately, especially not total wars, so we do not really know what the capabilities there are exactly. Does this situation remind you of one world has already experienced, like the pre-WWI scenario above?

Granted, so far I don't see current situation as a powder keg like Europe was back then - I think that we've learned something and no one really wants that kind of war. Wait, no, I take that back - there are people who really do want that war to happen - they're ones that would supply either one or both or all sides with weapons - but they are minority (hopefully) and thus don't have that much power (hopefully) and so they don't get their way (again, hopefully). Unfortunately these people have lots of (bought and paid for) political power so it might not be that simple...

But still, this thought is enough to make me feel uneasy. Possibility is there, lurking in depths of political disagreements. Religion certainly is playing a role too there, but that at the moment it is restricted to "not a major power" status so I don't expect real war from there. And given mentioned technological advances, I really, really do not want to see how that war would be fought...




sunnuntai 7. elokuuta 2016

File save safety: the reason


Some time ago I wrote about saving a file in a way which wouldn't lose previously saved data if saving fails. I said that I don't know what actually happened to the phone then; everything behaved like disk was full but df indicated it wasn't; I still had about 3GB free on internal storage.

Well, yesterday it happened again, and I got message about it mentioning app registry. That was enough for me to chase the rabbit down the hole in search for answers. As it turns out, Jolla phone uses btrfs as main file system, and it seems that btrfs is .. fragile .. whenever disk gets more than halfway full (and getting catastrophically worse when getting nearer to full), especially when dealing with small-ish devices (like 16GB Jolla has as internal storage). Typical tools, like df - indicate plenty of space available but btrfs has its own internal mechanism for allocation and disk actually is "full", resulting inability to write new files. Well, fsck.

So, not exactly great choice for phone storage, as people tend to have their devices full of all kinds of things. No idea why that was chosen, really, as I haven't seen any explanation for that. But at least there is microSD slot that can be used as storage for media, which tends to be the biggest consumer of space anyway.

Fortunately there are tools to mitigate the situation (btrfs-balancer and others) already installed on phone. Unfortunately those need things to be done from command line. While Jolla has terminal built in, the problem is that I don't expect most people to be able to do that. Or even be willing to do that, really.

I guess there is some very good feature in btrfs that is the reason for developers choosing it over more typical filesystems, but at this point it would have to be some mind-blowingly great reason to counter failure of this kind. Not cool, Jolla devs, not cool at all.




torstai 4. elokuuta 2016

Should I invest in solar panels?


To be short, Betteridge's law of headlines says very explicitly: No. But damn if they don't it sound tempting.

And despite previous post critisizing current renewable energy situation I still feel very tempted. If, for nothing else then for my own curiosity's sake.

But to expand a bit, I have a summer home, with running municipal water. Since it gets very cold here in winters this means that I need to spend a lot of electricity to heat the cottage even when I'm not there - emptying the water system is pretty much impossible. This being a bit remote location means that this isn't cheap.

My dad however has been encouraging me to get a few panels, 5 or so maybe, to aid with heating there. I'm guessing he'd like to have few panels of his own, too, in same order. The problem is that I've done the math and it doesn't look good.

The main problem is insolation. The word essentially means the amount of solar energy that reaches the ground. I don't have the hard numbers of insolation around here ("here" being close to 65 degrees northern latitude), but I do have numbes for Helsinki (60 degrees north). Up here the numbers are certainly even worse. Unfortunately I don't know how much worse exactly but I've assumed 60% of Helsinki figures in calculations below during the darkest time of the year.

Assuming six panels, 0.91m², each with 140W nominal power the numbers come out as follows:

October: 379 kWh total over month
November: 89 kWh
December: 8.5 kWh (total over the entire month!)
January:  38 kWh
February: 255 kWh
March: 742 kWh

In other words, during the darkest and coldest period of the year the production is practically nothing. But for other months the figures start to look a bit better - during spring and fall there should be enough power to cover at least some of the heating - at least during sunny days.

During summer there is no need heating so savings there are close to zero, aside water heating (granted, that takes a fair bit of energy) and possibly refrigerator (no idea how well it would work during nights as sun doesn't really fully settle).

Now to the main problem again: energy storage. Grid-tie system is completely insane option here - I'd end up paying for each kWh I provide to the grid. So that's out immediately (and that isn't storage anyway, from broader perspective, it's just externalizing the storage problem to someone else).

Battery storage doesn't really make much sense in this situation either; a battery or a few could store enough energy for lights but not much else. So having batteries isn't actually worth the cost or trouble. But at least that would cut off one expensive part (batteries) from the system.

So let's say that I just use panels with inverter connected directly to them. Then there is the problem with brown-outs: I have no idea how inverter would work when usage is greater than what panels can provide. Not well, I fear. I've tried to find out that behavior conveniently seems to be left out from easily available documents.

On the other hand, at summer panels could provide more than 2000 kWh per month. The question is, then, what could I do with all that power. And unfortunately answer is pretty resounding "nothing". Some of that energy I could use when I'm there, but the remaining would pretty much go to waste, short of some ingenious personal fuel refinery gadget (no, those don't exist but man can dream, right?)

But still... It'd be a fun experiment, anyway, even if it wouldn't make any real economical sense.

And yes, I do realize that situation here is completely different than in south where air conditioning is major power hog. For that solar, even now, makes perfect sense. But even then there's still those 12 hours per day there without any solar power...



sunnuntai 31. heinäkuuta 2016

Writing a file, with a bit more safety


When you're writing out, say, a current software state to file (be it save of a game, or status of a map program, or current audiobook locations), you may want to be sure that the old data is overwritten only if storing new data was successful. Your user might not be very happy that, say, location data is invalid and unfixable (due to failed map settings store), or that all locations of audiobooks and podcasts are forgotten (unfortunately latter isn't my software so I can't but request author to fix it, but alas, no activity for ages...).

Like the link above may tell you, this concerns mostly Sailfish OS and thus Qt toolkit, but same principles apply for other systems too. Some systems however make this very, very difficult as actual implementation is very carefully hidden from you and may or may not be robust enough to do this for you.

Previously, due to simple laziness, I stored settings somewhat like this:

    QString file = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/config";
    QFile f(file);
    f.open(QIODevice::WriteOnly);
    QDataStream stream(&f);
    stream.setVersion(QDataStream::Qt_5_0);

    stream << data;
    // ...
    stream << lastData;

No close; since this is C++ this will be done automatically when function goes out of scope.

However, this will fail horribly if there is a problem, like running out of disk space or something else going wrong, and you may end up with zero-length file. And surprise surprise, something did go wrong today and I lost my map halfway through 30-mile biking trek, in middle of area I hadn't visited before. Just frickin' great.

What exactly happened with phone, I don't know. Some apps started behaving very weirdly. Eventually I restarted the phone which fixed most of the issue, but corrupted settings caused a bit more grief.

But this was sufficient motivation to fix the issue, hopefully once and for all.

To fix this, the change is relatively tiny:

    QString file = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/config.tmp";
    // ...
    stream << lastData;

    bool stastusOk = false;
    if (stream.status() == QDataStream::Ok) {
        statusOk = true;
    }

    f.close();

    if (statusOk) {
        file = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/config";
        QFile f2(file);
        if (f2.exists())
            f2.remove();

        f.rename(file);
    }

So, initially we create a temporary file where data is stored; once we know that the data was written successfully, that file is moved to replace the original file. Unfortunately Qt does not have function to "rename and delete target if it exists" so we have to add that extra part with f2 there. If rename then fails, this does all kinds of nasty things, but that, hopefully, will not happen. Of course you can check also the .tmp file on load if you are that paranoid (or just write alternatingly to two or three files, checking newest on load); I trust above to be sufficient. Until proven wrong, of course.

The documentation is not exactly clear whether stream status is available after closing the file, or if closing is needed, so I err'd on the side of caution as I didn't feel like experimenting.

Ignoring the details, the priciple is same for other systems too. First write temporary data, then copy over to replace original. This way the changes of data loss and corruption are minimized. If you want to get really paranoid a data checksum can also be thrown in for good measure.



torstai 28. heinäkuuta 2016

Green Energy: Somebody Else's Problem


Now, I know this is a pretty large wall of (possibly somewhat incoherent, due to few rounds of re-writing and editing) text, and you might - due to various reasons - find this difficult or off-putting to read. In that case, please skip to the very end and read just the last two chapters. I've tried to sum all this up there, hopefully in easier-to-read fastion.

Recently I saw an article about how environmental organizations declare that Sweden could fully be powered by renewable energy sources by 2020. Renewables in this context typically means pretty much solar and wind, with some hydroelectric and maybe some other other sources (biomass and whatnot) thrown in, but majority would be from those two mentioned first. And I consider this kind of thinking pretty damn dangerous, at best.

I'm certainly rooting for renewables but when something like this is said, I want to see a plan. A real plan, with details on how the required amount of energy is generated, day by day. But of course they can't provide such a plan - when ambitious claim like this is made, people behind it look at two numbers: kilowatt-hours used in a country over a year, and number of kilowatt-hours generated. And why not - by ignoring the fact that energy storage is at the moment unsolved problem these claims can be made without being completely dishonest.

See, the problem with wind and solar is that they do not provide constant about of energy. The consumption of energy, however, is relatively constant and predictable. I'm more familiar with Finland's numbers so I'll use those here instead, but Sweden's numbers should be fairly similar.

Take this figure below (I think I've used this same figure in previous post). This is from the first week of this year which was quite a cold one. And dark one, mind you - solar production is essentially zero during the winter months here, due to northern location.

The red graph is total electricity consumption. You can see that energy consumption spikes during the days and is at lowest during nights, difference here being almost 2000MW. This same day/night variance is there, every day of the year, only in summers the difference is smaller, about 1000MW.

The black graph is domestic energy production. You may notice how it is way below usage graph. This, too, is these days fairly constant (unfortunately, I might add), only the amount of deficit varies. At the moment there is not enough domestic production so we import a lot of energy from Norway (mostly hydro) and Russia (who knows how that is produced, nuclear and coal very likely).

So here we have clear pattern; energy usage is relatively constant, with some day/night variation. And we can see the consumption here rising because it was cold that week, getting colder by the day. Heating takes a lot of energy.


Here is then wind production graph from the same period. Can you spot the problem already?

Oh, by the way, this data is directly from FinGrid, who manages the Finland's energy grid and thus is very well aware of what is being used and produced - and where.


The problem is that it's highly variable. Ignore the fact that there's just 600MW produced at peak; if we scale the total wind power production up ten or twenty times, we get a graph with maximum number of 6000 or 12000MW, but the zero point doesn't move. Graph will still have roughly the same shape (remember, this is entire country's wind generation, not just some small area; although not all windmills are included so there is some extrapolating included by data provider)

During that time period the wind power consumption was below 200MW until 11th day (with minimum hovering at about 100MW for about two days and in the middle of that period, on single day - 8th - it reached about 300MW in between), rising to about 600MW after that (for few days at least). So during the coldest, most power-hungry period of the year we have five days with less than third of maximum generation from wind and practically nothing from solar.

I don't know about you but in my book this is a major problem here. Do think about this:
Finland's maximum power usage there was (and is) about that 15000MW. About 2100MW of that is from hydro right now, and there really isn't any practical way to build more of that. Industry (paper mills for example) produces about 1100MW, let's assume that remains about constant. How much solar and wind you would need to realisticly cover that difference?

Now, this peak is always during the darkest, coldest time of the year, so unless there is ridiculous amount of solar the winter production is approximately nothing

And you do have to expect long dry spells with wind, like you see above; only about one sixth of peak power. Yeah, the figures will not be pretty. Either we'll be overproducing at crazy amounts at
times with no way to actually use it all (short of some methods of producing, say, hydrogen for fuel - again something that isn't realistic in near term), or we'd be badly short. Not good either way.

Energy storage? Okay, show me the storage system that can handle, let's day, full three days of shortage of "just" constant 3000MW. If you can point me to that kind of system, please show me, I'll really want to be proven wrong here! Electric cars are out immediately - people won't be happy if their cars will drain their batteries to the grid on the first day, never being able to recharge before full supply returns three days later, so it needs to be something else.
But let's look at larger scale yet. After all, we're next to Sweden (which was originally mentioned here), with their own presumably fully renewable grid. And their power situation is about as sorry as ours - no solar, almost no wind (due to geographical location right next to us, weather locally is fairly similar), just the hydro. So they need to import energy too! (or you know, they, too, would have had massively overbuilt wind, with same issues with variance mentioned above)

Norway (next to Sweden) has vast amounts of hydro, but even that has limits - they only can export that much before they, too, would be short. Certainly not enough for both Sweden and Finland. And there is also limit on how much international grid connections can transfer energy.

Russia then? Both Finland and Sweden would be importing energy from there (Sweden doesn't have land border so they would be connected through Finland's grid), and some from south, Estonia or Denmark and their grid with continental Europe connections. And when you go past national boundaries you really don't know how the energy is produced - in this case it very well could be mostly coal, imported from a country that doesn't care. Nasty, dirty, CO2-spewing coal. There goes any claims anyone could have about "green" energy. But apparently that CO2 doesn't count as it isn't produced here - despite the reason of those emissions very clearly is here.

Funnily enough, I've been told that this is the exact situation in Germany now: By shutting down their nuclear plants they can claim to be green, but in reality, just over the border in Poland there's lots of coal plants that feed the Germany's need for electricity when green sources happen to have shortages. I haven't verified if this is true, but at this point, considering above points about problems with wind and solar, it is way too plausible to ignore. I don't know about you, but I'll take nuclear power any day over horribly dirty coal.

Now, I deliberately have kept this speculation in very near future because that can be predicted somewhat easily, being just few years away. If we go past that, there might be actually viable energy storage methods used which can help out a bit. But I have some serious trouble imagining energy storages capable of even mentioned 3000MW output over even two days, which is something that would be needed when relying on wind and solar as much as green energy enthusiasts' want us to. And in countries with larger population this figure would need to be massively higher.

In the end, by externalizing the power production you only make it somebody else's problem. And how clean or dirty that production is, is pretty much out of your control. So much for the (near-term) green dependency. Short of some major - no, huge - energy density breakthroughs, it ain't happening.

So now the TL;DR:

Now, make no mistake, I am absolutely positive that we have to make serious and even drastic reductions to the CO2 output in global level. The problem here is that current actions that are being taken are proverbially making us jump out of the frying pan and into the fire. By making the easy choices - that is, building solar and wind - we must satisfy the highly varying production levels somehow as the electricity usage is fairly constant. "Smart grid" can only do so much before reduction options there run out. Add the fact that people want to shut down nuclear power - which is currently our best way to reduce dependency on coal and other fossil fuels - and end result is that we collectively end up producing more CO2, despite all the gloating articles how some country went on a full day using renewables. Just single day you say? Well, let me see the figures for the remaining of the year then.

Really, the path we have currently taken is not a dependable way forward. 



sunnuntai 24. heinäkuuta 2016

How many PCB layers?


One of the first decisions you need to do when starting a board design is number of layers you want to use. Many simple jobs can be done with just single layer, and for DIY milling/etching that might be the easiest way. However, since you can get professionally manufactured 2-layer boards for next to nothing (link as an example, there are others), I don't even bother myself anymore.

For many purposes 2 layers is sufficient so you might not need to go higher than that. However, there is a point where designing PCB with two layers is just too much of a trouble. Maybe there are too many traces, maybe ground and power planes (well, traces) get too broken, maybe you just want to pack lots of components on a small board, maybe you want to to that nice chip with fine-pitch BGA package with lots of balls.

Next option is 4-layer board with vias fully through the board. The good thing is that you can do a lot with this setup, and this is still easily available, even for prototyping (itead, linked above, takes about $10 for 2-layer 5x5cm board; 4 layers is $65. More expensive certainly, but not that much really).

At some point even that gets too difficult, especially if you have components on both sides of the board, so you may want to go for blind or buried vias. They're great - you can have a via from layer 1 to 2, and another via (with other signal) from layer 3 to 4, at exactly same location! Imagine how much more you can fit on a board with these!

Unfortunately they come with a cost, in this case literally. For prototyping there aren't that many PCB manufacturers who want to make them, and cost can easily jump to $200+ range (and that's the cheap end) for just a few boards. That might be a bit too much for you, especially since you may need several iterations (each costing that $200) to work out issues of design.

The good thing is, however, that if you are looking for even moderate production runs (let's say 100+ units), the actual production cost difference is tiny. If 2-layer board costs, say, $4, the 4-layer with blind vias might just be $8 (with initial costs included). And with larger runs the difference gets even smaller.

And even better, going to 6 or 8 layers just barely increases the production cost. Initial costs are even higher, yes, but per board the increase might actually be very small. So, unless you are planning to do only a few boards, there really isn't any reason not to go for blind vias if they make your life easier.

So what to do if you eventually want a 4-layer board but don't want to waste too much money prototyping? One option is to make larger board initially: Say you want your final board to be 5x10 cm. You first design a two-layer board with size of 10x20cm. No need to even have all the traces there - if some signal is too difficult to route you just replace it with pads at each end and connect it with a wire. That's good enough for testing the initial design, as long as you pay attention to high-current and high-frequency traces between board parts.

Then, when you design works well enough, you can scratch the prototype PCB design and start over with different board structure, moving components to their final (or close to final) posititions, change board type and start routing it again. Yes, this adds lots of work, and must be done very carefully to avoid routing mistakes when essentially re-doing entire board, but if your monetary budget is tight but work time cheap-ish (as it often is with hobby-type projects), it just might be worth the effort.



perjantai 22. heinäkuuta 2016

Another broken tablet


Some time ago I got another new Android tablet - this time just about the cheapest one I could find with sensible specifications. This was essentially meant to be plaything for our kid so I didn't want to invest too much money as I expected it to be treated badly. So I ended up with Acer Iconia One. From start I could tell that the build quality wasn't exactly great - it felt flimsy and plasticy, in short pretty much what you'd expect from cheap device.

Well, it took about two weeks until it broke the first time. Unfortunately this happened at Thailand, in middle of our two-week stay. I have absolutely no idea what happened it but display suddenly started to show some very serious "ghosting" symptoms and became very dark. Even after full power-off and even factory reset it showed traces of image shown before these. Very weird. At home I took it back and it was replaced for warranty. No problems with that since.

Now it stopped charging completely. The USB port showed signs of bad contact already before this, but now it became completely dead. So I took a closer look:


Again, through microscope with phone camera so bad quality, but I'm pretty sure you can tell that this is one unhappy USB connector. No wonder it's dead.

I suspect that this would not be covered by warranty so I didn't even bother but took it apart. Insides weren't surprising - one PCB, battery, display with touch, speakers, cameras, microphone and that's just about it. PCBs have become smaller since the last time I opened one but all the major parts are there still.


Start from top left and proceeding down and right the connectors are: Display, touch, cameras (two of them, one facing front, one back), Micro-SD, buttons (four buttons, but only three of them are exposed outside enclosure), battery, headphone and the USB.

Bottom side is fully covered with tape (no components at all), to avoid shorts as this is placed directly on top of display module. There is combined GPS/WiFi antenna on the back cover, connected via the connectors you can see there above the audio jack.

Speakers and microphone were soldered on pads; those you can see at lower left and right side of board. Cheap, cheap...

Underneath leftmost can (which ended next to camera connectors) there was mystery BGA chip with marking 8539 (left to Flash chip on picture) I couldn't find any information about, and then there is a switching regulator - very likely to drive display backlight.

Underneath next can were Hynix Flash chip, two memory chips, Mediatek ARM processor (next to memories) and Mediatek MT6323 which appears to be power management IC.

Last can I didn't open, I expect radio to be there. So in all nothing too exciting, and really - this is pretty much what every phone or tablet has these days. More expensive devices use just a larger memory that costs few dollars (!!) more, and/on few dollars more expensive processor with a bit better specs. Maybe a bit better camera and more refined build quality.

I just can't but wonder how much of the "cheap" external feel of this is actually very deliberately planned and designed to encourage shopper to go for a bit more expensive model with "better" feel, with exactly same parts inside...

But back to the USB.

Surprisingly the USB connector was a bit sturdier than most I've seen in these devices - this actually has through-hole pins that hold it on the PCB better. Unfortunately I didn't have exactly the same connector handy, but I had one close enough to work. But first, taking the old one off.

Hint: If you have trouble desoldering lead-free solder apply some new leaded solder there first. This will bring the melting point of combined solder down a bit, making the process a bit easier. This makes especially the ground pins in middle of large ground planes so much easier to desolder cleanly.

I first wicked most of the solder away from the through holes with desoldering braid, then used hot air (at 350 degrees C) to melt solder enough to allow connector to be lifted out. After that I cleaned the holes and pads as well as I could:


The mounting hole pitch wasn't the same with new connector, so I straightened rear ground pins and then cut the one pointing towards audio connector shorter, as the partially desoldered pin you see there, middle one, right next to USB pin, is not ground but some other signal. I wouldn't want to short that out.

The small chip you see there next to USB pads is very likely some common mode filter to reduce interference. It's placed uncomfortably close to USB, making soldering the pins difficult, but with some flux, patience, steady hand and thin solder tip I managed. Not the prettiest job I've done but it works, and hopefully lasts a bit longer than the previous connector. I deliberately went a bit overboard with solder on ground pins; more solder should make the mechanical connection there a bit more harder the break with stress.


And now I have a working tablet again, with just about a hour of work.