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).

Thursday, November 23, 2017

External gear pump swept volume

The following picture is a visual representation for the swept volume of one gear in external gear pump. The total swept volume of the pump is twice this value.

Wednesday, November 22, 2017

Radio pallet shuttle system selection and design

Few days ago, I came across what is called "Pallet shuttle system" which is used in pallet rack system as an alternative to "drive-in" and "drive through" of fork lifts to save time and increase safety levels.

The following table shows some useful selection criteria. It is also useful for people who are willing to design this piece of equipment. Based on the table below, and by some reversed engineering of the top brands manufacturing this equipment; I found that "Mecalux" is really the best design from all aspects.

Radio pallet shuttle system selection
All pallets are of the same item Yes
Mixed items:
Pick one item from one end and the other from the other end
Handling equipment Fork lift and stacker
Shuttle dimensions _
Minimum pallet size _
Maximum pallet size _
Maximum pallet overhang distance _
Maximum pallet deflection _
Maximum track distance _
Lifting distance _
Underneath ground clearance _
Operating conditions
Operating temperature:
Negative operating temperatures for refrigerators
Ingress protection IP  
Four wheel drive Preferred
Maximum load [kg] _
Full-load speed _
No-load speed _
Acceleration and deceleration profiles _
Lifting speed _
Weight-dependent acceleration  
Number of wheels to extend life of wheels  
Lift the whole upper plate  
Energy and efficiency
Energy consumption to fully charge the battery _
Regenerative breaking system Preferred
Standby mode Yes
Monitoring and control
Monitor battery charge remotely Yes
Monitor battery remaining time remotely Yes
Switching between manual and automatic modes Yes
Remote control Yes
Remote control communication technology requires no infrastructure Yes
Handheld remote control Yes
Rechargeable remote control Yes
Remote control battery level indicator  
Light display in remote control Yes
Remote control drop down distance 3 meters
Magnetic mount remote control Yes
Large buttons and icons in remote control Yes
Iconic color-coded buttons Yes
Single-hand operated remote control Yes
Single remote controls multiple shuttles Yes
No. of controlled shuttles using single remote Unlimited
Remote control range [m] _
No interference between multiple remote controls Yes
User accounts and authentication Yes
PC programmable Preferred
Programmable maximum speed Preferred
Programmable maximum acceleration Preferred
Programmable loading and unloading positions Yes
First In Last Out
Loading and unloading in the same location
First In First Out
Loading and unloading are in opposite locations
Programmable home (for FIFO system) Yes
RS232 Yes
RS485 Yes
Ethernet Preferred
Wi-Fi Preferred
Shuttle power permanent push button Yes
Power indicator light Yes
Forward and backward blinking indication lights Yes
Auto-homing Yes
Auto-home and stop when battery is very low Yes
Partial loading Yes
Partial unloading (unload certain amount of pallets) Yes
Automatic loading (LIFO) Yes
Automatic unloading (LIFO) Yes
Unload one-by-one, to reduce number of reallocations. This saves energy and increase the life time of the shuttle. In this mode, the default home position will be the unloading side and when the shuttle detects that the pallet is removed it will go back and bring the next pallet Yes
Partial compacting Yes
Full compacting Yes
Self-align shuttle with pallet Yes
Weight measurement Preferred
Odometer Preferred
On-deck pallet detection Yes
Detect any pallet regardless the material:
[1] Wood
[2] Plastic
[3] Steel
Detect any pallet regardless the color Yes
Detect any pallet regardless the pattern Yes
Pallet size detection Preferred
Variable pallet size Yes
Programmable pallet spacing Yes
Counting number of pallets Yes
Calculate remaining pallets to fully-load the track Preferred
Wide-angle navigation camera on both sides Optional
Flash light for camera Yes
Speed monitoring Preferred
Audible alarm Yes
Shuttle number (ID) label on:
[1] Front
[2] Back
[3] Bottom (large)
[4] Top (large)
Bottom lights to easily recognize the shuttle specially when the shuttle is at elevated heights Preferred
Possibility of two shuttles in the same lane (for FIFO) Preferred
Forced operation function Yes
Location signal
To know where the shuttle cart is
Alarm when there is a place left for only one pallet and the labor place a pallet above it Yes
Auto-seek remote coverage Yes
Rechargeable battery Yes
Battery technology Lithium polymer
Lithium ion
Sealed battery Yes
Fire retardant casing Yes
Battery life (years) 5
Battery life (number of charges) 1000
Battery price (cheaper battery is preferred)  
Battery charger Yes
Battery charger rating 220 V - 50 Hz
Battery charger stop after charging is complete Yes
Battery full-charge alarm Preferred
Battery charging time < 8 hours
Battery charge percent indicator in the charging station Yes
Battery discharge time at maximum load > 8 hours
Battery location is close as possible to the side edge of the shuttle, so it can be removed ergonomically Yes
Battery weight (for ergonomics)  
Battery number label Yes
Onsite charging Preferred
Charging station for single battery Yes
Spare battery Yes
Standby operating time _
Remove battery without any hand tools Yes
Rail end stoppers Yes
Pallet centralizers Yes
Emergency push button on both sides (front and back) Yes
Human hit safety (specially for ground racks) Yes
Auto-home at enough distance from the rack end, so the fork lift will not hit it during unloading. Yes
End of rail (track) detection (using two sensors) Yes
End of rail (track) detection sensors can detect track end of any color Yes
End of rail (track) detection sensors can detect track end full of dust Yes
Open rail (track) detection Yes
Anti collision with other pallet Yes
Obstacle detection Yes
Rail detection Yes
Rail bump detection Preferred
On-floor detection Preferred
Bottom anti-slip surface to avoid slipping from fork lift Yes
Electromagnetic locking system:
Bottom very strong electromagnets to hold firmly with fork lift
Electromagnetic locking system indictor light in the bottom Preferred
Detect if it is lifted on fork lift, so it will not operate even if it is in automatic mode Yes
Stop laser beams when it is lifted on fork lift Yes
Rubber bumper at the front and end Yes
Rubber stoppers at both sides in the front and back to avoid hitting track stoppers Yes
Wheels are almost at the end of the shuttle to prevent flipping back Yes
Pallet slip detection:
Stop in case of pallet slip.
Pallet flip detection:
Stop in case of pallet flip.
Side rollers to make sure that the shuttle is always on track Yes
Anti-slip surface Yes
Braking system Yes
Sealing plugs (caps) for all communication interface ports on the shuttle Yes
No wires, shrink wraps, clamps, frames can tangle with wheels Yes
Ratchet lifting Preferred
Human cart accessory (with chair inside) Yes
Shuttle can not move if placed on normal floor Yes
Electromechanical lifting system Yes
Overload protection:
[1] Over current
[2] Over temperature
Overload indication Yes
Battery over-discharge protection Yes
Spring loaded rail wiper to clean rails and avoid wheel slippage and wheel pitting Yes
On-shuttle battery level indicator Preferred
Wheel slip detection Yes
Normally free to move when battery is dead Yes
Normally not-elevated when battery is dead Yes
Rust free materials Yes
Dust proof sensors Yes
Moisture proof sensors Yes
Another shuttle can push or pull faulty shuttle Yes
Shuttle can be lifted using fork lift if it is placed on flat floor Yes
Shuttle have underneath pocket for forklift Preferred
Front and back hooks for pulling it in case of getting faulty Yes
Easy replaceable wheels Yes
Protective guard for buttons and user interface when hit another object Yes
Maximum load label on the top (readable from both sides) Yes
Weight overload audible alarm Yes