|
使用3轴加速度传感器lis3dsh读取加速度数据,转换成倾角程序
单片机使用MSP430FR5969软I2C
单片机程序
- /*******************************************************************************
- * Copyright (C), 2017, XiaCheDan Tech. Co., Ltd.
- * FileName: main.c
- * Author: littleshrimp
- * Version : 1.0
- * Date: 2017-06-25 13:55
- * Description:
- * Function List: //
- * 1. -------
- * History:
- * <author> <time> <version > <desc>
- * littleshrimp 2017-06-25 13:55 build this moudle
- ******************************************************************************/
- /*
- MSP430FR5969
- -----------------
- | P2.0/UCA0TXD|----> PC
- | |
- | |
- | P2.1/UCA0RXD|<---- PC
- | |
- SCL --o--|P3.5 |
- | |
- SDA --o--|P3.6 |
- */
- /*******************************************************************************
- * * INCLUDES
- * */
- #include "msp430.h"
- #include <stdio.h>
- #include <math.h>
- #include <stdint.h>
- #include "uart.h"
- #include "soft_i2c.h"
- #include "timer.h"
- /*******************************************************************************
- * * MACROS
- * */
- /*******************************************************************************
- * * CONSTANTS
- * */
- #define BASE64 0
- #define STRING 1
- /*******************************************************************************
- * * TYPEDEFS
- * */
- /*******************************************************************************
- * * GLOBAL VARIABLES
- * */
- /*******************************************************************************
- * * EXTERNAL VARIABLES
- * */
- /*******************************************************************************
- * * EXTERNAL FUNCTIONS
- * */
- /*******************************************************************************
- * * LOCAL VARIABLES
- * */
-
- uint8_t data[3];
- uint16_t temp_code;
- float temperature;
- uint8_t crc;
- /*******************************************************************************
- * * PROFILE CALLBACKS
- * */
- /*******************************************************************************
- * * LOCAL FUNCTIONS
- * */
- /*******************************************************************************
- * * PUBLIC FUNCTIONS
- * */
-
-
- #define LIS3DSH_SLAVE_ADDR (0x1E << 1)//7bit
- #define LIS3DSH_WHO_I_AM 0x0F
- #define LIS3DSH_OUT_T 0x0C
- #define LIS3DSH_STATUS 0x27
- #define LIS3DSH_CTRL_REG4 0x20
- #define LIS3DSH_CTRL_REG3 0x23
- #define LIS3DSH_CTRL_REG5 0x24
- #define LIS3DSH_CTRL_REG6 0x25
- uint8_t buf[10];
- void lis3dsh_init(void)
- {
- uint8_t data;
- i2c_init();//初始化I2C
- i2c_read_n_byte(LIS3DSH_SLAVE_ADDR,LIS3DSH_WHO_I_AM,&buf[0],1);
- // data = 0x17;//0001:3.125Hz 0:continuous update 111:x,y,z enable
- data = 0x97;//1001:1600Hz 0:continuous update 111:x,y,z enable
- i2c_write_n_byte(LIS3DSH_SLAVE_ADDR,LIS3DSH_CTRL_REG4,&data,1);
- i2c_read_n_byte(LIS3DSH_SLAVE_ADDR,LIS3DSH_OUT_T,&buf[1],1);
- i2c_read_n_byte(LIS3DSH_SLAVE_ADDR,LIS3DSH_STATUS,&buf[2],7);
- }
- void dco_init(void)
- {
- // Configure one FRAM waitstate as required by the device datasheet for MCLK
- // operation beyond 8MHz _before_ configuring the clock system.
- FRCTL0 = FRCTLPW | NWAITS_1;
- // Clock System Setup
- CSCTL0_H = CSKEY >> 8; // Unlock CS registers
- CSCTL1 = DCORSEL | DCOFSEL_4; // Set DCO to 16MHz
- CSCTL2 = SELA__VLOCLK | SELS__DCOCLK | SELM__DCOCLK; // Set SMCLK = MCLK = DCO,
- // ACLK = VLOCLK
- CSCTL3 = DIVA__1 | DIVS__1 | DIVM__1; // Set all dividers
- CSCTL0_H = 0; // Lock CS registers
- }
- int main( void )
- {
- uint32_t i = 0;
- float x = 0,y = 0,z = 0;
- float ax,ay,az;
- uint8_t status;
- char inBuf[64];//base64缓存
- char outBuf[64];//base64缓存
- WDTCTL = WDTPW + WDTHOLD;//停止看门狗
- PM5CTL0 &= ~LOCKLPM5;//这个是一定要加的,不然GPIO不能使用
- dco_init();
- lis3dsh_init();
- uart_init();
- while(1)
- {
-
- i2c_read_n_byte(LIS3DSH_SLAVE_ADDR,LIS3DSH_STATUS,&buf[2],7);
- #if (BASE64 == 1) //base 64输出
- base64_encode((const uint8_t *)(&buf[2]),outBuf,7); //做BASE64转换
- uart_tx_string(outBuf);//输出到PC
- uart_tx_string("\r\n");//换行
- #elif (STRING == 1) //字符串输出 status = buf[2];//status
- ax = (buf[3] + (buf[4] << 8)) * 0.06 + 2;
- ay = (buf[5] + (buf[6] << 8)) * 0.06 + 2;
- az = (buf[7] + (buf[8] << 8)) * 0.06 + 2;
-
- x = atan((float)ax/(float)sqrt(ay*ay+az*az)) * 180.00 / 3.1415926;
- y = atan((float)ay/(float)sqrt(ax*ax+az*az)) * 180.00 / 3.1415926;
- z = atan((float)az/(float)sqrt(ax*ax+ay*ay)) * 180.00 / 3.1415926;
-
- if (z < 0)
- {
- x= 180-x;
- y= 180-y;
- }
-
- sprintf(outBuf,"angle:\tx=%.2f\ty=%.2f\tz=%.2f\r\n",x,y,z);
- // sprintf(outBuf,"%d",i++);
- uart_tx_string(outBuf);//输出到PC
- uart_tx_string("\r\n");//换行
- sleep(650);
- #else //二进制输出
- outBuf[0] = 0x55;
- outBuf[1] = buf[4];
- outBuf[2] = buf[3];
- outBuf[3] = buf[6];
- outBuf[4] = buf[5];
- outBuf[5] = buf[8];
- outBuf[6] = buf[7];
- uart_tx_bytes(outBuf,7);//输出到PC
- #endif
- }
- }
复制代码
上位机演示
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Drawing.Drawing2D;
- using System.IO.Ports;
- using System.Threading;
- namespace 倾角演示
- {
- public partial class Form1 : Form
- {
- Bitmap bmp = new Bitmap(Image.FromFile("img.png"));
- SerialPort serialPort = new SerialPort();//串口
- public Form1()
- {
- InitializeComponent();
- UpdateSerialPorts();
- }
- void UpdateSerialPorts()
- {
- String[] ports = System.IO.Ports.SerialPort.GetPortNames();//获得全部串口
- if (ports.Length == 0) return;//如果串口数量为0退出
- comboBox1.Items.Clear();//清除原有comboBox中的数据后重新添加
- comboBox1.Items.AddRange(ports);//添加串口
- comboBox1.Text = ports[ports.Length - 1];//设置显示最后一个串口
- }
- /// <summary>
- /// 以逆时针为方向对图像进行旋转
- /// </summary>
- /// <param name="b">位图流</param>
- /// <param name="angle">旋转角度[0,360](前台给的)</param>
- /// <returns></returns>
- public Bitmap Rotate(Bitmap b, int angle)
- {
- angle = angle % 360;
- //弧度转换
- double radian = angle * Math.PI / 180.0;
- double cos = Math.Cos(radian);
- double sin = Math.Sin(radian);
- //原图的宽和高
- int w = b.Width;
- int h = b.Height;
- int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
- int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
- //目标位图
- Bitmap dsImage = new Bitmap(W, H);
- Graphics g = Graphics.FromImage(dsImage);
- //计算偏移量
- Point Offset = new Point((W - w) / 2, (H - h) / 2);
- //构造图像显示区域:让图像的中心与窗口的中心点一致
- Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);
- Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
- g.TranslateTransform(center.X, center.Y);
- g.RotateTransform(360 - angle);
- //恢复图像在水平和垂直方向的平移
- g.TranslateTransform(-center.X, -center.Y);
- g.DrawImage(b, rect);
- //重至绘图的所有变换
- g.ResetTransform();
- g.Save();
- g.Dispose();
- return dsImage;
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- pictureBox1.Image = bmp;
- }
- int i = 0;
- private void button1_Click(object sender, EventArgs e)
- {
- serialPort.PortName = comboBox1.Text;//串口名为当前comboBox的本
- serialPort.BaudRate = 115200;//速率
- serialPort.DataBits = 8;//停止位
- serialPort.Parity = System.IO.Ports.Parity.None;
- serialPort.StopBits = System.IO.Ports.StopBits.One;
- serialPort.Handshake = System.IO.Ports.Handshake.None;
- // serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort_DataReceived);
- serialPort.Open();//打开串口
- timer1.Enabled = true;
- }
- private void comboBox1_DropDown(object sender, EventArgs e)
- {
- UpdateSerialPorts();
- }
- public void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
- {
- }
- private void Form1_FormClosing(object sender, FormClosingEventArgs e)
- {
- Application.Exit();//退出
- System.Environment.Exit(0);//退出时关闭所有线程
- }
- private void timer1_Tick(object sender, EventArgs e)
- {
- float x = 0, y = 0, z = 0;
- try
- {
- if (serialPort.BytesToRead < 10) return;
- string str = serialPort.ReadLine();
- string[] s = str.Split('\t');
- if (s.Length >= 4)
- {
- s[1] = s[1].Replace("x=", "");
- s[2] = s[2].Replace("y=", "");
- s[3] = s[3].Replace("z=", "");
- s[3] = s[3].Replace("\r", "");
- s[3] = s[3].Replace("\n", "");
- x = float.Parse(s[1]);
- y = float.Parse(s[2]);
- z = float.Parse(s[3]);
- pictureBox1.BeginInvoke((ThreadStart)delegate
- {
- pictureBox1.Image = Rotate(bmp, (int)y);
- pictureBox1.Refresh();
- });
- }
- }
- catch (Exception ex)
- {
- }
- }
- }
- }
复制代码
|
|