Archive

Archive for the ‘Code’ Category

VHDL inferred gating

February 3rd, 2010 David No comments

So this was an interesting find. We have been working with a rather large VHDL code base, and noticed a huge amount of control logic was being generated during synthesis. It seems that part of this is due to an interesting “feature” of VHDL, or I suppose more exactly of synthesis tools (we saw this with XST and Synplicity).

If you have some case statement, if then else, or switch, etc. Look carefully at signal assignments in each of the various cases. We were not always assigning to each signal in every case. This obviously follows from different cases doing different things.. but here is the tricky part. Clock gating and/or registering of signals is *inferred* for any signal that is not assigned to in all cases!

This can eat up logic fast, and if you are running near capacity of your target device, it can make it even worse, the added logic, clocking, and routing can cause the implementation to balloon. For example targeting an LX110-T, if we went above ~80% utilization, by the time we got through mapping and place&route we were close to 95%. The only way we could account for this was the extra logic used for the inferred control signals.

This may not matter in a lot of designs where you have plenty of room in the part, or maybe you don’t for some reason have a lot of case statements. We ended up refactoring and just assigning a signal to itself or some don’t care value in the other cases.

Categories: Algorithm, Code, Embedded, Xilinx Tags: , ,

Learning LINQ

November 5th, 2009 Markis No comments
LINQPad is a great tool to test linq queries.

http://www.linqpad.net

 
And the 101 samples from msdn is a great place to get started in learning LINQ.
 
C#
Categories: Linq Tags: ,

Seth Godin talks about tech and marketing

August 22nd, 2009 David No comments

This is a great talk…. go check it out…

Vid is here

Categories: Code Tags: ,

Zune HD poised for great things?

August 12th, 2009 David No comments

Anyone out there heard about the new Zune HD? You might hear about it a lot more soon. I wrote about this a while back when there was less info, just an announcement really. But now we have videos and reviews. I have to say it looks impressive so far. And finally something that LOOKS just as good as an Apple product too.

The screen looks great, and this has the new nvidia tegra chipset, so the graphics should be excellent.

Sure it plays music, has an HD radio tuner, video, and all that… but I secretly hope this is just the beginning of the Zune take over of the world. I’m serious. What if they added a UMTS modem? Instant cell phone…. And the Zune OS looks a whole heck of a lot better than the upcoming release of WinMobile…

Ok, and here is the other killer things for Zune (phone or otherwise). Apps. Lets look at programming on Apple vs Microsoft platforms. (For the sake of this exercise, I’m ignoring shell scripts or C++ command line app, etc). For GUI programming and GUI apps you have XCode vs .NET.. and then you have Java on both sides. But Java GUIs are worse than other of the other options, so we can ignore that too. I’ve coded on both sides and I have to say .NET is the easiest development system I’ve ever used, by far. VisualStudio is epic for debugging and development.

So.. Zune goes all app store on us… and you get to use .NET mobile to develop the apps. This would explode overnight. EVERYONE knows C# or VB… but to break into the Apple app store you have to figure out XCode’s development methodology and Obj-C. That sucks. No one uses Obj-C except Apple and I really just don’t like it.

This would be better than Android as well. I’m a big fan of Google and what they are doing with Android, but the SDK is still a bit rough, and the GUI design is no were near as good as what a Microsoft tool would bring.

And the HD has an nvidia chip set. What if we got some mobile version of DirectX? Think about the gaming potential of that too?

So that is my wild dream.. a Zune Phone with a .NET dev tool and an app store… Do it MS… DO IT.

C# and Serializing Structs to byte arrays

July 2nd, 2009 David 1 comment

So I have a application in C# that is communicating to something else via UDP messages. The messages are byte packed arrays of data. There are several bytes of header and then N bytes of data whos format is described in the header. I might send several Ints, or a string, or whatever.

This is pretty easy to handle in C/C++ as you can get raw pointers to everything. So if each message type is a struct, I can get a char* to the address of the struct and just read N bytes and send that out.

The problem on the C# end is this isnt so easy. If I want to pull messages apart and put them back into structs I have to do this manually each multi byte field at a time. So I was left with a function call for each message type to serialize it, and then another to deserialize it, each one having to know exactly what was in each message, so if I changed a message I’d have to edit all the handling functions. What I needed was a way to jsut get the raw bytes the in the received array into a struct of the right type, and vice versa. Fortunately there are some tricky ways to make this super easy.

First, we have to make sure the structs we declare in C# and packed. Here is an example:

using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential, Pack=1)]
struct msg1{
     int a;
     int b
     short c;
}

This will ensure there are no gaps between elements in the struct.

Next, we need a way to take an array of Bytes and copy it directly into the struct:

public static T DeserializeMsg< T >(Byte[] data) where T : struct
        {
            int objsize = Marshal.SizeOf(typeof(T));
            IntPtr buff = Marshal.AllocHGlobal(objsize);

            Marshal.Copy(data, 0, buff, objsize);

            T retStruct = (T)Marshal.PtrToStructure(buff, typeof(T));

            Marshal.FreeHGlobal(buff);

            return retStruct;
        }

Lets say we have a msg1 struct populated and we want to send that out over UDP. We need to serialize it back to raw bytes. This function will do just that:

public static Byte[] SerializeMessage< T >(T msg) where T : struct
        {
            int objsize = Marshal.SizeOf(typeof(T));
            Byte[] ret = new Byte[objsize];

            IntPtr buff = Marshal.AllocHGlobal(objsize);

            Marshal.StructureToPtr(msg, buff, true);

            Marshal.Copy(buff, ret, 0, objsize); 

            Marshal.FreeHGlobal(buff);

            return ret;
        }

Thats it!

qrcode

Simple UDP

June 23rd, 2009 David No comments

There are many reasons why you might need to send data or messages between devices on your network. Maybe you want to control a remote box, or you have a small linux setup running somewhere remotely and you want to sent and receive data. There are obviously several ways to do this, and one is using sockets and UDP.

This code came about when I needed to talk to an embeded CPU in a Xilinx FPGA. I have ethernet on the card as well, and the CPU is setup to handle it. I wanted to send control commands to the CPU from my Linux workstation to verify some functionality. To do this, I have two pieces of code: (1) a “server” that spins on the FPGA and receives the incoming messages, and a “client” app that can send a command to the “server”. This is a trvial example and the code is basic, but you can see how easy it would be to expand as needed.

The Client:

#include 
#include 
#include 
#include 
#include 

void die(char* msg) { perror(msg); exit(1); }

int main(int argc, char *argv[]) {
	int sock;
	struct sockaddr_in server;
	unsigned short int serverPort = 9999; 	

	sock= socket(AF_INET, SOCK_DGRAM, 0);
	if(sock < 0 ) die("failed to create socket");

	server.sin_family = AF_INET;
	server.sin_addr.s_addr = inet_addr("127.0.0.1");
	server.sin_port = serverPort; . 

	char msg[] = "Hello World. ";
	printf("We will send the message: \"%s\" to the server. \n", msg); 

	if (sendto(socketDescriptor, msg, strlen(msg), 0, (struct sockaddr *) &server, sizeof(server)) < 0) {
                   die("failed to send message");
	}

	return 0;
}

And now the Server:

#include 
#include 
#include 
#include 
#include 
#include 

#define BUFFSIZE 255
void Die(char* msg) { perror(msg); exit(1); }

int main(int argc, char* argv[]){
	int sock;
	struct sockaddr_in echoserver;
	struct sockaddr_in echoclient;

	char buffer[BUFFSIZE];
	unsigned int echolen, serverlen, clientlen;
	int rec = 0;

	if(argc != 2){
		fprintf(stderr, "USAGE: %s
\n", argv[0]);
		exit(1);
	}

	/* create UDP socket */
	if((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0){
		Die("failed to create socket");
	}

	memset(&echoserver, 0, sizeof(echoserver));
	echoserver.sin_family = AF_INET;
	echoserver.sin_addr.s_addr = htonl(INADDR_ANY);
	echoserver.sin_port = htons(atoi(argv[1]));

	serverlen = sizeof(echoserver);
	if(bind(sock, (struct sockaddr *) &echoserver, serverlen) < 0) {
		Die("failed to bind.");
	}

	while(1){

		clientlen = sizeof(echoclient);
		if((rec = recvfrom(sock, buffer, BUFFSIZE, 0, (struct sockaddr*)&echoclient, &clientlen)) < 0){
			Die("failed to rec mesg");
		}
		printf("client connected: %s\nData: %s\n\n", inet_ntoa(echoclient.sin_addr),buffer);

	}
}
Categories: C, Code, Embedded, Uncategorized, Xilinx Tags: , , , ,

C++ itoa

June 11th, 2009 David No comments

It’s super annoying that c/c++ has an atoi function but not an itoa. I’ve had to implement this countless times in my code, and I have a nice snipet that has worked well for me. This function supports output in an base from 2 to 16, and has a “pad” option that add a leading “0″ if the number of chars in the output string are not a multiple of two. This is nice for hex formatting.

string itoa(int value, int base, bool pad){
    enum { kMaxDigits = 35 };
    string buf;
    buf.reserve( kMaxDigits);

    //check that the base is valid
    if(base < 2 || base > 16) return buf;
    int quotient = value;

    //translate number to string with base
    do{
        buf += “0123456789abcdef”[std::abs( quotient % base )];
        quotient /= base;
    } while( quotient );

    //append negative sign for base 10
    if(value <0 && base == 10) buf += '-';

    reverse( buf.begin(), buf.end() );

    if(pad && base != 10) if(buf.length()%2 == 1) buf = "0" + buf;

    return buf;
} 
Categories: C++, Code Tags:

Outlook txt alerts

June 11th, 2009 David No comments

Like many people I use Outlook at work for mail and calendaring. However Android doesn’t yet have a free solution for checking mail, and other non-smart phones may not either. I can use the webmail interface, but its not convenient to check that all the time. Also, I have a pager at work for times and places that I can’t have my phone with me, it would be nice to get notifications and email alerts on my pager. Luckily Outlook has some nice macro features to solve this. I setup a macro to send a page with the From and Subject lines from the mail on receipt. This can also be extended to send a txt message to your phone with the same info, or hook the meeting reminders and forward those as well.

Simply go to Tools -> Macro -> Visual Basic Editor and click on “TheOutlookSession” in the project pane. Add this code:

Sub PageMe(MyMail as MailItem)
    Dim strID as String
    Dim olNS as Outlook.NameSpace
    Dim msg as Outlook.MailItem
    Dim rply as Outlook.MailItem

    strID = MyMail.EntryID
    Set olNS = Application.GetNamespace("MAPI")
    Set msg = olNS.GetItemFromID(strID)

    Set rply = Application.CreateItem(olMailItem)
    rply.Body = "New mail from: " + msg.SenderName + " Subj: " + msg.Subject
    rply.To = "youremail@here.com"
    rply.Send
    Set msg = Nothing
    Set rply = Nothing
    Set olNS = Nothing
End Sub


Categories: Code, VB Tags: , ,

A simple bootloader…

June 11th, 2009 David No comments

If you have ever used a Linux distro on an embedded system you know that a bootloader is a necessity. I’ve been working with PetaLinux for the Xilinx MicroBlaze and we have been using FS-boot to launch U-boot and then bring up Peta. However, recently I switched to BlueCat linux to take advantage of the MicroBlaze’s MMU. However, BlueCat doesn’t document a clear way to boot from flash. Below is some simple code to boot BlueCat. Note: the concept was taken from a Xilinx app note.

#include <xparams.h>
#define KDI_FLASH_LOC 0xXXXXXXXX //location of the linux image in flash
#define KDI_DDR_LOC 0xXXXXXXXX //location in DDR that you want your image to end up
#define KDI_LEN 0xXXXXXXXX //length of your image in bytes

main(){

uint8_t* kdi_flash_ptr = (uint8_t*)KDI_FLASH_LOC;
uint8_t* kdi_ddr_ptr = (uint8_t*)KDI_DDR_LOC;

void* laddr;

memcpy(kdi_flash_ptr, kdi_ddr_ptr, KDI_LEN);

laddr = (void*)KDI_DDR_LOC;
(*laddr)();

}

You can use XPS to load your KDI file into flash, and then compile the bootloader into your bitstream, load the FPGA, and you are off!

Categories: Code, Embedded, Linux, Xilinx Tags: , , ,