High Voltage Programmer

I’ve been experimenting with using non-standard pins on an ATtiny85. Using XTAL1 and XTAL2 is simple if you run off the internal oscillator at 8MHz/3.3v but I want to also use the RESET pin as D5/A0.

When you re-purpose the RESET pin, you lose the ability to program using an ISP, so we have to use a high voltage serial programmer (HVSP) which basically applies 12v to the RESET pin to set the fuses.

I redesigned the stripboard from here for use with perfboard and used a 2N2222 transistor as I have plenty of them, as well as a DC barrel jack for the 12v supply.

The hv_rescue.ino sketch which you load onto an Uno is as follows, I modified it slightly to compile nicely without needing the IDE:

// AVR High-voltage Serial Programmer
// Originally created by Paul Willoughby 03/20/2010
// http://www.rickety.us/2010/03/arduino-avr-high-voltage-serial-programmer/
// Inspired by Jeff Keyzer http://mightyohm.com
// Serial Programming routines from ATtiny25/45/85 datasheet

// Desired fuse configuration
#define  HFUSE  0xDF   // Defaults for ATtiny25/45/85
#define  LFUSE  0x62

//#define  HFUSE  0x5F   // reset as gpio5
//#define  LFUSE  0xE2   // 8mhz internal oscillator

// For Attiny13 use
// #define HFUSE 0xFF
// #define LFUSE 0x6A  

#define  RST     13    // Output to level shifter for !RESET from transistor to Pin 1
#define  CLKOUT  12    // Connect to Serial Clock Input (SCI) Pin 2
#define  DATAIN  11    // Connect to Serial Data Output (SDO) Pin 7
#define  INSTOUT 10    // Connect to Serial Instruction Input (SII) Pin 6
#define  DATAOUT  9    // Connect to Serial Data Input (SDI) Pin 5 
#define  VCC      8    // Connect to VCC Pin 8

int inByte = 0;         // incoming serial byte Computer
int inData = 0;         // incoming serial byte AVR

void establishContact() {
  while (Serial.available() <= 0) {
    Serial.println("Enter a character to continue");   // send an initial string
    delay(1000);
  }
}

int shiftOut2(uint8_t dataPin, uint8_t dataPin1, uint8_t clockPin, uint8_t bitOrder, byte val, byte val1)
{
	int i;
        int inBits = 0;
        //Wait until DATAIN goes high
        while (!digitalRead(DATAIN));
        
        //Start bit
        digitalWrite(DATAOUT, LOW);
        digitalWrite(INSTOUT, LOW);
        digitalWrite(clockPin, HIGH);
  	digitalWrite(clockPin, LOW);
        
	for (i = 0; i < 8; i++)  {
                
		if (bitOrder == LSBFIRST) {
			digitalWrite(dataPin, !!(val & (1 << i)));
                        digitalWrite(dataPin1, !!(val1 & (1 << i)));
                }
		else {
			digitalWrite(dataPin, !!(val & (1 << (7 - i))));
                        digitalWrite(dataPin1, !!(val1 & (1 << (7 - i))));
                }
                inBits <<=1;
                inBits |= digitalRead(DATAIN);
                digitalWrite(clockPin, HIGH);
		digitalWrite(clockPin, LOW);
                
	}

        
        //End bits
        digitalWrite(DATAOUT, LOW);
        digitalWrite(INSTOUT, LOW);
        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
        
        return inBits;
}

void readFuses(){
     //Read lfuse
    shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x04, 0x4C);
    shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x00, 0x68);
    inData = shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x00, 0x6C);
    Serial.print("lfuse reads as ");
    Serial.println(inData, HEX);
    
    //Read hfuse
    shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x04, 0x4C);
    shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x00, 0x7A);
    inData = shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x00, 0x7E);
    Serial.print("hfuse reads as ");
    Serial.println(inData, HEX);
    
    //Read efuse
    shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x04, 0x4C);
    shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x00, 0x6A);
    inData = shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x00, 0x6E);
    Serial.print("efuse reads as ");
    Serial.println(inData, HEX);
    Serial.println(); 
}

void setup()
{
  // Set up control lines for HV parallel programming
  pinMode(VCC, OUTPUT);
  pinMode(RST, OUTPUT);
  pinMode(DATAOUT, OUTPUT);
  pinMode(INSTOUT, OUTPUT);
  pinMode(CLKOUT, OUTPUT);
  pinMode(DATAIN, OUTPUT);  // configured as input when in programming mode
  
  // Initialize output pins as needed
  digitalWrite(RST, HIGH);  // Level shifter is inverting, this shuts off 12V
  
  // start serial port at 9600 bps:
  Serial.begin(9600);
  
  establishContact();  // send a byte to establish contact until receiver responds 
  
}

void loop()
{
  // if we get a valid byte, run:
  if (Serial.available() > 0) {
    // get incoming byte:
    inByte = Serial.read();
    Serial.println(byte(inByte));
    Serial.println("Entering programming Mode\n");

    // Initialize pins to enter programming mode
    pinMode(DATAIN, OUTPUT);  //Temporary
    digitalWrite(DATAOUT, LOW);
    digitalWrite(INSTOUT, LOW);
    digitalWrite(DATAIN, LOW);
    digitalWrite(RST, HIGH);  // Level shifter is inverting, this shuts off 12V
    
    // Enter High-voltage Serial programming mode
    digitalWrite(VCC, HIGH);  // Apply VCC to start programming process
    delayMicroseconds(20);
    digitalWrite(RST, LOW);   //Turn on 12v
    delayMicroseconds(10);
    pinMode(DATAIN, INPUT);   //Release DATAIN
    delayMicroseconds(300);
    
    //Programming mode
    
    readFuses();
    
    //Write hfuse
    Serial.println("Writing hfuse");
    shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x40, 0x4C);
    shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, HFUSE, 0x2C);
    shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x00, 0x74);
    shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x00, 0x7C);
    
    //Write lfuse
    Serial.println("Writing lfuse\n");
    shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x40, 0x4C);
    shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, LFUSE, 0x2C);
    shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x00, 0x64);
    shiftOut2(DATAOUT, INSTOUT, CLKOUT, MSBFIRST, 0x00, 0x6C);

    readFuses();    
    
    Serial.println("Exiting programming Mode\n");
    digitalWrite(CLKOUT, LOW);
    digitalWrite(VCC, LOW);
    digitalWrite(RST, HIGH);   //Turn off 12v
  }
}

I then uploaded the following sketch to the ATtiny85 using make ispload, as you can see its using D5 to blink an LED:

const int led = 5;

void setup()
{
    pinMode(led, OUTPUT);
}

void loop()
{
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
}

The Makefile is as follows, I used the latest IDE and the ATTinyCore as it supports more chips and I wanted to experiment with something other than the usual arduino-tiny or attiny-master with IDE 1.0.5:

ARDUINO_DIR = $(HOME)/arduino-1.8.5

ISP_PROG       = usbasp
AVRDUDE_OPTS   = -v
ALTERNATE_CORE = ATTinyCore
BOARD_TAG      = attinyx5
BOARD_SUB      = 85
F_CPU          = 8000000L
ISP_HIGH_FUSE  = 0x5F
ISP_LOW_FUSE   = 0xE2

include $(HOME)/Arduino-Makefile/Arduino.mk

The important bit is to then edit the hv_rescue.ino file to set the fuses:

#define  HFUSE  0x5F   // reset as gpio5
#define  LFUSE  0xE2   // 8mhz internal oscillator

Then upload that to the Uno, connect the HVSP board with the ATtiny85 mounted, and press a key to set the fuses. If you don’t edit the script it’ll just reset the fuses to their defaults of 0xDF and 0x62.

The order is important, as you can’t ISP the chip after you’ve set the fuse to disable RESET, so you can’t use make set_fuses for example, you have to use the HVSP to set the fuses, after ISP’ing the sketch. If you want to edit the sketch, you’ll have to reset the fuses, then ISP the sketch and set the fuses back again, so its not something you want to do often – maybe develop using a regular GPIO pin like D2, then when you’re ready switch to D5.

I made a PR to fix that – so you make ispload to upload the sketch, then make set_fuses to set the fuses, after which you need to reset them using the HVSP.

You can then blink six LED’s using an ATTiny85 (the RESET pin has lower power output) with just VCC and GND connected (no crystal etc.) using for example:

#include <avr/io.h>

void setup()
{
    // set d0-d5 as outputs
    DDRB = B11111111;
}

void loop()
{
    // set all high
    PORTB = B11111111;
    delay(500);

    // invert all
    PORTB ^= PORTB;
    delay(500);
}

There are other more complicated sketches around which can auto-detect the chip and prompt for the fuses to set, but they seem to require a button and a 12v DC-DC boost converter, as per the Rescue Shield

RPi Soldering Scope

I’m thinking of making a soldering microscope from a Raspberry Pi (either a spare B+ I have or maybe a ZeroW). I had looked at Andonstar ADMSM201 or Lapsun 14MP HDMI 180x scopes, but they each have their limitations – crap software, tiny focal length requiring additional lenses, £200+ pricetags…..

So looking at it, I just have to buy a Pi camera module with a CS mount and a decent lens. Then I can either stream the display or plug into a HDMI monitor. Even without a Barlow lens I should get at least 20cm working area beneath the camera.

The only problem is how to mount it. I’m thinking of a threaded rod from a 3D printer attached to my wooden 3rd arm board and some sort of 3D printed bracket. I only really need up/down not left/right or forwards/backwards (I can just move whatever I’m soldering). I even thought of a laboratory retort stand.

I’m going to try without illumination initially, and potentially make something from a Neopixel ring that could be controlled by the Pi and potentially powered from the same USB supply.

BOM is currently:

I’ve made a pi camera to CS mount adaptor and I’ve also modified my Pi ZeroW case to include a screw-on CS mount adaptor and holes for a shutdown/reset button and wires for a Neopixel ring which I’ll probably use instead of a regular LED ring, or I may use a 12v PSU and some spare LED strip.

ArduinoOTA Solution for ESP8266

I’ve wasted about three days trying to get OTA upgrades to work on my ESP8266 boards. They take 1-2 OTA’s and then don’t even boot into the sketch. Tried my Gizwits WiFi Witty and ESP12F on a breakout board with an LDO as described in my earlier post. Then I tried my old NodeMCUv2 board and it worked fine, all of the time.

Turns out we need moar powah!

The HT7833 LDO on the white breakout boards from the earlier post, are supposed to be able to put out 500mA so I guess its not a current problem but a voltage one, when measuring what gets through to the ESP its just over 3.3v. I bypassed the LDO and fed a 3.7v LiPo to VCC and it works fine now!

Whilst playing around trying to get it to work I added the 4x 10k resistors and a 100nF capacitor across the ESP’s VCC/GND pins as well as a 470uF capacitor across the power rails feeding the LDO, as per here. Didn’t seem to make any difference.

On a related note, the pinout of those white boards is insane. Turns out the VCC pin on the white board is where you should feed the supply into the LDO. It’s connected to VIN (middle pin). But bizarrely VCC on the ESP is not fed from there, its fed from a via from the LDO’s VOUT (right pin) and it seems CH_PD is fed from that via the leftmost 10k resistor on the breakout. So don’t power other components or connect other ESP pins to VCC as it’ll be running 8v or whatever you’re inputting!

I removed the LDO and had to replace the middle 000 resistor (solder blob) so that the breakout VCC goes to the ESP VCC.

So essentially if you want to use the LDO (I’d advise against it) you have to remove the 000 resistor and feed the LDO up to 8v via the breakout’s VCC pin, then run a jumper wire from VOUT on the LDO to the ESP’s VCC pin. I used the leftmost via as seen from the top, near VCC/GPIO13 pins rather than running a wire over and under the breakout.

If you don’t want to use the LDO, leave the breakout as it was and feed 3.7v into the VCC pin.

Update: I found that you can power the breakout from an external ~3.5v power source (with short wires) as long as you add:

  • 470uF capacitor on power rail
  • 0.1uF capacitor on power rail near to the VCC/GND pins
  • 10k pullup on RST pin
  • 10k pullup on GPIO0
  • 10k pullup on GPIO2
  • No pulldown on GPIO15 it already has one
  • No pullup on CH_PD it already has one

You can just about manage OTA’s this way but more than one sensor or LED and the thing falls over again! Nodemcu’s just seem much more robust.

I’ve received my free Amazon Echo – wow I need to get another when they’re £80 again! They are amazing! I’ve been using the fauxmoESP library to control the LED on an ESP8266, sooooo easy.

Here’s my sketch, including OTA code. Note to generate an MD5SUM to use as your OTA password, you need to call echo -n "otapassphrase" | md5sum to ensure you don’t get a newline! Then pass espota.py the plaintext string.

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include "fauxmoESP.h"

// init vars
const int RED = 15;
const int GREEN = 12;
const int BLUE = 13;

// constructor
fauxmoESP fauxmo;

void callback(uint8_t device_id, const char * device_name, bool state)
{
    Serial.print("Device ");
    Serial.print(device_name);
    Serial.print(" state: ");
    if (state)
    {
        Serial.println("ON");
        analogWrite(RED, random(0,1023));
        analogWrite(GREEN, random(0,1023));
        analogWrite(BLUE, random(0,1023));
    }
    else
    {
        Serial.println("OFF");
        analogWrite(RED, 0);
        analogWrite(GREEN, 0);
        analogWrite(BLUE, 0);
    }
}

void setup()
{
    // configure led
    pinMode(RED, OUTPUT);
    pinMode(GREEN, OUTPUT);
    pinMode(BLUE, OUTPUT);
    analogWrite(RED, 512);
    analogWrite(GREEN, 0);
    analogWrite(BLUE, 0);

    // debug
    Serial.begin(115200);
    Serial.setDebugOutput(false);
    Serial.println("After connection, ask Alexa to 'turn pixel on' or 'off'");

    // wifi
    WiFi.mode(WIFI_STA);
    WiFi.begin("myssid", "mypassword");
    WiFi.config(IPAddress(192, 168, 1, 2), IPAddress(192, 168, 1, 1), 
         IPAddress(255, 255, 255, 0), IPAddress(8,8,8,8));

    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }

    // ota
    ArduinoOTA.setPasswordHash("b7e82cbfc5bf5f1a44d8e5e526e2f1fe");
    ArduinoOTA.begin();

    // fauxmo
    fauxmo.addDevice("pixel");
    fauxmo.onMessage(callback);
}

void loop()
{
    fauxmo.handle();
    ArduinoOTA.handle();
}

I’ve improved my ESP Makefile to handle OTA and debugging etc (mind the word-wrapping on the fqbn line)

ARDUINO_PATH = $(HOME)/arduino-1.8.3
SKETCHBOOK   = $(HOME)/arduino16
ESPTOOL		 = $(SKETCHBOOK)/hardware/esp8266com/esp8266/tools/esptool/esptool
ESPOTA		 = $(SKETCHBOOK)/hardware/esp8266com/esp8266/tools/espota.py
SKETCH 		 = $(notdir $(CURDIR)).ino
TARGET_DIR   = $(CURDIR)/build-esp8266
MONITOR_PORT = /dev/ttyUSB0
OTA_IP		 = 192.168.1.2
OTA_PASSWD	 = otapassphrase
#DEBUG		 = ,Debug=Serial,DebugLevel=all_____
DEBUG		 = 

all:
	@ mkdir -p $(TARGET_DIR)

	$(ARDUINO_PATH)/arduino-builder -compile -logger=machine \
	-hardware "$(ARDUINO_PATH)/hardware" \
	-hardware "$(SKETCHBOOK)/hardware" \
	-tools "$(ARDUINO_PATH)/tools-builder" \
	-tools "$(ARDUINO_PATH)/hardware/tools/avr" \
	-built-in-libraries "$(ARDUINO_PATH)/libraries" \
	-libraries "$(SKETCHBOOK)/libraries" \
	-fqbn=esp8266com:esp8266:generic:CpuFrequency=80,CrystalFreq=26,FlashFreq=40,
        FlashMode=dio,UploadSpeed=115200,FlashSize=4M3M,ResetMethod=nodemcu$(DEBUG) \
	-ide-version=10803 \
	-build-path "$(TARGET_DIR)" \
	-warnings=none \
	-prefs=build.warn_data_percentage=75 \
	-verbose "$(SKETCH)"

flash:
	$(ESPTOOL) -v -cd nodemcu -cb 115200 -cp $(MONITOR_PORT) -ca 0x00000 -cf $(TARGET_DIR)/$(SKETCH).bin

ota:
	$(ESPOTA) -i $(OTA_IP) -I 192.168.1.3 -a $(OTA_PASSWD) -f $(TARGET_DIR)/$(SKETCH).bin

clean:
	rm -rf $(TARGET_DIR)

monitor:
	screen $(MONITOR_PORT) 115200

Once you’ve discovered your device using the Alexa app (or go to echo.amazon.com then “Smart Home” > Devices > Discover) you just say “Alexa, turn pixel on”.

Budget Portable Power Supply

I just made a portable power supply out of a few components. I wanted something more flexible than my bench supply.

So the parts list is: TP4056, which can charge a LiIon or LiPo battery at the same time as powering a circuit from it, or USB. In powerbank terms it would be called pass-through. It also provides over [dis]charge protection but I don’t think reverse polarity protection (could be solved with a diode). I made another post detailing how to adjust the charge current, but I’ve left it at the default 1A for this project. I buy these in packs of five usually, they come to about 26p each.

Next up is the MT3608 DC-DC boost convertor, not sure why they’re called that when the chip is actually a B6286K. That can boost 2v input to 28v (24v?) 2A output, adjustable with the onboard potentiometer. Cost me 29p. I used some small jumper cables to join the OUT +/- of the TP4056 to the IN +/- of the boost.

Taking the output from that we have the voltmeter which samples the input and displays it on a nice 7-segment display. Cost me 76p. You have to wire the red and white wires both to the boost converter’s output as the display only works down to 4.5v, but in this configuration you can can power the boost converter from 2v and have the voltmeter still display as long as the boost’s output is 4.5v or more. Largely irrelevant in this project as the TP4056 output is always going to be above about 3.3v or so from the batteries. A smaller alternative without the case is this for 75p.

I soldered some pin headers onto the boost converter’s output pads alongiside the voltmeter wires. I also soldered some JST cables to the BAT +/- pads of the TP4056 as eventually I’ll use a LiPo battery instead of the Li-Ion (which I just temporarily connected using magnets). To charge the battery just connect a powerbank or whatever to the micro USB connector on the TP4056 board (not the one on the boost board). JST cables cost me 10p each in a pack of ten pairs (red+black female & red+black male, times ten).

So total cost of £1.40, plus the price of the battery.

I made some 3D printable containers for the individual parts but probably won’t use them for this project:

Update: I’m thinking about making a case that will hold the battery, boost, charger and voltmeter with a JST connector or Dupont cables or screw terminals as output, access to the potentiometer for adjusting the voltage and the micro USB port for charging; as everything is about the same size:

Update 2: I made the case, swapped the Li-Ion for a LiPo here.

Big Update

Its been quite a while since my last post, so here’s a big one…..

I’ve been doing a lot of 3D printing since I received my FlashForge Creator Pro 2016. I learned OpenSCAD and FreeCAD, my designs are here. I’ve made various enclosures for Arduino’s and Raspberry Pi’s, as well as USBASP cases, voltmeter cases, solder tip holders, calliper battery savers, resistor forming tools, soldering helping hands, bottle openers, trolley tokens, SD card holders, PIR cases, Dremel accessories, various 3D printer upgrades and the usual calibration prints.

Yesterday I upgraded Dad’s Lenovo B570 laptop to Ubuntu 16.04 from 12.04, which was fun due to its broken EFI setup – basically it has a BIOS and not SecureBoot but the installer sees it as using GPT+EFI instead of a simple MBR. Weirdness such as failure to boot from USB and then failure to boot from HDD once I’d installed from DVD ensued. Boot-Repair fixed the problem, from what I can see it installed some dummy EFI files in the EFI partition, which the 12.04 install obviously nuked. Had to disable hardware acceleration in Chrome to prevent Flash flickering, but otherwise it seems to be working fine.

Today I modified an SG90 servo for continuous rotation, basically removed the wiper on the potentiometer and replaced it with a couple of SMD resistors, and cut the tab off of the largest gear. I found that there is no trimpot to adjust the zero position on my servo so I altered my code to send 100 instead of 90 for “stop”, which I found using some trial and error. Values lower than 100 move clockwise (the lower the number, the faster movement) and greater than 100 moves anti-clockwise (the higher, the faster).

When you write a value to the servo, you’re no longer giving it a degree value, you’re setting a pusle width. So instead of “rotate to 40 degrees” you’re saying “run for 1200uS”, just like a DC motor with H-bridge, which is essentially what is inside a servo. The upside is that the servo can rotate 360 degrees, the downside is that you don’t know where its rotated to as the microcontroller receives no feedback.

My test code is below – its moves it left, right, fast, slow and stop.

continuous_servo.ino

#include <Servo.h>

// create servo object
Servo myservo;

// speeds for my sg90
#define FASTCW  45
#define SLOWCW  90
#define STOP    100
#define FASTACW 135
#define SLOWACW 110

void setup()
{
    // attach servo to D9
    myservo.attach(9);
}

void loop()
{
    myservo.write(FASTCW);
    delay(2000);

    myservo.write(STOP);
    delay(1000);

    myservo.write(FASTACW);
    delay(2000);

    myservo.write(STOP);
    delay(1000);

    myservo.write(SLOWCW);
    delay(2000);

    myservo.write(STOP);
    delay(1000);

    myservo.write(SLOWACW);
    delay(2000);
    
    myservo.write(STOP);
    delay(1000);
}

Makefile

BOARD_TAG = uno
MONITOR_PORT = /dev/ttyUSB0
include /usr/share/arduino/Arduino.mk

I’ve also been making custom power cables lately, such as a USB to DC jack for giving 5v to older projects such as a 555 astable from a powerbank. It seems that microUSB should be the new go-to connector for power instead of 2.1×5.5mm DC jacks these days. I’ve actually got some USB-to-DIP breakout boards as well as the TP4056 Li-On charger boards. I’ve also got some USB boost regulators on the way that apparently can output up to 28v or something silly. My next custom cable will likely be banana plugs to pin headers as its a pain trying to put a male pin header on a screw terminal.

Finally I had a play with a MCP23017 port expander which I was thinking of using when my ESP8266 projects don’t have enough pins – like my RTC clock could have done with 1-2 more buttons. But it seems like a lot of wiring e.g. 8 pins before you’ve even added any I/O, and a lot of calls to the Wire library e.g. 4 calls just to send an output like lighting an LED, so I think I’ll hold out for ESP32’s to be generally available before doing any more pin-intensive projects.