Category Archives: Programming

328P PIN CHANGE INTERRUPTS

#120 ATMEGA 328P Pin Change Interrupts

The 328P has 3 ports B, C, D you will need to know the basics of how they work to before reading this.

The 328P only has 2x external interrupts however there are also 23x pin change interrupts and I will be focusing on the latter for now.

INTx (external interrupts) can report events under four situations: low, any, falling, rising. PCINTx (pin change interrupts) can report events on only one situation: any, which is basically a change in the pin so we can categorise the 23x as change interrupts only.

Using these pin change interrupts are surprisingly easy but require a few steps. However once they are configured code size and complexity can be reduced significantly. Also never forget you paid for the IC and it’s hardware peripherals.. so USE THEM.

You can run a loop checking button states with multiple variables including timing and state variables etc. or…. you can run a similar reduced loop with the use of the pin change interrupts making your life so much easier while not compromising much resources.

So to get started you need to follow 3 steps:

  1. Turn the pin change interrupts on
  2. Choose the pins to interrupt
  3. Use the ISR for the chosen pins

STEP 1:

To turn on the pin change interrupts you will need to use the PCICR register.

Writing 1 to bit 0 will turn on the portB (PCINT0 – PCINT7)
Writing 1 to bit 1 will turn on the portC (PCINT8 – PCINT14)
Writing 1 to bit 2 will turn on the portD (PCINT16 – PCINT23)
From bit 3 onwards (from right to left) bits are ignored.

STEP 2:

Now you need to choose which pins you want to interrupt.
You will need to use a mask and the 328P has 3 masks: PCMSK0, PCMSK1, and PCMSK2
These masks are set in the same way as the PCICR register was set.

STEP 3:

Now you need to use the correct ISR for the chosen pins.
make sure to keep the ISR as fast as possible and use as little code as possible in the ISR.
Also if you have any variables in the ISR make sure to make them volatile. This tells the compiler that it could change at any time and to reload it each time instead of optimizing it.

Full Super Simple Example:

Links:

MPLABX VS ARDUINO IDE

#119 Differences and similarities between the two

Recently I wrote about the pros and cons etc. about different programmers used to program embedded devices. I mentioned a few examples like ST-Link, PicKit and standard DIY programmers. Now since programmers work hand in hand with the programming software on your PC I decided to talk a bit about the 2 IDEs I use often. (Although you can easily setup platform IO with a compiler for embedded devices I will be focusing mostly on full IDEs but will make mentions to using text editors)

So I’ll start with the Arduino IDE. it’s simple to install and to get started with. There’s many libraries and there’s a wide support on the internet. Note: at least in my experience in South Africa at the public school I went to there was basically no interest or effort to promote Arduino and similar platforms. Looking back this was very disappointing since I’m 99% sure I would have gotten into Arduino much earlier in life if certain educational departments had made an effort in promoting Science instead of supporting political nonsense like the “science must fall” movement but I digress.

That being said Arduino is not all fun and games, it’s a great learning introduction tool but can promote bad code practices and reliance on libraries for work. Arduino also heavily promotes using easy functions instead of port manipulation methods… even in advanced projects… this can be a bit annoying especially when you want to use a library in a project with a different MCU and also when you want to keep code small and efficient. This can really bloat your MCU code and as you can imagine there is really not much room “literally” when programming embedded devices. Macros for port manipulation can really help but relying on digitalwrite(pin1); to pull a pin high or low can really cause some confusion later on

There may be more pros and cons not mentioned above but really I just want to get into the stuff that I can mention off the top of my head for this article.

Now switching to the free MPLABX IDE. I can say that the learning curve is quite steep but easy to get into with repetitive use. Once you get familiar with the layout you can start seeing quite a few pros compared to Arduino. having the ability to view the entire file structure in the IDE helps a ton. Also AVR has been integrated into MPLABX for some years now so you can easily program Arduino style. The IDE promotes professional main.c files and avr-main.c files which is very cool (I’m not really into ASM programming at least for now there’s a very big learning curve but one day I’ll get into it I hope 🙂 ) MPLABX also supports a huge variety of ICs and you can easily download updates for these as well as some libraries. Another pro is the GUI MCC (MPLAB Code Configurator) ok, ok I’m not a huge fan because I always somehow bloat up my project and break things but I can totally see how it could help by providing a GUI for setting clocks and bits etc. Another cool feature is that there are options for dark mode in the ide and it uses NetBeans.

There are a few downsides to the MPLABX IDE for example when using a 4k screen the Nebeans part always has blurry visuals now you can adjust the DPI but then all the text is super small and when adjusting the text it becomes inconsistent in certain places. Like for example the IDE text is small but your code text is big. This has always been an issue for me but I guess I’m just suffering from a 4k screen 🙂 Another issue is that I have always had to use expensive dedicated programmers when using MPLABX non of my DIY CH340N etc. programmers will work with MPLABX. Also programming AVR requires an AVR programmer so you can’t just use a PicKit3 for everything. Another pro is that it’s easy to choose compilers in a list. You cans install multiple compilers without issue. Another great feature is that you can install the so called MPLABEXT extension using visual studio code so you don’t have to use the IDE but can keep compatibility. Another cool feature is the ability to read and program the fuses or (configuration bits for PIC). Once again there may be some pros and cons not mentioned but I’m just writing this off the top of my head.

An honourable mention goes to the text editor approach. This is very light weight and generally bloat free and offers a lot of flexibility which makes using visual studio code a great choice but of course it’s not really a dedicated IDE.

Now to close off I will include to code samples to show the differences between the Arduino IDE and MPLABX IDE I will be programming an AVR device the ATtiny826 in the comparison examples.

Arduino blink code example including a blink without delay and a fast blink sample I made :



MPLABX blink code example including a blink without delay and a fast blink sample I made :

DIFFERENT PROGRAMMERS

#118 A look at different types of programmers

Different programmers for different IC’s some work with others.. some don’t

Over the years I have used different programmers for PIC,AVR,ST,ESP and WCH microcontrollers from simple FTDI TX RX programming to more advanced PICKit 5 dedicated programmers.

All the different types have their pros and cons but by far the most used by me is the cheap FTDI and serial TTL types for example programmers using the CH340, PL2303 and FT232 IC’s

Though the PL2303 is outdated there’s still many floating around and certain applications require the IC like when interfacing with old radios.

PICKit3, PICKit3.5 and the new PICKit5

With that being said you may ask why do we need a dedicated programmer? Well it depends…

Using the cheap common options I just mentioned above is good enough for a hobbyist but when you design a product you want something that’s is reliable common and has a guaranteed life span with support for the foreseeable future so that you will always have parts available for projects and the programmer.

USBasp AVR Programmer using SPI
STM Programmer


WCH-LinkE programmer can also program STM IC’s

Another big point is uniformity, dedicated programmers will usually be using parts with certain thresholds and voltages + current etc. all that data will be kept constant and accurate while a cheap programmer will most likely have a huge threshold..

A very important point is the ISP + debugging. A dedicated programmer will be able to do programming and debugging easily with a few pins. While a cheap programmer will require more pins and many times 2x programmers… 1 for debugging and 1 for programming.

BUS PIRATE can program with SPI
Arduino Nano with built in CH340 IC for serial programming
A n old DIY programmer of mine based on the CH340N IC

Dedicated programmers also have full support by the IC company as long as you have an original also they offer some really useful features like the PicKit5’s blue tooth option and stand alone programming or changing of source binaries on a phone.

All you need is the programmer and a phone is optional if you need to change things like binaries but really you can give a pickit5 to any technician and they can easily update supported IC’s without needing to mess around on a desktop/laptop computer. This is a very useful feature.

Now there also are EEPROM programmers and true universal programmers that can do EEPROMS and MCU’s like the old TL866II Plus which has a list here of all the supported IC’s. These programmers work well and allow easy access for single IC’s some can also read and write when an IC is in circuit but others require de-soldering. These programmers are usually quite large with Zif sockets.

EEPROM Programmer CH341B
Universal programmer the TL866II Plus

Now I just mentioned a few examples there is much more to talk about but I’m not going to be writing books here…

ROBOGUARD INTEGRATION

#105 Custom integration sensors with custom receiver

V1.0 breadboard prototype with DIY EEPROM module
V1.0 stripboard soldered prototype with USB and Lipo battery
Testing 2x custom sensors (1x ATTINY85 and 1x ATTINY412) with 433 RF modules

Recently I wanted to integrate the RoboGuard system with some custom sensors on my farming property.

This motivated me to study the hardware and RF protocols used by the RoboGuard

I would like to also account for multiple RoboGuard transmitters scattered over the property each RoboGuard device has 2x pir sensors and sends an alarm signal once both are triggered.

They also send a heartbeat ping every 15min.

They have a range of roughly 400m from transmitter RoboGuard to receiver HQ.

Testing EEPROM data storage.

Now the RoboGuard system uses 433.92Mhz to send signals to the HQ however the HQ can only add up to 8 paired RoboGuards.

Once you reach this limit you will need to purchase more RoboGuard units.

For example if you had 12 RoboGuards, 2 HQ units would be required but if you wanted an HQ that can store more than 8 you would be out of luck.

luckily I had made my own custom RoboGuard receiver and was able to add my own DIY sensors to the RoboGuard device ecosystem

The protocol used is 433.92 ASK and each RoboGuard has 3 signals

  • alarm
  • tamper/learn
  • heartbeat ping
Testing penetration behind galvanised shed (using CY33 module)

Now my receiver needs to store the received device learn UID and this is done via EEPROM on my board

Now my custom device receives all signals just like the RoboGuard HQ.

Next is communicating with the TAK Server.

I could swap the 328P for an ESP8266 which allows WiFi connectivity to the internet

This then allows the device to connect wirelessly.

It still receives RF data from the RoboGuards and just ports these signals over the internet

In future I will make a device with an integrated WiFi connection but In this case all I wanted was more zones and an affordable extra device to keep in my laboratory permanently with the capability to receive 433mhz signals walking around the premises. If need be

Overall my unit contains

A speaker
6 push buttons
2000mAH Lipo battery
built in charger
ability to add clients 12 RoboGuards (more depending on EEPROM size)
433 MHz superheterodyne receiver only
logic to handle all these features

Front of the 433 Transmitter
Back of the 433 Transmitter

More info + datasheets and schematics etc. on my GitHub here

REVERSING ANB CRACK

#101 Reverse Engineering A Simple Crack

A lot of times the ordinary everyday person is unable to resist using pirated software. After all it’s free and usually works, there is the chance of contracting a virus or other malware but using reputable “sources” is acceptable because if many comments praise the distributor then obviously the software can be fine right?

Well…. not necessarily… in some cases bots can create comments and high seed counts creating the appearance of a well received product. Also flags as false positives can be used as camouflage, sometimes the crack installs discrete backdoors sometimes following the living of the land principal. Basically using the files and programs already installed out of the box on Windows or Linux. This makes it very difficult to find the malware as no foreign exe or files are used (at least in the initial stage of infection)

Therefore antivirus software can get stuck with behavior analysis and hash scans. Creating large files (hundreds of megabytes) and reversing code, using BOM to obfuscate are a few little tricks that may be caught by themselves but layering all these techniques can make the malware almost undetectable.

So I decided to create an example using a real life application and crack I found for IBM analyst’s notebook which is used by private and government organizations. Opening a broad portal to many computers luckily when I decoded the scripts I did not see anything too suspicious. however after the patch (DTD.dll) is installed I do not know what behavior the application will show.

The application was downloaded via torrent and yes all the files were correct no man in the middle attacks took place.

Three files are present after unzipping IBM i2 Analyst’s Notebook 9.2.3 Multilingual.zip

Luckily windows CMD and Powershell are used to copy the cack.

crack.zip
IBM_I2_ANB_V9.2.3.exe
IBM_I2_CHART_READER_V9.2.3.exe

Initial folder contents.

Inside crack.zip
bin.dat
patch.bat
Readme.txt

Crack folder contents.

Interesting enough Readme.txt only instructs the user to run patch.bat although the file DTD.dll is copied to \Program Files (x86)\Common Files\i2 Shared\i2 Analyst’s Notebook 7\Components\DTD.dll

There’s no mention of the i2 Analyst’s Notebook 7 folder and we are presumably installing version 9.2.3

patch.bat is obfuscated due to some carefully chosen bytes at the very beginning of the file that are able to trick file and other charset detection software.

Obfuscated patch.bat file
Taking a peek inside the obfuscated patch.bat file

As referenced by this

However once we remove the character and save the file we can see that the .bat file calls Powershell and then extracts and reverses a script from the bin.dat file.. then runs the extracted script in the terminal.

After removing the character

This 1st Powershell script checks for admin privilege then reverses and reads another script from bin.dat.

The 2nd Powershell script checks the install folders and makes use of the windows dialogs then uses virtualalloc to copy DTD.dll from the bin.dat file to the
\Program Files (x86)\Common Files\i2 Shared\i2 Analyst’s Notebook 7\Components\ directory

Then ends with a messagebox Patch complete!

Opening DTD.dll with dependency viewer shows only 4 functions.

Methods inside of the DTD.dll file

A VirusTotal scan of DTD.dll shows only 3 positives.

UPSILON REMOTE MONITOR

#100 Monitoring A Line UPS Remotely

Modernizing the old UPSilon 2000 application was a daunting task my first thought was to read the serial output but unfortunately the UPS is listed as a HID device and not a simple COM port. So I went down the rabbit hole of trying to communicate with hid devices which have strict security to combat keyloggers. I tried to use kernel32 and the create file read and write file methods but I got access denied. Looking closer I could read some of the inputs of the ups hid device but it was going to take too long to figure out direct communication to the ups without an SDK or a good example app using USB HID to communicate with a UPS.

Computer Management Hid UPS

Some details of my ups hid were:
VID = 0001 PID = 0000 Path = \?\hid#vid_0001&pid_0000#6&7efa158&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030} SerialNumber = Manufacturer = MEC Product: MEC0003

Communication over USB

So after wasting 2 days I went back to the drawing board this time instead of using Wireshark to catch the USB packets I decided to take a closer look at the upsilon 2000 application. unfortunately the .dll's don’t show any useful functions in dependency viewer so I can’t call C++ functions from them in C#. So next I switched Wireshark to local monitoring and I found some very useful traffic.

tcp.port == 2570 connect as a client and get data
tcp.port == 8652 read the data from the sms server
udp.port == 11541 udp data

Port 8652 allows me to read alerts sent to the SMS server but instead I re-direct them to my C# application.

GET /smssend_hide.cgi?$sms_recptmobile=0123456789&$sms_content=DESKTOP-294DAYV: This is a test message!&$sms_code=1 HTTP/1.1
User-Agent: RUPS2K SMS
Host: 127.0.0.1
Connection: Keep-Alive

Port 2570 allows me to TCP connect as a client with no auth and now I get all the stat report strings every 1 second.

(238.7 238.7 238.7 007 50.1 27.4 --.- 00001000

The UDP port 11541 always receives upsXXXcnt001 for constant monitoring and I haven’t observed any other use besides this.

ups000cnt001 – connected ups
upsdiscnt001 – not connected

The exe files communicating between themselves are
Monw32.exe 11541 udp listner
RupsMon.exe 2570 tcp listner
UPSilon.exe connects as client

So after finding this info I was able to build a C# app that works in conjunction with UPSilon 2000 but the C# app offers more flexibility such as remote messaging via Telegram or forwarding the stats to a webserver for remote viewing.

The application checks the cd key every time it starts it connects to an IP in Taiwan http://upsilon.icv99.net on port 80 however is you go to port 8080 you get a webpage cd key checking form.
http://59.124.238.71:80
http://upsilon.icv99.net:8080/download_sys/
http://upsilon.icv99.net:8080/download_sys/keycheck.php?cdkey_check=testkey

Reporting serial key and NTFS to home via: http://59.124.238.71

The only thing I couldn’t do was send commands directly to the ups because that communication link is done within the upsilon app itself however I am happy with the overall outcome.

Source code of my application can be found on GitHub

PRACTICALLY USING THE LOAD-SHEDDING API

#89 An example app showing a practical use case with the API

Using the Eskom load-shedding API is very straight forward however I have noticed that a lot of people get stuck on the last call where an html document is returned instead of Json data. This can throw a spanner in the works because a developer can’t just get the results as a key value pair… the HTML must be parsed and then put into Json before it can be used effectively.

This parsing process is actually quite easy and jut requires a loop with a bit of regex magic to return the values line by line.

Once the values are returned we can then place them into our own Json object and then do something useful with them like creating a loop which reads the times and compares them to the time on my PC then when the json objects time is 10 minutes away the loop then initiates a shutdown of my fan so that it doesn’t drain my ups battery unnecessarily.

Below I have written a small proof of concept application in C# to help inspire others with their projects.

I make use of the LoadShedding.NET.dll library made by IsaTippens using my endpoint documentation and documentation from PolarizedIons.

However in the end I only focused on 2 API endpoints to simplify the example app.

This makes my example much simpler.

You can take a look at my example code on GitHub

DESIGN A TRAINER/KEYGEN

#85 Designing a trainer/keygen in C#

When I think about trainers 3 things come to mind.. original chiptunes, nostalgic games on windows and imaginative unique art styles. funny enough there was a decent amount of programming hacks and tricks used but people rarely think of that nowadays.

I have created an example template application with just the chiptunes and a little bit of art included. I will not include any logic for cracking games or programs etc. this article is just focusing on the visual and music design for nostalgic and educational purposes.

Please se the GitHub link to the source code here.

PLAYING OLD .XM FILES

#84 Playing old .xm music files

Back when Keygens and Trainers were the go to applications for poor kids wanting to play the latest games or experiment with the latest software’s the chiptune went hand in glove with these tiny applications. These applications were almost exclusively found on Windows computers

These applications were designed to be as small as possible many of them were written in Assembly or C++ and had all the resources embedded in the .exe at highly compressed ratios.

Even with the music file and the graphics accommodating the functionality of these programs they still managed to stay very small in size.

Thus a whole culture surrounding the traditional past time of “cracking” was born. Unfortunately there’s not much practical use for these activity’s in this day and age. Almost everything revolves around the “Internet Browser” and “Web Applications”. However artistically the past time lives on and we can still create these applications in Assembly, C#, C++ etc. as desktop applications.

Intresting links:

http://keygenmusic.org

https://modarchive.org

https://www.winasm.org

https://github.com/Xyl2k/Xylitol-MASM32-snippets

https://github.com/kitsune94/XM-Resource-Demo

https://www.un4seen.com

WHY .NET AND THE DIFFERENCES

#83 The differences between .Net Framework and .Net Core

.Net Framework was created around the year 2000. It’s not just C#, languages are built on top of the .Net Framework. they language like C# are converted into the common intermediate language (CIL).

.Net Framework is now over 20 years old. there’s a lot of checks and processes that have been added which bloat the system. However this is necessary because the .Net Framework still needs to work with older applications E.G an app made in the early 2000s.

So basically the .Net Framework is slowing down apps in the new world of software so many new advancements can’t be leveraged by the .Net Framework.

In 2016 Microsoft started the process of .Net Core. which is a new improved version of the .Net Framework with changes like how processes are executed and what is supported/not supported. Also a lot of backward compatibility has been removed for things no longer needed.

.Net Core has a massive speed increase compared to .Net Framework. Also the code in .Net Framework will run 97% of the time in .Net core however some structures and 3rd party dependencies will have to be changed this is true as of [.Net Core 5].

.Net Framework will still be supported for many years, however new development should be using .Net Core.