Posts | Comments

Planet Arduino

Archive for the ‘C’ Category

Sep
30

C++ 4 Stroke Engine Simulation MFC Visual Studio 2008

4 stroke, C, Engine, MFC, VS2008 Comments Off on C++ 4 Stroke Engine Simulation MFC Visual Studio 2008 


C++ 4 Stroke Engine Simulation MFC Visual Studio 2008




Sep
30

C++ 4 Stroke Engine Simulation MFC Visual Studio 2008

4 stroke, C, Engine, MFC, VS2008 Comments Off on C++ 4 Stroke Engine Simulation MFC Visual Studio 2008 


C++ 4 Stroke Engine Simulation MFC Visual Studio 2008

Wrote this back in 2005 when I was doing a boring managers job and didn't want all my skills to desert me. Function keys 2,3,4,5 and shift let you rotate the whole thing in X,Y,Z and zoom with the mouse.






Jul
30

New Generic EPiServer Page Type

C, EPiServer, Generic Lincoln University, HTML, qualifications Comments Off on New Generic EPiServer Page Type 


New Generic EPiServer Page Type

For you budding coders new or otherwise.

A simple piece of code which when its added to the load event of a EPiServer page can pull any variable from EPiServer or SharePoint using a HTML template with some tags embedded in it


EPiServer page templates in Visual Studio 2008



A bit of the HTML template. For example  the tags  labelled [sp:Title] with the value of a SharePoint variable called Title The same thing applies to EPI server values when a [es:TemplateFileName] tag is found its value is replaced with the EPiServer value for the page in question called TemplateFileName 

Here is the EPiServer page property setup for the course2014 page type. New property variable can be added here and displayed on a page without recompiling the whole website which improves the process with much lower technical risk and more flexibility, allowing user editing of the content in SharePoint and/or EPiServer as user currently do for any page  and allowing the developer to create rich web content and test it of line.

A side effect of this development will allow us to upgrade the new Quals pages so the actual content can be edited in the same way as any other EPiServer page 



A bit of the template file

<link rel="stylesheet" type="text/css" href="/QualsReform2014/Styles/coursereform2014.css" />
<script type="text/JavaScript" src="/QualsReform2014/script/coursereform2014.js"></script>

<div style="background:red">

     
    <div class="course_id_container">
        <h1><script type="text/JavaScript">CourseID('[sp:CourseCode]')</script> <script type="text/JavaScript">CourseDescription('[sp:Title]')</script></h1>
    </div>

    <div id="course_info">
     
        
        <div id="course_container">
           
              <br />
           
              
              <div id="course_desciption">
              <script type="text/JavaScript">Introduction('[sp:Introduction]')</script>
              </div>
           
              <br />
           

The C# code that loads and parses the HTML template and replaces the tags with values

            try
            {
                string filename = TemplateFileName;


                if (!File.Exists(filename))
                {
                    template.Append("Template file not found

"
 + filename + "
");
                    return;
                }

                string courseCode = Request[StructuredSearchController.CourseQueryID];

                if (courseCode == null)
                {
                    template.Append("Course code argument supplied is invalid
"
);
                    return;
                }

                if (courseCode.Length < 3)
                {
                    template.Append("No course code argument supplied
"
);
                    return;
                }

                myStructuredRecored = DynamicStructuredDataUtility.GetCourse(courseCode);

                if (myStructuredRecored == null)
                {
                    template.Append("Invalid course code supplied
"
);
                    return;
                }
           

                //Grab the template and do the work
                using (StreamReader sr = new StreamReader(filename))
                {
                   
                    while (!sr.EndOfStream)
                    {
                        string fline = sr.ReadLine();


                        //Handle SharePoint fields
                        int FSPfldi = 0;

                        int SSPfldi = fline.IndexOf("[sp:", FSPfldi);

                        while (SSPfldi > -1)
                        {
                            FSPfldi = fline.IndexOf("]", SSPfldi);

                            string SPfieldName = fline.Substring(SSPfldi+4, FSPfldi- SSPfldi - 4);

                            //template.Append(SPfieldName + "
");

                            if (!string.IsNullOrEmpty(SPfieldName))
                            {
                                //string FieldValue = getStructuredData(SPfieldName);
                               
                                object obj = null;

                               try {
                                    obj = getStructuredData(SPfieldName); }
                                catch { obj = "SharePoint Field: " + SPfieldName + " Not Found
"
; }

                                if (obj != null)
                                {
                                    string FieldValue = obj.ToString();

                                    //template.Append(SPfieldName + " = " + FieldValue + "
");

                                    fline = fline.Replace("[sp:" + SPfieldName + "]", FieldValue);
                                }
                            }
                           
                            if (FSPfldi > fline.Length)
                                break;

                            SSPfldi = fline.ToUpper().IndexOf("[SP:", FSPfldi);


                        }//End of while (SSPfldi > -1)



                        //Handle EPiServer Fields
                        int FEPifldi = 0;

                        int SEPifldi = fline.IndexOf("[es:", FEPifldi);

                        while (SEPifldi > -1)
                        {
                            FEPifldi = fline.IndexOf("]", SEPifldi);

                            string EPifieldName = fline.Substring(SEPifldi + 4, FEPifldi - SEPifldi - 4);

                            //template.Append(EPifieldName + "
");

                            if (!string.IsNullOrEmpty(EPifieldName))
                            {
                                //string FieldValue = getStructuredData(SPfieldName);

                                object obj = null;

                                try
                                {
                                    obj = CurrentPage[EPifieldName].ToString();
                                }
                                catch { obj = "EPiServer Field: " + EPifieldName + " Not Found
"
; }

                                if (obj != null)
                                {
                                   string FieldValue = obj.ToString();

                                    //template.Append(EPifieldName + " = " + FieldValue + "
");

                                    fline = fline.Replace("[es:" + EPifieldName + "]", FieldValue);
                                }
                            }

                            if (FEPifldi > fline.Length)
                                break;

                            SEPifldi = fline.ToUpper().IndexOf("[ES:", FEPifldi);


                        }//End of while (SEPifldi > -1)

                        //Add modified line to output
                        template.Append(fline);
                    }
                }


               

                //Response.Write(template);

            }
            catch (Exception ex)
            {
                template.Append(ex.Message);
                template.Append(ex.StackTrace);
            }



Jan
05

Kalman Filter for Arduino and C# Test Harness

C, kalman filter, Senza categoria, stability, test harness Comments Off on Kalman Filter for Arduino and C# Test Harness 

Kalman filter test harness with mimic C# code converted from Arduino code originally writen by Kristian Lauszus, TKJ Electronics.

The filter inputs in the test harness are driven from the sliders but could easily be fed from a real sensor. Another day perhaps?

The whole project is here Kalman Test




The C# class 

/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.

 This software may be distributed and modified under the terms of the GNU

 General Public License version 2 (GPL2) as published by the Free Software
 Foundation and appearing in the file GPL2.TXT included in the packaging of
 this file. Please note that GPL2 Section 2[b] requires that all works based
 on this software must also be made publicly available under the terms of
 the GPL2 ("Copyleft").

 Contact information

 -------------------

 Kristian Lauszus, TKJ Electronics

 Web      :  http://www.tkjelectronics.com
 e-mail   :  kristianl@tkjelectronics.com
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KalmanTest

{
    public class Kalman
    {
         /* variables */
        double Q_angle; // Process noise variance for the accelerometer
        double Q_bias; // Process noise variance for the gyro bias
        double R_measure; // Measurement noise variance - this is actually the variance of the measurement noise
    
        double angle; // The angle calculated by the Kalman filter - part of the 2x1 state matrix
        double bias; // The gyro bias calculated by the Kalman filter - part of the 2x1 state matrix
        double rate; // Unbiased rate calculated from the rate and the calculated bias - you have to call getAngle to update the rate
    
        double[,] P =  new double[2,2]; // Error covariance matrix - This is a 2x2 matrix
        double[] K = new double[2]; // Kalman gain - This is a 2x1 matrix
        double y; // Angle difference - 1x1 matrix
        double S; // Estimate error - 1x1 matrix


        public Kalman() {


            /* We will set the varibles like so, these can also be tuned by the user */

            Reset();
        
            // Reset bias
            // Since we assume tha the bias is 0 and we know the starting angle (use setAngle), 
            //the error covariance matrix is set like so - see: http://en.wikipedia.org/wiki/Kalman_filter#Example_application.2C_technical
            SetDefaults();
        }

        // The angle should be in degrees and the rate should be in degrees per second and the delta time in seconds

        public double getAngle(double newAngle, double newRate, double dt) {
            // KasBot V2  -  Kalman filter module - http://www.x-firm.com/?page_id=145
            // Modified by Kristian Lauszus
            // See my blog post for more information: http://blog.tkjelectronics.dk/2012/09/a-practical-approach-to-kalman-filter-and-how-to-implement-it
                        
            // Discrete Kalman filter time update equations - Time Update ("Predict")
            // Update xhat - Project the state ahead
            /* Step 1 */
            rate = newRate - bias;
            angle += dt * rate;
        
            // Update estimation error covariance - Project the error covariance ahead
            /* Step 2 */
            P[0,0] += dt * (dt*P[1,1] - P[0,1] - P[1,0] + Q_angle);
            P[0,1] -= dt * P[1,1];
            P[1,0] -= dt * P[1,1];
            P[1,1] += Q_bias * dt;
        
            // Discrete Kalman filter measurement update equations - Measurement Update ("Correct")
            // Calculate Kalman gain - Compute the Kalman gain
            /* Step 4 */
            S = P[0,0] + R_measure;
            /* Step 5 */
            K[0] = P[0,0] / S;
            K[1] = P[1,0] / S;
        
            // Calculate angle and bias - Update estimate with measurement zk (newAngle)
            /* Step 3 */
            y = newAngle - angle;
            /* Step 6 */
            angle += K[0] * y;
            bias += K[1] * y;
        
            // Calculate estimation error covariance - Update the error covariance
            /* Step 7 */
            P[0,0] -= K[0] * P[0,0];
            P[0,1] -= K[0] * P[0,1];
            P[1,0] -= K[1] * P[0,0];
            P[1,1] -= K[1] * P[0,1];
        
            return angle;
        }

        public void setAngle(double newAngle) { angle = newAngle; } // Used to set angle, this should be set as the starting angle

        public double getRate() { return rate; } // Return the unbiased rate
    
        /* These are used to tune the Kalman filter */
        public void setQangle(double newQ_angle) { Q_angle = newQ_angle; }
        public double getQangle() { return Q_angle; }

        public void setQbias(double newQ_bias) { Q_bias = newQ_bias; }

        public double getQbias() { return Q_bias; }

        public void setRmeasure(double newR_measure) { R_measure = newR_measure; }

        public double getRmeasure() { return R_measure; }


        public void Reset()

        {            
            bias = 0; // Reset bias
            P[0, 0] = 0; // Since we assume tha the bias is 0 and we know the starting angle (use setAngle), the error covariance matrix is set like so - see: http://en.wikipedia.org/wiki/Kalman_filter#Example_application.2C_technical
            P[0, 1] = 0;
            P[1, 0] = 0;
            P[1, 1] = 0;
        }

        public void SetDefaults()

        {
            /* We will set the varibles like so, these can also be tuned by the user */
            Q_angle = 0.001;
            Q_bias = 0.003;
            R_measure = 0.03;
        }

    }//End of class

}


The whole project is here Kalman Test




Introduction

There are many types of microcontrollers on the market, and it would be fair to say one of the two most popular types is the Microchip PIC series. The PICs are great as there is a huge range of microcontrollers available across a broad range of prices. However learning how to get started with the PIC platform isn’t exactly simple. Not that we expect it to be, however a soft start is always better. There are some older books, however they can cost more than $100 – and are generally outdated. So where do you start?

It is with this problem in mind that led fellow Australian David Meiklejohn to develop and offer his PIC Training Course and Development Board to the marketplace via his company Gooligum Electronics.

In his words:

There is plenty of material available on PICs, which can make it daunting to get started.  And some of the available material is dated, originally developed before modern “flash” PICs were available, or based on older devices that are no longer the best choice for new designs.  Our approach is to introduce PIC programming and design in easy stages, based on a solid grounding in theory, creating a set of building blocks and techniques and giving you the confidence to draw on as we move up to more complex designs.

So in this article we’ll examine David’s course package. First of all, let’s look at the development board and inclusions. Almost everything you will need to complete all the lessons is included in the package, including the following PIC microcontrollers:

You can choose to purchase the board in kit form or pre-assembled. If you enjoy soldering, save the money and get the kit – it’s simple to assemble and a nice way to spend a few hours with a soldering iron.

Although the board includes all the electronic components and PICs – you will need are a computer capable of running Microchip MPLAB software, a Microchip PICkit3 (or -2) programming device and an IC extractor. If you’re building the kit, a typical soldering iron and so on will be required. Being the  ultra-paranoid type, I bought a couple extra of each PIC to have as spares, however none were damaged in my experimenting. Just use common-sense when handling the PICs and you will be fine.

Assembly

Putting the kit board together wasn’t difficult at all. There isn’t any surface-mount parts to worry about, and the PCB is silk-screened very well:

The rest of the parts are shipped in antistatic bags, appropriately labelled and protected:

Assembly was straight forward, just start with the low-profile parts and work your way up. The assembly guide is useful to help with component placement. After working at a normal pace, it was ready in just over an hour:

The Hardware

Once assembled (or you’ve opened the packaging) the various sections of the board are obvious and clearly labelled – as they should be for an educational board. You will notice a large amount of jumper headers – they are required to bridge in and out various LEDs, select various input methods and so on. A large amount of jumper shunts is included with the board.

It might appear a little disconcerting at first, but all is revealed and explained as you progress through the lessons. The board has decent rubber feet, and is powered either by the PICkit3 programmer, or a regulated DC power source between 5 and 6V DC, such as from a plug-pack if you want to operate your board away from a PC.

However there is a wide range of functions, input and output devices on the board – and an adjustable oscillator, as shown in the following diagram:

The Lessons

There is some assumed knowledge, which is a reasonable understanding of basic electronics, some computer and mathematical savvy and the C programming language.

You can view the first group of lessons for free on the kit website, and these are included along with the additional lessons in the included CDROM. They’re in .pdf format and easy to read. The CDROM also includes all the code so you don’t have to transcribe it from the lessons. Students start with an absolute introduction to the system, and first learn how to program in assembly language in the first group of tutorials, followed by C in the second set.

This is great as you learn about the microcontroller itself, and basically start from the bottom. Although it’s no secret I enjoy using the Arduino system – it really does hide a lot of the actual hardware knowledge away from the end user which won’t be learned. With David’s system – you will learn.

If you scroll down to the bottom of this page, you can review the tutorial summaries. Finally here’s a quick demonstration of the 7-segment displays in action:

Where to from here? 

Once you run through all the tutorials, and feel confident with your knowledge, the world of Microchip PIC will be open to you. Plus you now have a great development board for prototyping with 6 to 14-pin PIC microcontrollers. Don’t forget all the pins are brought out to the row of sockets next to the solderless breadboard, so general prototyping is a breeze.

Conclusion

For those who have mastered basic electronics, and have some C or C-like programming experience from using other development environments or PCs – this package is perfect for getting started with the Microchip PIC environment. Plus you’ll learn about assembly language – which is a good thing. I genuinely recommend this to anyone who wants to learn about PIC and/or move into more advanced microcontroller work. And as the entire package is cheaper than some books –  you can’t go wrong. The training course is available directly from the Gooligum website.

Disclaimer - The Baseline and Mid-Range PIC Training Course and Development Board was a promotional consideration from Gooligum Electronics.

In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, subscribe  for email updates or RSS using the links on the right-hand column? And join our friendly Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other –  and we can all learn something.


Introduction

[Updated 18/06/2013]

There are many types of microcontrollers on the market, and it would be fair to say one of the two most popular types is the Microchip PIC series. The PICs are great as there is a huge range of microcontrollers available across a broad range of prices. However learning how to get started with the PIC platform isn’t exactly simple. Not that we expect it to be, however a soft start is always better. There are some older books, however they can cost more than $100 – and are generally outdated. So where do you start?

It is with this problem in mind that led fellow Australian David Meiklejohn to develop and offer his PIC Training Course and Development Board to the marketplace via his company Gooligum Electronics.

In his words:

There is plenty of material available on PICs, which can make it daunting to get started.  And some of the available material is dated, originally developed before modern “flash” PICs were available, or based on older devices that are no longer the best choice for new designs.  Our approach is to introduce PIC programming and design in easy stages, based on a solid grounding in theory, creating a set of building blocks and techniques and giving you the confidence to draw on as we move up to more complex designs.

So in this article we’ll examine David’s course package. First of all, let’s look at the development board and inclusions. Almost everything you will need to complete all the lessons is included in the package, including the following PIC microcontrollers:

You can choose to purchase the board in kit form or pre-assembled. If you enjoy soldering, save the money and get the kit – it’s simple to assemble and a nice way to spend a few hours with a soldering iron.

Although the board includes all the electronic components and PICs – you will need are a computer capable of running Microchip MPLAB software, a Microchip PICkit3 (or -2) programming device and an IC extractor. If you’re building the kit, a typical soldering iron and so on will be required. Being the  ultra-paranoid type, I bought a couple extra of each PIC to have as spares, however none were damaged in my experimenting. Just use common-sense when handling the PICs and you will be fine.

Assembly

Putting the kit board together wasn’t difficult at all. There isn’t any surface-mount parts to worry about, and the PCB is silk-screened very well:

barepcbss

The rest of the parts are shipped in antistatic bags, appropriately labelled and protected:

allthebitsss

Assembly was straight forward, just start with the low-profile parts and work your way up. The assembly guide is useful to help with component placement. After working at a normal pace, it was ready in just over an hour:

finishedboardss

The Hardware

Once assembled (or you’ve opened the packaging) the various sections of the board are obvious and clearly labelled – as they should be for an educational board. You will notice a large amount of jumper headers – they are required to bridge in and out various LEDs, select various input methods and so on. A large amount of jumper shunts is included with the board.

It might appear a little disconcerting at first, but all is revealed and explained as you progress through the lessons. The board has decent rubber feet, and is powered either by the PICkit3 programmer, or a regulated DC power source between 5 and 6V DC, such as from a plug-pack if you want to operate your board away from a PC.

However there is a wide range of functions, input and output devices on the board – and an adjustable oscillator, as shown in the following diagram:

boardlayoutonceassembledss

The Lessons

There is some assumed knowledge, which is a reasonable understanding of basic electronics, some computer and mathematical savvy and the C programming language.

You can view the first group of lessons for free on the kit website, and these are included along with the additional lessons in the included CDROM. They’re in .pdf format and easy to read. The CDROM also includes all the code so you don’t have to transcribe it from the lessons. Students start with an absolute introduction to the system, and first learn how to program in assembly language in the first group of tutorials, followed by C in the second set.

This is great as you learn about the microcontroller itself, and basically start from the bottom. Although it’s no secret I enjoy using the Arduino system – it really does hide a lot of the actual hardware knowledge away from the end user which won’t be learned. With David’s system – you will learn.

If you scroll down to the bottom of this page, you can review the tutorial summaries. Finally here’s a quick demonstration of the 7-segment displays in action:

Update – 18/06/2013

David has continued publishing more tutorials for his customers every few months – including such topics as the EEPROM and pulse-width modulation. As part of the expanded lessons you can also get a pack which allows experimenting with electric motors that includes a small DC motor, the TI SN75441 h-bridge IC, N-channel and P-channel MOSFETS and more:

motorkit

So after the initial purchase, you won’t be left on your own. Kudos to David for continuing to support and develop more material for his customers.

Where to from here? 

Once you run through all the tutorials, and feel confident with your knowledge, the world of Microchip PIC will be open to you. Plus you now have a great development board for prototyping with 6 to 14-pin PIC microcontrollers. Don’t forget all the pins are brought out to the row of sockets next to the solderless breadboard, so general prototyping is a breeze.

Conclusion

For those who have mastered basic electronics, and have some C or C-like programming experience from using other development environments or PCs – this package is perfect for getting started with the Microchip PIC environment. Plus you’ll learn about assembly language – which is a good thing. I genuinely recommend this to anyone who wants to learn about PIC and/or move into more advanced microcontroller work. And as the entire package is cheaper than some books –  you can’t go wrong. The training course is available directly from the Gooligum website.

Disclaimer - The Baseline and Mid-Range PIC Training Course and Development Board was a promotional consideration from Gooligum Electronics.

In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, subscribe  for email updates or RSS using the links on the right-hand column? And join our friendly Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other –  and we can all learn something.

The post Review: Gooligum Electronics PIC Training Course and Development Board appeared first on tronixstuff.

Oct
22

Giving the Arduino deques, vectors and streams with the standard template library

arduino, arduino hacks, AVR, C, object oriented, Software Development, standard template library Comments Off on Giving the Arduino deques, vectors and streams with the standard template library 

The Arduino IDE is extremely similar to C++, but judging from the sketches you can find on the Internet, you’d never know it. Simpler Arduino projects can make do with just toggling IO pins, reading values, and sending serial data between two points. More complex builds fall into the category of real software development, and this is where the standard Arduino IDE falls miserably short.

[Andy] saw this lack of proper libraries for more complicated pieces of software as a terrible situation and decided to do something about it. He ported the SGI Standard Template Library to bring all those fun algorithms and data structures to any AVR chip, including the Arduino.

Going over what’s included in [Andy]‘s port reads just like a syllabus for an object-oriented programming class. Stacks, queues, and lists make the cut, as do strings and vectors. Also included is just about everything in the   and headers along with a few Arduino-oriented additions like a hardware serial and liquid crystal streams.

With all these objects floating around, [Andy] says it will make an impact on Flash and SRAM usage in an AVR. Still, with all the hullabaloo over faster and larger ARM micros, it’s nice to see the classic 8-bit microcontroller becoming a bit more refined.


Filed under: arduino hacks, Software Development


  • Newsletter

    Sign up for the PlanetArduino Newsletter, which delivers the most popular articles via e-mail to your inbox every week. Just fill in the information below and submit.

  • Like Us on Facebook