Tuesday, June 26, 2018

Excel VBA create combinations

If you have a set of elements let's say {A,B,C,D,E} that you want to create all possible non-repeating combinations for, then here you are two simple and straight forward methods. In some cases you may need to know the all possible combinations rather than counting or calculating their count like in the Design of Experiments DOE.

Unfortunately, in this post I am not going to share a copy-and-paste code, but I will introduce two algorithms to implement them easily using any programming language in any suitable way.

As an example, there are 31 possible combinations for the previous set which is hard to calculate manually and the problem can be more serious with higher number of elements.

In both methods we will use letter-coded elements and will rely on some string processing functions. For example, if you have five billiard balls with five different colors, the following coding may be applied:

Method 1:

In this method we will create (initialize) an empty two-dimensional string matrix having number of rows (M) equals the number of elements (n) and number of columns (N) equals the maximum number of combinations for a given group size. Let's name this matrix "Combinations". This matrix will contain -when it is completely filled- all possible combinations for the given set of elements. Each row of this matrix will contain the combinations of (i) number of elements where (i) is the row number of "Combinations". The main advantage of this matrix structure is to contain data in a compact form instead of having long one-dimensional array. This structure also makes it easy to calculate the combinations manually on paper or in spreadsheet.

For the example shown above, the "Combinations" matrix will look like the following image:

The method pseudo code looks like the following sequence:

Define the elements {"A","B","C","D","E"}

First of all, add all elements to the first row of "Combinations" matrix

For each row (i) of "Combinations" matrix starting from first row to the row before the last row

Set column_counter=0

For each non-empty combination in column (j) in the current row (i) of "Combinations" matrix

For each element in elements

If the element is not contained in the current combination string then

If the element alphabetical order is higher than the alphabetical order of the last element in the combination string (ASCII code of element is larger than the ASCII code of the last element in the combination) then

Create new combination by string concatenation = current combination + element 

Increment column_counter by one 

Add this combination to the first empty cell in the next row of "Combinations" where row number equals i+1 and column number equals column_counter

End If

End If

Next Element

Next Combination

Next Row of "Combinations"

The evolution of "Combinations" matrix during the solution process looks like the following animated .GIF file (frame each 5 seconds)

Method 2:

This method is definitely more simple than the previous method. The core principle of this method is making a good use of binary number representation that it is made of zeros and ones 00101. Each bit in this binary format will represent the existence of the element in this combination; zero (0) means not-exist while one (1) means exist.

To apply this method, we create one-dimensional array for the elements of size (n), one-dimensional array for the binary number representation of size (n) as well, and one dimensional array of size (2^n)-1 for the generated combinations.

The method will go in the following workflow:

For each decimal number starting from 1 to (2^n)-1

Convert the decimal number to n-bit binary format

Multiply each element letter by the corresponding bit value in the binary array and join the results. Note that this is a symbolic multiplication which will return a string where  A * 1 = "A" and A * 0 ="".

The resulting string is a possible combination which will be added to the combinations array.

Next decimal number

Since this method produces combinations in a non-sorted way, alphabetical sorting for combinations may be required for better display of data.

To better understand the method, the following is an animated .GIF file (frame each 5 seconds) which shows how the method works.

Key words:

Unique non-repeating combinations algorithm

Combinations using binary number representation

Combinations programming

Combinations pseudo code C++ and VBA

Efficient combinations algorithm

Compute combinations

How to compute combinations

Excel VBA combinations of cells

Combinations matrix

Monday, May 14, 2018

PCB design tips and tricks

Electronic circuit design:

[1] Draw well-formatted schematics

[2] Define operating conditions, moisture condensation, and water ingress

Board geometry:

[1] Define PCB shape, dimensions, and weight.

[2] Make holes for PCB mounting

[3] Make cuts or slots for easy PCB pullout from its assembly

[4] If wires are going to be soldered directly on PCB, the make a setup for strain relief like clamps or zip ties

[5] Make sure that the PCB has only one possibility to mount in the device by making slots or non-symmetric guides.

[6] Use PCB cut for isolation between high and low voltage

[7] Make holes under IC sockets, to eject ICs easily from the back

[8] Design for penalization (multiple PCBs in one shot)


[1] Start your design with single layer PCB first. If one layer is not enough, then move to two layers and so on.

[2] If you are going to control high power loads, then you may use PCB with thicker copper layer (2 oz/ft2 instead of 1 oz/ft2)

Components location:

[1] Design to use electronic components that are available in your local market

[2] You may use some THT components as SMD

[3] Divide your design into modules and locate inputs and outputs of each module

[4] Sort modules based on the connections

[5] Put power components on one layer and control components on the other layer

[6] Define the orientation at which the PCB will operate to place hot components at the top.

[7] Place service components always accessible as possible like: memory cards, SIM cards,  batteries, fuses, varistors, potentiometers, ... etc

[8] Place components as near as possible to other related components

[9] ِAlign or array components of the same type and package

[10] Put spare components in the PCB (such as a spare fuse)

[11] Use sockets for components expected to be replaced or upgraded, or if you afraid of overheating IC chips during soldering

[12] Make your design smarter, so it can be used to produce different variants by just adding or removing few components

[13] Place micro-controller in the middle of the PCB.

[14] Make status LEDs that till you that the PCB is alive

[15] Consider ICSP pins to reprogram your micro-controller in the future

[16] If your PCB has no user-interface, then make an external debugging interface

[17] Consider using external removable jumpers to enable or disable a function

[18] Save areas for TO22 package layed flat

[19] Consider heat sinks orientation

[20] Use PCB copper area as heat sink for heat-dissipating components

[21] Use one large screw terminal block instead of multiple small blocks if they are going to be placed beside each other because it is difficult to align them 

[22] Place components in locations where it is easy to de-solder. For example, don't place and SMD component trapped between high components from all directions.


[1] Check the manufacturing capabilities of the PCB manufacturer you are going to deal with first. If you plan to etch this PCB manually, then use large tracks and large track spacing.

[2] For power tracks, calculate track width so that the voltage drop is accepted and track temperature is maintained constant at given ambient conditions and cooling method

[3] Use through hole components to jump over tracks if you have limited number of layers

[4] If you have limited number of layers, use wire jumpers

[5] Keep enough area empty of tracks around holes so screw head or hexagonal spacer will not affect them

[6] Avoid putting pads in the way of a track

[7] Use decoupling capacitors just beside the IC

[8] Avoid using stubs

[9] Use low impedance tracks for high frequency lines by making shorter paths and wider tracks

[10] Reduce number of bends in the track as possible

[11] Use shorter paths

[12] Use very short paths for power lines used as relays to get compact PCB

[13] Use short spikes between components and large tracks

[14] Don't use right angle path

[15] Don't use acute angle paths

[16] Maintain the parallelism and equi-spacing of data lines

[17] Keep enough clearance between tracks

[18] Avoid using loopy tracks (antenna)

[19] Use ground plane to connect all ground pins and avoid the hassle of connecting them

[20] Use ground plane carefully. If you are going to control high power loads and use ground plane, make sure that there is enough area for current to flow

[21] Get rid of thin islands

[22] If ground plane is used, keep areas under high voltage components void (clear of copper) to avoid dielectric failure.

[23] Keep areas under transformers empty of tracks

[24] Avoid passing tracks under components or IC chips as possible for easy track tracing and repair in the future

[25] Use star connection for 5V instead of daisy chain

[26] Use parallel tracks for sensors to cancel noise

[27] Avoid passing tracks between pads


[1] Use unique labels for all components

[2] Label component code if there is enough space

[3] Use component code if it only has no alternatives or it is not allowed to be replaced with another component

[4] As possible, put labels beside components, not under them

[5] Try to avoid placing labels on tracks

[6] Create labels in ascending way from the top-left corner to the bottom-right corner so that they can be reached easily by eye sweeping

[7] Label soldering pads to test connectivity

[8] Create label for revision number and production date

[9] Create label for contact details: company name, website address, phone number, or email

[10] Create label for disposal method


[1] Consider test pads. Test pads are flat blind pads where they are expected to be used for testing and troubleshooting purposes.

[2] Consider golden fingers

[3] Consider connector pads. Connector pads are this pads that can be cut to permanently enable or disable a function

[4] Keep enough distance between soldering pad and track

[5] Snap all pins to perforated weaver board, so you can prototype easily

[6] Make sure that no pins will touch component in the back.

[7] Avoid over-sizing of through holes

[8] Use thin pads as fuses

[9] via under SMD IC chip to save space

[1] Print your PCB to paper and place components on it to check matching of the footprint

[2] Try your circuit on bread board

[3] Visualize your design in 3D

[4] Get rough figure for the price of the PCB

Additional references:



Sunday, April 22, 2018

Tips and tricks to reduce Arduino sketch size

If you are using Arduino board and you have limited flash memory size, the following are some tips and tricks to reduce sketch size:

[1] First of all, try to divide your code into blocks to help you analyze what portion of code consumes much memory. For example, make blocks for "Measuring", "Control", "Display", ... etc. Create a spread sheet named "Sketch size analysis" and write down the size of each code block and sort blocks from largest to smallest. The following is an example for sketch size analysis of one of my projects:

[2] Reduce #include of libraries as possible as long as compiling will not output errors

[3] Avoid using serial port initialization and serial port printing for debugging purpose

[4] Avoid using float numbers as possible

[5] Avoid using string arrays as possible. Use character arrays instead "const char*"

[6] Use #define for constants so the compiler will replace this constant name with the corresponding value

[7] Get rid of non-used portions of code

[8] For TFT displays, avoid using custom fonts, use small font sizes, reduce number of character bitmaps in font file. You can reduce number of characters by using all letters as small (abcd...) or all letter as capital (ABCD...)

[9] For TFT displays, draw logos, icons, and clip arts using union and intersection of geometric shapes instead of using bitmaps

[10] Convert duplicated code to function

[11] Reduce string constants whenever possible

[12] Avoid using math functions like "pow()" or "log()"

[13] Calculate arrays in real-time

[14] Avoid using string functions like "sprintf()" and "dtostrf()"

[15] Avoid using standard functions that have too much options or cases while you only have one case. Create your own function

[16] Reduce variables used as possible

[17] Store 8 Boolean variables in one byte using bitwise operations

[18] Use the minimal variable size possible for your data type

[19] Don't assign default values for global variables that will be calculated later or called from EEPROM

[20] Store const arrays to EEPROM if you have enough space in EEPROM

Friday, March 30, 2018

Arduino 2.8" 240x320 SPI TFT screen

Two weeks ago I bought a 2.8" 320x240 pixels RGB color TFT display having graphics driver chip ILI9341 and using Serial Peripheral Interface SPI for communication with Arduino board. You can find the display details in this link:

The display has 8 pins as shown in the picture below. Unfortunately, this screen does no have Chip Select CS (Slave Select SS) pin which is required if you are interfacing multiple SPI devices. Apart from the power pins (GND and VCC), this display needs only 4 digital pins to operate successfully and these pins are: CLK, MOSI, RES, and DC. 

Pins BLK and MISO are optional and are not mandatory for operation of the display. In case you want to connect MISO pin with Arduino board, you can connect it directly because Arduino digital pins read any voltage level above 1.5V as digital HIGH.

This display is powered through VCC pin using 3.3V and for this reason all incoming signal levels should be within 3.3V. Powering this display with 5V will not harm or damage the screen immediately, but will turn the whole screen into white. These signal levels can be achieved using the simple voltage divider circuit as the shown in the images below. 

The following is wiring of this display with Arduino Uno using hardware SPI interface (click the image to see it on full scale).

The following is wiring of this display with Arduino Uno using software SPI interface (click the image to see it on full scale). You can use different digital pins and define them in the code.

From software side of view, this display can be integrated with Arduino (I am using Arduino IDE 1.8.3) using one of two options:

First option:

Using both: Adafruit GFX library and Adafruit ILI9341 library. You can download these libraries using the library manager in Arduino IDE as shown in the images below. 

To kick off the coding, the code below is used to draw a black screen with a white rectangle drawn in the middle.

#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"

// For the Adafruit shield, these are the default.
#define TFT_DC 9
#define TFT_CS 10
#define TFT_RES 8

// Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC,TFT_RES);

// In case you want to use software SPI, define pin numbers above and uncomment the line below
//Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RES, TFT_MISO);

void setup() {
tft.setRotation(1);    // Use screen horizontally
tft.fillRect(0,0,320,240,0x0000);     //fill the screen with black rectangle
tft.fillRect(80,60,160,120,0xFFFF);     // draw white rectangle in the middle

void loop(void) {

Second option:

Using UCGlib library. This library also is available from Arduino library manager. To learn more about this library you can go to reference page from this link

To make things easier, here is a very simple code for this library as well.

#include "SPI.h"
#include "Ucglib.h"

#define TFT_DC 9
#define TFT_CS 10
#define TFT_RES 8

// Hardware SPI
Ucglib_ILI9341_18x240x320_HWSPI ucg(TFT_DC,TFT_CS,TFT_RES);

// In case you want to use software SPI, define pin numbers above and uncomment the line below
//Ucglib_ILI9341_18x240x320_SWSPI ucg(TFT_CLK,TFT_MOSI,TFT_DC, TFT_CS,TFT_RES);

void setup() {

void loop() {



Egypt UGE 2.8" (2.8 inch) SPI RGB TFT LCD screen display 320x240 wiring circuit diagram

Egypt UGE 2.8" (2.8 inch) SPI RGB TFT LCD screen display 320x240 code

2.8" (2.8 inch) SPI RGB TFT LCD screen display 320x240 driver IC chip ILI9341

SPI TFT display without Chip Select CS pin

SPI TFT display without Slave Select SS pin

8 pin SPI TFT LCD screen display 320x240

Cheap Chinese SPI TFT LCD screen display 320x240

Friday, March 16, 2018

Programming Atmel ATMEGA328-PU microcontroller using Arduino Mega board

The following method is used if ATMEGA328-PU microcontroller will be used with external oscillator 16 MHz. Before going on any steps, you should download Arduino IDE and install it. In this tutorial I am using Arduino IDE version 1.8.3

We want to use Arduino Mega 2560 as an ISP programmer for Atmel ATMEGA328-20PU DIP package microcontroller. To do this, we will do some steps for software and hardware.

A. Make the programmer

First: Software preparation:
[1] Before any wiring or creating any mess, connect Arduino Mega 2560 board to your PC using the USB cable

[2] Open Arduino IDE -> File -> Examples -> 11.Arduino ISP -> ArduinoISP.
By doing this "ArduinoISP" sketch will be opened. Keep the sketch as it is without any modification.

[3] Select Tools -> Board -> Arduino/Genuino Mega or Mega2560

[4] Select Tools -> Processor -> ATMEGA2560

[5] Select the correct COM port from Tools -> Port

[6] Select Sketch -> Upload

[7] By uploading the sketch, we have finished the software part.

Second: Hardware preparation:

[1] As many references said, we need 10 uF electrolytic capacitor (in my case I used a 33 uF capacitor which was available for me and it did the job). Connect the positive (long) lead of the capacitor to RESET pin of Arduino Mega 2560 and the short (negative) lead of the capacitor to GND pin of Arduino Mega. This capacitor is needed to disable resetting Arduino Mega.

[2] Now, we have turned our Arduino Mega 2560 to a programmer.

Saturday, March 3, 2018

Nestle water bottle dimensions

Key words:

Nestle Egypt 1.5 liter PET mineral water bottle dimensions

Nestle Egypt 1.5 liter PET mineral water bottle size

Standard 1.5 liter PET mineral water bottle dimensions

Water bottle dimensions for packaging design

Water bottle dimensions for cardboard box design

Wednesday, February 7, 2018

Sunrise and sunset color gradient

The following picture is an approximation for sunrise and sunset color gradient. It is not based on scientific approach, it is just a personal impression. The picture is created on Microsoft office 2013 using two rectangles and gradient fill with five color stops: white, yellow, red, blue, and black.


Sunrise and sunset colors 

Sunrise and sunset color gradient

Sunrise and sunset color bar

Sunrise and sunset color simulation

Sunrise and sunset simulation

Sunrise and sunset color change

Sunrise and sunset color gradient

Sunday, December 17, 2017

Kitchen door frame aluminum profile

The following cross-section drawing shows one of the commonly used aluminum profiles in kitchen cabinets in Egypt. It is usually used for cabinet door frames. I drew this profile myself using a scrap piece (it was painted) from a nearby aluminum workshop. The real dimensions may slightly vary because of painting thickness. The drawing shows only the governing dimensions of the profile in millimeters. You can also download the CAD model of the profile from this link.

Orthogonal bars of this profile are connected at door frame corners using the following plastic connector or joint (in the render below). You can download the CAD model from this link.

Tags and keywords:

Kitchen cabinet door frame aluminum profile dimensions

Kitchen cabinet door frame aluminum profile drawing

Kitchen cabinet door frame aluminum profile Egypt

Kitchen cabinet door frame aluminum profile 3D cad model

Kitchen cabinet door frame aluminum profile

Kitchen cabinet door frame aluminum profile STL

Kitchen cabinet door frame aluminum profile assembly

Kitchen cabinet door frame aluminum profile plastic connector


Sunday, December 10, 2017

Desktop FDM 3D printer bed leveling

In this post I propose a simple and smart method to level the bed or build plate of most desktop FDM 3D printers (like CReality CR-10S 3D printer). It comes as an alternative to the traditional A4 paper tightness method.

The method simply uses a digital multi-meter (a cheap one can work fine) and aluminum tape of known thickness. First of all, the build plate is cleaned and four pieces of aluminum tape will be placed at the corners of the build plate with no wrinkles or trapped air beneath. Then, the digital multi-meter will be set on electric continuity tester (buzzer) which will beep when the resistance is lower than certain small value. One probe -let's say the red one- of this multi-meter will be connected to the hot end heater block (which is electrically conductive) and the probe can be placed in the hole of the NTC sensor to be clamped using the set screw.  After that, the user will configure the printer to enter the step-by-step bed leveling mode and the extruder moves to the first point. At this instant, the other probe -the black one- will be connected to the piece of aluminum tape at the corner at which adjustment is being done. Bed level adjustment screw will be tuned until the buzzer sound is heard and so this point is calibrated. The same process will be done for the rest of points and the whole build plate is leveled.

If the entire area of the build plate will not be used in the future prints, you can leave aluminum tape pieces in their places for future bed leveling.


Saturday, November 25, 2017

Electrical cable tray oblong punching dimensions

The picture below shows two standard metric sizes for oblong punching used in electric cable trays (specifically in Egypt).