Membuat AVR Programmer Lewat Koneksi Serial

AVR910 – AVR Programmer

schematic AVR910Rangkaian ini adalah AVR programmer dari koneksi serial ke ISP.

Rangkaian di atas dapat  dimodif agar terkoneksi secara USB dengan menambahkan chip USB2Serial seperti PL-2303HX. Jadi Programmer tersebut dapat terkoneksi dengan port USB PC ataupun laptop tanpa harus ada port RS232. Driver untuk chip tersebut bisa didownload di webnya.

Untuk kode mikrokontroler ATTiny2313 dapat diunduh di forum sbb

elektroda.pl/rtvforum/topic2382719.html

Kalau saya lebih senang dengan file avr910_2313_ver31.asm karena maksimal baudratenya bisa sampai 115200. Untuk mendapat file hex, file asm dicompile dengan AVRStudio 4. Setelah itu downloadkan ke chip ATTiny2313 lewat bantuan ISP programmer lainnya. Dan AVR910 kita siap digunakan untuk mendownload program mikrokontroler AVR kita.

Referensi
_________________

elektroda.pl/rtvforum/topic2382719.html
kmitl.ac.th/~kswichit/avr910/avr910.htm
atmel.com/Images/doc0943.pdf

Membuat Server Video Streming Sederhana Visual C# 2012

Berdasarkan post sebelumnya http://wangready.wordpress.com/2011/10/09/akuisisi-gambar-dari-webcam-menggunakan-aforge-net-library-berbasis-bahasa-c/

saya edit dan tambahkan timer untuk menyimpan file gambar pada server xampp. Jadi instal dulu xampp.

private void timer1_Tick(object sender, EventArgs e)
        {
            Bitmap im1 = videoSourcePlayer.GetCurrentVideoFrame();
            pictureBox1.Image = im1;
            im1.Save(@"C:\xampp\htdocs\my_page\tes_buff.jpg");
            try
            {
                System.IO.FileInfo f = new System.IO.FileInfo(@"C:\xampp\htdocs\my_page\tes_buff.jpg");
                long s1 = f.Length;
                label4.Text = s1.ToString();
                if(s1>100000)
                    System.IO.File.Copy(@"C:\xampp\htdocs\my_page\tes_buff.jpg", @"C:\xampp\htdocs\my_page\tes.jpg", true);
            }
            catch (Exception a)
            {
            }
        }

file gambar saya simpan di C:\xampp\htdocs\my_page\tes.jpg . File bisa di browse lewat page html sederhana sbb.

<html>
<head>
<title>HTML in 10 Simple Steps or Less</title>
<meta http-equiv="refresh" content="0.5" >
</head>
<body>
<img src="http://10.7.21.8/my_page/tes.jpg"/>
</body>

Untuk mengganti folder file browsing saya mengedit file dari index.php di folder htdocs menjadi /my_page/

<?php
	if (!empty($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'])) {
		$uri = 'https://';
	} else {
		$uri = 'http://';
	}
	$uri .= $_SERVER['HTTP_HOST'];
	header('Location: '.$uri.'/my_page/');
	exit;
?>

gambar bisa distreaming juga lewat aplikasi yang contohnya ada di example library aforge.net langsung mengakses file .jpg nya dengan alamat URL server. file project aplikasinya ada di directory \AForge.NET\Framework\Samples\Vision\MotionDetector

Map Koordinat GPS Visual C#

map

map_gui

Source static map yang digunakan adalah dari openstreetmap karena free. Bisa juga menggunakan google map Static Maps API V2 Developer akan tetapi 25 000 free static map requests per application per 24 hour period. Lebih dari itu harus mempunyai API_KEY  Google Maps API for Business.

Item yang digunakan pada contoh ini menggunakan picturebox1 untuk menampilkan map yang di browsing lewat koneksi internet, timer1 memberi jeda waktu untuk merefresh map, dan label1 untuk menampilkan parameter yang ingin dipantau (fleksible untuk memudahkan memeriksa parameter2). Karena input latitude dan longitude yang saya berikan adalah dengan format yang terdapat pada SiRF NMEA Reference Manual hardware GPS, dengan format Latitude ddmm.mmmm,N/S Indicator, Longitude dddmm.mmmm, N/S Indicator, maka saya melakukan konversi dahulu kedalam desimal.

 
Decimal Degrees = Degrees + minutes/60 + seconds/3600

 

public double conversi_degrees(double time_deg)
{
   double depan = (double)(int)time_deg;
   double belakang = time_deg - depan;
   double degrees = (double)(int)(depan/100);
   double minutes = Math.Round(time_deg - (degrees*100),6);
   double dec_degrees = degrees + Math.Round((minutes/60),6);
   return (dec_degrees);
}

 
Setelah didapat nilai dalam format desimal, maka variabel tersebut siap dimasukan ke dalam format URL dari openstreetmap untuk kemudian ditampilkan di picturebox1.
kode lengkap.
 

using System;
using System.Windows.Forms;

namespace GPS_MAP
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int jum_pin = 5;
        double center_lat_val = -658.62665;
        double center_long_val = 10737.81812;
        double[] center_lat_pin = new double[5] { -658.62665, -658.62665, -658.62665, -658.62665, -658.62665 };
        double[] center_long_pin = new double[5] { 10737.81812, 10737.92722, 10738.03632, 10738.14542, 10738.25442 };
        
        string url_data;
        string pin_data;

        int count = 15;
        private void timer1_Tick(object sender, EventArgs e)
        {
            double lat_val;
            double long_val;
            lat_val = conversi_degrees(center_lat_val);
            long_val = conversi_degrees(center_long_val);
            int val_zoom = count;
            pin_data = "";
            for (int i = 0; i < jum_pin; i++)
            {
                double lat_pin = conversi_degrees(center_lat_pin[i]);
                double long_pin = conversi_degrees(center_long_pin[i]); 
                pin_data += string.Format("{0},{1},lightblue{2}|", lat_pin, long_pin,i+1);
            }
            url_data = String.Format("http://staticmap.openstreetmap.de/staticmap.php?center={0},{1}&zoom={2}&size=600x300&maptype=mapnik&markers={3}",lat_val,long_val,val_zoom,pin_data);
            pictureBox1.ImageLocation = url_data;

            label1.Text = url_data;
        }

        public double conversi_degrees(double time_deg)
        {
            double depan = (double)(int)time_deg;
            double belakang = time_deg - depan;
            double degrees = (double)(int)(depan/100);
            double minutes = Math.Round(time_deg - (degrees*100),6);
            double dec_degrees = degrees + Math.Round((minutes/60),6);
            return (dec_degrees);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }

        protected override void OnMouseWheel(MouseEventArgs mea)
        {
            if (mouse_stat_enter == 1)
            {
                count += mea.Delta / 120;
                if (count < 0)
                    count = 0;
                else if (count > 18)
                    count = 18;
            }
        }

        int mouse_pos_X, mouse_pos_Y;
        int prev_mouse_pos_X, prev_mouse_pos_Y;
        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            pictureBox1.Cursor = Cursors.Hand;
            prev_mouse_pos_X = e.X;
            prev_mouse_pos_Y = e.Y; 
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            pictureBox1.Cursor = Cursors.Default;
            mouse_pos_X = e.X;
            mouse_pos_Y = e.Y;
            int delta_X = prev_mouse_pos_X - mouse_pos_X;
            int delta_Y = prev_mouse_pos_Y - mouse_pos_Y;
            double constanta;
            if((count >=15)&&(count<=18))
                constanta = 20;
            else if((count >=12)&&(count<15))
                constanta = 8;
            else if((count >=9)&&(count<12))
                constanta = 1;
            else if((count >=6)&&(count<9))
                constanta = 0.5;
            else if((count >=3)&&(count<6))
                constanta = 0.1;
            else
                constanta = 0.1;
            center_lat_val -= (double)delta_Y/(count*constanta);
            center_long_val += (double)delta_X/(count * constanta);
        }

        int mouse_stat_enter = 0;
        private void pictureBox1_MouseEnter(object sender, EventArgs e)
        {
            mouse_stat_enter = 1;
        }

        private void pictureBox1_MouseLeave(object sender, EventArgs e)
        {
            mouse_stat_enter = 0;
        }
    }
}

 
________________________________________
Daftar Pustaka
wiki.openstreetmap.org/wiki/Static_map_images
staticmap.openstreetmap.de/
developers.google.com/maps/documentation/staticmaps/
itouchmap.com/latlong.html
andrew.hedges.name/experiments/convert_lat_long/

Template HMI Sederhana C# VS2012

HMI_simple
FILE DOWNLOAD

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Configuration;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

            //------------------------------------------------------------------
            int panjang = pictureBox1.Size.Height;
            int lebar = pictureBox1.Size.Width;
            Graphics g = this.pictureBox1.CreateGraphics();
            Pen p1 = new Pen(Color.Black, 3);
            Pen p2 = new Pen(Color.GreenYellow, 3);
            int batas_panjang = panjang * (100-level_panjang)/100;
            for (int y = 0; y < batas_panjang; y++)
            {
                g.DrawLine(p1, new Point(0, y), new Point(lebar, y));
            }
            for (int y = batas_panjang; y < panjang; y++)
            {
                g.DrawLine(p2, new Point(0, y), new Point(lebar, y));
            }
            //------------------------------------------------------------------
            //------------------------------------------------------------------
           /* label1.Text = panjang_O.ToString() + " " + lebar_O.ToString() +
                Environment.NewLine + Y.ToString() +
                Environment.NewLine + X.ToString() +
                Environment.NewLine + jarum.ToString();*/
        }
        Bitmap default_image;
        int level_panjang;
        int Stat_button1;
        private void button1_Click(object sender, EventArgs e)
        {
            if (Stat_button1 == 0)
            {
                button1.Text = "ON";
                button1.ForeColor = Color.Black;
                button1.BackColor = Color.Yellow;
                Stat_button1 = 1;
            }
            else
            {
                button1.Text = "OFF";
                button1.ForeColor = Color.White;
                button1.BackColor = Color.DarkBlue;
                Stat_button1 = 0;
            }

        }

        private void trackBar1_Scroll(object sender, EventArgs e)
        {
            level_panjang = trackBar1.Value;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            default_image = (Bitmap)pictureBox3.Image.Clone();
            pictureBox4.Enabled = false;

            int x_ = pictureBox3.Size.Width;
            int y_ = pictureBox3.Size.Height;
            label2.Parent = pictureBox3;
            label2.BackColor = Color.Transparent;
            label2.BringToFront();
            label2.ForeColor = Color.DarkGreen;
            label2.Location = new Point(0, (int)(y_*0.7));

            button1.Text = "OFF";
            button1.ForeColor = Color.White;
            button1.BackColor = Color.DarkBlue;
        }

        int alarm_stat;
        private void timer2_Tick(object sender, EventArgs e)
        {
            float derajat = ((float)level_panjang/100) * 360;
            label2.Text = Convert.ToString((int)derajat);
            pictureBox3.Image = RotateImage(default_image, derajat-143);

            if (level_panjang > 50)
            {
                pictureBox4.Enabled = true;
                timer3.Enabled = true;

                if (alarm_stat == 0)
                {
                    if (this.WindowState == FormWindowState.Minimized)
                        this.WindowState = FormWindowState.Normal;
                    this.Show();
                    this.Activate();
                    this.ShowInTaskbar = true;
                    this.TopMost = true;
                    this.Focus();
                    alarm_stat = 1;
                }
            }
            else
            {
                pictureBox4.Enabled = false;
                timer3.Enabled = false;
                BackColor = Color.FromName("Control");
                pictureBox3.BackColor = Color.FromName("Control");

                if (alarm_stat == 1)
                {
                    this.TopMost = false;
                    alarm_stat = 0;
                }
            }
        }

        public static Image RotateImage(Image img, float rotationAngle)
        {
            //create an empty Bitmap image
            Bitmap bmp = new Bitmap(img.Width, img.Height);

            //turn the Bitmap into a Graphics object
            Graphics gfx = Graphics.FromImage(bmp);

            //now we set the rotation point to the center of our image
            gfx.TranslateTransform((float)bmp.Width / 2, (float)bmp.Height / 2);

            //now rotate the image
            gfx.RotateTransform(rotationAngle);

            gfx.TranslateTransform(-(float)bmp.Width / 2, -(float)bmp.Height / 2);

            //set the InterpolationMode to HighQualityBicubic so to ensure a high
            //quality image once it is transformed to the specified size
            gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;

            //now draw our new image onto the graphics object
            gfx.DrawImage(img, new Point(0, 0));

            //dispose of our Graphics object
            gfx.Dispose();

            //return the image
            return bmp;
        }

        int stat;
        private void timer3_Tick(object sender, EventArgs e)
        {
            if (stat == 0)
            {
                BackColor = Color.Red;
                pictureBox3.BackColor = Color.Red;
                Console.Beep();
                stat = 1;
            }
            else
            {
                BackColor = Color.FromName("Control");
                pictureBox3.BackColor = Color.FromName("Control");
                stat = 0;
            }
        }

        private void timer4_Tick(object sender, EventArgs e)
        {
            label4.Text = DateTime.Now.ToString();
        }
    }
}

Mem-Plot Data Serial Pada Matlab

serial_plot_matlab

Gambar di atas didapat dengan simulasi mikrokontroler dengan proteus -> virtual serial port emulator ->Matlab

Bagaimana memplot data yang di akuisisi oleh mikrokontroler lalu ditampilkan di Matlab?

Missal data yang dikirim dari mikro adalah sebagai berikut.

while (1)
      {
      // Place your code here    
       for(i=0;i<360;i+=60) 
       {        
            sin_wave = 100*sin(i * 0.0174532925);
            printf("data %d %f 100 \n\r",i,sin_wave);
       }   
      }

Kode di matlab untuk menampilkan grafik seperti gambar di atas.

clc
clear all
close all

%*******************inisialisasi serialport*****************************
delete(instrfindall); 
S1 = serial ('COM3', 'Baudrate', 9600, 'DataBits', 8, 'Parity','none'); 
fopen(S1);
figure,
time_t = 1;
for zz=1:1000
    clf; % clear current figure (refresh the polt)
    t = [];
    buffer_data = [];
    ii=0;
    while(ii<10)
        linedata = fgetl(S1);
        data_dec = textscan(linedata,'data %d %f %d');
        dat_A  = data_dec{1};
        dat_B  = data_dec{2};
        dat_C  = data_dec{3};
        t = time_t:time_t + 9;
        buffer_data = [buffer_data; dat_A dat_B dat_C]; 
        ukur = size(buffer_data);
        ii = ukur(1);
    end
    plot(t, buffer_data(:,1),'r-');hold on
    plot(t, buffer_data(:,2),'g-');hold on
    plot(t, buffer_data(:,3),'b-');hold off
    axis([time_t,time_t + 9,-120,360]);    
    time_t = time_t + 10;
    drawnow;
end

Line Follower Robot Berbasis Sensor Kamera

Robot dirancang mempunyai sensor kamera, yaitu webcam. Data citra diakuisisi menggunakan komputer lewat software MATLAB. Di komputerlah semua algoritma utama dibuat. Komputer menghasilkan output data PWM yang kemudian dikirim ke mikrokontroler lewat koneksi USB2Serial. Mikrokontroler akan menerjemahkan data yang diterima dari komputer menjadi sinyal PWM. Sinyal ini masuk ke motor driver baru kemudian masuk ke motor dengan tegangan maksimal tegangan baterai, yaitu 11,1V. Robot juga dirancang untuk dapat mengenali posisi dengan mengenali landmark yang terdapat pada beberapa posisi pada garis. Dengan menambahkan data peta garis ke dalam sistem pengolahan data, robot dapat bergerak otomatis ke posisi yang diinginkan atau disebut posisi target.

Robot mendeteksi garis dengan menggunakan metode filter warna. Metode filter warna juga digunakan untuk mendeteksi keberadaan landmark. Sebelum landmark dapat diproses untuk dikenali, citra landmark yang sudah dicrop dirotate dengan berdasarkan data kemiringan yang terdeteksi oleh Transformasi Hough. Dengan demikian input untuk proses pengenalan landmark menjadi sesuai dengan kriteria. Algoritma pengenalannya menggunakan metode PCA (Principle Component Analysis) yang terlebih dahulu membuat data latih.

Berikut skematik sistem mikrokontrolernya.

sch_con
_________________________________________________
DAFTAR PUSTAKA
[1] Armbrust , C. Braun , T. Föhst, T. Proetzsch, M. Renner, A. Schäfer, B.H., Berns K. The Robust Autonomous Vehicle for Off-road Navigation. Technische Universität Kaiserslautern.
[2] Bräunl, Thomas. EMBEDDED ROBOTICS: Mobile Robot Design and Applicationswith Embedded Systems. Springer-Verlag Berlin Heidelberg 2003, 2006. Germany.
[3] Datasheet mikrokontroler ATmega32.
[4] Datasheet IC H-Bridge L298.
[5] Francois Dupuis, Jean. Parizeau, Marc. Evolving a Vision-Based LineFollowing Robot Controller. Departement de genie electrique et de genie informatique. Universite Laval, Quebec. Canada.
[6] Kim, Kyungnam.Face Recognition using Principle Component Analysis. Department of Computer Science. University of Maryland, College Park MD 20742, USA.
[7] Pitowarno, Endra.2006.”ROBOTIKA: Desain, Kontrol, dan Kecerdasan Buatan”. Percetakan Andi Offset. Yogyakarta. Indonesia.
[8] Pranata Kusuma, Andri. 2013. Analysis Of Hough Transform Algorithm For Circle And Ellipse Detection Based On Digital Image Processing. Tugas Akhir Program Sarjana. Institut Teknologi Telkom.
[9] Rusdinar, Angga. Kim, Jungmin. Lee, Junha. Kim, Sungshin. 2011. Implementation Of Real-Time Positioning System Using Extended Kalman Filter And Artificial Landmark On Ceiling. School of Electrical Engineering, Pusan National University, Busan, 609-735, Korea.
[10] Schworer, Ian. 2005.Navigation and Control of an Autonomous Vehicle. Virginia Polytechnic Institute and State University. Blacksburg,Virginia.
[11] Sigit, Riyanto. 2007. Robotikaa, Sensor, dan Aktuator. Yogyakarta : Graha Ilmu.
[12] W. Wall, Richard. Bennett, Jerry. Eis, Greg. Lichy, Kevin. Owings, Elizabeth. Creating A Low-Cost Autonomous Vehicle. University of Idaho Moscow.

Membuat Virtual Joystik C#

Project kali ini adalah membuat sebuah aplikasi pada PC yang berperan menjembatani sebuah controller game yang mempunyai interface serial dengan game di PC. Controller game yang dimaksud adalah sebuah accelerometer (post sebelumnya).  Library yang digunakan adalah vjoy atau Virtual joystick. Library-nya bisa di download di link berikut.

vjoystick.sourceforge.net/site/index.php/dev

Compiler menggunakan Visual C# Express 2010.

Pada post sebelumnya saya merancang program GUI dengan chart untuk mengecek data yang diterima. Berikut tampilannya.

vjoy1

berikut kode nya.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Configuration;

namespace serial
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //—menset event handler untuk DataReceived event—
            serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(DataReceived);
            //—menampilkan nama serialport yang tersedia pada
            // komputer—
            string[] portNames = System.IO.Ports.SerialPort.GetPortNames();
            for (int i = 0; i <= portNames.Length - 1; i++)
            {
                cbbCOMPorts.Items.Add(portNames[i]);
            }
            btnDisconnect.Enabled = false;
            horison = pictureBox1.Image;

            chart1.ChartAreas["ChartArea1"].AxisX.Minimum = 0.0;
            chart1.ChartAreas["ChartArea1"].AxisX.Maximum = 200.0;
            chart1.ChartAreas["ChartArea1"].AxisY.Minimum = -60.0;
            chart1.ChartAreas["ChartArea1"].AxisY.Maximum = 60.0;

            chart1.Series["Series1"].Color = Color.Cyan;
            chart1.Series["Series2"].Color = Color.Red;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            //—menutup akses serialport apabila akses serialport terbuka—
            if (serialPort.IsOpen)
            {
                serialPort.Close();
            }
            try
            {
                //—mengatur beberapa parameter untuk koneksi serial
                // port—
                serialPort.PortName = cbbCOMPorts.Text;
                serialPort.BaudRate = 9600;
                serialPort.Parity = System.IO.Ports.Parity.None;
                serialPort.DataBits = 8;
                serialPort.StopBits = System.IO.Ports.StopBits.One;
                //—buka serial port—
                serialPort.Open();
                //—menampilkan status dari serial port dan
                // enable/disable -kan tombol—
                lblMessage.Text = cbbCOMPorts.Text + " connected.";
                btnConnect.Enabled = false;
                btnDisconnect.Enabled = true;
                timer1.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            try
            {
                //—tutup serial port—
                serialPort.Close();
                //—menampilkan status dari serial port dan
                // enable/disable -kan tombol—
                lblMessage.Text = serialPort.PortName +" disconnected.";
                btnConnect.Enabled = true;
                btnDisconnect.Enabled = false;
                timer1.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                //—menulis tipe data string pada serial port—
                serialPort.Write(txtDataToSend.Text + Environment.NewLine);
                //—menambahkan string yang telah dikirim pada TextBox control—
                txtDataReceived.AppendText(">" + txtDataToSend.Text +  Environment.NewLine);
                txtDataReceived.ScrollToCaret();
                //—bersihkanTextBox control—
                txtDataToSend.Text = string.Empty;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        string kata;
        string[] buff_kata = new string[8];
        //—Event handler untuk DataReceived event—
        private void DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                kata = serialPort.ReadLine();
                buff_kata = SplitWords(kata);
                if (kata != string.Empty)
                {
                    //txtDataReceived.Text = kata;
                    txtDataReceived.BeginInvoke(new myDelegate(updateTextBox));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        static string[] SplitWords(string s)
        {
            //
            // Split on all non-word characters.
            // ... Returns an array of all the words.
            //
            return Regex.Split(s, " ");
            // @      special verbatim string syntax
            // \W+    one or more non-word characters together
        }

        //—Delegate and subroutine untuk ditampilkan pada TextBox control—
        public delegate void myDelegate();

        double  Kk,
                Xk_topi,
                Pk,
                R = 0.1,
                Q = 0.002,
                Xk_topi_prev = 0,
                Pk_prev = 1,
                Pk_update,
                Xk_topi_update;
        int kalman_filter_ku(double Zk)
        {
            //Time Update
            Xk_topi_update = Xk_topi_prev;
            Pk_update = Pk_prev + Q;
            //Measurement Update
            Kk = Pk_update / (Pk_update + R);
            Xk_topi = Xk_topi_update + (Kk * (Zk - Xk_topi_update));
            Pk = (1 - Kk) * Pk_update;
            Xk_topi_prev = Xk_topi;
            Pk_prev = Pk;
            return ((int)Xk_topi);
        }

        Image horison;
        int data_y,
            kalman_y;
        public void updateTextBox()
        {
            try
            {
                data_y = Convert.ToInt32(buff_kata[2]);
            }
            catch (Exception a)
            {

            }
            kalman_y = kalman_filter_ku((double)data_y);
            txtDataReceived.Text = "ACC:"+data_y.ToString()+" Kalman:"+kalman_y.ToString();
        }

        public static Image RotateImage(Image img, float rotationAngle)
        {
            //create an empty Bitmap image
            Bitmap bmp = new Bitmap(img.Width, img.Height);

            //turn the Bitmap into a Graphics object
            Graphics gfx = Graphics.FromImage(bmp);

            //now we set the rotation point to the center of our image
            gfx.TranslateTransform((float)bmp.Width / 2, (float)bmp.Height / 2);

            //now rotate the image
            gfx.RotateTransform(rotationAngle);

            gfx.TranslateTransform(-(float)bmp.Width / 2, -(float)bmp.Height / 2);

            //set the InterpolationMode to HighQualityBicubic so to ensure a high
            //quality image once it is transformed to the specified size
            gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;

            //now draw our new image onto the graphics object
            gfx.DrawImage(img, new Point(0, 0));

            //dispose of our Graphics object
            gfx.Dispose();

            //return the image
            return bmp;
        }

        int time,
            time_prev,
            amp,
            amp_offset = 0,
            amp_prev = 220,
            volt_div = 1,
            end_scope = 200,
            amp_kalman,
            amp_prev_kalman;
        private void timer1_Tick(object sender, EventArgs e)
        {
            pictureBox1.Image = RotateImage(horison, data_y);
            pictureBox2.Image = RotateImage(horison, kalman_y);
            time++;
            time_prev = time - 1;

            amp = (data_y * volt_div) + amp_offset;
            chart1.Series["Series1"].Points.AddXY(time, amp);
            amp_kalman = (kalman_y * volt_div) + amp_offset;
            chart1.Series["Series2"].Points.AddXY(time, amp_kalman);

            amp_prev = amp;
            amp_prev_kalman = amp_kalman;

            if (time > end_scope)
            {
                chart1.Series["Series1"].Points.Clear();
                chart1.Series["Series2"].Points.Clear();
                time = 0;
            }
        }
    }
}

Sedangkan untuk pengaplikasian controler game-nya saya disain lebih sederhana dengan tampilan sebagai berikut.
vjoy2
berikut kode nya.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using vJoyInterfaceWrap;
namespace serial
{
    public partial class Form1 : Form
    {
        // Declaring one joystick (Device id 1) and a position structure.
        static public vJoy joystick;
        static public vJoy.JoystickState iReport;
        static public uint id = 1;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //—menset event handler untuk DataReceived event—
            serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(DataReceived);
            //—menampilkan nama serialport yang tersedia pada
            // komputer—
            string[] portNames = System.IO.Ports.SerialPort.GetPortNames();
            for (int i = 0; i <= portNames.Length - 1; i++)
            {
                cbbCOMPorts.Items.Add(portNames[i]);
            }
            btnDisconnect.Enabled = false;
            joystick = new vJoy();
            if (!joystick.AcquireVJD(id))
            {
                txtDataReceived.Text = "gagal";
            }
            else
            {
                txtDataReceived.Text = "berhasil";
                joystick.SetAxis(16384, id, HID_USAGES.HID_USAGE_X);   //min 16 center 16384 max 32767
                joystick.SetAxis(16384, id, HID_USAGES.HID_USAGE_Y);   //min 16 center 16384 max 32767
            }
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            //—menutup akses serialport apabila akses serialport terbuka—
            if (serialPort.IsOpen)
            {
                serialPort.Close();
            }
            try
            {
                //—mengatur beberapa parameter untuk koneksi serial
                // port—
                serialPort.PortName = cbbCOMPorts.Text;
                serialPort.BaudRate = 9600;
                serialPort.Parity = System.IO.Ports.Parity.None;
                serialPort.DataBits = 8;
                serialPort.StopBits = System.IO.Ports.StopBits.One;
                //—buka serial port—
                serialPort.Open();
                //—menampilkan status dari serial port dan
                // enable/disable -kan tombol—
                lblMessage.Text = cbbCOMPorts.Text + " connected.";
                btnConnect.Enabled = false;
                btnDisconnect.Enabled = true;
                timer2.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            try
            {
                //—tutup serial port—
                serialPort.Close();
                //—menampilkan status dari serial port dan
                // enable/disable -kan tombol—
                lblMessage.Text = serialPort.PortName +" disconnected.";
                btnConnect.Enabled = true;
                btnDisconnect.Enabled = false;
                timer2.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                //—menulis tipe data string pada serial port—
                serialPort.Write(txtDataToSend.Text + Environment.NewLine);
                //—menambahkan string yang telah dikirim pada TextBox control—
                txtDataReceived.AppendText(">" + txtDataToSend.Text +  Environment.NewLine);
                txtDataReceived.ScrollToCaret();
                //—bersihkanTextBox control—
                txtDataToSend.Text = string.Empty;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        string kata;
        string[] buff_kata = new string[8];
        //—Event handler untuk DataReceived event—
        private void DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                kata = serialPort.ReadLine();
                buff_kata = SplitWords(kata);
                if (kata != string.Empty)
                {
                    //txtDataReceived.Text = kata;
                    txtDataReceived.BeginInvoke(new myDelegate(updateTextBox));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        static string[] SplitWords(string s)
        {
            //
            // Split on all non-word characters.
            // ... Returns an array of all the words.
            //
            return Regex.Split(s, " ");
            // @      special verbatim string syntax
            // \W+    one or more non-word characters together
        }

        //—Delegate and subroutine untuk ditampilkan pada TextBox control—
        public delegate void myDelegate();

        public void updateTextBox()
        {
            //data_y = Convert.ToInt32(buff_kata[2]);
            //kalman_y = kalman_filter_ku((double)data_y);
            //txtDataReceived.Text = "ACC:"+data_y.ToString()+" Kalman:"+kalman_y.ToString();
            //txtDataReceived.Text = "x:"+buff_kata[1] + " y:"+buff_kata[2]+" ori"+kata;
        }
        double  Kk_x,
                Xk_topi_x,
                Pk_x,
                R_x = 0.1,
                Q_x = 0.0002,
                Xk_topi_prev_x = 0,
                Pk_prev_x = 1,
                Pk_update_x,
                Xk_topi_update_x;
        int kalman_filter_ku_x(double Zk_x)
        {
            //Time Update
            Xk_topi_update_x = Xk_topi_prev_x;
            Pk_update_x = Pk_prev_x + Q_x;
            //Measurement Update
            Kk_x = Pk_update_x / (Pk_update_x + R_x);
            Xk_topi_x = Xk_topi_update_x + (Kk_x * (Zk_x - Xk_topi_update_x));
            Pk_x = (1 - Kk_x) * Pk_update_x;
            Xk_topi_prev_x = Xk_topi_x;
            Pk_prev_x = Pk_x;
            return ((int)Xk_topi_x);
        }

        double  Kk_y,
                Xk_topi_y,
                Pk_y,
                R_y = 0.1,
                Q_y = 0.0002,
                Xk_topi_prev_y = 0,
                Pk_prev_y = 1,
                Pk_update_y,
                Xk_topi_update_y;
        int kalman_filter_ku_y(double Zk_y)
        {
            //Time Update
            Xk_topi_update_y = Xk_topi_prev_y;
            Pk_update_y = Pk_prev_y + Q_y;
            //Measurement Update
            Kk_y = Pk_update_y / (Pk_update_y + R_y);
            Xk_topi_y = Xk_topi_update_y + (Kk_y * (Zk_y - Xk_topi_update_y));
            Pk_y = (1 - Kk_y) * Pk_update_y;
            Xk_topi_prev_y = Xk_topi_y;
            Pk_prev_y = Pk_y;
            return ((int)Xk_topi_y);
        }

        int val_z_prev;
        private void timer2_Tick(object sender, EventArgs e)
        {
            int val_x,
                val_y,
                kalman_x,
                kalman_y,
                buff_val_x =0,
                buff_val_y =0,
                val_z =0;
            try
            {
                buff_val_y = Convert.ToInt32(buff_kata[1]);
                buff_val_x = Convert.ToInt32(buff_kata[2]);
                val_z = Convert.ToInt32(buff_kata[3]);
                //txtDataReceived.Text = buff_val_x.ToString() + " " + buff_val_y.ToString();
            }
            catch (Exception a)
            {

            }

            val_x = (buff_val_x * 410) + 16384;
            val_y = (buff_val_y * 410) + 16384;

            kalman_x = kalman_filter_ku_x((double)val_x);
            kalman_y = kalman_filter_ku_y((double)val_y);

            if      ((val_z_prev > 80) && (val_z < -30))//kotak
            {
                //txtDataReceived.AppendText("===============kotak"+Environment.NewLine);
                joystick.SetBtn(true, id, 1);
            }
            else if ((val_z_prev < -30) && (val_z > 80))//eek
            {
                //txtDataReceived.AppendText("++++++++++++++++eek" + Environment.NewLine);
                joystick.SetBtn(true, id, 2);
            }
            else
            {
                //txtDataReceived.AppendText("none" + Environment.NewLine);
                joystick.SetBtn(false, id, 1);
                joystick.SetBtn(false, id, 2);
            }

            joystick.SetAxis(kalman_x, id, HID_USAGES.HID_USAGE_X);   //min 16 center 16384 max 32767
            joystick.SetAxis(kalman_y, id, HID_USAGES.HID_USAGE_Y);   //min 16 center 16384 max 32767
            val_z_prev = val_z;
        }
    }
}

Jangan lupa untuk memasukan library vjoynya.

vjoy3
Berikut hasilnya.

Berikut file project yang bisa di download.

Accelerometer LIS302DL di STM32F4-Discovery

Compiler yang saya gunakan adalah Coocox IDE dengan library gcc-arm-none-eabi. Untuk mengakses sensor tersebut saya menggunakan beberapa file dari project demo bawaan STM32F4-Discovery yang di build di uVision Keil. Untuk itu, saya mengedit beberapa bagian karena arsitektur programming-nya sedikit berbeda dengan Coocox. Berikut file yang saya gunakan.

USART1_lib.h –> sudah di post sebelumnya
lis302dl_lib_ku.h
stm32f4_discovery_lis302dl.h –> file demo bawaan STM32F4-Discovery berbasis uVision keil
Sedangkan Repository yang dicentang adalah:
-C Library
-M4 CMSIS Core
-CMSIS Boot
-RCC
-GPIO
-EXTI
-SPI
-I2C
-DMA
-Flash
-TIM
-USART
-SYSCGF
Lengkapnya sebagai berikut.

lis302dl_lib_ku.h

 

#ifndef __LIS302DL_LIB_KU_H
#define __LIS302DL_LIB_KU_H

#include "stm32f4_discovery_lis302dl.h"
#include "stm32f4xx_flash.h"
/* Includes ------------------------------------------------------------------*/
#include <stdio.h>
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
typedef struct
{
  uint8_t acc_x;                         /* Power-down/Active Mode */
  uint8_t acc_y;                         /* Power-down/Active Mode */
  uint8_t acc_z;
}acc_data;
uint32_t LIS302DL_TIMEOUT_UserCallback(void);
void Fail_Handler(void);
void Accelerometer_MEMS_Init(void);
acc_data Accelerometer_MEMS(void);

#endif

 
lis302dl_lib_ku.c
 

#include "lis302dl_lib_ku.h"

#define MEMS_PASSCONDITION              15

/* MEMS Microphone SPI Interface */
#define SPI_SCK_PIN                   GPIO_Pin_10
#define SPI_SCK_GPIO_PORT             GPIOB
#define SPI_SCK_GPIO_CLK              RCC_AHB1Periph_GPIOB
#define SPI_SCK_SOURCE                GPIO_PinSource10
#define SPI_SCK_AF                    GPIO_AF_SPI2

#define SPI_MOSI_PIN                  GPIO_Pin_3
#define SPI_MOSI_GPIO_PORT            GPIOC
#define SPI_MOSI_GPIO_CLK             RCC_AHB1Periph_GPIOC
#define SPI_MOSI_SOURCE               GPIO_PinSource3
#define SPI_MOSI_AF                   GPIO_AF_SPI2

extern uint8_t Buffer[6];
#define TESTRESULT_ADDRESS         0x080FFFFC
#define ALLTEST_PASS               0x00000000
#define ALLTEST_FAIL               0x55555555
#define ABS(x)         (x < 0) ? (-x) : x
#define MAX(a,b)       (a < b) ? (b) : a

uint8_t Buffer[6];

void Delay(uint32_t nTime)
{
  nTime *= 8000;
  while(nTime != 0)
  {
	  nTime--;
  }
}
void Fail_Handler(void)
{
  FLASH_EraseSector(FLASH_Sector_11, VoltageRange_3);
  FLASH_ProgramWord(TESTRESULT_ADDRESS, ALLTEST_FAIL);

  while(1)
  {
    Delay(5);
  }
}

uint8_t DemoEnterCondition = 0x00;
uint32_t LIS302DL_TIMEOUT_UserCallback(void)
{
   if (DemoEnterCondition == 0x00)
  {Fail_Handler();
  }
  else
  {
    while (1)
    {
    }
  }
  return 0;
}

void Accelerometer_MEMS_Init(void)
{
	LIS302DL_InitTypeDef  LIS302DL_InitStruct;
	LIS302DL_FilterConfigTypeDef LIS302DL_FilterStruct;

	/* Set configuration of LIS302DL*/
	LIS302DL_InitStruct.Power_Mode = LIS302DL_LOWPOWERMODE_ACTIVE;
	LIS302DL_InitStruct.Output_DataRate = LIS302DL_DATARATE_100;
	LIS302DL_InitStruct.Axes_Enable = LIS302DL_X_ENABLE | LIS302DL_Y_ENABLE;
	LIS302DL_InitStruct.Full_Scale = LIS302DL_FULLSCALE_2_3;
	LIS302DL_InitStruct.Self_Test = LIS302DL_SELFTEST_NORMAL;
	LIS302DL_Init(&LIS302DL_InitStruct);

	/* Set configuration of Internal High Pass Filter of LIS302DL*/
	LIS302DL_FilterStruct.HighPassFilter_Data_Selection = LIS302DL_FILTEREDDATASELECTION_OUTPUTREGISTER;
	LIS302DL_FilterStruct.HighPassFilter_CutOff_Frequency = LIS302DL_HIGHPASSFILTER_LEVEL_1;
	LIS302DL_FilterStruct.HighPassFilter_Interrupt = LIS302DL_HIGHPASSFILTERINTERRUPT_1_2;
	LIS302DL_FilterConfig(&LIS302DL_FilterStruct);

	/* Required delay for the MEMS Accelerometre: Turn-on time = 3/Output data Rate
	                                                             = 3/100 = 30ms */
	Delay(80);
}

acc_data Accelerometer_MEMS(void)
{
  uint8_t temp;
  uint8_t xdata, ydata = 0;
  acc_data ukur_data;

  /* Read WHO_AM_I register */
  LIS302DL_Read(&temp, LIS302DL_WHO_AM_I_ADDR, 1);

  /* Check device identification register, this register should contains
  the device identifier that for LIS302DL is set to 0x3B */
  if (temp != 0x3B)
  {
    Fail_Handler();
  }


    LIS302DL_Read(Buffer, LIS302DL_OUT_X_ADDR, 6);

    ukur_data.acc_x = Buffer[0];
    ukur_data.acc_y = Buffer[2];
    ukur_data.acc_z = Buffer[4];
    return(ukur_data);
}

 
stm32f4_discovery_lis302dl.h
 

/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F4_DISCOVERY_LIS302DL_H
#define __STM32F4_DISCOVERY_LIS302DL_H

#ifdef __cplusplus
 extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_spi.h"
/** @addtogroup Utilities
  * @{
  */
  
/** @addtogroup STM32F4_DISCOVERY
  * @{
  */ 

/** @addtogroup STM32F4_DISCOVERY_LIS302DL
  * @{
  */
  

/** @defgroup STM32F4_DISCOVERY_LIS302DL_Exported_Types
  * @{
  */
   
/* LIS302DL struct */
typedef struct
{
  uint8_t Power_Mode;                         /* Power-down/Active Mode */
  uint8_t Output_DataRate;                    /* OUT data rate 100 Hz / 400 Hz */
  uint8_t Axes_Enable;                        /* Axes enable */
  uint8_t Full_Scale;                         /* Full scale */
  uint8_t Self_Test;                          /* Self test */
}LIS302DL_InitTypeDef;

/* LIS302DL High Pass Filter struct */
typedef struct
{
  uint8_t HighPassFilter_Data_Selection;      /* Internal filter bypassed or data from internal filter send to output register*/
  uint8_t HighPassFilter_CutOff_Frequency;    /* High pass filter cut-off frequency */
  uint8_t HighPassFilter_Interrupt;           /* High pass filter enabled for Freefall/WakeUp #1 or #2 */ 
}LIS302DL_FilterConfigTypeDef;  

/* LIS302DL Interrupt struct */
typedef struct
{
  uint8_t Latch_Request;                      /* Latch interrupt request into CLICK_SRC register*/
  uint8_t SingleClick_Axes;                   /* Single Click Axes Interrupts */
  uint8_t DoubleClick_Axes;                   /* Double Click Axes Interrupts */ 
}LIS302DL_InterruptConfigTypeDef;  

/**
  * @}
  */
  
/** @defgroup STM32F4_DISCOVERY_LIS302DL_Exported_Constants
  * @{
  */

/* Uncomment the following line to use the default LIS302DL_TIMEOUT_UserCallback() 
   function implemented in stm32f4_discovery_lis302dl.c file.
   LIS302DL_TIMEOUT_UserCallback() function is called whenever a timeout condition 
   occure during communication (waiting transmit data register empty flag(TXE)
   or waiting receive data register is not empty flag (RXNE)). */   
/* #define USE_DEFAULT_TIMEOUT_CALLBACK */

/* Maximum Timeout values for flags waiting loops. These timeouts are not based
   on accurate values, they just guarantee that the application will not remain
   stuck if the SPI communication is corrupted.
   You may modify these timeout values depending on CPU frequency and application
   conditions (interrupts routines ...). */   
#define LIS302DL_FLAG_TIMEOUT         ((uint32_t)0x1000)

/**
  * @brief  LIS302DL SPI Interface pins
  */
#define LIS302DL_SPI                       SPI1
#define LIS302DL_SPI_CLK                   RCC_APB2Periph_SPI1

#define LIS302DL_SPI_SCK_PIN               GPIO_Pin_5                  /* PA.05 */
#define LIS302DL_SPI_SCK_GPIO_PORT         GPIOA                       /* GPIOA */
#define LIS302DL_SPI_SCK_GPIO_CLK          RCC_AHB1Periph_GPIOA
#define LIS302DL_SPI_SCK_SOURCE            GPIO_PinSource5
#define LIS302DL_SPI_SCK_AF                GPIO_AF_SPI1

#define LIS302DL_SPI_MISO_PIN              GPIO_Pin_6                  /* PA.6 */
#define LIS302DL_SPI_MISO_GPIO_PORT        GPIOA                       /* GPIOA */
#define LIS302DL_SPI_MISO_GPIO_CLK         RCC_AHB1Periph_GPIOA
#define LIS302DL_SPI_MISO_SOURCE           GPIO_PinSource6
#define LIS302DL_SPI_MISO_AF               GPIO_AF_SPI1

#define LIS302DL_SPI_MOSI_PIN              GPIO_Pin_7                  /* PA.7 */
#define LIS302DL_SPI_MOSI_GPIO_PORT        GPIOA                       /* GPIOA */
#define LIS302DL_SPI_MOSI_GPIO_CLK         RCC_AHB1Periph_GPIOA
#define LIS302DL_SPI_MOSI_SOURCE           GPIO_PinSource7
#define LIS302DL_SPI_MOSI_AF               GPIO_AF_SPI1

#define LIS302DL_SPI_CS_PIN                GPIO_Pin_3                  /* PE.03 */
#define LIS302DL_SPI_CS_GPIO_PORT          GPIOE                       /* GPIOE */
#define LIS302DL_SPI_CS_GPIO_CLK           RCC_AHB1Periph_GPIOE

#define LIS302DL_SPI_INT1_PIN              GPIO_Pin_0                  /* PE.00 */
#define LIS302DL_SPI_INT1_GPIO_PORT        GPIOE                       /* GPIOE */
#define LIS302DL_SPI_INT1_GPIO_CLK         RCC_AHB1Periph_GPIOE
#define LIS302DL_SPI_INT1_EXTI_LINE        EXTI_Line0
#define LIS302DL_SPI_INT1_EXTI_PORT_SOURCE EXTI_PortSourceGPIOE
#define LIS302DL_SPI_INT1_EXTI_PIN_SOURCE  EXTI_PinSource0
#define LIS302DL_SPI_INT1_EXTI_IRQn        EXTI0_IRQn 

#define LIS302DL_SPI_INT2_PIN              GPIO_Pin_1                  /* PE.01 */
#define LIS302DL_SPI_INT2_GPIO_PORT        GPIOE                       /* GPIOE */
#define LIS302DL_SPI_INT2_GPIO_CLK         RCC_AHB1Periph_GPIOE
#define LIS302DL_SPI_INT2_EXTI_LINE        EXTI_Line1
#define LIS302DL_SPI_INT2_EXTI_PORT_SOURCE EXTI_PortSourceGPIOE
#define LIS302DL_SPI_INT2_EXTI_PIN_SOURCE  EXTI_PinSource1
#define LIS302DL_SPI_INT2_EXTI_IRQn        EXTI1_IRQn 


/******************************************************************************/
/*************************** START REGISTER MAPPING  **************************/
/******************************************************************************/

/*******************************************************************************
*  WHO_AM_I Register: Device Identification Register
*  Read only register
*  Default value: 0x3B
*******************************************************************************/
#define LIS302DL_WHO_AM_I_ADDR                  0x0F

/*******************************************************************************
*  CTRL_REG1 Register: Control Register 1
*  Read Write register
*  Default value: 0x07
*  7 DR: Data Rate selection.
*        0 - 100 Hz output data rate
*        1 - 400 Hz output data rate
*  6 PD: Power Down control.
*        0 - power down mode
*        1 - active mode
*  5 FS: Full Scale selection.
*        0 - Typical measurement range 2.3
*        1 - Typical measurement range 9.2
*  4:3 STP-STM Self Test Enable:
*              STP |  STM |   mode
*            ----------------------------
*               0  |  0   |   Normal mode
*               0  |  1   |   Self Test M
*               1  |  0   |   Self Test P
*  2 Zen: Z axis enable.
*         0 - Z axis disabled
*         1- Z axis enabled
*  1 Yen: Y axis enable.
*         0 - Y axis disabled
*         1- Y axis enabled
*  0 Xen: X axis enable.
*         0 - X axis disabled
*         1- X axis enabled
********************************************************************************/
#define LIS302DL_CTRL_REG1_ADDR                 0x20

/*******************************************************************************
*  CTRL_REG2 Regsiter: Control Register 2
*  Read Write register
*  Default value: 0x00
*  7 SIM: SPI Serial Interface Mode Selection. 
*         0 - 4 wire interface
*         1 - 3 wire interface
*  6 BOOT: Reboot memory content
*          0 - normal mode 
*          1 - reboot memory content
*  5 Reserved
*  4 FDS: Filtered data selection.
*         0 - internal filter bypassed
*         1 - data from internal filter sent to output register
*  3 HP FF_WU2: High pass filter enabled for FreeFall/WakeUp#2.
*               0 - filter bypassed
*               1 - filter enabled
*  2 HP FF_WU1: High pass filter enabled for FreeFall/WakeUp#1.
*               0 - filter bypassed
*               1 - filter enabled
*  1:0 HP coeff2-HP coeff1 High pass filter cut-off frequency (ft) configuration.
*                 ft= ODR[hz]/6*HP coeff
*            HP coeff2 | HP coeff1 |   HP coeff
*            -------------------------------------------
*                 0     |     0     |   8
*                 0     |     1     |   16
*                 1     |     0     |   32
*                 1     |     1     |   64
*            HP coeff |  ft[hz]   |  ft[hz]   |
*                     |ODR 100Hz | ODR 400Hz  |
*            --------------------------------------------
*              00     |    2      |     8     |
*              01     |    1      |     4     |
*              10     |    0.5    |     2     |
*              11     |    0.25   |     1     |
*******************************************************************************/
#define LIS302DL_CTRL_REG2_ADDR              0x21

/*******************************************************************************
*  CTRL_REG3 Register: Interrupt Control Register
*  Read Write register
*  Default value: 0x00
*  7 IHL active: Interrupt active high/low.
*                0 - active high
*                1 - active low
*  6 PP_OD: push-pull/open-drain.
*           0 - push-pull
*           1 - open-drain
*  5:3 I2_CFG2 - I2_CFG0 Data signal on INT2 pad control bits
*  2:0 I1_CFG2 - I1_CFG0 Data signal on INT1 pad control bits
*        I1(2)_CFG2  |  I1(2)_CFG1  |  I1(2)_CFG0  | INT1(2) Pad
*        ----------------------------------------------------------
*              0     |      0       |       0      | GND
*              0     |      0       |       1      | FreeFall/WakeUp#1
*              0     |      1       |       0      | FreeFall/WakeUp#2
*              0     |      1       |       1      | FreeFall/WakeUp#1 or FreeFall/WakeUp#2
*              1     |      0       |       0      | Data ready
*              1     |      1       |       1      | Click interrupt
*******************************************************************************/
#define LIS302DL_CTRL_REG3_ADDR              0x22

/*******************************************************************************
*  HP_FILTER_RESET Register: Dummy register. Reading at this address zeroes 
*  instantaneously the content of the internal high pass filter. If the high pass
*  filter is enabled all three axes are instantaneously set to 0g.
*  This allows to overcome the settling time of the high pass filter.
*  Read only register
*  Default value: Dummy
*******************************************************************************/
#define LIS302DL_HP_FILTER_RESET_REG_ADDR     0x23

/*******************************************************************************
*  STATUS_REG Register: Status Register
*  Default value: 0x00
*  7 ZYXOR: X, Y and Z axis data overrun.
*           0: no overrun has occurred
*           1: new data has overwritten the previous one before it was read
*  6 ZOR: Z axis data overrun.
*         0: no overrun has occurred 
*         1: new data for Z-axis has overwritten the previous one before it was read
*  5 yOR: y axis data overrun.
*         0: no overrun has occurred
*         1: new data for y-axis has overwritten the previous one before it was read
*  4 XOR: X axis data overrun.
*         0: no overrun has occurred
*         1: new data for X-axis has overwritten the previous one before it was read
*  3 ZYXDA: X, Y and Z axis new data available
*           0: a new set of data is not yet available
*           1: a new set of data is available
*  2 ZDA: Z axis new data available.
*         0: a new set of data is not yet available
*         1: a new data for Z axis is available
*  1 YDA: Y axis new data available
*         0: a new set of data is not yet available
*         1: a new data for Y axis is available
*  0 XDA: X axis new data available
*         0: a new set of data is not yet available
*         1: a new data for X axis is available
*******************************************************************************/
#define LIS302DL_STATUS_REG_ADDR             0x27

/*******************************************************************************
*  OUT_X Register: X-axis output Data
*  Read only register
*  Default value: output
*  7:0 XD7-XD0: X-axis output Data
*******************************************************************************/
#define LIS302DL_OUT_X_ADDR                  0x29

/*******************************************************************************
*  OUT_Y Register: Y-axis output Data
*  Read only register
*  Default value: output
*  7:0 YD7-YD0: Y-axis output Data
*******************************************************************************/
#define LIS302DL_OUT_Y_ADDR                  0x2B

/*******************************************************************************
*  OUT_Z Register: Z-axis output Data
*  Read only register
*  Default value: output
*  7:0 ZD7-ZD0: Z-axis output Data
*******************************************************************************/
#define LIS302DL_OUT_Z_ADDR                  0x2D

/*******************************************************************************
*  FF_WW_CFG_1 Register: Configuration register for Interrupt 1 source.
*  Read write register
*  Default value: 0x00
*  7 AOI: AND/OR combination of Interrupt events. 
*         0: OR combination of interrupt events
*         1: AND combination of interrupt events 
*  6 LIR: Latch/not latch interrupt request
*         0: interrupt request not latched
*         1: interrupt request latched
*  5 ZHIE: Enable interrupt generation on Z high event.
*          0: disable interrupt request
*          1: enable interrupt request on measured accel. value higher than preset threshold
*  4 ZLIE: Enable interrupt generation on Z low event.
*          0: disable interrupt request
*          1: enable interrupt request on measured accel. value lower than preset threshold
*  3 YHIE: Enable interrupt generation on Y high event.
*          0: disable interrupt request
*          1: enable interrupt request on measured accel. value higher than preset threshold
*  2 YLIE: Enable interrupt generation on Y low event. 
*          0: disable interrupt request
*          1: enable interrupt request on measured accel. value lower than preset threshold
*  1 XHIE: Enable interrupt generation on X high event.
*          0: disable interrupt request
*          1: enable interrupt request on measured accel. value higher than preset threshold
*  0 XLIE: Enable interrupt generation on X low event.
*          0: disable interrupt request
*          1: enable interrupt request on measured accel. value lower than preset threshold
*******************************************************************************/
#define LIS302DL_FF_WU_CFG1_REG_ADDR         0x30

/*******************************************************************************
*  FF_WU_SRC_1 Register: Interrupt 1 source register.
*  Reading at this address clears FF_WU_SRC_1 register and the FF, WU 1 interrupt
*  and allow the refreshment of data in the FF_WU_SRC_1 register if the latched option
*  was chosen.
*  Read only register
*  Default value: 0x00
*  7 Reserved
*  6 IA: Interrupt active.
*        0: no interrupt has been generated
*        1: one or more interrupts have been generated
*  5 ZH: Z high. 
*        0: no interrupt
*        1: ZH event has occurred 
*  4 ZL: Z low.
*        0: no interrupt
*        1: ZL event has occurred
*  3 YH: Y high.
*        0: no interrupt
*        1: YH event has occurred 
*  2 YL: Y low.
*        0: no interrupt
*        1: YL event has occurred
*  1 YH: X high.
*        0: no interrupt
*        1: XH event has occurred 
*  0 YL: X low.
*        0: no interrupt
*        1: XL event has occurred
*******************************************************************************/
#define LIS302DL_FF_WU_SRC1_REG_ADDR           0x31

/*******************************************************************************
*  FF_WU_THS_1 Register: Threshold register
*  Read Write register
*  Default value: 0x00
*  7 DCRM: Reset mode selection.
*          0 - counter resetted
*          1 - counter decremented
*  6 THS6-THS0: Free-fall/wake-up threshold value.
*******************************************************************************/
#define LIS302DL_FF_WU_THS1_REG_ADDR          0x32

/*******************************************************************************
*  FF_WU_DURATION_1 Register: duration Register
*  Read Write register
*  Default value: 0x00
*  7:0 D7-D0 Duration value. (Duration steps and maximum values depend on the ODR chosen)
 ******************************************************************************/
#define LIS302DL_FF_WU_DURATION1_REG_ADDR     0x33

/*******************************************************************************
*  FF_WW_CFG_2 Register: Configuration register for Interrupt 2 source.
*  Read write register
*  Default value: 0x00
*  7 AOI: AND/OR combination of Interrupt events. 
*         0: OR combination of interrupt events
*         1: AND combination of interrupt events 
*  6 LIR: Latch/not latch interrupt request
*         0: interrupt request not latched
*         1: interrupt request latched
*  5 ZHIE: Enable interrupt generation on Z high event.
*          0: disable interrupt request
*          1: enable interrupt request on measured accel. value higher than preset threshold
*  4 ZLIE: Enable interrupt generation on Z low event.
*          0: disable interrupt request
*          1: enable interrupt request on measured accel. value lower than preset threshold
*  3 YHIE: Enable interrupt generation on Y high event.
*          0: disable interrupt request
*          1: enable interrupt request on measured accel. value higher than preset threshold
*  2 YLIE: Enable interrupt generation on Y low event. 
*          0: disable interrupt request
*          1: enable interrupt request on measured accel. value lower than preset threshold
*  1 XHIE: Enable interrupt generation on X high event.
*          0: disable interrupt request
*          1: enable interrupt request on measured accel. value higher than preset threshold
*  0 XLIE: Enable interrupt generation on X low event.
*          0: disable interrupt request
*          1: enable interrupt request on measured accel. value lower than preset threshold
*******************************************************************************/
#define LIS302DL_FF_WU_CFG2_REG_ADDR         0x34

/*******************************************************************************
*  FF_WU_SRC_2 Register: Interrupt 2 source register.
*  Reading at this address clears FF_WU_SRC_2 register and the FF, WU 2 interrupt
*  and allow the refreshment of data in the FF_WU_SRC_2 register if the latched option
*  was chosen.
*  Read only register
*  Default value: 0x00
*  7 Reserved
*  6 IA: Interrupt active.
*        0: no interrupt has been generated
*        1: one or more interrupts have been generated
*  5 ZH: Z high. 
*        0: no interrupt
*        1: ZH event has occurred 
*  4 ZL: Z low.
*        0: no interrupt
*        1: ZL event has occurred
*  3 YH: Y high.
*        0: no interrupt
*        1: YH event has occurred 
*  2 YL: Y low.
*        0: no interrupt
*        1: YL event has occurred
*  1 YH: X high.
*        0: no interrupt
*        1: XH event has occurred 
*  0 YL: X low.
*        0: no interrupt
*        1: XL event has occurred
*******************************************************************************/
#define LIS302DL_FF_WU_SRC2_REG_ADDR           0x35

/*******************************************************************************
*  FF_WU_THS_2 Register: Threshold register
*  Read Write register
*  Default value: 0x00
*  7 DCRM: Reset mode selection.
*          0 - counter resetted
*          1 - counter decremented
*  6 THS6-THS0: Free-fall/wake-up threshold value.
*******************************************************************************/
#define LIS302DL_FF_WU_THS2_REG_ADDR          0x36

/*******************************************************************************
*  FF_WU_DURATION_2 Register: duration Register
*  Read Write register
*  Default value: 0x00
*  7:0 D7-D0 Duration value. (Duration steps and maximum values depend on the ODR chosen)
 ******************************************************************************/
#define LIS302DL_FF_WU_DURATION2_REG_ADDR     0x37

/******************************************************************************
*  CLICK_CFG Register: click Register
*  Read Write register
*  Default value: 0x00
*  7 Reserved
*  6 LIR: Latch Interrupt request.
*         0: interrupt request not latched
*         1: interrupt request latched
*  5 Double_Z: Enable interrupt generation on double click event on Z axis.
*              0: disable interrupt request
*              1: enable interrupt request
*  4 Single_Z: Enable interrupt generation on single click event on Z axis.
*              0: disable interrupt request
*              1: enable interrupt request
*  3 Double_Y: Enable interrupt generation on double click event on Y axis.
*              0: disable interrupt request
*              1: enable interrupt request
*  2 Single_Y: Enable interrupt generation on single click event on Y axis.
*              0: disable interrupt request
*              1: enable interrupt request
*  1 Double_X: Enable interrupt generation on double click event on X axis.
*              0: disable interrupt request
*              1: enable interrupt request
*  0 Single_y: Enable interrupt generation on single click event on X axis.
*              0: disable interrupt request
*              1: enable interrupt request
 ******************************************************************************/
#define LIS302DL_CLICK_CFG_REG_ADDR     0x38

/******************************************************************************
*  CLICK_SRC Register: click status Register
*  Read only register
*  Default value: 0x00
*  7 Reserved
*  6 IA: Interrupt active.
*        0: no interrupt has been generated
*        1: one or more interrupts have been generated
*  5 Double_Z: Double click on Z axis event.
*        0: no interrupt
*        1: Double Z event has occurred 
*  4 Single_Z: Z low.
*        0: no interrupt
*        1: Single Z event has occurred 
*  3 Double_Y: Y high.
*        0: no interrupt
*        1: Double Y event has occurred 
*  2 Single_Y: Y low.
*        0: no interrupt
*        1: Single Y event has occurred 
*  1 Double_X: X high.
*        0: no interrupt
*        1: Double X event has occurred 
*  0 Single_X: X low.
*        0: no interrupt
*        1: Single X event has occurred 
*******************************************************************************/
#define LIS302DL_CLICK_SRC_REG_ADDR        0x39

/*******************************************************************************
*  CLICK_THSY_X Register: Click threshold Y and X register
*  Read Write register
*  Default value: 0x00
*  7:4 THSy3-THSy0: Click threshold on Y axis, step 0.5g
*  3:0 THSx3-THSx0: Click threshold on X axis, step 0.5g
*******************************************************************************/
#define LIS302DL_CLICK_THSY_X_REG_ADDR        0x3B

/*******************************************************************************
*  CLICK_THSZ Register: Click threshold Z register
*  Read Write register
*  Default value: 0x00
*  7:4 Reserved
*  3:0 THSz3-THSz0: Click threshold on Z axis, step 0.5g
*******************************************************************************/
#define LIS302DL_CLICK_THSZ_REG_ADDR         0x3C

/*******************************************************************************
*  CLICK_TimeLimit Register: Time Limit register
*  Read Write register
*  Default value: 0x00
*  7:0 Dur7-Dur0: Time Limit value, step 0.5g
*******************************************************************************/
#define LIS302DL_CLICK_TIMELIMIT_REG_ADDR        0x3D

/*******************************************************************************
*  CLICK_Latency Register: Latency register
*  Read Write register
*  Default value: 0x00
*  7:0 Lat7-Lat0: Latency value, step 1msec
*******************************************************************************/
#define LIS302DL_CLICK_LATENCY_REG_ADDR        0x3E

/*******************************************************************************
*  CLICK_Window Register: Window register
*  Read Write register
*  Default value: 0x00
*  7:0 Win7-Win0: Window value, step 1msec
*******************************************************************************/
#define LIS302DL_CLICK_WINDOW_REG_ADDR        0x3F

/******************************************************************************/
/**************************** END REGISTER MAPPING  ***************************/
/******************************************************************************/

#define LIS302DL_SENSITIVITY_2_3G                         18  /* 18 mg/digit*/
#define LIS302DL_SENSITIVITY_9_2G                         72  /* 72 mg/digit*/

/** @defgroup Data_Rate_selection                 
  * @{
  */
#define LIS302DL_DATARATE_100                             ((uint8_t)0x00)
#define LIS302DL_DATARATE_400                             ((uint8_t)0x80)
/**
  * @}
  */
  
/** @defgroup Power_Mode_selection 
  * @{
  */
#define LIS302DL_LOWPOWERMODE_POWERDOWN                   ((uint8_t)0x00)
#define LIS302DL_LOWPOWERMODE_ACTIVE                      ((uint8_t)0x40)
/**
  * @}
  */
  
/** @defgroup Full_Scale_selection 
  * @{
  */
#define LIS302DL_FULLSCALE_2_3                            ((uint8_t)0x00)
#define LIS302DL_FULLSCALE_9_2                            ((uint8_t)0x20)
/**
  * @}
  */
  
/** @defgroup Self_Test_selection 
  * @{
  */
#define LIS302DL_SELFTEST_NORMAL                          ((uint8_t)0x00)
#define LIS302DL_SELFTEST_P                               ((uint8_t)0x10)
#define LIS302DL_SELFTEST_M                               ((uint8_t)0x08)
/**
  * @}
  */  

/** @defgroup Direction_XYZ_selection 
  * @{
  */
#define LIS302DL_X_ENABLE                                 ((uint8_t)0x01)
#define LIS302DL_Y_ENABLE                                 ((uint8_t)0x02)
#define LIS302DL_Z_ENABLE                                 ((uint8_t)0x04)
#define LIS302DL_XYZ_ENABLE                               ((uint8_t)0x07)
/**
  * @}
  */
 
 /** @defgroup SPI_Serial_Interface_Mode_selection 
  * @{
  */
#define LIS302DL_SERIALINTERFACE_4WIRE                    ((uint8_t)0x00)
#define LIS302DL_SERIALINTERFACE_3WIRE                    ((uint8_t)0x80)
/**
  * @}
  */ 

 /** @defgroup Boot_Mode_selection 
  * @{
  */
#define LIS302DL_BOOT_NORMALMODE                          ((uint8_t)0x00)
#define LIS302DL_BOOT_REBOOTMEMORY                        ((uint8_t)0x40)
/**
  * @}
  */   

 /** @defgroup Filtered_Data_Selection_Mode_selection 
  * @{
  */
#define LIS302DL_FILTEREDDATASELECTION_BYPASSED           ((uint8_t)0x00)
#define LIS302DL_FILTEREDDATASELECTION_OUTPUTREGISTER     ((uint8_t)0x20)
/**
  * @}
  */ 
  
 /** @defgroup High_Pass_Filter_Interrupt_selection 
  * @{
  */  
#define LIS302DL_HIGHPASSFILTERINTERRUPT_OFF              ((uint8_t)0x00)
#define LIS302DL_HIGHPASSFILTERINTERRUPT_1                ((uint8_t)0x04)
#define LIS302DL_HIGHPASSFILTERINTERRUPT_2                ((uint8_t)0x08)
#define LIS302DL_HIGHPASSFILTERINTERRUPT_1_2              ((uint8_t)0x0C)
/**
  * @}
  */ 
  
 /** @defgroup High_Pass_Filter_selection 
  * @{
  */
#define LIS302DL_HIGHPASSFILTER_LEVEL_0                   ((uint8_t)0x00)
#define LIS302DL_HIGHPASSFILTER_LEVEL_1                   ((uint8_t)0x01)
#define LIS302DL_HIGHPASSFILTER_LEVEL_2                   ((uint8_t)0x02)
#define LIS302DL_HIGHPASSFILTER_LEVEL_3                   ((uint8_t)0x03)
/**
  * @}
  */


/** @defgroup latch_Interrupt_Request_selection 
  * @{
  */
#define LIS302DL_INTERRUPTREQUEST_NOTLATCHED              ((uint8_t)0x00)
#define LIS302DL_INTERRUPTREQUEST_LATCHED                 ((uint8_t)0x40)
/**
  * @}
  */

/** @defgroup Click_Interrupt_XYZ_selection 
  * @{
  */
#define LIS302DL_CLICKINTERRUPT_XYZ_DISABLE               ((uint8_t)0x00)
#define LIS302DL_CLICKINTERRUPT_X_ENABLE                  ((uint8_t)0x01)
#define LIS302DL_CLICKINTERRUPT_Y_ENABLE                  ((uint8_t)0x04)
#define LIS302DL_CLICKINTERRUPT_Z_ENABLE                  ((uint8_t)0x10)
#define LIS302DL_CLICKINTERRUPT_XYZ_ENABLE                ((uint8_t)0x15)
/**
  * @}
  */

/** @defgroup Double_Click_Interrupt_XYZ_selection 
  * @{
  */
#define LIS302DL_DOUBLECLICKINTERRUPT_XYZ_DISABLE         ((uint8_t)0x00)
#define LIS302DL_DOUBLECLICKINTERRUPT_X_ENABLE            ((uint8_t)0x02)
#define LIS302DL_DOUBLECLICKINTERRUPT_Y_ENABLE            ((uint8_t)0x08)
#define LIS302DL_DOUBLECLICKINTERRUPT_Z_ENABLE            ((uint8_t)0x20)
#define LIS302DL_DOUBLECLICKINTERRUPT_XYZ_ENABLE          ((uint8_t)0x2A)
/**
  * @}
  */
/**
  * @}
  */ 
  
/** @defgroup STM32F4_DISCOVERY_LIS302DL_Exported_Macros
  * @{
  */
#define LIS302DL_CS_LOW()       GPIO_ResetBits(LIS302DL_SPI_CS_GPIO_PORT, LIS302DL_SPI_CS_PIN)
#define LIS302DL_CS_HIGH()      GPIO_SetBits(LIS302DL_SPI_CS_GPIO_PORT, LIS302DL_SPI_CS_PIN)
/**
  * @}
  */ 

/** @defgroup STM32F4_DISCOVERY_LIS302DL_Exported_Functions
  * @{
  */ 
void LIS302DL_Init(LIS302DL_InitTypeDef *LIS302DL_InitStruct);
void LIS302DL_InterruptConfig(LIS302DL_InterruptConfigTypeDef *LIS302DL_InterruptConfigStruct);
void LIS302DL_FilterConfig(LIS302DL_FilterConfigTypeDef *LIS302DL_FilterConfigStruct);
void LIS302DL_LowpowerCmd(uint8_t LowPowerMode);
void LIS302DL_FullScaleCmd(uint8_t FS_value);
void LIS302DL_DataRateCmd(uint8_t DataRateValue);
void LIS302DL_RebootCmd(void);
void LIS302DL_ReadACC(int32_t* out);
void LIS302DL_Write(uint8_t* pBuffer, uint8_t WriteAddr, uint16_t NumByteToWrite);
void LIS302DL_Read(uint8_t* pBuffer, uint8_t ReadAddr, uint16_t NumByteToRead);

/* USER Callbacks: This is function for which prototype only is declared in
   MEMS accelerometre driver and that should be implemented into user applicaiton. */  
/* LIS302DL_TIMEOUT_UserCallback() function is called whenever a timeout condition 
   occure during communication (waiting transmit data register empty flag(TXE)
   or waiting receive data register is not empty flag (RXNE)).
   You can use the default timeout callback implementation by uncommenting the 
   define USE_DEFAULT_TIMEOUT_CALLBACK in stm32f4_discovery_lis302dl.h file.
   Typically the user implementation of this callback should reset MEMS peripheral
   and re-initialize communication or in worst case reset all the application. */
uint32_t LIS302DL_TIMEOUT_UserCallback(void);

#ifdef __cplusplus
}
#endif

#endif /* __STM32F4_DISCOVERY_LIS302DL_H */

 
stm32f4_discovery_lis302dl.c
 

/* Includes ------------------------------------------------------------------*/
#include "stm32f4_discovery_lis302dl.h"

/** @addtogroup Utilities
  * @{
  */ 

/** @addtogroup STM32F4_DISCOVERY
  * @{
  */ 

/** @addtogroup STM32F4_DISCOVERY_LIS302DL
  * @{
  */


/** @defgroup STM32F4_DISCOVERY_LIS302DL_Private_TypesDefinitions
  * @{
  */

/**
  * @}
  */

/** @defgroup STM32F4_DISCOVERY_LIS302DL_Private_Defines
  * @{
  */
__IO uint32_t  LIS302DLTimeout = LIS302DL_FLAG_TIMEOUT;   

/* Read/Write command */
#define READWRITE_CMD              ((uint8_t)0x80) 
/* Multiple byte read/write command */ 
#define MULTIPLEBYTE_CMD           ((uint8_t)0x40)
/* Dummy Byte Send by the SPI Master device in order to generate the Clock to the Slave device */
#define DUMMY_BYTE                 ((uint8_t)0x00)

/**
  * @}
  */

/** @defgroup STM32F4_DISCOVERY_LIS302DL_Private_Macros
  * @{
  */

/**
  * @}
  */ 
  
/** @defgroup STM32F4_DISCOVERY_LIS302DL_Private_Variables
  * @{
  */ 

/**
  * @}
  */

/** @defgroup STM32F4_DISCOVERY_LIS302DL_Private_FunctionPrototypes
  * @{
  */
static uint8_t LIS302DL_SendByte(uint8_t byte);
static void LIS302DL_LowLevel_Init(void);
/**
  * @}
  */

/** @defgroup STM32F4_DISCOVERY_LIS302DL_Private_Functions
  * @{
  */

//uint32_t LIS302DL_TIMEOUT_UserCallback(void)
//{
  /* Block communication and all processes */
//  while (1)
//  {
//  }
//}
/**
  * @brief  Set LIS302DL Initialization.
  * @param  LIS302DL_Config_Struct: pointer to a LIS302DL_Config_TypeDef structure 
  *         that contains the configuration setting for the LIS302DL.
  * @retval None
  */
void LIS302DL_Init(LIS302DL_InitTypeDef *LIS302DL_InitStruct)
{
  uint8_t ctrl = 0x00;
  
  /* Configure the low level interface ---------------------------------------*/
  LIS302DL_LowLevel_Init();
  
  /* Configure MEMS: data rate, power mode, full scale, self test and axes */
  ctrl = (uint8_t) (LIS302DL_InitStruct->Output_DataRate | LIS302DL_InitStruct->Power_Mode | \
                    LIS302DL_InitStruct->Full_Scale | LIS302DL_InitStruct->Self_Test | \
                    LIS302DL_InitStruct->Axes_Enable);
  
  /* Write value to MEMS CTRL_REG1 regsister */
  LIS302DL_Write(&ctrl, LIS302DL_CTRL_REG1_ADDR, 1);
}

/**
  * @brief  Set LIS302DL Internal High Pass Filter configuration.
  * @param  LIS302DL_Filter_ConfigTypeDef: pointer to a LIS302DL_FilterConfig_TypeDef 
  *         structure that contains the configuration setting for the LIS302DL Filter.
  * @retval None
  */
void LIS302DL_FilterConfig(LIS302DL_FilterConfigTypeDef *LIS302DL_FilterConfigStruct)
{
  uint8_t ctrl = 0x00;
  
  /* Read CTRL_REG2 register */
  LIS302DL_Read(&ctrl, LIS302DL_CTRL_REG2_ADDR, 1);
  
  /* Clear high pass filter cut-off level, interrupt and data selection bits*/
  ctrl &= (uint8_t)~(LIS302DL_FILTEREDDATASELECTION_OUTPUTREGISTER | \
                     LIS302DL_HIGHPASSFILTER_LEVEL_3 | \
                     LIS302DL_HIGHPASSFILTERINTERRUPT_1_2);
  /* Configure MEMS high pass filter cut-off level, interrupt and data selection bits */                     
  ctrl |= (uint8_t)(LIS302DL_FilterConfigStruct->HighPassFilter_Data_Selection | \
                    LIS302DL_FilterConfigStruct->HighPassFilter_CutOff_Frequency | \
                    LIS302DL_FilterConfigStruct->HighPassFilter_Interrupt);
  
  /* Write value to MEMS CTRL_REG2 register */
  LIS302DL_Write(&ctrl, LIS302DL_CTRL_REG2_ADDR, 1);
}

/**
  * @brief Set LIS302DL Interrupt configuration
  * @param  LIS302DL_InterruptConfig_TypeDef: pointer to a LIS302DL_InterruptConfig_TypeDef 
  *         structure that contains the configuration setting for the LIS302DL Interrupt.
  * @retval None
  */
void LIS302DL_InterruptConfig(LIS302DL_InterruptConfigTypeDef *LIS302DL_IntConfigStruct)
{
  uint8_t ctrl = 0x00;
  
  /* Read CLICK_CFG register */
  LIS302DL_Read(&ctrl, LIS302DL_CLICK_CFG_REG_ADDR, 1);
  
  /* Configure latch Interrupt request, click interrupts and double click interrupts */                   
  ctrl = (uint8_t)(LIS302DL_IntConfigStruct->Latch_Request| \
                   LIS302DL_IntConfigStruct->SingleClick_Axes | \
                   LIS302DL_IntConfigStruct->DoubleClick_Axes);
  
  /* Write value to MEMS CLICK_CFG register */
  LIS302DL_Write(&ctrl, LIS302DL_CLICK_CFG_REG_ADDR, 1);
}

/**
  * @brief  Change the lowpower mode for LIS302DL
  * @param  LowPowerMode: new state for the lowpower mode.
  *   This parameter can be one of the following values:
  *     @arg LIS302DL_LOWPOWERMODE_POWERDOWN: Power down mode
  *     @arg LIS302DL_LOWPOWERMODE_ACTIVE: Active mode  
  * @retval None
  */
void LIS302DL_LowpowerCmd(uint8_t LowPowerMode)
{
  uint8_t tmpreg;
  
  /* Read CTRL_REG1 register */
  LIS302DL_Read(&tmpreg, LIS302DL_CTRL_REG1_ADDR, 1);
  
  /* Set new low power mode configuration */
  tmpreg &= (uint8_t)~LIS302DL_LOWPOWERMODE_ACTIVE;
  tmpreg |= LowPowerMode;
  
  /* Write value to MEMS CTRL_REG1 regsister */
  LIS302DL_Write(&tmpreg, LIS302DL_CTRL_REG1_ADDR, 1);
}

/**
  * @brief  Data Rate command 
  * @param  DataRateValue: Data rate value
  *   This parameter can be one of the following values:
  *     @arg LIS302DL_DATARATE_100: 100 Hz output data rate 
  *     @arg LIS302DL_DATARATE_400: 400 Hz output data rate    
  * @retval None
  */
void LIS302DL_DataRateCmd(uint8_t DataRateValue)
{
  uint8_t tmpreg;
  
  /* Read CTRL_REG1 register */
  LIS302DL_Read(&tmpreg, LIS302DL_CTRL_REG1_ADDR, 1);
  
  /* Set new Data rate configuration */
  tmpreg &= (uint8_t)~LIS302DL_DATARATE_400;
  tmpreg |= DataRateValue;
  
  /* Write value to MEMS CTRL_REG1 regsister */
  LIS302DL_Write(&tmpreg, LIS302DL_CTRL_REG1_ADDR, 1);
}

/**
  * @brief  Change the Full Scale of LIS302DL
  * @param  FS_value: new full scale value. 
  *   This parameter can be one of the following values:
  *     @arg LIS302DL_FULLSCALE_2_3: +-2.3g
  *     @arg LIS302DL_FULLSCALE_9_2: +-9.2g   
  * @retval None
  */
void LIS302DL_FullScaleCmd(uint8_t FS_value)
{
  uint8_t tmpreg;
  
  /* Read CTRL_REG1 register */
  LIS302DL_Read(&tmpreg, LIS302DL_CTRL_REG1_ADDR, 1);
  
  /* Set new full scale configuration */
  tmpreg &= (uint8_t)~LIS302DL_FULLSCALE_9_2;
  tmpreg |= FS_value;
  
  /* Write value to MEMS CTRL_REG1 regsister */
  LIS302DL_Write(&tmpreg, LIS302DL_CTRL_REG1_ADDR, 1);
}

/**
  * @brief  Reboot memory content of LIS302DL
  * @param  None
  * @retval None
  */
void LIS302DL_RebootCmd(void)
{
  uint8_t tmpreg;
  /* Read CTRL_REG2 register */
  LIS302DL_Read(&tmpreg, LIS302DL_CTRL_REG2_ADDR, 1);
  
  /* Enable or Disable the reboot memory */
  tmpreg |= LIS302DL_BOOT_REBOOTMEMORY;
  
  /* Write value to MEMS CTRL_REG2 regsister */
  LIS302DL_Write(&tmpreg, LIS302DL_CTRL_REG2_ADDR, 1);
}

/**
  * @brief  Writes one byte to the LIS302DL.
  * @param  pBuffer : pointer to the buffer  containing the data to be written to the LIS302DL.
  * @param  WriteAddr : LIS302DL's internal address to write to.
  * @param  NumByteToWrite: Number of bytes to write.
  * @retval None
  */
void LIS302DL_Write(uint8_t* pBuffer, uint8_t WriteAddr, uint16_t NumByteToWrite)
{
  /* Configure the MS bit: 
       - When 0, the address will remain unchanged in multiple read/write commands.
       - When 1, the address will be auto incremented in multiple read/write commands.
  */
  if(NumByteToWrite > 0x01)
  {
    WriteAddr |= (uint8_t)MULTIPLEBYTE_CMD;
  }
  /* Set chip select Low at the start of the transmission */
  LIS302DL_CS_LOW();
  
  /* Send the Address of the indexed register */
  LIS302DL_SendByte(WriteAddr);
  /* Send the data that will be written into the device (MSB First) */
  while(NumByteToWrite >= 0x01)
  {
    LIS302DL_SendByte(*pBuffer);
    NumByteToWrite--;
    pBuffer++;
  }
  
  /* Set chip select High at the end of the transmission */ 
  LIS302DL_CS_HIGH();
}

/**
  * @brief  Reads a block of data from the LIS302DL.
  * @param  pBuffer : pointer to the buffer that receives the data read from the LIS302DL.
  * @param  ReadAddr : LIS302DL's internal address to read from.
  * @param  NumByteToRead : number of bytes to read from the LIS302DL.
  * @retval None
  */
void LIS302DL_Read(uint8_t* pBuffer, uint8_t ReadAddr, uint16_t NumByteToRead)
{  
  if(NumByteToRead > 0x01)
  {
    ReadAddr |= (uint8_t)(READWRITE_CMD | MULTIPLEBYTE_CMD);
  }
  else
  {
    ReadAddr |= (uint8_t)READWRITE_CMD;
  }
  /* Set chip select Low at the start of the transmission */
  LIS302DL_CS_LOW();
  
  /* Send the Address of the indexed register */
  LIS302DL_SendByte(ReadAddr);
  
  /* Receive the data that will be read from the device (MSB First) */
  while(NumByteToRead > 0x00)
  {
    /* Send dummy byte (0x00) to generate the SPI clock to LIS302DL (Slave device) */
    *pBuffer = LIS302DL_SendByte(DUMMY_BYTE);
    NumByteToRead--;
    pBuffer++;
  }
  
  /* Set chip select High at the end of the transmission */ 
  LIS302DL_CS_HIGH();
}

/**
  * @brief  Read LIS302DL output register, and calculate the acceleration 
  *         ACC[mg]=SENSITIVITY* (out_h*256+out_l)/16 (12 bit rappresentation)
  * @param  s16 buffer to store data
  * @retval None
  */
void LIS302DL_ReadACC(int32_t* out)
{
  uint8_t buffer[6];
  uint8_t crtl, i = 0x00;
   
  LIS302DL_Read(&crtl, LIS302DL_CTRL_REG1_ADDR, 1);  
  LIS302DL_Read(buffer, LIS302DL_OUT_X_ADDR, 6);
  
  switch(crtl & 0x20) 
    {
    /* FS bit = 0 ==> Sensitivity typical value = 18milligals/digit*/ 
    case 0x00:
      for(i=0; i<0x03; i++)
      {
        *out =(int32_t)(LIS302DL_SENSITIVITY_2_3G *  (int8_t)buffer[2*i]);
        out++;
      }
      break;
    /* FS bit = 1 ==> Sensitivity typical value = 72milligals/digit*/ 
    case 0x20:
      for(i=0; i<0x03; i++)
      {
        *out =(int32_t)(LIS302DL_SENSITIVITY_9_2G * (int8_t)buffer[2*i]);
        out++;
      }         
      break;
    default:
      break;
    }
 }

/**
  * @brief  Initializes the low level interface used to drive the LIS302DL
  * @param  None
  * @retval None
  */
static void LIS302DL_LowLevel_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;
  SPI_InitTypeDef  SPI_InitStructure;

  /* Enable the SPI periph */
  RCC_APB2PeriphClockCmd(LIS302DL_SPI_CLK, ENABLE);

  /* Enable SCK, MOSI and MISO GPIO clocks */
  RCC_AHB1PeriphClockCmd(LIS302DL_SPI_SCK_GPIO_CLK | LIS302DL_SPI_MISO_GPIO_CLK | LIS302DL_SPI_MOSI_GPIO_CLK, ENABLE);

  /* Enable CS  GPIO clock */
  RCC_AHB1PeriphClockCmd(LIS302DL_SPI_CS_GPIO_CLK, ENABLE);
  
  /* Enable INT1 GPIO clock */
  RCC_AHB1PeriphClockCmd(LIS302DL_SPI_INT1_GPIO_CLK, ENABLE);
  
  /* Enable INT2 GPIO clock */
  RCC_AHB1PeriphClockCmd(LIS302DL_SPI_INT2_GPIO_CLK, ENABLE);

  GPIO_PinAFConfig(LIS302DL_SPI_SCK_GPIO_PORT, LIS302DL_SPI_SCK_SOURCE, LIS302DL_SPI_SCK_AF);
  GPIO_PinAFConfig(LIS302DL_SPI_MISO_GPIO_PORT, LIS302DL_SPI_MISO_SOURCE, LIS302DL_SPI_MISO_AF);
  GPIO_PinAFConfig(LIS302DL_SPI_MOSI_GPIO_PORT, LIS302DL_SPI_MOSI_SOURCE, LIS302DL_SPI_MOSI_AF);

  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_DOWN;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

  /* SPI SCK pin configuration */
  GPIO_InitStructure.GPIO_Pin = LIS302DL_SPI_SCK_PIN;
  GPIO_Init(LIS302DL_SPI_SCK_GPIO_PORT, &GPIO_InitStructure);

  /* SPI  MOSI pin configuration */
  GPIO_InitStructure.GPIO_Pin =  LIS302DL_SPI_MOSI_PIN;
  GPIO_Init(LIS302DL_SPI_MOSI_GPIO_PORT, &GPIO_InitStructure);

  /* SPI MISO pin configuration */
  GPIO_InitStructure.GPIO_Pin = LIS302DL_SPI_MISO_PIN;
  GPIO_Init(LIS302DL_SPI_MISO_GPIO_PORT, &GPIO_InitStructure);

  /* SPI configuration -------------------------------------------------------*/
  SPI_I2S_DeInit(LIS302DL_SPI);
  SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
  SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
  SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low;
  SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge;
  SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
  SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;
  SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
  SPI_InitStructure.SPI_CRCPolynomial = 7;
  SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
  SPI_Init(LIS302DL_SPI, &SPI_InitStructure);

  /* Enable SPI1  */
  SPI_Cmd(LIS302DL_SPI, ENABLE);

  /* Configure GPIO PIN for Lis Chip select */
  GPIO_InitStructure.GPIO_Pin = LIS302DL_SPI_CS_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(LIS302DL_SPI_CS_GPIO_PORT, &GPIO_InitStructure);

  /* Deselect : Chip Select high */
  GPIO_SetBits(LIS302DL_SPI_CS_GPIO_PORT, LIS302DL_SPI_CS_PIN);
  
  /* Configure GPIO PINs to detect Interrupts */
  GPIO_InitStructure.GPIO_Pin = LIS302DL_SPI_INT1_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_NOPULL;
  GPIO_Init(LIS302DL_SPI_INT1_GPIO_PORT, &GPIO_InitStructure);
  
  GPIO_InitStructure.GPIO_Pin = LIS302DL_SPI_INT2_PIN;
  GPIO_Init(LIS302DL_SPI_INT2_GPIO_PORT, &GPIO_InitStructure);
}

/**
  * @brief  Sends a Byte through the SPI interface and return the Byte received 
  *         from the SPI bus.
  * @param  Byte : Byte send.
  * @retval The received byte value
  */
static uint8_t LIS302DL_SendByte(uint8_t byte)
{
  /* Loop while DR register in not emplty */
  LIS302DLTimeout = LIS302DL_FLAG_TIMEOUT;
  while (SPI_I2S_GetFlagStatus(LIS302DL_SPI, SPI_I2S_FLAG_TXE) == RESET)
  {
    if((LIS302DLTimeout--) == 0) return LIS302DL_TIMEOUT_UserCallback();
  }
  
  /* Send a Byte through the SPI peripheral */
  SPI_I2S_SendData(LIS302DL_SPI, byte);
  
  /* Wait to receive a Byte */
  LIS302DLTimeout = LIS302DL_FLAG_TIMEOUT;
  while (SPI_I2S_GetFlagStatus(LIS302DL_SPI, SPI_I2S_FLAG_RXNE) == RESET)
  {
    if((LIS302DLTimeout--) == 0) return LIS302DL_TIMEOUT_UserCallback();
  }
  
  /* Return the Byte read from the SPI bus */
  return (uint8_t)SPI_I2S_ReceiveData(LIS302DL_SPI);
}

#ifdef USE_DEFAULT_TIMEOUT_CALLBACK
/**
  * @brief  Basic management of the timeout situation.
  * @param  None.
  * @retval None.
  */
#endif /* USE_DEFAULT_TIMEOUT_CALLBACK */

 
main.c
 

#include "USART1_lib.h"
#include "lis302dl_lib_ku.h"
#include <stdio.h>

char kata2[16];
int8_t data_x,data_y,data_z;
int main(void)
{
  acc_data siap_kirim_acc;
  usart_inisialisasi();
  Accelerometer_MEMS_Init();
  while(1)
  {
	  siap_kirim_acc = Accelerometer_MEMS();
	  data_x = siap_kirim_acc.acc_x;
	  data_y = siap_kirim_acc.acc_y;
	  data_z = siap_kirim_acc.acc_z;
	  sprintf(kata2,"head %d %d %d \n\r",data_x,data_y,data_z);
	  usart_puts(kata2);
	  Delay(50);
  }
  return 0;
}

 

USART Tx Pada STM32F4 Discovery

Saya menggunakan compiler Coocox IDE dengan libarary GNU Tools ARM Embedded. Lengkapnya kunjungi website berikut

coocox.org/CoIDE/Compiler_Settings.html

Pada artikel ini saya menggunakan USART1. Pertama, buatlah new project dengan settingan menggunakan chip STM32F407VG yang merupakan mikrokontroler pada STM32F4 Discovery.Setelah itu, pada setting repository yang muncul kemudian, beri tanda centang pada bagian:
C Library
M4 CMSIS Core
CMSIS BOOT
RCC
GPIO
USART

Setelah itu tambahkan file USART1_lib.c dan USART1_lib.h ke file project dengan cara klik kanan pada project window tepat pada nama project kita. Lalu klik Add Files dan pilih filenya. Ini program utamanya.

#include "stm32f4xx.h"
#include "USART1_lib.h"

char kata[16];
int main(void)
{
	usart_inisialisasi();
    while(1)
    {
    	sprintf(kata,"oke data %2.2f \n\r",353.34);
    	usart_puts(kata);
    }
}

Kode di atas akan mengirim data “oke data 353.34 [enter]“.

Berikut lampiran untuk USART1_lib.c

#include "USART1_lib.h"

void RCC_Configuration(void)
{
	/* enable peripheral clock for USART2 */
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);

	/* GPIOA clock enable */
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
}

void GPIO_Configuration(void){

	/* Configure USART Tx as alternate function  */
	  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
	  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;

	  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
	  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
	  GPIO_Init(GPIOB, &GPIO_InitStructure);

	/* Connect PXx to USARTx_Tx*/
	  GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_USART1);
}

void USART1_Configuration(void)
{

		USART_InitStructure.USART_BaudRate = 9600;
		USART_InitStructure.USART_WordLength = USART_WordLength_8b;
		USART_InitStructure.USART_StopBits = USART_StopBits_1;
		USART_InitStructure.USART_Parity = USART_Parity_No;
		USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
		USART_InitStructure.USART_Mode = USART_Mode_Tx;

		USART_Init(USART1, &USART_InitStructure);
		USART_Cmd(USART1, ENABLE); // enable USART2
}

void USART1_PutChar(char c)
{
	uint8_t ch;
	ch = c;
	/* Place your implementation of fputc here */
	/* e.g. write a character to the USART */
	USART_SendData(USART1, (uint8_t) ch);

	/* Loop until the end of transmission */
	while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET)
	{}
}

void PORTA_Configuration(void)
{
		/* GPIOD Periph clock enable */
		RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);

		/* Configure PD12, PD13, PD14 and PD15 in output pushpull mode */
		GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1| GPIO_Pin_2| GPIO_Pin_3| GPIO_Pin_4| GPIO_Pin_5| GPIO_Pin_6| GPIO_Pin_7;
		GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
		GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
		GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
		GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
		GPIO_Init(GPIOA, &GPIO_InitStructure);
}

void usart_puts(char *data)
{
	int i=0;
	int n = strlen(data);
	for(i=0;i<n;i++)
	{
		USART1_PutChar(data[i]);
	}
}

void usart_inisialisasi()
{
	setvbuf( stdout, 0, _IONBF, 0 );
	RCC_Configuration();
	PORTA_Configuration();
	GPIO_Configuration();
	USART1_Configuration();
}

Berikut lampiran untuk USART1_lib.h

#ifndef __USART1_LIB_H
#define __USART1_LIB_H

#include "stm32f4xx.h"
#include "stm32f4xx_usart.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"
#include <stdio.h>
#include <string.h>

#ifdef __GNUC__
  /* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
     set to 'Yes') calls __io_putchar() */
  #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
  #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */

USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;

void RCC_Configuration(void);
void GPIO_Configuration(void);
void USART1_Configuration(void);
void USART1_PutChar(char c);
void PORTA_Configuration(void);
void usart_puts(char *data);
void usart_inisialisasi();
#endif

Jika terdapat error, bisa diperhatikan beberapa pertanyaan berikut yang saya temukan di forum-forum internet dan solusinya
______________________________________________________________________________________________________
1.Problem Send Floating Point with “PRINTF”
coocox.org/forum/topic.php?id=856
Chloe

1 year ago

Hi hendriyawan achmad,

1. The Retarget printf component was once simpilified, and support for float variables was removed, so DO NOT select the component.

2. Besides changing
(void *)&pulStack[STACK_SIZE-1],
to
(void (*)(void))((unsigned long)pulStack + sizeof(pulStack)),

you need to modify function _write( ) in syscalls.c to

int _write( int file, char *ptr, int len )
{
int txCount;

(void)file;

for ( txCount = 0; txCount < len; txCount++)
{
UART_SendData(UART0, ptr[txCount]); //Don't forget to include "lpc11xx_uart.h"
}

return len;
}
——————————————————————–

3. In main.c, before using printf( ) function, add

/* Set unbuffered mode for stdout (newlib) */
setvbuf( stdout, 0, _IONBF, 0 ); //Don't forget to include
——————————————————————–

Sorry for my late reply. Hope this can do some help.

Best regards
______________________________________________________________________________________________________
2.STM32F4 Discovery HARDFPU – CooCox CoIDE printf to USART
mutty.brb.cz/node/282
This is a little howto for setting up of STM32F4 development board with a functional printf which would send it’s conntaints even if it’s float variables into established USART with the processor flag set at HARDFPU in IDE developed by CooCox version 1.6.0

Nice header, heh ?! :)
I searched the internet! That’s what I’ve done.

Firstly set up HSE_VALUE

> in system_stm32f4xx.c change the external oscilator frequency
HSE_VALUE=8000000
> discovery board has not default pre-stock frequency (which is 25MHz) it has 8MHz

Secondaly this manual how to set up printf in FPU SOFT by jfragos

Abstract: “

Coocox – Project – config

> choose “Base C library”, do not use the “Redirect”
> later we are gonna change the “m” library to FPUHARD compatibile so leave it like that

file changes:

> in startup/startup_stm32f4xx.c) change
(void *)&pulStack[STACK_SIZE-1],
> to
(void (*)(void))((unsigned long)pulStack + sizeof(pulStack)),

> bigger stack size = in startup/startup_stm32f4xx.c
#define STACK_SIZE 0×00002000 /*! (8KBs will do)
> asd

> include wherever it’s needed – main.c, syscall.c etc.
#include
> in main before printf cast
/* Set unbuffered mode for stdout (newlib) */
setvbuf( stdout, 0, _IONBF, 0 );

> in syscalls/syscalls.c some USART sending function
> i.e. sending to USART2

int _write(int file, char *ptr, int len)
{
/* Place your implementation of fputc here */
/* e.g. write a character to the USART */
int counter;

counter = len;
for (; counter > 0; counter–)
{
if (*ptr == 0) break;
USART_SendData(USART2, (uint16_t) (*ptr));
/* Loop until the end of transmission */
while (USART_GetFlagStatus(USART2, USART_FLAG_TC) == RESET);
ptr++;
}
return len;
}

” End of abstract.

Now it should handle doubles, but only for FPU Soft.. just continue.. you must change moooore :)

Now for the FPU HARD tutorial from blog.stm32f4.eu/

Abstract: “

CooCox – projects – configuration – link

> link appropriet library.. if you inserted “m” earlier, erase it first, than add this Hard FPU
GCCARM\arm-none-eabi\lib\armv7e-m\fpu\libm.a (Hard FPU)
GCCARM\arm-none-eabi\lib\armv7e-m\softft\libm.a (Soft FPU)
> for me the name of the library is acctually libgcc.a

Next items I am not sure about if they need to be done.. I’ve done them and it works

> in startup_stm32f4xx.c un-comment
extern void SystemInit(void); /*! in startup_stm32f4xx.c add SystemInit(); call before main(); function call in
void DefaultResetHandler()
{
..
SystemInit();
main();
}

” End of Abstract
and I think next item is optional cause it practicly does the same thing as HSE_Value

> in startup_stm32f4xx.c
#define PLL_M 25

Initialize your USART from eliaselectronics.com
add printf to main :)

#include
..
int main(void){
setvbuf( stdout, 0, _IONBF, 0 );
int a = 100;
float f = 10.123;
double d = 10.123;
printf(“I will not do anything, until I am done! %d %2.2f %2.2f”, a, f, d);
while(1) {}
return(42);
}

Compile download and run..

Now you can add a debug breakpoint into USAR_IRQHandler to the part when the text is read, add an expression of the string into which you read the data, and start debug mode.

Or you just can connect the usart into some display or whatever :).

I hope this will work for you, and I stumble if it helps :)

If some-one nows how to get the printf print into the CooCox debug console, please leave a comment with a link or explanation..

(: please please please :)

Have a better day!
______________________________________________________________________________________________________
3.STM32F4 compile problem on example project (IOtoggle)
[cc] collect2: ld returned 1 exit status

BUILD FAILED
Total time: 1 second
answers.launchpad.net/gcc-arm-embedded/+question/209568
Terry Guo (terry.guo) said on 2012-09-26: #1

Hi Amin,

The assert_param is a macro defined in file stm32f4xx_conf.h. This file will be included only when another macro USE_STDPERIPH_DRIVER is explicitly defined. You can find this in file stm32f4xx.h. The usage of assert_param is explained in where it is defined.

To solve your problem, please open “Project” -> “Configuration” and add USE_STDPERIPH_DRIVER into table “Defined symbols”. Depends on how you are going to use assert_param, you may need further work.
______________________________________________________________________________________________________

Kalman Filter

Pada bilgin.esme.org/BitsBytes/KalmanFilterforDummies.aspx kalman filter mulai dijelaskan dari bentuk yg sederhana agar lebih mudah dimengerti terutama untuk belajar awal.kalman1

kalman2

Pada page tersebut dijelaskan dengan sederhana tentang kalman filter. Pada bagian akhir ada sebuah contoh perhitungan untuk menghitung sebuah model sederhana 1 dimensi kalman filter.

kalman3

kalman4

kalman5

Dari contoh tersebut saya mencoba mensimulasikan konsepnya pada MATLAB dengan input random. Berikut program yang saya buat.

clc
clear all
close all
xk = 0;
Pk = 1;
R = 0.1;
buff_xk = [];
buff_zk = [];
pure_zk = [];
for k=1:100

    zk = (rand-rand);

    Pk = Pk + 0.000001;

    Kk = Pk/(Pk+R);
    xk = xk + (Kk*(zk - xk));
    Pk = (1-Kk)*Pk;

    buff_xk = [buff_xk xk];
    pure_zk = [pure_zk 1];
    buff_zk = [buff_zk zk];
end
figure;
plot(buff_xk,'r');
hold on;
plot(buff_zk,'g');
plot(pure_zk,'b');

Hasil plot

kalman6

Hasilnya cukup lumayan.

Berikut saya coba simulasikan untuk aplikasi mikrokontroler.

kalman7

Dan Berikut kodenya.

/*****************************************************
Chip type           : ATmega32
Program type        : Application
Clock frequency     : 16.000000 MHz
Memory model        : Small
External SRAM size  : 0
Data Stack size     : 512
*****************************************************/

#include

#define RXB8 1
#define TXB8 0
#define UPE 2
#define OVR 3
#define FE 4
#define UDRE 5
#define RXC 7

#define FRAMING_ERROR (1<<FE)
#define PARITY_ERROR (1<<UPE)
#define DATA_OVERRUN (1<<OVR)
#define DATA_REGISTER_EMPTY (1<<UDRE)
#define RX_COMPLETE (1<<RXC)

// USART Receiver buffer
#define RX_BUFFER_SIZE 8
char rx_buffer[RX_BUFFER_SIZE];

#if RX_BUFFER_SIZE<256
unsigned char rx_wr_index,rx_rd_index,rx_counter;
#else
unsigned int rx_wr_index,rx_rd_index,rx_counter;
#endif

// This flag is set on USART Receiver buffer overflow
bit rx_buffer_overflow;

// USART Receiver interrupt service routine
interrupt [USART_RXC] void usart_rx_isr(void)
{
char status,data;
status=UCSRA;
data=UDR;
if ((status & (FRAMING_ERROR | PARITY_ERROR | DATA_OVERRUN))==0)
   {
   rx_buffer[rx_wr_index]=data;
   if (++rx_wr_index == RX_BUFFER_SIZE) rx_wr_index=0;
   if (++rx_counter == RX_BUFFER_SIZE)
      {
      rx_counter=0;
      rx_buffer_overflow=1;
      };
   };
}

#ifndef _DEBUG_TERMINAL_IO_
// Get a character from the USART Receiver buffer
#define _ALTERNATE_GETCHAR_
#pragma used+
char getchar(void)
{
char data;
while (rx_counter==0);
data=rx_buffer[rx_rd_index];
if (++rx_rd_index == RX_BUFFER_SIZE) rx_rd_index=0;
#asm("cli")
--rx_counter;
#asm("sei")
return data;
}
#pragma used-
#endif

// USART Transmitter buffer
#define TX_BUFFER_SIZE 8
char tx_buffer[TX_BUFFER_SIZE];

#if TX_BUFFER_SIZE<256
unsigned char tx_wr_index,tx_rd_index,tx_counter;
#else
unsigned int tx_wr_index,tx_rd_index,tx_counter;
#endif

// USART Transmitter interrupt service routine
interrupt [USART_TXC] void usart_tx_isr(void)
{
if (tx_counter)
   {
   --tx_counter;
   UDR=tx_buffer[tx_rd_index];
   if (++tx_rd_index == TX_BUFFER_SIZE) tx_rd_index=0;
   };
}

#ifndef _DEBUG_TERMINAL_IO_
// Write a character to the USART Transmitter buffer
#define _ALTERNATE_PUTCHAR_
#pragma used+
void putchar(char c)
{
while (tx_counter == TX_BUFFER_SIZE);
#asm("cli")
if (tx_counter || ((UCSRA & DATA_REGISTER_EMPTY)==0))
   {
   tx_buffer[tx_wr_index]=c;
   if (++tx_wr_index == TX_BUFFER_SIZE) tx_wr_index=0;
   ++tx_counter;
   }
else
   UDR=c;
#asm("sei")
}
#pragma used-
#endif

// Standard Input/Output functions
#include

// Declare your global variables here
float sensor[10] = {    0.39,
        	        0.50,
        	        0.48,
        	        0.29,
        	        0.25,
        	        0.32,
        	        0.34,
        	        0.48,
        	        0.41,
        	        0.45};
float   Kk,
        Xk_topi,
        Pk,
        R = 0.1,
        Q = 0,
        Xk_topi_prev    = 0,
        Pk_prev         = 1,
        Pk_update,
        Xk_topi_update;
float kalman_filter_ku(float Zk)
{
//Time Update
        Xk_topi_update = Xk_topi_prev;
        Pk_update = Pk_prev + Q;
//Measurement Update
        Kk = Pk_update/(Pk_update + R);
        Xk_topi = Xk_topi_update + (Kk*(Zk-Xk_topi_update));
        Pk = (1-Kk)*Pk_update;
        Xk_topi_prev = Xk_topi;
        Pk_prev = Pk;
        return(Xk_topi);
}

void main(void)
{
// Declare your local variables here
int i;
// Input/Output Ports initialization
// Port A initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTA=0x00;
DDRA=0x00;

// Port B initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTB=0x00;
DDRB=0x00;

// Port C initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTC=0x00;
DDRC=0x00;

// Port D initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTD=0x00;
DDRD=0x00;

// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: Timer 0 Stopped
// Mode: Normal top=FFh
// OC0 output: Disconnected
TCCR0=0x00;
TCNT0=0x00;
OCR0=0x00;

// Timer/Counter 1 initialization
// Clock source: System Clock
// Clock value: Timer 1 Stopped
// Mode: Normal top=FFFFh
// OC1A output: Discon.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
// Timer 1 Overflow Interrupt: Off
// Input Capture Interrupt: Off
// Compare A Match Interrupt: Off
// Compare B Match Interrupt: Off
TCCR1A=0x00;
TCCR1B=0x00;
TCNT1H=0x00;
TCNT1L=0x00;
ICR1H=0x00;
ICR1L=0x00;
OCR1AH=0x00;
OCR1AL=0x00;
OCR1BH=0x00;
OCR1BL=0x00;

// Timer/Counter 2 initialization
// Clock source: System Clock
// Clock value: Timer 2 Stopped
// Mode: Normal top=FFh
// OC2 output: Disconnected
ASSR=0x00;
TCCR2=0x00;
TCNT2=0x00;
OCR2=0x00;

// External Interrupt(s) initialization
// INT0: Off
// INT1: Off
// INT2: Off
MCUCR=0x00;
MCUCSR=0x00;

// Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=0x00;

// USART initialization
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART Receiver: On
// USART Transmitter: On
// USART Mode: Asynchronous
// USART Baud rate: 9600
UCSRA=0x00;
UCSRB=0xD8;
UCSRC=0x86;
UBRRH=0x00;
UBRRL=0x67;

// Analog Comparator initialization
// Analog Comparator: Off
// Analog Comparator Input Capture by Timer/Counter 1: Off
ACSR=0x80;
SFIOR=0x00;

// Global enable interrupts
#asm("sei")

for(i=0;i<10;i++)
{
        printf("Sensor:%f\n\r",sensor[i]);
        printf("Kalman:%f\n\r\n\r",kalman_filter_ku(sensor[i]));
}

while (1)
      {
      // Place your code here

      };
}

Secara proses dan hasil, memang kurang memuaskan karena disain program dan sensor masih jauh dari kriteria sebuah aplikasi kalman filter.
Iseng-iseng saya coba aplikasikan kodingan di atas untuk memfilter data accelerometer pada modul STM32F4 Discovery dengan cara mengirim data hasil pengukuran via serial port kemudian ditampilkan dengan aplikasi yang dibuat dengan Visual C# Express 2010.

kalman-kalman-an_3
Berikut hasilnya.

kalman-kalman-an_1
Dan saya coba aplikasikan untuk mengontrol sebuah game di PC dengan bantuan library Vjoystick.

kalman-kalman-an_2

Berikut videonya.

++++++++++++++++++++++++++++++++++++

DAFTAR PUSTAKA

cs.cornell.edu/Courses/cs4758/2012sp/materials/MI63slides.pdf

bilgin.esme.org/BitsBytes/KalmanFilterforDummies.aspx

Follow

Get every new post delivered to your Inbox.