Charliplexing LEDs on an Arduino Nano

12 LED charlieplex, 4 pins, Arduino Nano (clone)

12 LED charlieplex, 4 pins, Arduino Nano (clone)

“Charlieplexing” is a way to drive more than one LED per output pin on ports/processors that can set their pins to input in addition to 0 and 1. It’s done by connecting two LEDs in opposite directions between any two pairs of pins from the ones used. Here, four are, so 1<->2, 1<->3, 1<->4, 2<->3, 2<->4, 3<->4 (six pairs). When using them, all pins are set to INPUT (they will not provide nor sink voltage or current) except two. Those final two are 1,0 or 0,1 – i.e. +5v and ground, lighting one of the two LEDs connected to it depending on direction.

In order to appear to have more than one lit, cycle through and quickly light each that should be lit in turn and do it at a fast enough rate to not be seen (50 Hz at least). Here’s brief example code, should work on most Atmega based Arduinos, perhaps others too (dunno about interrupts – it’s usually similar but it’s not standardized).

/*
 * Charlieplexer example
 * 
 * Controls 12 LEDs using 4 output pins. This is done using combinations of 0/1/INPUT and the
 * diode behavior of LEDs to selectively power arbitrary single ones, then using a timer
 * interrupt to rapidly cycle through those that should appear lit. The array "bri" determines which should be lit.
 * 
 * Circuit:
 * The four pins used are connected to D12-D8 (the leftmost four on an Arduino Nano).
 * Each is connected to a resistor. Two LEDs, in opposite directions, are then connected
 * between each possible two-pin selection, i.e. 1-2 1-3 1-4 2-3 2-4 3-4
 * The current will pass through two resistors and one LED when on. If they're evenly lit
 * ("extra" time from off-LEDs isn't given to on-LEDs) the duty cycle will be ~8% (8% lit, 92% unlit).
 * The resistor should be chosen accordingly. 2.4kOhmn works, but is pretty dim. 240 Ohm would still be
 * well within current limits.
 * 
 * Patrik Lundin, 2016
 * 
 * This example code is public domain
 */

  // Number of LEDs
#define PL 12
  // "Frequency", but really delay per pre-divisor on the timer interrupt
#define fq 100

  // Display state, i.e. which LED should be lit (or not) this cycle
int ds = 0;

  // Array holding on/ff values for LEDs. byte because I might implement partially lit sometime.
//byte bri[] = { 0,0,0,0,0,0,0,0,0,0,0,0 };
byte bri[] = { 255,0,255,0,255,0,255,0,255,0,255,0 };
//byte bri[] = { 255,0,0,0,0,0,0,0,0,0,0,0 };

  // Values to write to PORTB. Determines which pin is powered
byte pv[] = { 
    0b00001000, 
    0b00000100,
    0b00010000, 
    0b00001000,  
    0b00010000, 
    0b00000100,
    0b00000010,
    0b00000100,
    0b00000010,
    0b00001000,
    0b00000010,
    0b00010000,
    0
  };
  // Values to write to DDRB for each LED. Determines High impedence (disconnect) pins.
  // The two selected will be 5v and GND as determined by pv
byte ps[] = { 
    0b00001100, 
    0b00001100,
    0b00011000, 
    0b00011000,
    0b00010100,
    0b00010100,
    0b00000110,
    0b00000110,
    0b00001010,
    0b00001010,
    0b00010010,
    0b00010010,
    0 
  };

ISR(TIMER1_COMPA_vect){
  byte ods;

    // check if current LED is lit, if so light it.
  if(bri[ds]) {
    PORTB = pv[ds];
    DDRB = ps[ds];
  } else {
    DDRB = 0;
    PORTB = 0;
  }

    // next LED (for next cycle). Back to 0 at PL
  if(ds==PL)
    ds = 0;
  else
    ds++;

/* // This snipplet can replace the above to skip over any unlit LEDs.
   // This gives lit LEDs more time (brightness), but unevenly.
  ods = ds;
  do {
    if(ds==PL)
      ds = 0;
    else
      ds++;
  } while(!bri[ds] && ods!=ds);
  */
}

void setup_int() { // Start timer interrupt
  cli();
  TCCR1A = 0;
  TCCR1B = 0;

  OCR1A = fq; 
  // Some approximate refresh speeds at an unknown prescaler setting:
    //156 400 hz 125 500 hz 100 625 hz
    //78  800 hz, 69 905 hz, 50 1250 Hz

  TCCR1B |= (1 << WGM12); // CTC mode |8
    // Don't have my notes on the prescaler - uncommenting the bottom |= puts it at "very slow".
  TCCR1B |= (1 << CS12); // |4
  //TCCR1B |= (1 << CS10); // Prescaler |1 
  TIMSK1 |= (1 << OCIE1A); // Enable timer compare 
  sei(); 
} 

long sttime; // time storage for the main loop 

void setup() { 
  DDRB = 0; 
  PORTB = 0; 
  Serial.begin(9600); 
  Serial.println("Go"); 
  setup_int(); 
  sttime = millis(); 
} 

void loop() { 
  int inc; 
  byte ch; 
  long now; 

    // This isn't part of the charlieplexing - it's just a loop that blinks (inverts) all LEDs once per second 
     // so it does at least something even by itself. 

  now = millis(); 
  if(now-sttime>1000) { // if it's been 1000 milliseconds blink
    sttime+=1000;
    for(inc=0;inc<=PL;inc++) { 
       // Invert on/off (or opposite brightness if that was implemented) 
      ch = bri[inc]; bri[inc] = 255 - ch; 
    } 
  } 
  if(Serial.available()>0) { // Does nothing, but here you/I could add actions for chars gotten over serial (debug)
    inc = Serial.read();
    switch(inc) {
      case 'l':
      break;
      default:
      break;
    }
  }
}

 

Approving ADB debugging on a broken-touch android

I like to play with partially broken phones and tablets. Well, kind of anyway, it comes with it’s own frustrations, but they’re an often overlooked source of hardware. Most of their neat things (screen, sensors, audio, wifi, bluetooth..) aren’t really possible to separate out – things are so integrated now – but they also come with their own CPU/GPU. Often a powerhouse by embedded standards, certainly enough to pass things along to a lesser but more accessible arduino or desktop. I tend toward android, because even though it’s not a raspberry pi, they’re somewhat linux-ish, and can often be made to run something approximating a small server with Deploy Linux, kbox3, termux, or even just busybox with some add-ons.

Very often, the main issue is that either the screen is broken or the screen works but has no touch capability. No-screen you’re usually stuck flashing something custom (depends a lot on device) but on many devices, no-touch (but working screen) can be handled by plugging in a mouse/keyboard via usb-otg. That is, one of those little wires with usb-micro-b on one end and a USB female (as you see on a hub or computer) to plug the mouse/kb/combo into on the other end. With this, you’ll often get a mouse pointer, and you can (sort of) limp yourself along installing something more permanent.

However, if it’s a fairly recent android, you’ll soon bump into another roadblock. Ok, I just did, not sure about others. Trying to activate USB adb debugging (so you can shell in from desktop, push/pull apps and data, root it, so on) requires both the usb port (pops up a permissions box) *and* touch or mouse (to click ok). If you disconnect the usb to the desktop, the popup goes away.

If you have root (or other enhanced access), you can add a key in /data/misc/adb/adb_keys and set a local variable (ADB_KEY on windows) to match, letting you in without he OK. If you it’s a debug build, you can do “adb disable-verity” to disable checking it. I had neither. So, another way around I saw mentioned is a bluetooth mouse. If you have one, pair that (can be done with the usb mouse in), good to go. If you don’t (me) you can use TrueMouse Lite on another, non-broken, android to fully emulate a mouse. There’s a ton of other remotes, but most require an app on the client side, and usually android isn’t supported. TrueMouse does require root, and is a 9 day trial, but it shows up as a true BT mouse. So any other rooted and functioning android, in my case an LG Fuel from a $5 special tracfone sale, works. Click the OK, boom, access.

Saying the alphabet backwards

Being tested for a concussion? Trying to convince a police officer you’re not high as a kite? This won’t really help you – normal people can’t do it anyway. It’s rarely used as a “brain works” thing, especially if an authority figure asks, they’re just rattling you a bit. If you decide to squarely designate yourself “the kind of person who obviously practiced reciting the alphabet backwards”, be sure to follow up by further segmenting that to “by that I mean geek, not drunk/druggie”.

But, either way, if you want to say the alphabet backwards, here’s a way to mnemonic it. It’s partly by some guy on reddit, partly me adding stuff back in that I forgot over and over.

When first asked, your try will probably be “ZYX”. Good job, like most people, you know the last three. If not.. learn them.

Next, we’ll name two states – West Virginia and Utah. Their abbreviations are “WV UT” which are the next four. I don’t have a universal reason those are the two states, but if nothing else perhaps you can eek out “W” as the fourth from last (before X) and thus go “Oh yeah, WV. UT”.

Next, the phrase “It’s our cue, pee on Martin Luther King Jr”. This is not recommended behavior, nor is it any reflection on his legacy. It’s merely a sentence that has the appropriate letter sounds – “tS R Q P on MLK Jr”. Since you’ll have forgotten the order of things, it actually overlaps by a letter – you just said “UT”, so peek at your own prior answer and go “starts with T. Oh yeah, iTS R Q..”. The main tripup is feeling that “cue” should have something like “to” after it (perhaps notice that you just said T) and that Jr only stands for J, (MLKJ, nor MLKJR). Again, it might help that you said R just then, by the “its”.

Next, do a jihg (and misspell it with h) because you’re fed up (or chased by feds, if you wish). Again, one letter overlap – with any luck the “MLKJ” will lead you to “J.. oh yeah, JIHG.. FED”.

There’s no overlap for the next bit. In fact there is no next bit – you are here supposed to realize you said “D”, and through sheer brainpower figure out that “CBA” is the finishing three. In summary:

ZYX (think of how it ends..) WV UT (West Virginia, UTah) SRQPONMLKJ (t-> It’s our cue, pee on MLK Jr) JIGH FED (j->do jig with bonus h, because fed up) CBA (d->that’s hella early in the alphabet – I’ll reverse ABC live)

Practice a bit and you’ll convince yourself you can do it. Try it again in a few days or hours (set an alarm or something) and patch what you ended up forgetting after all. Try again in another same unit (day, hour) if it’s still there, do another in a week. Two of those, and done – stuck forever. It may well be that you just remember it in a day, then in a week, and realize this whole exercise was sufficiently absurd to stick it in your brain. Go forth and wait years for a situation where you might be able to earn bragging rights with it, hope it’s still there by then.

If you actually manage to do it enough times to make the sentences and words fade out (like you were supposed to do with the alphabet song, but it never happened and you still have to start singing it to access alphabetic order) knowing it actually has real live uses if you deal with alphabetized data (like a library, or the herbal supplements at walmart) – you’re often presented with “You’re on M, need to go to F, how far is that?”. It’d be better to actually know the alphabet as a non-sequential thing, like knowing the ordinal for each letter (A=1 B=2 C=3 .. but so that you can do ordinal->letter->ordinal in arbitrary order, not by singing and counting) but a solid compromise is being able to do both “F..GHIJKLM.. six more between” and “M..LKJIHGF.. six in the other direction”.

Setting up domain mail service through yandex

Yandex is a google-like service in Russia. It’s the fourth largest search engine world wide, and also provides things like mail, online storage, DNS, etc. It’s slightly less stringent about checking accessing IP, which can be bad (if your account gets hacked, it may be less protected from geographically unlikely access) but also good (if you actually travel, or need to access it from a VPN or a remote server, they will allow you to do so, while google has a tendency to demand phone verification or just plain kick you out on the basis that you look like you hacked your own account).

Supplies:

A domain, including access to it’s DNS records.

Somewhere to access them from.

Step 1: Set up an account at yandex.com. This can be done from passport.yandex.com or by clicking “log in” and then “register” on any yandex page. It will ask you for a name, address, and phone number. If you don’t feel like supplying a recovery phone, click “I don’t have a cell phone” – it’ll be ok with that and ask you to instead supply a recovery question. Pick as strong of a password as you need to and make note of it and your recovery question(s)/answers – while they’re laxer with where you choose to access your account they are harsher than google in terms of recovery. Do not count on being able to recover from a lost password/recovery Q – it’s not totally impossible, but it’s also highly likely that it’ll be permanently lost.

Step 2: Go to domain.yandex.com. Enter your domain name in the “connect domain”. If you aren’t logged in with the account you made, you’ll be asked to do so.

Step 3: Demonstrate that the domain is yours. They provide a few options, but the easiest is probably to add a specified NS record. They’ll give you a hostname (y2a3n323a234f.yourdomain.com or something) that you’ll be asked to add as an alias (CNAME) for one of their hosts. Add it to your DNS settings, if using bind, add a “y2a3n323a234f IN CNAME the.host.they.said.ru” to the zone file, update it’s serial number so it propagates and tell bind to restart or reload (usually “service bind9 reload” (or …restart). Give it a bit to spread though the DNS network. If possible check from another perspective (such as your own machine if it’s not using the same DNS server authoritative to your domain) by looking up your CNAME (nslookup y2a3n323a234f.yourdomain.com from windows or linux prompt). Once it seems established though out that it’s there, click the button on the yandex page to tell them to look for it. If you tell it to check too soon and too many times, it will throttle you (usually tell you to wait a half hour before rechecking) so it’s worth giving it a bit to make sure it’s out there. If it throttles you, double check that you did in fact add the correct CNAME and that it’s visible and wait out your timeout. There’s no real way around this and it is necessary to avoid DNS poisoning attacks (sending out false information getting central DNS caches to temporarily misreport).

Step 4: Once they admit it’s your domain, add MX records for their hosts. They’ll tell you where, usually a few hosts like mail34.yandex.com. They’ll quote you exact MX records and priorities to add, in the vast majority of cases the recommended settings are what you’ll want (I can’t really think of a situation where they wouldn’t be).

Step 5: Set up mailboxes and/or catchall address (where to send xyzzy@yourdomain.com if there is no xyzzy mailbox). You can set up something like 1000 free, though they say if you need more or more storage, contact them – I’m not sure what they’d do or charge if you somehow needed more.

Step 6: Done. Start using. When logging in to a mailbox the first time (logout and go to the address they supply to log in with username only, or log in at mail.yandex.com with the full address (user@domain.com) and pass) they’ll ask you to enter new recovery information, name, and accept TOS for that particular address (so that if it’s not yours, the new user, too, accepts them). These sub-accounts can be recovered (or deleted, modified, etc) using the main account you used to create the domain, so that isn’t as picky. They have even less recourse for recovering from them directly though – as admin of the domain they’re considered your users/your problem if they forget their password. If you wish to use imap/pop/etc for third party clients, this can be activated in their setup screens. Some push options are available, support depends a bit on the third party client. There are mobile apps available (similar to gmail) which work as a more user friendly way to set up push notifications but with the same downsides as any third party apps.

ONN Model NB14W1201 2000mAh Power Bank

Onn Powerbank model ONB14W1201, $2 clearance buy, but handy and functional. Reading a bunch last night about Li-ion chargers, I had a sudden urge to look inside.

Peeking into it. Wait, is that..

..roundness? This looks so much like a plain standard cell, or one of those half-length ones.

It’s a plain ol’ 18650 Li-ion cell with a little driver! The white parts pop apart down the other side, btw..

Circuit closeup

Looks like standard ICs and they left the numbers on. I’ll look into it more later, but these look like what I bumped into constantly hunting obscure Shenzen parts no one has sheets for.

Driver Board

Another for good measure in case something is out of focus.

It’s spot welded in (as internal batteries or individual cells usually are – the strips are often zink plated stainless to handle the heat changes. But it could probably be modified to charge 18650 (probably the most common Li-ion cell around and the basis for most “normal” high power rechargables) or to recharge your phone with infinite 2000-2300 mAh chunks for a few bucks a cell. Possibly even expanded with a few in parallel but that might get adventurous current wise. Will have to see what the ICs claim to be.

Got caught up in a DNS amplified DDoS attack

Sure I’ve heard them mentioned. Along with everything else that’s wrong with traditional DNS, a great deal of it is done via UDP as opposed to TCP. I.e. no “Hi Server! (msg1)” – “Hi Client! This a connection? (inre:msg1, msg2)” – “It sure is, dear Server! (inre:msg2, msg3)” – “Cool! What? (inre:msg3, msg4)” and so on, lobbing packets of information back and forth, all pieced together. No, DNS goes “Hi I’m client X I need to look up Y”, “Ok cool, heres YINFO”. Since there’s no connection, you can lie about the sending address, causing the server to shove the response at some innocent other host, which will sit there when suddnely “Ok, cool, heres YINFO!”. It’ll go “Wut?” to itself and toss it. But, as an extension of overloading a server with junk traffic, this can make you suddenly much louder – ask a question with a *really* long answer, and suddenly you can not just cause people to deal with your puny internet connection but cause them to receive many times that much form other servers you’ve tricked into sending it.

So until now, my DNSes have always been limited enough to not have this happen. But seeing up a new server, DNS was the main issue – it hung multiple times from lack of functioning DNS. So I wasn’t too careful, and suddenly someone, many many someones, were requesting lots and lots of data.

So, now thinking for an additional second about it, I realize there’s really not much preventing this besides just not taking requests from outsiders. But there has to be some slack too – it’s not like everyone can have individual DNSes, nor can it be 100% centralized. And here, I’m not even sure how should have answers, but at least a decent chunk of local boxes.

Then when you do block, or (as I first did) just rip down your DNS shingle altogether for now, it’s not really stopping it much at first. After all, the point here is to shove traffic at someone else – there’s no real way to see if it makes it. It’s possible (and a good idea for effective mayhem) to mix it up and throw an answer back to yourself (more like “a place you control”) to make sure you’re not wasting your traffic sending into nothing, but.. that’s riskier than just sending it to the target, and a little trickier, and there isn’t that much punishment for slacking off and not checking often.

Finally fail2ban (set to bounce the requests with orders to the next router up that packets going “from” one for the targets to my dns needs to find another route, nothing down this path) started working, set up per https://debian-administration.org/article/623/Blocking_a_DNS_DDOS_using_the_fail2ban_package . After a set time, it’ll start accepting again, but after a set amount.. ban again. It’s working pretty well and slowing it down. Looks like the herds are moving on. But that was way more of a thing than I expected. Worth configuring carefully the first time, I think.

Moorse law seems very near breaking.

Yeah, I know, just like it has been the past 30 years, but for general purpose cores it’s broken now, actively, not-looking-like-it-catching-up-again broken. I’m writing this on a i5-540M (yes, the one I inserted myself to replace a A6200), a two-die monstrosity with separate GPU on it (though a crazy good deal, 2400+ passmark for $20) pressed at 32 nanometers (cue patting my laptop gently like a trusty workhorse – me and connor been through a lot) That was 2010 level tech. 22nm in 2013 was a little late, but not *that* late, and while the original law said “transistors per square inch” it’s usually more broadly used as “transistors swedes living in kansas use for daily operations”. Or (possibly) “transisotrs you can sort of expect to use in your average general purpose CPU”. Either way, bigger dies with better cooling mostly made up the difference speed wise. This year, people are pressing 14 nm, and it’s a big deal, but we *should* be pressing 5-6 nm. Intel and nvida are doing some testing at that level, but that’s “wonder if perhaps we could”, not something inching closer to production. By normal rates, we would now be kind of over 5 nm – like I’m supposed to be buying your 5 nm CPU stuff at garage sales after the HDD failed, not reading about how it’s pretty much established that it’s not a physical imposibillity.

So single thread is irreperably not catching up, which is understandable – there’s no particular reason to belive it would. But what about the fancy throughput driven kilocore stuff? I said “nVida” out loud earlier, what gives? Well, they’ve kept up, and they might just swing it. Now that Intel seems at least partially over continually shooting themselves in the foot and covering their ears going “LALALALALALA We don’t see any demand for smaller massive multicore processors” we seem marginally closer to perhaps establishing some sort of standard for computational throughput jobs and some measumrent of device cababillity for said jobs (How smoothly does this http://nothisispatrik.com/wobblebrot.htm wobbling mandelbrot operate on your machine? You know what would make it faster and smoother? You’d have to.. actually no one knows – there’s no reasonable spec to quote for massivley paralell operations besides “get a better GPU. And by “better”, I mean.. I have no idea what I mean by it”). One of Sarahs friends (unprovoked) pointed out that if you chained a pile of Raspis together and only used the GPU part, you could build a fairly cheap supercomputer, so the next generation isn’t missing what’s happening here, but most GPUs are way locked down and extremely propriatary.

So ironically, I think if we’re going to survive this itteration (because surely they world will stop spinning if we’re not doubling everyt two years ;-)) the solution is probably going to have to be political. GPU people are going to have to unglue thier cards from the vest and let us play, we’re going to have to establish a sane way to quote “dick size” (compare to camrea megapixels) so that people with money can throw tremendous amounts of it at being the best. CL is a good start, but we still need metrics, we still need higher level access, and we *might* need a killler app (although really I think that will appear organically).

BWA15HO107 Blackweb Wireless Touch Keyboard

BWA15HO107 Blackweb Wireless Touch Keyboard.
Continuing my quest for the right input device, I found this newcomer on the cheap at Walmart. Blackweb is their store brand in electronics – I suppose Great Value wasn’t good enough or they want electronics separate from everything else. Hopes were not particularly high, but there aren’t many TouchPad keyboards to choose from so..
It surprisingly turns out it’s pretty good. Compared to Logitech and Microsoft? Yes, actually, but with some major caveats.
The build quality is terrible. Very plasticy. The keys rattle quite a bit. But they do type, never been a huge chiklet fan. The touch pad is very sensitive, which is a little annoying as I flail around with my pinkie typing. It’ll. probably pass, I had this with the Logitech k400 too, and somewhat with the MS no-insert-key lookalike. They were also both 90% chiklets, more sturdy, but still no more comfortable due to that.
So what makes it usable? Well, it has all keys. Including ins and del. It has fn-ctrl and fn-win mapped to mouse buttons, ie physical keys. So both of the full on deal-breaker faults are gone. Too bad so much else is worse.
It did have another, the minus on the number pad kept getting stuck, activating at the slightest touch and never stopping. so I did open it and taped the switch apart.

image

image

image

image

image

image

image

copy-as-curl to python converter

You know when you have the developer tools open in Chrome or Firefox (and IE? Who knows..) and set to the network tab, you can right-click a request and select “copy as cUrl”, and you get curl command line with a pile of flags that will reissue the exact same request? Well, if you didn’t, you can – start using it, it’s awesome for testing stuff that’s not so complex that you have to write a selenium or phantomJS script. Handy for working out how the back end (yours or someone elses..) deals with requests that can’t occur in the browser, but which can occur when some brat decides to fire up burpsuite and start sending it broken Unicode just to see if you did your homework.

But sometimes you need to write something a *little* interactive, but not much so that you need a headless or actual browser for it (or for something performance critical enough that you don’t want one) and working on something else I realized I spend an awful lot of time rewriting these curl command lines into python. Since that’s really just a straight “madlibs” insertion formula, there should really be something automatic that does that. So now there is:

uncurl.py

So.. there you go, if you, too, do that sometimes this will do that for you. The output uses urllib3 (might add on options to use requests or mechanize instead sometime) and is just a single function called getpage that fetches it and prints the headers and the response, and a “if __name__==” snipplet to run it if it’s executed directly (yes, I’ve taken a slight liberty in pretending there’s a -i on the curl command, because really there should be). If you give it and argument, it’ll read that file for the curl command, if there’s no options it’ll use the /dev/clipboard (i.e. the clipboard on linux/osx/cygwin, nothing particularly useful on winows). There’s no filters so it’ll add everything, including headers like “Host:” and stuff that technically shouldn’t be there, but when considering filtering I decided it’s probably better to retain the integrity of the curl command and you can delete or edit them yourself (just as the with curl command).

[EDIT] ..and in less than 24h it’s gotten a bug fix – the normal way of passing headers mixes up their order, which is slightly different than curl, and matters in certain edge cases. Also added the ability to skip -I if it’s been added. Still pretty strict on input order and not much error check..