Archive for category Software

Kenmore 158: Motor RPM Sensor Deglitching

The setscrew in the motor pulley lies directly in the path of the photosensor:

TCTR5000 Motor RPM Sensor - side view

TCTR5000 Motor RPM Sensor – side view

Which produces a glitch in the rising edge of the digital output as the pulley rotates from the dark to the light section:

Motor Sensor - Rising Edge Glitch

Motor Sensor – Rising Edge Glitch

The RPM signal goes to Arduino pin D2, where each falling edge triggers an interrupt handler:

const byte PIN_MOTOR_REV = 2;		// DI - IRQ 0 (must be D2)

... snippage...

void setup() {
... snippage ...

    attachInterrupt((PIN_MOTOR_REV - 2),ISR_Motor,FALLING);			// one IRQ / motor revolution

 ... snippage ...

The maximum motor speed is about 11 kRPM, so interrupts should be at least 5.5 ms apart and the digital input should be low. If that’s true, then the code updates a bunch of useful information:

struct pulse_t {
 byte Counter;
 unsigned long TimeThen;
 unsigned long Period;
 word RPM;
 byte State;

struct pulse_t Motor;

... snippage ...

// ISR to sample motor RPM sensor timing

void ISR_Motor(void) {

static unsigned long Now;


	Now = micros();

	if ((5000ul < (Now - Motor.TimeThen)) && !digitalRead(PIN_MOTOR_REV) ) {	// discard glitches
		Motor.Period = Now - Motor.TimeThen;
		Motor.TimeThen = Now;
		Motor.State = digitalRead(PIN_MOTOR_REV);		// always zero in a Physics 1 world


The scope trace shows that the handler takes about 7 µs to get control after the glitch (the left cursor should be on the falling edge, not the rising edge), so the input read occurs when the sensor output is over 4.5 V, causing the handler to discard this spurious interrupt.

Because Motor.Period is a four-byte unsigned long, the Arduino’s CPU must handle it in chunks. Rather than disable interrupts around each use, it’s better to read the value until two successive copies come back identical:

// Return current microsecond period without blocking ISR

unsigned long ReadTime(struct pulse_t *pTime) {

unsigned long Sample;

	do {
		Sample = pTime->Period;				// get all four bytes
	} while (Sample != pTime->Period);		//  repeat until not changed by ISR while reading

	pTime->Counter = 0;						// this is a slight race condition

	return Sample;

Because the interrupts don’t happen that often, the loop almost always executes only one time. On rare occasions, it’ll go back for another two values.

Converting the pulley rotation period into revolutions per minute goes like this:

		Motor.RPM = 60000000ul/ReadTime(&Motor);		// one (deglitched) pulse / rev

That’s easier than hiding the setscrew and it also discards any other glitches that may creep into D2

About these ads

, ,

Leave a comment

Kenmore 158: Power Switch Timing

The crash test dummy sewing machine now has a cheerful red momentary pushbutton in the same spot the original machine sported a 120 VAC push-on/push-off power switch:

Kenmore 158 - Digital Power Switch

Kenmore 158 – Digital Power Switch

It’s held in place by a dab of epoxy on the bottom. The threads aren’t quite long enough to engage the ring, so another dab of epoxy holds that in place. In the unlikely event I must replace the button, I’ll deploy a punch and hammer it out from the top; the slick paint on the sides of the straight-sided hole doesn’t provide much griptivity.

The button connects in parallel with the GX270’s front-panel button and the one on the Low Voltage Interface Board, so it operates exactly the same way. My original code didn’t include a delay before turning the power off, which meant that brushing the switch while doing something else would kill the power.

This is not to be tolerated…

You (well, I) must now hold the button down for one second to turn the power off. Releasing it before the deadline has no effect, other than blinking the green power LED on the front panel a few times.

The routine maintains a timer that allows it to yield control to the mainline code, rather than depend on a blocking timer that would screw up anything else that’s in progress:

// Handle shutdown timing when power button closes
// Called every time around the main loop

void TestShutdown(void) {
	if (LOW == digitalRead(PIN_BUTTON_SENSE)) {			// power button pressed?
		if (ShutdownPending) {
			if (1000ul < (millis() - ShutdownPending)) {
				printf("Power going off!\r\n");
				while(true) {
					TogglePin(PIN_PWR_G);				// show we have shut down
		else {
			ShutdownPending = millis();					// record button press time
			printf("Shutdown pending...\r\n");
	else {
		if (ShutdownPending) {
			ShutdownPending = 0ul;						// glitch or button released
			printf("Shutdown cancelled\r\n");

The normal Arduino bootloader imposes a similar delay while turning the power on, which means that you can’t accidentally light the machine up by bumping the switch. All in all, it’s much more user-friendly this way.

, ,

Leave a comment

Patient Sign-In App: Human Factors FAIL

It used to be we “signed in” at the dentist by exchanging pleasantries with the folks behind the desk, but that was so 20th Century. Now we’re confronted with an iPad sporting a form:

Patient Sign-in Tablet Form

Patient Sign-in Tablet Form

Pop Quiz: Assuming you filled in your birthdate and remembered how their files have recorded your name, where do you tap to proceed onward?

Reasoning by analogy from my Kindle Fire’s keyboard, I assumed the conspicuous bright blue Go button would do the trick.

Nope. That’s not it.

After a bit of fumbling around, it turns out to be the dark blue Next button (on the non-contrasting light gray title bar) at the right edge of the title bar.

I betcha I could have fun with some of those little icons…

In fact, the next time we showed up, the iDingus sported a popup asking if I wanted to update the firmware (or some such). Of course, I gave the receptionist an evil grin and tapped “Hit me!”

Word: this app nonsense isn’t ready for prime time.


Sony HDR-AS30V GPS Time vs. File Timestamps

Faced with the utter confusion caused by trying to figure out the interactions of the Sony HDR-AS30V time settings, I set it to local time, Time Zone GMT+0, DST off, enabled the GPS receiver, disabled the auto-off battery saver, and parked it outside with a nice view of the sky.

About ten minutes later it achieved GPS lock, which suggested the time wasn’t terribly wrong. After locking, the camera set itself to the current local time +1 hr, TZ = GMT-5, DST off; it apparently runs an embedded Linux distro, so it can convert from geographic location to time zone easily enough. It cannot know about DST, so I set DST on, the time jumped -1 hr, and it’s now set to local time, TZ = GMT-5, DST on.

A short movie produces this metadata:

exiftool MAH00046.MP4 | grep -i date
File Modification Date/Time     : 2014:09:02 17:58:49-04:00
File Access Date/Time           : 2014:09:02 16:59:51-04:00
File Inode Change Date/Time     : 2014:09:02 16:59:51-04:00
Create Date                     : 2014:09:02 20:58:41
Modify Date                     : 2014:09:02 20:58:48
Track Create Date               : 2014:09:02 20:58:41
Track Modify Date               : 2014:09:02 20:58:48
Media Create Date               : 2014:09:02 20:58:41
Media Modify Date               : 2014:09:02 20:58:48

exiftool MAH00046.MP4 | grep -i zone
Time Zone                       : -04:00

ll MAH00046.*
-rwxr-xr-x 1 ed ed 18M 2014-09-02 17:58 MAH00046.MP4
-rwxr-xr-x 1 ed ed 11K 2014-09-02 17:58 MAH00046.THM

ll -c MAH00046.*
-rwxr-xr-x 1 ed ed 18M 2014-09-02 16:59 MAH00046.MP4
-rwxr-xr-x 1 ed ed 11K 2014-09-02 16:59 MAH00046.THM

ll -u MAH00046.*
-rwxr-xr-x 1 ed ed 18M 2014-09-02 16:59 MAH00046.MP4
-rwxr-xr-x 1 ed ed 11K 2014-09-02 16:59 MAH00046.THM

Tue Sep  2 17:13:44 EDT 2014

date -u
Tue Sep  2 21:13:47 UTC 2014

The camera quickly achieves GPS lock with DST on (so it’s still able to use its recent GPS ephemeris data) and doesn’t change any of the current time, Time Zone, or DST values (so it’s happy with all that).

Based on that short experiment:

  • Internal Exif timestamp values are UTC
  • Time Zone Exif value is (Actual Time Zone + DST)
  • File modification is (local ending time +1 hour)

Some poking about shows that I misunderstood the “create” time, which actually holds the time when the file metadata changed, meaning there’s no way to tell when the file was created. I did know that the “access” time tracks the last time the file was opened: reading the Exif data will update the access time.

The +1 hr offset in the modification timestamp will (probably) vanish when DST goes off in the fall.

The Exif data contains the correct UTC times for the video’s Create and Modify dates, as well as the net Time Zone offset, which means I (well, a script using exiftool) can calculate the (UTC or local) time corresponding to the beginning & end of the video file. Indeed, exiftool can whack the file’s modification time directly from the Exif data:

exiftool '-FileModifyDate<ModifyDate' MAH00046.MP4
1 image files updated

Extracting still images proceeds from a time relative to the start, so the number of frames plus the calculated start time gives the actual time for that frame, modulo converting frames into hh:mm:ss.ff format and getting the addition correct.

Perhaps it makes more sense to set the modification time to the starting time of the video, thus simplifying the calculations:

exiftool '-FileModifyDate<CreateDate' MAH00046.MP4
1 image files updated

Both of those times are the UTC values, so a further adjustment based on the time zone would be in order. It’s not clear whether exiftool can perform that calculation internally or if it must be a two-step process.

A cheat may be in order: the thumbnail file modification timestamp matches the starting time of the corresponding video file. The script can base its calculations on the thumbnail timestamp. Of course, both of those are subject to the FAT-vs-DST problem.

More pondering is obviously in order.

For what it’s worth, the raw GPS log data from the camera lives in the PRIVATE/SONY/GPS/ directory, with a YYMMDDnn.LOG file name. It relentlessly accumulates two records every second:


The battery life is so terrible with the GPS on that I don’t plan to use it much at all, but at least now I know how to set the clock’s time…


Sony HDR-AS30V vs. ExFAT vs. Ext2 Times: Total Bafflement

I’d like to overlay a timestamp on still images extracted from Sony HDR-AS30V camera videos, ideally including the frame number, to record exactly when the incident occurred. Movie players use relative time, with 00:00:00 at the beginning of the file, so we’ll need either the file timestamp or the timestamp recorded in the image’s Exif data, plus the frame number modulo 60 (or, shudder, 59.94 for NTSC).

The ExFAT format used on 64 GB MicroSD cards stores the file’s creation time, its modification time (writing data), and the most recent access time (reading data). That’s similar to the Linux ext2/3/4 filesystem time and unlike plain old FAT, which omits the access time.

The various FAT formats store local time, with no regard for time zones, Daylight Saving Time, or anything else. Linux stores times as UTC and converts to local time on the fly. This has catastrophic consequences for getting any of this right.

It helps to have alias ls='ls -h --color=auto --time-style=long-iso' in your .bashrc file.

The HDR-AS30V has a year-month-day calendar, a 24-hour clock, a Time Zone value, and a separate DST on/off setting.

Turning DST on adds 1 hr to the Time Zone value, turning it off subtracts 1 hr. That has the side effect of changing the clock time: not what I expected. You must, therefore, set the TZ first, then DST, then the clock, which does not follow the menu’s natural order of things.

The camera sets file timestamps as it creates the files, but Linux also meddles with the values while displaying them. Some doc suggests that Linux regards FAT file timestamps as UTC and applies DST correction, which seems to match what I see. There’s a mount option (-o tz=UTC) that seems to have no effect, as well as an undocumented time offset (-o time_offset=60) that also has no effect.

Setting the TZ to GMT+0 (Sony uses GMT, not UTC) for simplicity, setting the clock to the correct local time, and twiddling DST shows that:

  • Rebooting (remove /insert battery) doesn’t change anything
  • Metadata in file = clock setting – DST setting (-1 on, +0 off)
  • MP4 / THM file create / modify times = always clock +1 hour
  • MP4 / THM file access times = as create / modify until next Linux access

Under those conditions, with the clock set to (locally accurate) 1908, UTC+1, and DST off, then the Exif timestamp metadata for a movie created at that time look like this:

exiftool /mnt/part/MP_ROOT/100ANV01/MAH00036.MP4 | grep -i date
File Modification Date/Time     : 2014:09:01 20:08:09-04:00
File Access Date/Time           : 2014:09:01 19:10:14-04:00
File Inode Change Date/Time     : 2014:09:01 20:08:09-04:00
Create Date                     : 2014:09:01 19:08:03
Modify Date                     : 2014:09:01 19:08:08
Track Create Date               : 2014:09:01 19:08:03
Track Modify Date               : 2014:09:01 19:08:08
Media Create Date               : 2014:09:01 19:08:03
Media Modify Date               : 2014:09:01 19:08:08

The corresponding filesystem values:

ll /mnt/part/MP_ROOT/100ANV01/
total 146M
... snippage ...
-rwxr-xr-x 1 ed root  14M 2014-09-01 20:08 MAH00036.MP4
-rwxr-xr-x 1 ed root 8.5K 2014-09-01 20:08 MAH00036.THM

ll -c /mnt/part/MP_ROOT/100ANV01/
total 146M
... snippage ...
-rwxr-xr-x 1 ed root  14M 2014-09-01 20:08 MAH00036.MP4
-rwxr-xr-x 1 ed root 8.5K 2014-09-01 20:08 MAH00036.THM

ll -u /mnt/part/MP_ROOT/100ANV01/
total 146M
... snippage ...
-rwxr-xr-x 1 ed root  14M 2014-09-01 19:10 MAH00036.MP4
-rwxr-xr-x 1 ed root 8.5K 2014-09-01 20:08 MAH00036.THM

The THM file contains a 160×120 pixel JPG thumbnail image taken from the first frame of the corresponding MP4 file. For longer movies, it’s more obvious that the MP4 file creation date is the start of the movie and its modification date is the end. The maximum 4 GB file size of corresponds to exactly 22:43 of 1920×1080 movie @ 60 frame/sec (the metadata says 59.94).

The +1 hour offset in the file create / modify times comes from the FAT timestamp being (incorrectly) adjusted by the Linux DST setting. When exiftool reads the MP4 file, that resets its access time to the actual time as seen by Linux, thereby crushing the bogus FAT time.

Doing the seemingly sensible thing of setting the camera to have the correct local time (roughly 1930), the correct time zone, and the correct DST setting produces this jumble:

exiftool /mnt/part/MP_ROOT/100ANV01/MAH00037.MP4 | grep -i date
File Modification Date/Time     : 2014:09:01 20:33:15-04:00
File Access Date/Time           : 2014:09:01 20:33:14-04:00
File Inode Change Date/Time     : 2014:09:01 20:33:15-04:00
Create Date                     : 2014:09:01 23:33:11
Modify Date                     : 2014:09:01 23:33:14
Track Create Date               : 2014:09:01 23:33:11
Track Modify Date               : 2014:09:01 23:33:14
Media Create Date               : 2014:09:01 23:33:11
Media Modify Date               : 2014:09:01 23:33:14

ll /mnt/part/MP_ROOT/100ANV01/MAH00037*
-rwxr-xr-x 1 ed root  11M 2014-09-01 20:33 /mnt/part/MP_ROOT/100ANV01/MAH00037.MP4
-rwxr-xr-x 1 ed root 8.2K 2014-09-01 20:33 /mnt/part/MP_ROOT/100ANV01/MAH00037.THM

ll -c /mnt/part/MP_ROOT/100ANV01/MAH00037*
-rwxr-xr-x 1 ed root  11M 2014-09-01 20:33 /mnt/part/MP_ROOT/100ANV01/MAH00037.MP4
-rwxr-xr-x 1 ed root 8.2K 2014-09-01 20:33 /mnt/part/MP_ROOT/100ANV01/MAH00037.THM

ll -u /mnt/part/MP_ROOT/100ANV01/MAH00037*
-rwxr-xr-x 1 ed root  11M 2014-09-01 19:34 /mnt/part/MP_ROOT/100ANV01/MAH00037.MP4
-rwxr-xr-x 1 ed root 8.2K 2014-09-01 20:33 /mnt/part/MP_ROOT/100ANV01/MAH00037.THM

The only correct time in that mess is in the next-to-last line: the access time for the MP4 file. Every other timestamp comes out wrong, with the internal metadata values being off by +4 hours; that suggests the camera sets the internal timestamps to UTC.

As nearly as I can figure, the only way to make this work requires setting the clock to the local time, TZ to UTC+0, and DST off. That will screw up the filesystem timestamps, but at least the Exif metadata will be correct, for some value of correct.

The camera’s GPS receiver depends on the clock for its initial synchronization. I don’t know how the TZ and DST settings affect the clock’s correctness for that purpose.

I do not know if / how / when the displayed times have been altered by the programs that display them.

I think exiftool can extract the times from the internal metadata and fix up the filesystem times, but that’ll take more tinkering.

Sheesh & similar remarks…


Booklet Printing

Most technical papers intended for publication in Refereed Journals have huge margins. When I print them up as pamphlets for E-Z reading in the Comfy Chair, the text becomes an unreadably small block in the middle of the page.

Having tried various simple hacks that don’t work, the best solution so far involves a bit of PostScript magic…

pdfcrop --margins 36 whatever.pdf
pdftops -level3 -origpagesizes whatever-crop.pdf -f 1

Which will emit whatever-crop_book.pdf. Print the odd pages, reinsert the stack, print the even pages, then either fold or slice/bind as appropriate.

The --margins 36 puts a little whitespace around the text, which may be needed to get the text block out of the gutter if you’re binding the booklet. For those documents, --margins "36 0 18 0" may be more useful; note the blanks, not commas. This requires tuning for best picture, depending on the incoming PDF layout.

The -origpagesizes prevents the next step from assuming an incorrect page size. This is definitely necessary, at least in my experience so far.

The -f 1 enlarges the source text to fill the output page, which is the key step making the whole thing work for small incoming page sizes. However, there’s a weird interaction between this and the pdfcrop margins that I haven’t figured out yet; a zero-width incoming margin [may | may not] jam some line ends against the right edge of the output sheet.

That’s all derived from some booklet-printing hints in the Scribus wiki. A working link (as of today, anyhow) for the script:

The R380 emits pages bassackwards for reading, but in the proper order for duplexing: the blank side of the first sheet is on the bottom of the stack, so it becomes the top of the flipped stack, ready to go back into the printer as the first sheet again.

Conversely, the HPLJ1200 produces output in normal reading order, with the blank side of the last sheet on top of the stack: flip and print the back sides in reverse order.


Verifying a 64 GB MicroSD Card

Having just acquired a pair of 64 GB MicroSD cards for the HDR-AS30V camera, I found that I don’t have enough free disk space for 64 GB of white noise and, thus, can’t use the same technique as for the 32 GB card. I now, however, have a stockpile of helmet camera video files that are close enough to white noise for my purposes and come in convenient chunks.

Start by copying enough big video files to nearly fill the card:

sudo mount /dev/sdb1 /mnt/backup
sudo mount -o uid=ed /dev/sdc1 /mnt/part
FUSE exfat 1.0.1
cd /mnt/backup/Video
find -iname MAH*MP4 -size +3G | head -16 | xargs -I{} rsync -vrt --progress {} /mnt/part
sending incremental file list
  4,275,755,727 100%   11.94MB/s    0:05:41 (xfr#1, to-chk=0/1)

sent 4,276,799,695 bytes  received 35 bytes  12,487,006.51 bytes/sec
total size is 4,275,755,727  speedup is 1.00
... snippage ...

The head -16 ensures that you won’t waste a lot of time copying too many files. The card has about 59 GB free, so 16 x 4 GB is about right.

The -vrt adds verbosity and omits permission settings that ExFAT doesn’t understand; otherwise, you’d just use -va and be done with it.

Then tuck some smaller files into the remaining nooks and crannies:

find -iname MAH*MP4 -size -400M | head -16 | xargs -I{} rsync -vrt --progress {} /mnt/part
... snippage ...

Some fiddling with the -size -400M and head -16 values may be in order, depending on how many snippets of video data you may have.

Compare the copies with the original files:

cd /mnt/part
for f in * ; do find /mnt/backup/Video/ -name $f | xargs diff $f ; done

If you don’t see anything, then they’re all good!

There’s probably an algorithmic solution that would eliminate the guesstimation, but very nearly all of the time goes to copying and comparing, so it can’t make much difference.