October 15, 2020

I have a new blog!

 

 

May 13, 2015

Using the ADC on NodeMCU (ESP8266)

The ADC on ESP8266 is poorly documented. It is note even mentioned in the datasheet. I did some measurements with a variable power supply to understand how it works. The experiments are done with the NodeMCU firmware 0.95. File: nodemcu_20150213.bin (link)

What pin is the ADC input?
TOUT on an ESP8266 module.
A0 on a NodeMCU Devkit.

What is the range of the NodeMCU ADC input?
Measured range: 0 - Vdd. (About 3.1 V in this case)
Number of bits: 10 bit (Codes: 0-1024)

Note that the NodeMCU board has a voltage divider on the ADC input. The ESP8266 module it self has 0 - 1.0 V input range.

Readings are done with the command: print(adc.read(0))
0.5 V => 167
1.0 V => 330
1.5 V => 498
2.0 V => 666
2.5 V => 828
3.0 V => 995
3.1 V => 1024 (saturated)

I did a plot of the values and it looks linear.
Do I need to power down WiFi before using the ADC?
There seems that it at least has been a problem in earlier versions of the SDK but I did not have any problems with interference when using WiFi and the ADC at the same time. If you see any issues try to power down the radio with:
wifi.sleeptype(wifi.MODEM_SLEEP)

Can I measure the supply voltage?
It is possible to read the supply voltage. It is done internaly in the chip so thre is no need to connect it to the ADC input. Use the NodeMCU command:
print(node.readvdd33())
for later versions og NodeMCU firmware use:
print(adc.readvdd33())

It returns a value in mV. I got 3123. Be careful to use this call since it is buggy and will cause reboots quite often when called!

May 8, 2015

Power Meter pulse logger with ESP8266 running NodeMCU


This device is installed in my home to monitor the usage of electricity. It counts the pulses from the meter and produces a log file with number of pulses and a time stamp that can later be analyzed. The hardware is quite simple. The NodeMCU development kit board with an ESP8266 running the NodeMCU firmware is connected to a phototransistor with an pull-down resistor. The firmware and my lua script seems stable since it has been running for more than 10 days without problems.




The phototransistor used is PT204-6C. It is aimed at the pulse windows on the power meter.

I also working on a php script that produces a diagram.
Below is the NodeMCU lua code. Pin 1 is set to generate an interrupt on the rising edge. I had some issues with pulses counted multiple times probably due to bounce in the input signal. I have solved this by only inrement the counter if there is a gap of 20 ms or more between interrupts since the pulse is about 10 ms wide. This is done with the method described in my previous post. Every 60 seconds it also loads a webpage with a php script that writes to a log file.
elog.lua
pin = 1
led = 0
min_pw_ms = 20
upload_rate_ms = 60000

pulse_detected = 0
timestamp = 0
counter = 0
conn = nil

gpio.mode(led, gpio.OUTPUT)
gpio.mode(pin, gpio.INT)

gpio.write(led, gpio.LOW)

if not wifi.sta.getip() then
print("Connecting to wifi")
wifi.setmode(wifi.STATION)
    wifi.sta.config("net_name","net_pwd")
ip = wifi.sta.getip()
print(ip)
end

function upload() 
conn = net.createConnection(net.TCP, 0) 
conn:on("receive", 
function(conn, payload) 
success = true
print(payload)
end)
conn:on("disconnection", 
function(conn, payload)
print('\nDisconnected')
end)
conn:on("connection", 
function(conn, payload) 
print('\nConnected') 
conn:send("GET/ logdata.php?"
.."timestamp="..timestamp
.."&key=your-key"
.."&counter="..counter
.." HTTP/1.1\r\n" 
.."Host: your_host.com\r\n" 
.."Connection: keep-alive\r\n"
.."Accept: */*\r\n" 
.."User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n" 
.."\r\n")
end)
print("Opening port")
conn:connect(80,'your_host.com') 
end

function pin1up(level)
pulse_detected = 1
end

function maintask()
        print("Counter is:"..counter)
        if not wifi.sta.getip() then
            print("Connecting to AP, Waiting...") 
        else  
            gpio.write(0, gpio.HIGH)
            print("Uploading to server...")
            upload()
       end
end

function pulsetask()
timestamp = timestamp + 1
if pulse_detected == 1 then
counter = counter + 1
pulse_detected = 0
end
end

gpio.trig(pin, "up", pin1up)
tmr.alarm(0, upload_rate_ms, 1, maintask);
tmr.alarm(1, min_pw_ms,      1, pulsetask);

maintask();

This is the php script on the server. It has a simple security feature with a secret key to avoid bots bloating the log. The firmaware loads the url:
http://your-host.com/logdata.php?timestamp=1111&key=your-key&counter=8888
The script extracts the parameters from the url and creates an entry in a file. There is a new file create every 24 hour.
logdata.php
<?php
$delim = ", ";
$referer = getenv('HTTP_REFERER');
$timestamp = $_GET['timestamp'];
$counter = $_GET['counter'];
$key = $_GET['key'];

$secret = "your-key";

date_default_timezone_set("Europe/Stockholm");

$entry = date("Y-m-d") . $delim . date("H:i:s") . $delim . $timestamp . $delim . $counter . "\n";
         
echo $entry;

$file = "datalog_". date("Y-m-d") . ".txt";

if ($key === $secret)
{
  echo "Valid key\n";
  file_put_contents($file, $entry, FILE_APPEND);
}
else
{
  echo "Invalid key\n";
  echo $key;
}
?>

April 28, 2015

NodeMCU tmr.time() and tmr.now() bugs


The NodeMCU firmware has some nasty bugs in the tmr.time() and tmr.now() functions so don't use them!

From what I have observed in v0.95 and v0.9.6-dev_20150406 the following happens.

tmr.time(), that returns system time in seconds, makes a jump after 25430 seconds (about 7 hours).

       25427
       25428
       25429
       25430
       27043
       27044
       27045
       27046
       27047

tmr.now(), that returns system time in us, does at some point in time freeze and returns the same value for every call.

Theses bugs makes the functions unusable. The bugs seems to originate from the ESP8266 SDK used for the build rather that the implementation of NodeMCU it self. This will probably make it hard to fix. Luckily there is is a workaround since tmr.alarm() works fine. With tmr.alarm() you can easily create your own time measuring function. At least if you are fine with ms resolution. Hers thee code:

perid_ms = 100
timestamp = 0
tmr.alarm(0, period_ms, 1, function()
  timestamp = timestamp + 1
  end )

Then you can use the variable timestamp in you code to make time measurements.

September 17, 2014

Smartphone Controlled Home

This post describes a low cost open source home automation system that you can build your self. The goal is to use a smartphone as remote controller for your home. The system is based on the openHAB software and MySensors Arduino library.

Home automation enables you to observe and control your home. You can observe temperature, humidity, energy consumption and so on. It will also let you control your lights, media units, window blinds and other objects in your home. You can also create rules based on senors value, time of day or other conditions that will automatically control your home.


Home Automation System Parts
A standard WiFi router is used to connect the smartphone to your local network. The Server (or Controller) is a computer running openHAB runtime core. This is the heart in the system that keeps track of the system. This can be a Window or Linux computer. A Raspberry Pi will do the job. The Gateway (or Access Point) is an Arduino board running the myControler software. The sensor network is a radio network connecting the sensors and the Gateway.

User Interface
Below is a screenshot of the openHAB smart phone user interface. A web browser can also be used.


Security
The openHAB software with enabled encryption and authentication is fairly secure. But the sensor network has very few security features. Since the range of the sensor are limited it should not be a problem unless you live in a densely populated area. I would not connect it to my door lock or something that could cause damage or fire.

References
MySensors - Arduino library for the sensor radio network.
openHAB - Vendor and technology agnostic open source home automation software.

May 20, 2014

Add Verilog files recursively in Altera Quartus II

This post describes how you add multiple Verilog files recursively to your project in Altera Quartus II. If you are using VHDL you can simply change the file matching from "*.v" to "*.vhd*".

Create a file named "addallv.tcl" in your project folder with the contents listed below. Change "myfolder" to the name of the sub-folder below your project folder that contains the files (or folders with files) you would like to add. Run it in the Tcl Console with:

source addallv.tcl

addall.tcl:

package require ::quartus::project
package require fileutil
#addallv.tcl by http://www.thalin.se

set folderName "myfolder"

foreach file [fileutil::findByPattern $folderName *.v] {
    puts $file
    set_global_assignment -name VERILOG_FILE $file
}

Hints
You have to enable the the Tcl Console by selecting View -> Utility Windows -> Tcl Console.


Run the command by typing it in front of tcl> and press return.




May 16, 2014

8051 on Altera Cyclone IV

The 8051 microcontroller (aka MCS-51 or 80C51) was develop by Intel in 1980. Still over 30 year later its architecture is widely used. In this post am using the lightweight 8051 compatible core ligth52 from Open Cores on the Altera Cyclone IV TB276 board from my previous posts. This implementation runs the core at 75 MHz. It has some precompiled examples. To develop your own code you need the free SDCC C-compiler.You will also need python. I use python xy.

Download the design adopted to TB276 here.

Resource usage:
Logic elements: 1,239 / 6,272 ( 20 % )
Memory bits: 20,480 / 276,480 ( 7 % )
Embedded Multiplier 9-bit elements: 1 / 30 ( 3 % )
Total PLLs: 1 / 2 ( 50 % )

To get the serial port output I used an FTID cable (3.3 Volt version) with the following connections:
Black to GND
Oragen to pin 7
Yellow to pin 10
Others are unconnected.

Press button Key2 on the board to reset the core and start the output on the serial port. I used RealTerm to capture the output. Settings are 19200,8,N,1

8051

May 11, 2014

Example design for TB276 Altera Cyclone IV E FPGA board

This is an example design that defines the clock, led and button pins for the Canton-electronics TB276 board in one of my previous posts. It implements a small demo with the leds and buttons. Download the Verilog source code and project file from here: brd_test.qar. The .qar-file is an archive that can be extracted with Altera Quartus II.

How to build and download to the FPGA

1. Double click the .qar file to open it in Quartus II.

2. Press OK to extract the files and open the project.

3. Double click on Compile Design as illustrated below and wait for the compile to finish. It will take a few seconds.

Make sure that you have connected the power and the programming cable to the board. Make sure that the driver for the cable is installed. See my previous post for driver installation.



5. Hit the download button in the toolbar.

This will open the programmer window.

6. Press Hardware Setup to configure the programming cable.

7. Press Start to program the FPGA. Please note that this will program the FPGA directly and so the configuration is lost if power is cycled.

Here is a video of the result.

April 30, 2014

Ultimaker Cura slicer settings for RepRapPro Huxley

Here is how I configure Ultimaker Cura Slicer software for the RepRapPro Huxley 3D printer. The settings are for Cura 14.03 but will probably work for later versions also. The settings are for 1.75 mm PLA with 0.5 mm nozzle. When launching Cura a wizard will open.  I use these settings for my Huxley:

Step 1. RepaRap
Step 2. W=140,  D=140,  H=110, Nozzle = 0.5, Heated bed=yes, Bed center is (0,0,0) = no

Dowload my Cura profile from here.

In Cura load the file with: File -> Open profile...

I generate gcode files that i put on an SDCARD. I then use Pronterface to start the print.

Below are some screenshots of how is should look after loading the profile file.

Basic:


Advance:


End gcode. I have only changed the circled line:

April 22, 2014

Low cost Altera FPGA board

After using Xilinx FPGAs for many years I decide that it was time to take a look at Altera. I googled for a suitable low cost development board that would work with the free version of the Altera tools. Most boards are quite expensive but there are less expensive alternatives. I found a promising board from a vendor in China called Canton-electronics for only ~$40 this also includes a JTAG cable. I couldn't  resist from buying it. Two weeks later it arrived. My first tests show that the board and the cable works fine. I will post more details when I have tested it more thoroughly.

Hardware
Board: TB276
Download cable: Altera USB Blaster
Bundle with board and cable ~$40 from Canton-electronics.

Board specs
FPGA: Altera Cyclone IV E 4EP4CE6E22C8N
Flash chip: EPCS4, 4Mbit
Onboard oscillator: 25MHz
10 LEDs
2 Buttons

FPGA specs
Device: Altera Cyclone IV E 4EP4CE6E22C8N
Number of logic elements: 6272 LE
Number of IO pins: 92
Embedded memory: 270 Kbits
Embedded Multiplier 9-bit: 30 instances (18-bit: 15 instances)
Embedded PLLs: 2 instances
Serial Transceivers: None

Software
Altera Quartus II Web Edition (free version) download from: www.altera.com

Installing cable drivers
The USB-Blaster driver needs to be manual installed in the device manager. You find them here after installing Quartus II: C:\altera\13.1\quartus\drivers\usb-blaster

Programming the flash
If you want the FPGA to start with your configuration you need to program the EPCS4 flash chip. Here is a guide how to do this: http://retroramblings.net/?p=622

August 31, 2013

Tutorial: Create a 3D Printable cube with OpenSCAD

Download, install and launch OpenSCAD.

Type "cube(10);" in the edit box to the left.

In the menu select:
Design-> Compile and Render (CGAL) or press F6

and then:
Design-> Export as .STL

Give your file a suitable name e.g." my_cube.stl"

Print the file on your 3D Printer by loading the .stl file in you printer software.


Here is a good source to learn more about OpenSCAD:
http://edutechwiki.unige.ch/en/OpenScad_beginners_tutorial

June 13, 2013

Random numbers with Arduino

I was looking for a good random numbers function for Arduino. Here is a summary of what i found so far.

Pseudo-random algorithm

An algorithm that produce a sequence of numbers. It will generate the same sequence every time it is used. The built in Arduino library uses this method.

Sampling an unconnected analog input

The TrueRandom library used this approach. Seems to producing more 0s than 1s.

Independent Counter

The probably_random libray uses two counters with independent sources. Seems promising.

TRNG (True Random Number Generator) module

The Atmel SAM3X8E on Arduino DUE has a dedicated block for random numbers. There is a library available for this: advancedFunctions.

May 17, 2013

Electronics Home Lab

I have built my home lab inside a computer cabinet (IKEA Husar). It has a pull-out keyboard shelf that I use it as an extension of the workspace when the doors are open. My inspiration came from a friend that had built his lab in a two door closet. The main idea is to have a workspace that can be closed when not used and to be able to resume my work later. I have used this lab for nearly ten years and I am still happy with it!

In the upper part of the cabinet I keep commonly used tools and instruments. On the top shelf are two PSUs, a signal generator, assortment boxes with components, the SMD component kit and shelf trays with cables and small tools. On the lower shelves are things like multimeter, callipers and a power drill. At the bottom is the work space with a soldering station. On the left wall are screwdrivers, wrenches and pliers. To the left are cables hanging on hooks.The thing hanging under the shelf is an old radio scanner. You can also see a small vise hanging on the front of the workspace.

The lower part of the cabinet is used for storage of less commoly used things and toolboxes. To easily find what I looking for I use stackable clear plastic boxes.

When the doors are closed it blends nicely in to the rest of the apartment so that the muggles don't find it ;-)

May 7, 2013

Follow me on Twitter

I will start post my blog updates and other interesting things on twitter. My user name is @pthalin.  Follow me by clicking the Follow button to the right on top of this page.

April 26, 2013

Stop motion with Pentax K5 and Arduino


Sebastian Setz has created an Arduino library that can emulate an IR remote for a system camera. It supports all major brands. I created a sketch that takes a picture when i push a button. I used it to create a stop motion movie where it is important not to move the camera between shots. This library could also be used to make time laps shots where the camera takes pictures at a defined interval.

Below you can see my set up for the stop motion. To make a video of the jpg images i used MakeAVI.


Here is the video.
 

April 16, 2013

Develop for Arduino on Android - ArduinoDroid

ArduinoDroid is an Arduino development environment (IDE) for Android providing (almost) the same functionality as the computer version. Almost since not all boards and functions are supported yet. An OTG cable and Android device capable of OTG are needed to upload code to the board.

I loaded the app on my Sony Xperia V and compiled the blinker example.Then I connected the Arduino UNO and upload it without problems! A great job done by Anton Smirnov that develops this.

My set up.
 

Screenshot

April 12, 2013

Fixing slow and not responding Firefox

After the latest updates of Firefox it has started run extremely slow both at startup and when surfing. I often got "not responding" and freeze of Firefox for several seconds when loading a web page. I have also seen this on other computers. Finally I have found the magic cure. What you need to do is a reset that will rebuild your profile while keeping the most important settings (bookmarks, passwords, etc) and removing old junk.

To do the reset open the "Troubleshooting Information" window:
Windows XP: Help -> Troubleshooting Information
For later versions of Windows: Firefox > Help -> Troubleshooting Information 

Then press the Reset Firefox button.

For a detailed description see the Mozilla support here.

April 9, 2013

Arduino Pro Mini low power modification


In this post I use an Arduino Pro Mini 5V 16 MHz MEGA328 powered by an external 5 V source. My application will run on a small battery so I need to minimize the power consumption. I measured the board to consume about 16 mA in normal operation.

My application can be in sleep mode until an event occurs. This is how to enter sleep mode:
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_mode();


Make sure to used this include:
#include <avr/sleep.h>

Wake-up from sleep mode is done with an interrupt. That part is not covered in this post. In sleep mode I measured the current consumption to be 476 uA (microampere). To improve this is I did the following:
  1. Disabled the power on LED by removing the current limiting resistor. It got down to 152 uA.
  2. Removed the unused on board 5 Volt regulator to avoid leakage. This resulted in 136 uA.
The picture below shows the positions of the components that I have removed.

The battery that I will use is a 3.7 V 230 mAh Li-Po regulated by a TI TPS61200 Boost Converter. With an assumed efficiency of 90% I get 230 * (3.7 / 5) * 0.9 = 153 mAh. This gives the theoretical time of operation:

Sleep mode before: 476 uA => 321 h (~13days)
Sleep mode after: 136 uA => 1125 h (~46 days)
Normal operation  mode: 16 mA =>9.5 h

Conclusion: The improvement of the modification is about 3.5 times longer standby time in sleep mode. I was hoping for a month of standby time so with the improvements it should be enough for my design.

April 4, 2013

Monochrome 128x32 OLED Display

I purchased a tiny OLED display from the eBay seller wide.hk that also have a webpage. The dimensions for the module is about 13x34 mm and the interface is I2C.


Here is how to get the display running with Arduino. Download and install both these adafruit libraries:
https://github.com/adafruit/Adafruit_SSD1306
and:
https://github.com/adafruit/Adafruit-GFX-Library 

Hint: use the ZIP button on the github page to get all the files.

For installation instructions see my previous post.

Open the example ssd1306_128x32_i2c in the Arduino software. When compiling you will probably get this error mesage "ssd1306_128x32_i2c.ino:53:2: error: #error ("Height incorrect, please fix Adafruit_SSD1306.h!");"

To fix this open the newly installed library file: Adafruit_SSD1306.h
Find these lines in the file:
   #define SSD1306_128_64
//   #define SSD1306_128_32

change them to:
//   #define SSD1306_128_64
   #define SSD1306_128_32

Save the file and compile again. This time it should complete without errors.
Hint: Use CTRL+R to compile.

Connect your display to the Arduino UNO as follows:
  • ⏚ to GND
  • + to 5V
  • SDA to A4
  • SCL to A5
The library is also using pin 4 as reset. This display does not have a reset terminal so just leave it unconnected.

Upload the code to the Arduino and your display should wake up!
Hint: Use CTRL+U to Upload.

March 25, 2013

MSX emulatation on MK802

In this post i show how to install openMSX on MK802 running running a lubuntu 12.04 image from miniand.com

Open a terminal and install the openmsx-catapult package by typing:

sudo apt-get install openmsx-catapult


This will install all the needed packages. openMSX Catapult is a GUI to configure and launch the openMSX emulator. Start it by typing:

openmsx-catapult

Select a game ROM file under Cart A then press the Start key to start the emulation. With the default MSX type there is no need for a bios file. But for other types it will be needed. Below i have installed a bios file from Spectravide SVI-728.

If you have an USB game pad connected to your MK802 go to the Misc Controls tab and select joystic1 as Joystic port 1.
 When the emulaton is running you can enter fullscreen mode with the F12 key