Sunday, September 28, 2014

Adafruit NeoPixels + Windows Phone 8

This is something that i wanted to do since a long time. Individual control of RGB LEDs on the Adafruit NeoPixel Shield over a bluetooth connection using my Lumia 920 running the Windows Phone 8, After extensively surfing MSDN help articles on WP8 APIs etc - Finally finished it this weekend.

Find the updated design, click here

In brief the design goes like this - An Adafruit NeoPixel shield containing 40 WS2812B 4-pin chip RGB LEDs in a 5 x 8 matrix pattern is mounted on an Adafruit Bluetooth Shield, the EZ Link which is stacked over an Arduino UNO. The code running in the Arduino reads the commands received on the serial bluetooth link, parses it and controls the RGB LEDs. The command packet sent from the Windows Phone consists of 5 fields - two fields for the X and Y co-ordinates of the LED and 3 fields for the R,G and B data obtained from the color picker.

The application on the windows phone is simply a grid of tiles created using the Coding4Fun WP toolkit. Each tile is identified uniquely by its name. Each tile can be set to a different color when clicked and has a one to one mapping with the LEDs on the adafruit shield. The color can be previewed in realtime. Some application statistics and setup are shown in below images. Once the code is well-organized i shall put it up here, and no, i did not write 40 event handlers for each of the tiles. There is only one event handler to rule them all :P

Once powered up the Arduino waits for a command on the BT Serial interface. When the application is started on the windows phone it establishes a connection with the BT module. On clicking any of the square tiles in the main application window another window opens up from where the color for that particular LED can be chosen. Alternatively all the LEDs can be turned off using the Turn Off button. The two wires in the pic below are the RX/TX pins from the BT shield connected to the Arduino over the SoftSerial interface...





P.S - The red color of the tiles is the default theme color on application startup. The LEDs do not get affected by this color unless programmed to




Here is an earlier experiment with a s ingle RGB LED breakout using Processing. The code for this can be found in the description of the video....






Monday, September 22, 2014

A Brainfuck Interpreter in C

Brainfuck is an esoteric programming language noted for its extreme minimalism. The language consists of only eight simple commands and an instruction pointer. It is designed to challenge and amuse programmers, and was not made to be suitable for practical use. It was created in 1993 by Urban Müller - Wikipedia

In short brainfuck has eight commands or instructions:

+ : Increments the value at the current cell by one.
- : Decrements the value at the current cell by one.
> : Moves the data pointer to the next cell (cell on the right).
< : Moves the data pointer to the previous cell (cell on the left).
. : Prints the ASCII value at the current cell (i.e. 65 = 'A').
, : Reads a single input character into the current cell.
[ : If the value at the current cell is zero, skips to the corresponding ] .
    Otherwise, move to the next instruction.
] : If the value at the current cell is zero, move to the next instruction.
    Otherwise, move backwards in the instructions to the corresponding [ . 

Here is a basic brainfuck interpreter in C that takes brainfuck code, works on it and produces the intended output. The implementation uses a recursive approach (why ? because brainfuck) and a stack for interpreting the brainfuck code. The examples include a multiplication code, addition of a series of numbers and some ASCII printing. The code is compiled and tested on  Visual C++ 2010 Express.There are several other ways to interpret brainfuck code, this is just one of those...

Next i will try to see the possiblity of implementing this on an FPGA. 

/*
Brainfuck Interpreter Code.
http://en.wikipedia.org/wiki/Brainfuck
A recursive, stack based implementation in C
Scaling Options:
MAX_CELLS - Increase cell count depending on brainfuck program
MAX_STACK_SZ - Increase stack size.
Author : Rishi F.
Copyright (c) 2014 Rishi F.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_CELLS 512
int cells[MAX_CELLS] = { 0, };
int *ptr = cells;
int debug_index = 0;
#define MAX_STACK_SZ 1024
static char *stack[MAX_STACK_SZ] = { (char *)0, };
static int stack_ptr = 0;
#define push(p) (stack[stack_ptr++] = p)
#define pop() (stack[--stack_ptr])
#define empty() (stack_ptr == 0)
#define full() (stack_ptr == MAX_STACK_SZ)
#define ERR_SUCCESS 0
#define ERR_FAILURE 1
int codeCheck(char *code)
{
// Check for invalid characters
char *save = code;
while (*code != '\0')
{
switch (*code)
{
case '>':
case '<':
case '.':
case ',':
case '+':
case '-':
case '[':
case ']':
case ' ': // ignore whitespaces, tabs
case '\t':
break;
default:
printf("Error in BF Code at index: %d\n", ((int)code - (int)save));
return ERR_FAILURE;
}
code++;
}
// Check [] parentheses balancing
code = save;
while (*code != '\0')
{
if (full()){ exit(1); }
if (*code == '['){ push(code); }
if (*code == ']'){
if (empty()){
printf("Unbalanced [ ]\n");
return ERR_FAILURE;
}
pop();
}
code++;
}
if (!empty()){
printf("Unbalanced [ ]\n");
return ERR_FAILURE;
}
return ERR_SUCCESS;
}
void reset_cells()
{
// clear array
memset(cells, 0, MAX_CELLS);
debug_index = 0;
ptr = cells;
printf("\n");
}
char *brainfuck(char *s)
{
char *save = s;
while (*s != '\0') {
switch (*s)
{
case '+':
++*ptr; s++;
break;
case '-':
--*ptr; s++;
break;
case '>':
++ptr; ++debug_index; s++;
break;
case '<':
--ptr; --debug_index; s++;
break;
case '.':
putchar(*ptr); s++;
break;
case ',':
*ptr = getchar(); s++;
break;
case '[':
if (full()){ exit(1); } //crude error handling
if (*ptr == 0){
push(s);
while (!empty())
{
if (*++s == '['){ push(s); }
if (*++s == ']'){ pop(); }
}
s++;
}
else {
push(s);
s = brainfuck(s + 1);
s++;
}
break;
case ']':
if (*ptr == 0)
{
if (empty()) { exit(1); }
pop();
return s;
}
else
{
s = save;
}
break;
default:
s++;
break;
}
}
return s;
}
int main()
{
char *bfcode_multiply = "[ > [ >+ >+ << -] >> [- << + >>] <<< -] >>";
char *bfcode_sum = "[>>>>> + <<<<< -] > [>>>> + <<<< -] > [>>> + <<< -] > [>> + << -] > [> + < -]";
char *bfcode_while = "> - [ < ++ [ - ] +++";
char *bfcode_invalid = "> -[<] ++{ ] ++ + ";
char *bfcode_parenthesis = "> - [ < ] ++ [ - ] ] +++";
char *bfcode_bffed = "> -[<] ++[] +` + ] -";
char *bfcode_author[] = {
"++++++++ [ > ++++++++++ < - ] > ++ . >",
"+++++++ [ > ++++++++++ < - ] > +++ . >",
"++++++++ [ > ++++++++++ < - ] > +++ . >",
"+++++++ [ > ++++++++++ < - ] > ++ . >",
"+++++++ [ > ++++++++++ < - ] > +++ . >"
};
// You can add code here to verify input BF code string.
// Error check for any characters other than the ones specified by BF
// Check for balanced square brackets
cells[0] = 15;
cells[1] = 2;
// Multiply numbers stored in cell[0] and cell[1]
// Result in cell[2]
brainfuck(bfcode_multiply);
reset_cells();
cells[0] = 3;
cells[1] = 5;
cells[2] = 1;
cells[3] = 9;
cells[4] = 6;
// Add numbers in cell[0 ... 4]
// Store result in cell[5]
brainfuck(bfcode_sum);
reset_cells();
// ASCII display
brainfuck(bfcode_author[0]);
brainfuck(bfcode_author[1]);
brainfuck(bfcode_author[2]);
brainfuck(bfcode_author[3]);
brainfuck(bfcode_author[4]);
reset_cells();
// Invalidity tests
codeCheck(bfcode_invalid);
codeCheck(bfcode_parenthesis);
codeCheck(bfcode_bffed);
reset_cells();
cells[1] = 1;
if (!codeCheck(bfcode_while)) {
brainfuck(bfcode_while);
}
return 0;
}
view raw brainfuck.c hosted with ❤ by GitHub

Wednesday, September 10, 2014

Stuff in Assembly - Bubble Sort !

An ARM assembly implementation of B-Sort. Why Bubble Sort ? because - "the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems" - Donald Knuth

Created in RVDS 4.0. Output viewed in the memory window of the RV Debugger. Cortex-A8 v7 processor.





#define MAX_ELEMENTS 10
extern void __sortc(int *, int);
int main()
{
int arr[MAX_ELEMENTS] = {5, 4, 1, 3, 2, 12, 55, 64, 77, 10};
__sortc(arr, MAX_ELEMENTS);
return 0;
}
view raw main.c hosted with ❤ by GitHub



AREA ARM, CODE, READONLY
CODE32
PRESERVE8
EXPORT __sortc
; r0 = &arr[0]
; r1 = length
__sortc
stmfd sp!, {r2-r9, lr}
mov r4, r1 ; inner loop counter
mov r3, r4
sub r1, r1, #1
mov r9, r1 ; outer loop counter
outer_loop
mov r5, r0
mov r4, r3
inner_loop
ldr r6, [r5], #4
ldr r7, [r5]
cmp r7, r6
; swap without swp
strls r6, [r5]
strls r7, [r5, #-4]
subs r4, r4, #1
bne inner_loop
subs r9, r9, #1
bne outer_loop
ldmfd sp!, {r2-r9, pc}^
END
view raw sort.s hosted with ❤ by GitHub