Gauging button bounce on an #esp32 using atlast forth

I thought I’d try to get some kind of handle as to how much a button is bouncing around. Here’s the code:

23 input_pullup pinm
variable count
: ++ dup @ 1+ swap ! ;
: 0count 0 count ! ;
: igo 23 digr v0 @ <> if count ++   1 v0 @ - v0 ! then ;
: go 0count begin  igo     key? until count @ . ;
go

It counts the number of times the value of the button on pin 23 changes. Enter “go” on the serial port, press the button down, then release. Then hit the Return key to stop the loop and obtain a count of the number of times a change had been detected.

Most of the time it prints the value 2, which is the expected answer. Occasionally it will print 4 or 8. The highest value it reached was 10. So although my switch is pretty good, debouncing is still necessary.

 

Advertisements
Posted in Uncategorized | Leave a comment

#atlast #forthlang vs #micropython speed test on #esp32

A week or so ago I started out porting John Walker’s public domain Atlast Forth over to the Arduino. The code is highly portable, so who knows, maybe I’d get something going for the Uno, and maybe even the ATTiny85. Maybe.

I thought I’d do a little speed comparison to see if Atlast had any point at all to it. Micropython is an excellent and mature platform for microcontrollers, and is vastly superior to my own humble effort.

Anyway, do the speed test is to read a pin 20 times in a row and see how long it took.

The code on Micropython:

def fn():
    for i in range(20):
        switch.value()

That took 845us (microseconds).

Here’s the equivalent code using atlast:

: t 20 0 do 23 digr drop loop ;

Here’s the timing function:

: u usecs t usecs swap - . ;

That took 29us.

Wow.

Although my Forth is immature, and is quite inefficient in how it works, I am very happy about its speed relative to Micropython. So who knows, maybe it can add some value when Micropython is proving just a little too slow to be usable.

Happy programming.

Posted in Uncategorized | Leave a comment

Solving the #perl weekly challenge 6 in #racketlang

Seeings as I was playing with P6 (perl6), I thought I’d have a crack at the Perl Weekly Challenge #6. Here’s a recap of the first challenge:

Create a script which takes a list of numbers from command line and print the same in the compact form. For example, if you pass “1,2,3,4,9,10,14,15,16” then it should print the compact form like “1-4,9,10,14-16”.

I tried doing it in P6, but ran into a number of problems. In one attempt, I tried laying down delimiting markers. But P6 didn’t really seem to want to split my array the way I wanted. I also had problems creating arrays of arrays. Another odd problem was that P6 seemed to think that some of my arrays were read-only when I used them in curly braces. I found that to be totally unexpected. What also surprised me is that there does not seem to be a way to intersperse a value between elements in an array. It must exist, surely?

I am new to P6, of course, but the challenge gave me more difficulty than I expected. I eventually gave up on the P6 implementation, and switched to Racket:

#lang racket

(require srfi/13)

(define inputs '(1 2 3 4 9 10 14 15 16 18))

(define marked
  (let loop ((curr '()) (acc '()) (inputs inputs) (prev +inf.f))
    (if (empty? inputs)
        (cons curr acc)
        (let* ((el (car inputs))
               (rem (cdr inputs)))
          (if (empty? curr)
              (loop (cons el el) acc rem el)
              (if (= el (+ 1 prev))
                  (loop (cons (car curr) el) acc rem el)
                  (loop (cons el el) (cons curr acc) rem el)))))))                       

(define seqs
  (map (lambda (x)
         (let* ((el1 (car x))
                (el2 (cdr x))
                (diff (- el2 el1)))
           (case diff
             ((0) (number->string el1))
             ((1) (format "~a,~a" el1 el2))
             (else (format "~a-~a" el1 el2)))))
       marked))

(string-concatenate (add-between (reverse seqs) ","))                                           

I am not expert on Scheme, but at least I found a solution. I wonder what other solutions are like.

It is entirely possible that a P6 implementation would look a lot better than a Scheme implementation. I tend to dislike recursive constructs, but I think that in the case of the challenge presented, recursion works well. If I were to attempt a P6 implementation again, I think I would try to “transpile” the Scheme version.

I am not saying that Scheme is better, but forcing me to write in a recursive style seemed to make me uncover a correct solution. From what I can gather, P6 does not support TCO (Tail Call Optimisation), so it’s likely to be a memory hog on large arrays.

Posted in Uncategorized | Leave a comment

Accounts package in #perl6

I have written various accounts packages over the years using Haskell, Lisp, Python, Golang, Forth, C++, amongst others. The largest code-base  I had was approaching 4000 lines of code, and had such features as downloading share prices.

With the disappearance of good stock price sources, I decided it was time to ditch my current software and see if I could create something minimalistic, and more in tune with the UNIX philosophy.

After a few attempts, I eventually settled on a perl 5 script that I created that weighed in at 117 lines of code. It is able to prepare a set of accounts, show entries with running balances for an account of choice, creates a portfolio suitable for loading into Stockopedia, and even a file for uploading into CGTcalculator, which computes capital gains on a stock portfolio.

The code does, of course, keep things really simple. The input data files are text files of “commands”, which can be handily placed under version control. The trick to getting the code down to 117 lines is to use a high-level programming language, producing only the stuff you need, none of the stuff you don’t, and paring down your requirements.

In the past, I have toyed with the hugely popular wiegley ledger, which is also a plain text accounting system. I don’t recall how large the code base is, but I would imagine it is easily over 10k lines of code. GNUcash would dwarf even that. These programs do not play well with the UNIX pipeline, either, so I can’t really use them as pre- or post- processors.

My knowledge of perl 5 is near zero, as is my knowldege of perl 6. I had been interested in P6 a couple of years ago, but never stuck with it. I saw a few YouTube videos on P6 recently, and it sparked my interest again. I wondered if it was possible to rewrite my P5 proggie in P6.

After a few hours spread over a few days, I managed to get it working. Fortunately, P6 is starting to appear in repos like Ubuntu, which eliminates at least one barrier to entry. My finished programmed weighed in at 91 lines, and performs the same functions. That’s a 22% saving in code, or, put another way, my original code was 28% longer. I’m quite chuffed with that; a usable program in under 100 lines of code.

There’s some nice little touches in P6. One feature I particularly like is the “.” operator, which allows you to chain computations. This seems like a very natural way of doing things. You don’t have to introduce variables, and the sequence of expressions flow from left to right.

The gather/take command is rather handy, too. It allows you to generate multiple values to be be collected (gather’ed) over each loop.

Very nice.

P6 is rather sluggish, mind. I see this as a huge off-putting factor to most developers. My original P5 code took 0.051s (real time) to execute. The P6 code took 1.019s, which is around 20X as long. Oh well.

Also worth mentioning is that the last time I looked, it didn’t have a Windows 32-bit version. I dare say that the situation hasn’t changed. I am using Linux currently, and I may be disappointed if I have to move back to Windows. I do not have a 64-bit version of Windows.

It was fun working in P6, and I think it is likely that I will use it in other projects.

Update 05-May-2019: For those wanting to see the code for both P5 and P6, a gist is available. I hesitate to post, because both it and the underlying file format is undocumented. It also has a number of features that will not be of interest to anyone else. Most people won’t be interested in the portfolio feature, either. If all these extraneous features were stripped away, then an accounting package would only require about a dozen lines of code.

I noticed that I could perform a neat little reduction in my P6 code. Here:

my $qty-text = %qtys.map({sprintf("%-10s   %5d", .key, .value) }).sort.join("\n");
spurt('out/qty1.txt', $qty-text);

makes use of an intermediate variable. We can eliminate it using perl’s pipelining operator:

%qtys.map({sprintf("%-10s   %5d", .key, .value) }).sort.join("\n") ==> spurt('out/qty1.txt');

This is very neat feature of Perl 6 indeed. It seems to have an automatic currying feature. In fact, anonymous functions seem to feature heavily in P6, and are simply written in curly braces. There’s no need for declarations like

(lambda (x y) (whatever ...))

that you would have in Scheme/Python. This makes the code quite compact, and cuts out a lot of visual clutter.

Perl 6 clearly works hard to be a DWIM (Do What I Mean) language.

Posted in Uncategorized | 2 Comments

#vim: going plug-in free

I once read an article titled Stop the Vim Configuration Madness , where the user advocates avoiding plugins. I have read a number of similar articles.

Since then, I have disabled syntax highlighting, backing-up of files, and a couple of other tweaks. Actually, the suggestion of turning off syntax highlighting turned out to be a good one. I have always felt discontent with highlighting schemes. There is always something wrong with them. Usually is is comments or strings that are bad.

Having disabled syntax highlighting for over a year now, I can honestly say that I I prefer non-highlighting.

The only plug-in I had installed is “emmet”, which does some html insertions. I have recently written a script that obviates the need for it.

I basically do two things when I am writing html: have a nice layout for header level two, and creating links in lists.

Here’s what I do now:

In .vimrc, add the line:

command H :r! hh

The H is just my mnemonic for “html”, which I can call up by tyong

:H

What his does is call a script that I’ve written called “hh”, which does the donkey-work. Here’s the script:

#!/usr/bin/env bash

# helper for the H vim command
read cmd
case “$cmd” in
2) read title ; echo -e “<hr><h2>$title</h2>\n” ;;
lia) read link ; read desc ; echo -e “<li><a href=\”$link\”>$desc</a></li>” ;;
esac

So, you call up H, and then enter a command. I chose “2” to represent a heading of level 2., and “lia” to create a link. “lia” is the most complicated one, so I’ll describe how it works:

  1. You type in “lia”, then return
  2. Type in the link, then return
  3. Type in a description, then return

The script then echos an appropriate <li> <a> combo. The “:r!” command in vi takes the output from the script and places it in the buffer. Fantastic.

No doubt the script will grow as I place more demands on it.

The reason that I want to get rid of all plugins is that I often work on different machines and experiment with different Linux setups. I am growing tired of having to install plugins. So now I am determined to go plugin-free.

I’d like to share one final great little mapping that I have:

map <F7> mzgg=G`z

This reformats the whole of the file with proper indentation for the file type.

I think that we should remind ourselves that vim is not emacs, and they have, or ought to have, different philosophies. Emacs is “maximal”, where you set things up your own way. Vim ought to be “minimal”, where you don’t do things your way, you do them the vim way.

 

Posted in Uncategorized | Leave a comment

The markets

Morningstar reported yesterday that it was the worst year for the FTSE100 since 2008. The index was down 12.5% over the year, starting at 7648, and ending at 6728. Although disappointing, I don’t think it was necessarily anything exceptional.

It peaked in May at about 7877, a decline of 14.6%. So we’re not in a bear market yet, although we have had a correction. The support levels established in March 2018 failed and we’re in a distinct downtrend, so it wouldn’t surprise me if further falls are on the cards.

My portfolio is down 19.9% this year, so that’s obviously a huge disappointment to me. Undoubtedly most people did much better than me. Maybe I should have stuck to a Greenblatt Screen, or something. This year I have mostly been using mechanical criteria that I have seen on Stockopedia.

My prediction for 2019: the stock market will end up. Let’s see if I’m right, shall we? My reasoning is that Stockopdeia reports that the FTSE is on a trailing PE of 12.8. Although not screaming value, it’s pretty damn reasonable. Also, 2018 was a down year, which makes 2019 more likely to be an up year. There can be multiple down years, but they’re not all that common. I think we’d need more of a mess for that to happen.

Can the market end down on 2019? Yes, of course it can. The market can do anything it wants. But I think that the odds favour it being an up year.

Stay safe out there.

Posted in Uncategorized | Leave a comment

An adventure in Slackware

Ubuntu kept freezing on me for some reason. It seemed that Firefox was able to lock up the system. So I decided to install Slackware again.

Slackware is a fast system. And you know what, I really like its init system. It is so easy to understand. systemd is an opaque box of mysteries. There’s nothing obvious about it at all.

I think the problem with Linux is is aptly summed up in this post on reddit:

I’ve been a Linux user for a while now (around 2 years) and I can’t help but notice the difference between command line tools / kernel and the GUI options that are available. Running a Linux server without GUI is a flawless experience, running a desktop distro on the other hand is always a rough ride with bugs, glitches, driver problems etc…

Why is it that the lower level stuff is so well written and the front-end is so inconsistent?

Here’s some of the problems I ran into with Slackware:

  • VNC from sbopkg didn’t seem to work properly. I had to download and compile the latest version from its site
  • KDE seemed pretty nippy to me, which was a surprise, but doing something simple like pinning an app to the taskbar seemed frought with risk. It was too easy to delete stuff, and not easy enough to add stuff.
  • I have a pink noise generator which I use a lot. For some reason, it always locks the system when I run it from a virtual console. I have to run it within X Windows. Last night, alsa stopped working for some completely mysterious reason that I have yet to determine. It has forced me to reboot into Ubuntu
  • Lilo did not detect my Ubuntu partition correctly. I finally managed to fix it by copying the Ubuntu kernel over to the Slackware partition, and tweaking lilo.conf. There was a bit of effort on my part figuring out that I needed to copy over the kernel. Having said that, lilo was easy to configure thereafter. It is much easier to understand than grub. Grub is symptomatic of a lot of modern-day Linux tools: everything is hidden behind yet another layer of abstractions. As the saying goes: We can solve any problem by introducing an extra level of indirection, except for the problem of too many levels of indirection.
  • My root directory of 40GB is 60% full, according to ‘free -m’, which is odd, because I don’t even have a 40GB partition on my hard drive. I’ve yet to figure out what’s going on there.
  • Firefox is quite old, making it difficult to find adblockers. I guess I should try to download the latest version
  • Compiling Java from sbopkg was a mistake. It took a long time to compile, and my Java program looked like garbage anyway. I generally try to avoid Java like the plague, but there’s an app, “fidocadj”, that I really like. It is written in java. I also wanted to run the Arduino IDE, and thought Java might be necessary. I think that it bundles a version of Java, though, so I might be OK on that score. In the end, I found that Alien Bob had a binary version of Java, and that worked well for the app I was interested in.
  • I have yet to figure out automounting, and integrating it in with the desktop. I don’t mind typing out some mount commands, but it seems a little labour-intensive setting things up

So although Slackware is “stable”, I think you have to use a slightly odd definition of the word. It is certainly not without its wonks. It would be better if they had a more frequent release schedule. I’m sure it could be done if they put their mind to it. The problem is, some of the stuff in there is just a little too old and crufty, and could definitely do with a refresh.

I guess Slackware can be described as somewhat incomplete out of the box. You’re almost certainly going to have to sort something out. It’s a learning-curve. Distros like Ubuntu for the most part Just Work. The problem there is that you’re stuck with what you’ve got. “Automagical” is good until something goes wrong.

I think the Redditors post was spot-on. Linux stability is a little bit of a myth.

Random thought: Fluxbox is actually quite a nice window manager. It’s very simple. It looks butt-ugly out of the box, but with a few simple tweaks, it can look quite presentable. It’s very lightweight, and supports grouping. I think I’ll have to explore that feature more.

Happy new year, folks.

Posted in Uncategorized | Leave a comment