Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.

o0Higgy0o's Content

There have been 3 items by o0Higgy0o (Search limited from 29-March 23)


By content type

See this member's

Sort by                Order  

#57628 MMA8452Q triple axis accelerometer code example

Posted by o0Higgy0o on 18 April 2014 - 11:35 AM in Netduino Plus 2 (and Netduino Plus 1)

Hi,

 

I have recently been playing around with a MMA8452Q triple axis accelerometer from proto-pic. My basic premise was to set up 2 accelerometers and get them to send an interrupt when the acceleration was greater than 1g in any axis. I wanted to set them side-by-side and measure the time difference between the interrupts on an oscilloscope for a common 1g impulse shock, in my case I hoped it was very small. I managed to set the devices up on a 800Hz sample rate, 1g transient shock threshold and no debounce counter. Unfortunately for my application the time difference between the interrupts from both devices for the same impulse shock was too long (up to 1.5ms) so I need to rethink my original idea. Attached is my code as an example start for anyone else wishing to setup the accelerometers. Bare in mind my code is quick and dirty and worked for me but hopefully helpful. I used a Netduino Plus 2 on framework 4.3

 

For reference to understand the MMA8452Q useful Freescale info can be found:

 

Thank you to Stefan Thoolen for the netmftoolbox. I used the MultiI2C class and extended it slightly to help reading and writing to individual registers. I used individual toolbox cs files rather than referencing the whole toolbox hence the inclusion of Tools.cs and MultiI2C.cs .

 

Enjoy,

 

o0Higgy0o

Attached Files




#52984 Xively

Posted by o0Higgy0o on 28 September 2013 - 01:12 PM in Netduino Plus 2 (and Netduino Plus 1)

Hi,

 

I posted my code for sending temperature data to Xively. Hope it helps

 

http://forums.netdui...data-to-xively/




#50465 Sending data to Xively

Posted by o0Higgy0o on 13 June 2013 - 03:35 PM in Netduino Plus 2 (and Netduino Plus 1)

Hi,

 

Now that cosm has become Xively I decided to change my temperature senser feed over to xively rather than have it as a legacy cosm feed. I had some initial issues getting the PUT request right to send my temperature data for logging, but finally got it working. So to help anyone wanting to change to xively you will need to firstly set up a new feed and get a new ID and ApiKey. To send the data the DNS lookup is:

IPHostEntry entry = Dns.GetHostEntry("api.xively.com");

or to hard code the IP address: 

IPAddress remote_IP = IPAddress.Parse("216.52.233.120");

Host is api.xively.com

 

All the rest is as it was for cosm.

 

Here is my temperature sensing and basic socket sending code.  I used socket sending as I wanted to understand the basics of sending the put request. I have copied other peoples code in parts which has been very helpful and appreciated.

using Microsoft.SPOT;using Microsoft.SPOT.Hardware;using SecretLabs.NETMF.Hardware.Netduino;using System;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;namespace XivelyTemperature{    public class Program    {        const string ApiKey = "Your Key;        const string FeedId = "Your Feed Id";        const string UserAgent = "Xively Netduino Plus 2 Example"; // user agent is the project name        const string CRLF = "rn";        const double VoltsPerDegree = 0.01;        const double OffsetVolts = 0.5;        const double MaxVoltage = 3.3;        const uint MaxAdcValue = 4096;        // wait 10 mins between samples        const int SamplingPeriod = 60000;        const int ConnectionTimeout = 1000;        // if you don't want to use DNS (and reduce your sketch size)        // use the numeric IP instead of the name for the server:        static IPAddress remote_IP = IPAddress.Parse("216.52.233.120");    // numeric IP for api.xively.com        static OutputPort ledPort = new OutputPort(Pins.ONBOARD_LED, true);        static AnalogInput tempInPort = new AnalogInput(Cpu.AnalogChannel.ANALOG_0);        static Timer watchdog = null;        static TimerCallback timerDelegate = new TimerCallback(TimesUp);        const int WatchdogTime = 10000;        static Socket serversocket = null;        public static void Main()        {            IPEndPoint remoteEndPoint = new IPEndPoint(remote_IP, 80);            // use this if you want to use DNS lookup to get IP Address rather than hard code it            //IPHostEntry entry = Dns.GetHostEntry("api.xively.com");            //IPAddress address = entry.AddressList[0];            //IPEndPoint remoteEndPoint = new IPEndPoint(address, 80);            int rawValue;            double temperature;            string temp;            while (true)            {                try                {                    WaitUntilNextPeriod(SamplingPeriod);                    ledPort.Write(true);                    // start watchdog timer for SendData                    watchdog = new Timer(timerDelegate, null, WatchdogTime, Timeout.Infinite);                    Debug.Print("time: " + DateTime.Now);                    //Debug.Print("memory available: " + Debug.GC(true));                    rawValue = tempInPort.ReadRaw();                    Debug.Print("Raw value: " + rawValue.ToString());                    temperature = GetTempFromRaw(rawValue);                    temp = "Temperature, " + temperature.ToString("f");                    Debug.Print(temp);                    SendData(remoteEndPoint, temp);                    ledPort.Write(false);                }                catch (Exception ex)                {                    Debug.Print(ex.Message + " " + ex.StackTrace);                }                finally                {                    // Stop the timer                    watchdog = null;                    // garbage collect                    Debug.GC(true);                }            }        }        /// <summary>        /// send data to xively        /// </summary>        /// <param name="remoteEndPoint">endpoint to send data to</param>        /// <param name="temperature">string parameter to send</param>        private static void SendData(IPEndPoint remoteEndPoint, string temperature)        {            serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            serversocket.Connect(remoteEndPoint);            // calculate the length of the sensor reading in bytes:            int ContentLength = temperature.Length;            string WholePacket = string.Empty;            // send the HTTP PUT request:            WholePacket += "PUT /v2/feeds/" + FeedId.ToString() + ".csv HTTP/1.1rn";            WholePacket += "Host: api.xively.com" + CRLF;            WholePacket += "X-ApiKey: " + ApiKey + CRLF;            WholePacket += "User-Agent: " + UserAgent + CRLF;            WholePacket += "Content-Length: " + ContentLength.ToString() + CRLF;            // last pieces of the HTTP PUT request:            WholePacket += "Content-Type: text/csv" + CRLF;            WholePacket += "Connection: close" + CRLF;            WholePacket += CRLF;            // here's the actual content of the PUT request:            WholePacket += temperature + CRLF;            byte[] buffer = Encoding.UTF8.GetBytes(WholePacket);            serversocket.Send(buffer);            bool poll = serversocket.Poll(1000000, SelectMode.SelectRead);            if (serversocket.Available > 0)            {                buffer = new byte[serversocket.Available];                serversocket.Receive(buffer);                string resp = new string(Encoding.UTF8.GetChars(buffer));                Debug.Print(resp);            }            serversocket.Close();        }        /// <summary>        /// convert the raw ADC value to real temperature        /// </summary>        /// <param name="rawValue">int ADC value</param>        /// <returns>double real temperature</returns>        private static double GetTempFromRaw(int rawValue)        {            double voltsValue = (rawValue * MaxVoltage) / MaxAdcValue;            return (voltsValue - OffsetVolts) / VoltsPerDegree;        }        /// <summary>        /// sleep to next sample time        /// </summary>        /// <param name="samplingPeriod">time to sleep for</param>        private static void WaitUntilNextPeriod(int samplingPeriod)        {            long now = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;            var offset = (int)(now % samplingPeriod);            int delay = samplingPeriod - offset;            Debug.Print("sleep for " + delay + " msrn");            Thread.Sleep(delay);        }        /// <summary>        /// watchdog event to run when it kicks in        /// </summary>        /// <param name="state">object passed to method</param>        private static void TimesUp(object state)        {            Debug.Print("Watchdog kicked in");            PowerState.RebootDevice(true);        }    }}

cheers





home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.