blog

Drawing Rotated Lines and Bitmaps with Arduino

Often you need to draw a line at certain angle, and you find it hard to recall the math you learned in school to do this calculation. Same was the case with me recently when I was working on DashPanel-Arduino project.

First, I searched for ready to use snippet someone posted online, but I was out of luck. As the last resort, I looked up actual equation and converted it into a simple function which can be easily pasted in any Arduino source file.

#define DEG2RAD 0.0174532925

void drawAngularLine(int x, int y, int length, int rotation)
{
  float angleRadians = DEG2RAD * (rotation - 90);
  float x1 = x + cos(angleRadians) * length;
  float y1 = y + sin(angleRadians) * length;

  // SSD1306Wire I2C display object
  display1.drawLine(x, y, x1, y1);
}

While working on same project, I wanted to rotate a bitmap at runtime and draw on attached I2C OLED display. I stumbled upon this post on Arduino forum, and tweaked it a bit for my needs.

#define DEG2RAD 0.0174532925

void drawRotatedBitmap(SSD1306Wire *display, 
                       int16_t x, int16_t y, 
                       uint8_t w, uint8_t h, 
                       const uint8_t *bitmap, uint16_t angle)
{
  int16_t newx, newy;
  uint8_t data = 0;

  float cosa = cos(angle * DEG2RAD), sina = sin(angle * DEG2RAD);

  x = x - ((w * cosa / 2) - (h * sina / 2));
  y = y - ((h * cosa / 2) + (w * sina / 2));

  for (int16_t j = 0; j < h; j++)
  {
    for (int16_t i = 0; i < w; i++)
    {
      if ((j * w + i) & 7)
        data <<= 1;
      else
        data = pgm_read_byte(bitmap++);

      newx = 0.5 + x + ((i * cosa) - (j * sina));
      newy = 0.5 + y + ((j * cosa) + (i * sina));

      if (data & 0x80)
      {
        display->setPixel(newx, newy);
        //display.drawPixel(newx, newy, 1);
      }
      //else
      //  display.drawPixel(newx, newy, 0);
    }
  }
}

There’s a trick with this one. You need to make the bitmap size in multiples of 8, like 16×16 icon, 48×48 etc. Once you make 1bit bitmap (.bmp) using Photoshop or MS Paint, you will need to convert it to byte array using Image2Bitmap utility to use in your Arduino code.

For example, an arrow icon converted to byte array would look like this:

const static uint8_t PROGMEM icon_nav_arrow_16x[] {
	0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x01, 0x80, 0x03, 0xc0, 0x03, 0xc0, 0x07, 0xe0, 0x07, 0xe0,
	0x0f, 0xf0, 0x0f, 0xf0, 0x1f, 0xf8, 0x1f, 0xf8, 0x3e, 0x7c, 0x3c, 0x3c, 0x00, 0x00, 0x00, 0x00,
};

I hope these code snippets will help you save some time. Happy coding!

Project DashPanel-Arduino

Starting a new open source project DashPanel-Arduino. The aim is to develop a low-cost, easy to make gadget to show usable info for trip. It uses Arduino framework on ESP8266 WiFi enabled microcontroller.

The list of components is quite short at the moment,

  • 1x ESP8266 ModeMCU compatible DevKit
  • 1x GPS module – blox NEO M6
  • 2x OLED 0.96″ displays – I2C interface
  • 2x DS1820 temperature sensors

The initial version features following data on two OLED displays:

  • Current course with compass view with numeric value
  • Current speed
  • Latitude and longitude
  • Number of satellites locked
  • Clock with date and weekday
  • Altitude
  • Cabin & ambient temperatures

Project Setup and Repo

DashPanel-Arduio is developed using VS Code editor with PlatformIO extension for ease of environment setup, programming and deployment.

Before you clone the repo, just install VS Code, add PlatformIO extension to it and you’re all ready to build.

Start VS Code, go into Source Control section and click Clone Repository, paste the link to DashPanel-Arduio repo: https://github.com/chall3ng3r/DashPanel-Arduino

Once clone process is completed, from VS Code’s command palette select “PlatformIO Build” option or use the shortcut keys Ctrl + Alt + B. The first build will take a bit of time as it will download required SDKs and libraries. Give it few minutes. If there are no errors, everything is okay and you are ready to upload build to dev board.

You can setup the components on breadboard like I’ve done, connect NodeMCU with USB of your PC and chose PlatformIO Upload option from command palette or use shortcut keys Ctrl + Alt + U.

NodeMCU GPIO Connections:

  • Software Serial for GPS module: 13, 15
  • I2C for OLED displays: 4, 5
  • OneWire DS1820 Sensors: 2

The project is still work-in-progress, and not yet in final form. The plan is to make a 3D printable enclosure.

Future Plans

The reason for using ESP8266 for this project is to enable WiFi AP on it and have a webserver to serve mobile and PC optimized settings page.

Some of ideas include:

  • Setting time zone offset. Currently hard-coded.
  • Set destination coordinates and then it will show how far and which direction is the destination.
  • Maybe different screen layouts to choose from. Like one for off road trip, another for city trip, etc.
  • Feature to record the GPS coordinates in standard GPX format, then upload to cloud service when reaching in range of saved WiFi after a trip.

Why I needed to make this project? Back story is shared on PakWheels forum.

Do share your ideas to improve it further or you can join on GitHub to contribute.

Font Converter for Arduino

Currently working on a DIY project for my SUV where I needed to use ESP8266 WiFi enabled microcontroller with two tiny I2C displays and a GPS. I found a great display library by Daniel who goes by the name Squix, known for sharing Weather Station and other awesome open source projects. If you’re into DIY embedded hardware, do check out his blog https://blog.squix.org/

Squix’s display library can use font generated by online Font Converter which have good list of fonts to select from. Sometimes a custom font is needed, like in my case, and I struggled to quickly get my own font converted to supported format.

Searched for and found some options, but was not happy with them. Thanks to Daniel  for sharing source code of Font Converter, I digged the source and extracted just the part to convert the font.

I did bit of modification to pass font name, size and regular or bold option arguments to the console utility. I created a GitHub repo where source and compiled binary is available.

Usage example:

> java FontConverterV3 "Tahoma" 14 r > font-tahoma.h

Download and repo:

Soon enough, I will share the project which needed this utility.

QR Coder – Version 2

This is an update to my original QR Coder browser bookmark script. It’s been a while, and the Google Chart APIs I was using for this stopped working few days ago.

This is my daily use app, and unfortunately there’s still no way to easily transfer text info from one device to another without going through cloud.

In this update, I am now using GoQR service by FoundData. It’s pretty easy to use, and the service offers APIs to encode and decode QR code. Which is awesome. There’s also web form where one can generate QR codes.

For this update I’m breaking QR Coder in two parts.

QR Link

QR Link generates a QR code of the page you’re currently on. So you can share it with another device.

javascript:(function(){function QRCoder(){var u=window,t=document,n=t.createElement("div"),r=t.createElement("img"),i;r.src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data="+encodeURI(window.location),n.id="QRCoder",n.style.padding="50px",n.style.border="1px solid #f00",n.style.textAlign="center",n.style.backgroundColor="#ccc",n.onclick=function(){t.body.removeChild(t.getElementById("QRCoder"))},i=t.createElement("div"),i.style.fontFamily="serif",i.innerHTML="tap to hide",n.appendChild(r),n.appendChild(i),n.style.zIndex=6999,n.style.position="fixed",n.style.top="10px",n.style.left=u.innerWidth/2-130+"px",t.body.appendChild(n)}QRCoder();})()
  • Copy all the code shared above
  • Its one line of code, no line breaks
  • Bookmark this page, and edit the bookmark
  • Change bookmark’s name to “QR Link”
  • Paste the copied code in bookmark’s location / URL field
  • Save the bookmark. That’s it!

QR Text

QR Text is simple, and I’ve been using it in this form for long time. This is for quickly generating a QR code for your own custom text. Say, you need to make a call to a number on PC? no problem. QR Text, tel:+18001234567.

Or anything else text based, it’ll quickly make a QR code of it, but you need to be on some website. As on some browsers’ home feed doesn’t let this script work.

javascript:(function(){function QRCoder(){var u=window,t=document,n=t.createElement("div"),r=t.createElement("img"),i;r.src="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data="+prompt("Text data", ""),n.id="QRCoder",n.style.padding="50px",n.style.border="1px solid #f00",n.style.textAlign="center",n.style.backgroundColor="#ccc",n.onclick=function(){t.body.removeChild(t.getElementById("QRCoder"))},i=t.createElement("div"),i.style.fontFamily="serif",i.innerHTML="tap to hide",n.appendChild(r),n.appendChild(i),n.style.zIndex=6999,n.style.position="fixed",n.style.top="10px",n.style.left=u.innerWidth/2-130+"px",t.body.appendChild(n)}QRCoder();})()
  • Copy all the code shared above
  • Its one line of code, no line breaks
  • Bookmark this page, and edit the bookmark
  • Change bookmark’s name to “QR Text”
  • Paste the copied code in bookmark’s location / URL field
  • Save the bookmark. That’s it!

Oh yeah, you want the link to this page as QR code, here you go!

qr code

This works on latest Firefox, Edge, Chrome and mobile versions of these browsers too.

Do let me know how you use it and if you have any feedback.

Auto Discovery for Photon Server in Unity

Unity has become my first choice for most of the projects I do. Majority of them are branded games, some with custom hardware interaction, and some just plain apps.

The best thing about Unity is, it’s easy as Flash was for quick drag’n drop design and interaction components, plus it’s way more powerful and extendable.

Now back to the topic. In one of my current projects, I started using Photon Server. It’s pretty awesome and well supported server platform for multiplayer games, and realtime apps.

Photon Server in LAN enviroement provides no auto discovery APIs in PUN SDK. While, Unity’s own networking APIs have built-in auto discovery machanism. So, I made a simple solution for my project.

Use Unity’s auto discovery APIs to broadcast server’s address, so clients can connect to server easily.

Here’s pretty simple implementation of the idea:

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections;

public class LanDiscoveryScript : NetworkDiscovery
{
    // Use this for initialization
    void Start()
    {
        Initialize();

        if(Application.isMobilePlatform)
        {
            StartAsClient();
            //log("Starting client...");
        }
        else
        {
            // set broadcast data as IP address
            broadcastData = Network.player.ipAddress;

            StartAsServer();
            //log("Starting Server IP: " + broadcastData);
        }
    }

    // only running as client will receive broadcast event
    public override void OnReceivedBroadcast(string fromAddress, string data)
    {
        base.OnReceivedBroadcast(fromAddress, data);

        //log("OnReceivedBroadcast: " + fromAddress + "\nData: " + data);

        // set server's IP in PUN and connect to it
        PhotonNetwork.PhotonServerSettings.ServerAddress = data;
        PhotonNetwork.ConnectUsingSettings("1.0");
    }
}

 

This is just very basic example to give you the idea, you can use it as it is, or customize it with more data sent to clients as per app’s requirement.

Imminent Death of Adobe Flash

My fellow Flash developers, this post’s title and the post is not to start a new flaming war on the subject, it’s just an opinion which you may or may not agree with.

I posted some of the following ideas in a private forum, so I thought I’d just save some typing and add some more thoughts in original forum post(s) and publish here on my blog. This post is also long overdue, so here it goes.

I think Flash is really a strong brand and awesome technology. There are certain things Adobe have done wrong in terms of strategy and vision for this technology.

Macromedia and later Adobe pushed Flash Player too hard on mobile devices. Back in 2005 when I won a t-shirt from Flash Lite competition, all the developers sent a clear message to Flash team, that on mobile, Flash apps are the future, as all the apps submitted were installable apps on Symbian OS, not mobile browser based.

Flash’s experience in mobile browser was too bad, there were no contents optimized for mobile, and Adobe tried to run existing content in mobile browser, which failed miserably. So we saw Steve Jobs’s thoughts on Flash. Which I agree to, also for lazy engineers part. The focus should’ve been on installable mobile apps from the start. For same reason Adobe had to pull the Android version. I do not see why Flash team failed to see it early.

I also noticed that Flash product team tried hard to sell the Flash Player / AIR to ODMs to embed / pre-install in devices. They did for some, like Nokia / Blackberry. Idea was a clear fail from start, as there was no way to update Flash Player / AIR until ODMs releases an OS update. Also the failed idea to get share of revenue from Flash Player based games/apps if a developer makes more than a million in a year. That was just crazy.

Pretty late, Adobe recognized and thought, oh! we should package the runtime with the app, so it will run correctly with its required version of runtime, and not depend on ODMs (we made a product SWF2Go in 2007 which did this). I can’t believe what sort of people were in Flash team who did not recognized this from the very start where I personally sent emails to Flash team, managers with same idea, am sure many other developers may have asked them the same.

Now in current situation, the only bad name Flash gets is from its Flash Player in the browser. What Flash team can do now is to split the player, one only with AS2 support, which I believe is the root cause of most security issues, and one with only AS3 runtime. This should’ve been the strategy from the start. But Adobe kept two runtimes in same player. Continuously improving on AS3 version, and deprecating the AS2 version.

We need tons of new language features in AS3, not just renamed APIs. Look at C# for example, evolution from v1 to latest. And this is really important moving forward. I do not see any new language features since AS3 was introduced with Flash Pro CS3. Here I’d like to share a post from Dave Yang’s FB feed, which summarizes exactly my point about why I and many other Flash developers held on to AS2 for too long.

DaveYang-FB-Post-Programing

For installable apps, AIR needs to drop HTML (webkit) and just keep AS3. I have not seen a single AIR app which is done with HTML, it’s a useless feature which wastes bytes with every deployment. All I see is AS3 apps and games in stores, so I always think why there’s this HTML thing in AIR, when Adobe also promotes another product PhoneGap, which does the same thing, makes mobile apps with HTML. Can anyone from Adobe tell me why AIR needs HTML support?

Also, AIR needs to support more platforms if it needs to gain some ground in future, i.e. Windows Phone / Mobile support which is top requested feature, but it seems that no one at Adobe cares anymore.

flash-cs3

Now Flash Pro, this tool was awesome until CS3. Even before that there were versions which didn’t come with new features but just re-write of the Panels system. I’ve seen so many versions of Flash Pro which just did that. The team wasted time in re-writing Panels system, instead if improving on or adding new useful features. For example, the Info Panel did not show real-time X, Y and other details when mouse was held down (fields just froze until mouse is released), until I filed a feature in CS4 (I was first time in beta), and it was implemented in CS5.5. Two versions later, because team were re-writing the Panels (lazy engineers as Jobs pointed out). Unbelievable.

There are tons of things which Flash Pro team can bring, return to the core idea which made Flash popular, Design, Timeline, Animation and Scripting them. Each of these features Flash Pro can borrow ideas from other tools. And even they can come up with a new version in one iteration which can be so new and feature rich, many designers and developers will appreciate and will upgrade for sure.

I see why Flash is dead as there’s no revenue coming from this investment for Adobe. I.e. Flash Pro CC, most are holding back on CS6 or older versions like myself. AIR is free and a developer can use AIR SDK with free FlashDevelop or other tools to make apps, so Adobe do not get anything for their investment going forward with AIR. Flash Player team also gets a bad name when we see some security issues now and then, again there’s not much revenue from Flash Player (other than the Flash Player install page which keeps trying to install some useless software along).

Update 1:

Another reason, that all my Flash developer contacts from 2004 onwards have moved on to something else around 2010-ish. Some switched technology, some even on different directions doing amazing 3D printing, embedded hardware stuff.

What Adobe needs to do is to make Flash Pro, the tool so feature rich, so awesome that developer buys a copy, like the old days of Flash 5. Make the app store prominent and attractive to developers, to buy and sell pre-built assets ready to use in projects or to extend the editor.

unity3d

Unity is a perfect example Flash team can follow. Look how they’ve not wasted time in re-writing panels, but they made Unity Editor so open that there’s a whole ecosystem for extensions. And brilliant idea of selling pre-built assets. They are making tons of money from this idea. They were able to give away free version of Unity, along with a perpetual or subscription version and cloud build. I see great strategy to make revenue from tool, and the assets store for developers. I am using free version, but I have bought extensions, from which they got something. Maybe in future I might go for Pro version as well.

There’s still time, and if Adobe can make and follow good strategy, which I currently don’t see (hence the post’s title), they can come back in game again.

BTW, about me, I am developing with Flash since 1998 (ver 3/4). Done great stuff with Flash, contributed to Flash Player (no credits) and Flash Pro (top beta tester, CS4 to first CC), and developer of SWF2Go.com, Flash Lite to Symbian app maker.

Would love to hear what you think about Flash and its future.

// chall3ng3r //

I’m Back, Again!

It’s exactly one year and 9 days since I last posted on this blog. I had some issues with my MySQL DB for this blog which was wrongly set to some other encoding, than UTF8.

After exporting my blog data, then re-installing latest WordPress, then importing data back in, fixing, tweaking settings. Now this is the first post after the overhaul.

I have some cool topics to discuss on this blog in coming weeks. I’ll give you some hints for whats coming:

  • Flash on Mobile and its future
  • Unity3D, why I’m going for it
  • State of Windows Phone as a platform for developers
  • And some more random thoughts around these, stay tuned!

// chall3ng3r //

Slides and Code From Mobile Game Development with Adobe Flash Workshop

Recently I did couple of workshop for Mobile Game Development with Adobe Flash at Jinnah University for Women. In first one we covered basics and getting used to the Flash Pro IDE, and basics of ActionScript 3, Timeline, MovieClips and other concepts in Flash.

Mobile Game Development using Adobe Flash- chall3ng3r - final

In 2nd follow-up workshop, we did some intermediate experiments, and completed a game, Popcornia, with real graphics, Timeline and AS3.

[slideshare id=15617758&doc=mobilegamedevelopmentusingadobeflash-chall3ng3r-final-121213025833-phpapp02]

Download Source: mobile-game-development-with-flash-chall3ng3r.zip

The download contains full source of the game Popcornia, I did some more tweaks when I got home from workshop, so I recommend participants to download this updated version.

Ported to BlackBerry 10 OS

I ported this game for BlackBerry 10 based Z10 with very small modifications. Download full source code and batch files which use BB10 SDK command-line tools to package and signing.

// chall3ng3r //

Windows 8 Tip: Making All Apps Tile and Shortcut Real Easy

I recently upgraded my main work machine, Dell Studio 1558, to Windows 8 Pro. Only had one issue, where my ATI display driver was making Windows 8 Pro to crash after few minutes into the start screen. Other than this no issues. Smooth sailing so far :)

chall3ng3r-start-screen

There’s one thing that I realized after few hours of using Windows 8 start screen, the All Apps option is hidden under a right-click contextual menu. And I was accessing it a lot of times during the day.

I thought there might be a tile that I can place on the start screen, and can just place it on there and All Apps will be just a click away as compared to right-click then click All Apps button in lower-right corner. I’m a lefty, and the start menu we all are so used-to made me look for more apps button in the lower-left corner all the time :D

After some research, I found that there’s no built-in All Apps tile in Windows 8. So I made one myself. I don’t exactly remember where I found the snippet, but all credit goes to whoever found it. I just searched for it :D

All you have to do is make a New Shortcut on Desktop, and set its Target field to:

%windir%explorer.exe shell:::{2559a1f8-21d7-11d4-bdaf-00c04f60b9f0}

And Start in field to: %windir%. You can change the icon as per your liking of course. Click Ok to create the shortcut on your Desktop.

Now, right-click on this newly created shortcut, and select Pin to Start. Now you have a nice tile that you can just click to access all of your installed applications. Should be great for touch screens as well.

Please note that this is not a perfect hack, there’s a small visual hick-up, as if you click on tile, it will take you to the Desktop for a second, then back to All Apps list in modern UI. But it works :D

You can also download this shortcut file I created for myself, so you don’t have to go through all the hacking stuff ;)

Download: AllApps_Tile_Windows8.zip

// chall3ng3r //