Saturday, December 31, 2016

In the Moonlight

This is the moon simulator with bat silhouette which I made as a decor for this  Halloween.


The core part of the project is twelve backlight white LED modules ( I bought them from the adafruit). LEDs are controlled by Atmega328 micro controller. The schematic of the project is fairly simple:




Adm here you can see project assembly with some internals visible:




Twelve LED modules put in the middle of sandwich made out of two Plexiglas  sheets attached with the help of Velcro strips.  Paper Bat attached to the front of the moon with Velcro as well as front and back cardboard shields .

 Program to control the device is short enough to be present entirely in this blog:

/*
 * moon.c
 * Created: 10/22/2016 1:14:19 PM
 *  Author: jumbleview
 */ 
#include <avr/io.h>
#include <avr/interrupt.h>
#include "./pt-1.4/pt.h" // http://dunkels.com/adam/pt/

typedef enum {OUT_LOW, OUT_HIGH} OutputLevel;
volatile uint16_t pulses;

#define pinOut(port, bit, outLevel) \
(DDR##port |= (1 << ( DD##port##bit)));\
switch(outLevel) \
{\
 case OUT_LOW: (PORT##port &= ~(1 << (PORT##port##bit))); break;\
 case OUT_HIGH: (PORT##port |= (1 << (PORT##port##bit))); break;\
}
void clearAll()
{ // set all outputs low
 DDRB = 0xFF; PORTB = 0;
 DDRC = 0xFF; PORTC = 0;
 DDRD = 0xFF; PORTD = 0;
}
void activateTimer0()
{
 cli();
 pulses = 0;
 TCCR0A=0; // Normal operation
 TCCR0B=2; // f divider 64  : about 2 ms for interrupt ...
 TIMSK0 = 1; // for system clock f= 1Mhz (CKDIV8 set)
 sei();
}
struct pt wpt; // protothread descriptor

int moonlight(struct pt* mlpt)
{
 PT_BEGIN(mlpt);  // New Moon 
  PT_YIELD(mlpt); 
   pinOut(C,5,OUT_HIGH); pinOut(B,1,OUT_HIGH);
  PT_YIELD(mlpt);
   pinOut(D,0,OUT_HIGH); pinOut(B,2,OUT_HIGH);
  PT_YIELD(mlpt);
   pinOut(D,1,OUT_HIGH); pinOut(B,0,OUT_HIGH);
  PT_YIELD(mlpt); // First Quarter   
   pinOut(D,2,OUT_HIGH); pinOut(D,7,OUT_HIGH);
  PT_YIELD(mlpt);
   pinOut(D,3,OUT_HIGH); pinOut(D,6,OUT_HIGH);
  PT_YIELD(mlpt);
   pinOut(D,4,OUT_HIGH); pinOut(D,5,OUT_HIGH);
   pinOut(C,0,OUT_HIGH); pinOut(C,1,OUT_HIGH);
  PT_YIELD(mlpt);  // Full Moon + Red Eyes
  PT_YIELD(mlpt); 
   pinOut(C,0,OUT_LOW); pinOut(C,1,OUT_LOW);
   pinOut(C,5,OUT_LOW); pinOut(B,1,OUT_LOW);
  PT_YIELD(mlpt);
   pinOut(D,0,OUT_LOW); pinOut(B,2,OUT_LOW);
  PT_YIELD(mlpt);
   pinOut(D,1,OUT_LOW); pinOut(B,0,OUT_LOW);
  PT_YIELD(mlpt);  // Third Quarter
   pinOut(D,2,OUT_LOW); pinOut(D,7,OUT_LOW);
  PT_YIELD(mlpt);
   pinOut(D,3,OUT_LOW); pinOut(D,6,OUT_LOW);
  PT_YIELD(mlpt);
   pinOut(D,4,OUT_LOW); pinOut(D,5,OUT_LOW);
  PT_RESTART(mlpt); // New Moon
 PT_END(mlpt);
}
ISR(TIMER0_OVF_vect)
{
 pulses++;
 uint16_t mod =pulses%750;
 if (mod == 0){
  moonlight(&wpt);  
 }
}
int main(void)
{
 PT_INIT(&wpt); // initiate protothread structure...
 clearAll();
 activateTimer0();
    while(1) { }
}

To  compile and load program into the controller memory I used Atmel Studio 6.1. Code includes three header files.

  • File "io.h" contains definitions to work with input/output (comes with Studio installation)
  • File "interrupt.h" is defining interrupt vectors (comes with Studio installation)
  • File "pt.h" is Adam Dunkels implementation of protothread library.
Protothred library deserves some additional notes. I included it to my programming  tool box recently and nowadays use it any time I need to program embedded devices in "C ". It provides multitasking framework and allows to code device states efficiently and conveniently.  I highly recommend to try it for any programmer  who works with micro-controllers in "C".

As you can see device is simple to made and program. Some additional details you can find in my "Instructables" project.

The only problem I see is relatively high project price. Mostly it is the price of LED modules ($2.50 for each). Nothing could be done here. To gain some additional benefits I decided to substitute  Bat with Reindeer so the device is quite usable  as winter decor:


Saturday, September 3, 2016

Windows Console on Demand in Go

There are two kinds of Windows programs: Windows GUI or Console Application. There could be third case:  process, which does not have any visual representation at all and needs to be running in the background. For that case program maybe be built as Windows GUI, but it should not have any code, which creates Windows objects.  But what if  you want from application sometimes  to be silent and sometimes  to be verbose and to have a console. Possible use cases are:
  • Printing version of the utility if started with special flag (like -V)
  • Program needs complicated tune up through the  command line arguments or configuration file, but normally is  running on the background. It would be beneficially to have a choice either run it with console or run it quietly.
That could be achieved by compiling application as Windows GUI and allocating  or attaching console to the process during run-time if needed. There are a lot of examples how to do that in C/C++. When I myself looked for the solution several years ago I have found this link  helpful. Fragment of the code, which creates console may look like this.

 // taken from: http://www.codeproject.com/KB/dialog/ConsoleAdapter.aspx

 AllocConsole();
 int fdout = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
 FILE* fout = _fdopen(fdout, "w");
 *stdout = *fout;

 int fdin = _open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT);
 FILE* fin = _fdopen(fdin, "r");
 *stdin = *fin;


Nowadays I found myself  programming more and more in Go. While initially Go compiler was intended for Linux only,  that is not the case anymore. Windows now is the first class citizen in the Go word. Recently I needed to create application, which may open the console if that demanded by  command line argument, but work invisibly  otherwise . To my surprise there were not that many online information how to do that in Go. I did find one answered question in StackOverflow. Alas, proposed solution did not work for me out of the box. But using it as starting point and after some googling I have found workable solution. Here is sample of Go application, which will allocate console, print some prompt, wait for keyboard input and quit.

// go build -ldflags -H=windowsgui
package main

import "fmt"
import "os"
import "syscall"

func main() {
 modkernel32 := syscall.NewLazyDLL("kernel32.dll")
 procAllocConsole := modkernel32.NewProc("AllocConsole")
 r0, r1, err0 := syscall.Syscall(procAllocConsole.Addr(), 0, 0, 0, 0)
 if r0 == 0 { // Allocation failed, probably process already has a console
  fmt.Printf("Could not allocate console: %s. Check build flags..", err0)
  os.Exit(1)
 }
 hout, err1 := syscall.GetStdHandle(syscall.STD_OUTPUT_HANDLE)
 hin, err2 := syscall.GetStdHandle(syscall.STD_INPUT_HANDLE)
 if err1 != nil || err2 != nil { // nowhere to print the error
  os.Exit(2)
 }
 os.Stdout = os.NewFile(uintptr(hout), "/dev/stdout")
 os.Stdin = os.NewFile(uintptr(hin), "/dev/stdin")
 fmt.Printf("Hello!\nResult of console allocation: ")
 fmt.Printf("r0=%d,r1=%d,err=%s\nFor Goodbye press Enter..", r0, r1, err0)
 var s string
 fmt.Scanln(&s)
 os.Exit(0)
}
I would like to point some details about syscall.Syscall invocation for AllocConsole :
  • This function  has five arguments. It is different of what you will find in the online Go Doc . Looks like doc references Linux definition, which is not the same as Windows.
  • Second parameter here is number of arguments in dll function. For our case it is 0.
  • Function returns three variables, but only first is really meaningful. It is the result returned by AllocConsole function. Second variables always 0. Third variables  is an  error, but in cannot be analyzed in the regular Go way as far as it is never nil.  Still it could be useful: in case of success its value is different from value on failure (for example if application was build with no windowsgui flag and already has the console ) .


Saturday, April 9, 2016

Not for Insulation Only

Hobbyist and DYI makers very often extend usage of elements and components beyond its usual assignments.  I would like to share with you one such a case. 
Whenever you drill through the wooden or plastic sheet you has to be really careful not to drill through. The common well know method to prevent that is to use tape or scotch wrapped around the drill bit. Once I was out of tape and had to look for substitution. Piece of  heat shrink tube came in handy. It fitted drill bit exactly, I just needed to cut proper length of it. That was very lucky finding. I entirely stopped using tape for this task and switched to heat shrink or straw tubing. Especially convenient it becomes  for projects which  needed drilling with the same drill size but with different depth. Switching between tubes can be done in a second.  
The best result is achieved when tube sits tight  on the drill bit. In case you does not have exact heat shrink size, you may cut tube, which is too narrow,  alone. It will still work.  But you need to be more careful to stop drilling right at the moment when tube touches the surface. Otherwise it may be torn away by drill rotation.

Heat shrink actually suited for various tasks. I even   published blog, picturing some of  them : http://www.instructables.com/id/Not-for-Insulation-Only/,  Here is list from that blog in a short:
  • Controlling depth of drilling (that idea you actually see here).
  • Using heat shrink while hanging picture  on sheet rock wall
  • Protecting awl tip
  • Keeping tweezers tips together. 
  • Making paper clip to work better. 

That topic got some attention and was even featured by one of the site editor.  Author Phil B told me about one more usage of heat shrink:  fixing claps on kindle reader case. I am sure there are many more cases which extends usage of heat shrink tubes.