Categories

Arduino and MMA8653 accelerometer example

The NXP® MMA8653FC 10-bit accelerometer has industry leading performance in a small DFN package. Packed with embedded functions that include:

Flexible user-programmable options and two configurable interrupt pins
Overall power savings through inertial wake-up interrupt signals that monitor events and remain in a low-power mode during periods of inactivity

Features

Low-profile 2 x 2 x 1.0 mm DFN package
High sensitivity: 1 mg per LSB
Low noise: 150 micro g per root Hertz (independent of resolution)
Low-power mode: 7 micro amps
Interrupt and IIC interface supply: 1.62 to 3.6 V
Supply voltage : 1.95 to 3.6 V
Output data rate: 1.5 to 800 Hz

Connection

You need to use 3.3v for this device, the rest is easy Gnd and I2C

Code

 

#include <Wire.h>
 
// I2C BUS: already defined in "wire" librairy
// SDA: PIN 2 with pull up 4.7K to 3.3V on arduino Micro
// SCL: PIN 3 with pull up 4.7K to 3.3V on arduino Micro
// Accelerometer connected to +3.3V of arduino DO NOT CONNECT TO 5V (this will destroy the accelerometer!)
// all GND Pin of accelerometer connected to gnd of arduino
 
/********************ACCELEROMETER DATAS************/
// adresss of accelerometer
int adress_acc=0X1D; // MMA8653FC and MMA8652FC
// adress of registers for MMA8653FC
int ctrl_reg1 = 0x2A;
int ctrl_reg2 = 0x2B;
int ctrl_reg3 = 0x2C;
int ctrl_reg4 = 0x2D;
int ctrl_reg5 = 0x2E;
int int_source = 0x0C;
int status_ = 0x00;
int f_setup = 0x09;
int out_x_msb = 0x01;
int out_y_msb = 0x03;
int out_z_msb = 0x05;
int sysmod = 0x0B;
int xyz_data_cfg = 0x0E;
 
/******PROGRAM DATAS**********/
int result [3];
int axeXnow ;
int axeYnow ;
int axeZnow ;
 
 
void setup(){
Wire.begin(); // start of the i2c protocol
Serial.begin(9600); // start serial for output
ACC_INIT(); // initialize the accelerometer by the i2c bus. enter the sub to adjust the range (2g, 4g, 8g), and the data rate (800hz to 1,5Hz)
}
 
//------------------------------------------------------------------
 
void loop()
{
I2C_READ_ACC(0x00);
Serial.print(axeXnow); 
Serial.print(";");
Serial.print(axeYnow); 
Serial.print(";");
Serial.print(axeZnow); 
Serial.print(";");
Serial.println();
delay(500);
}
 
//------------------------------------------------------------------
 
void ACC_INIT()
{
I2C_SEND(ctrl_reg1 ,0X00); // standby to be able to configure
delay(10);
 
I2C_SEND(xyz_data_cfg ,B00000000); // 2G full range mode
delay(1);
// I2C_SEND(xyz_data_cfg ,B00000001); // 4G full range mode
// delay(1);
// I2C_SEND(xyz_data_cfg ,B00000010); // 8G full range mode
// delay(1);
 
I2C_SEND(ctrl_reg1 ,B00000001); // Output data rate at 800Hz, no auto wake, no auto scale adjust, no fast read mode
delay(1);
// I2C_SEND(ctrl_reg1 ,B00100001); // Output data rate at 200Hz, no auto wake, no auto scale adjust, no fast read mode
// delay(1);
// I2C_SEND(ctrl_reg1 ,B01000001); // Output data rate at 50Hz, no auto wake, no auto scale adjust, no fast read mode
// delay(1);
// I2C_SEND(ctrl_reg1 ,B01110001); // Output data rate at 1.5Hz, no auto wake, no auto scale adjust, no fast read mode
// delay(1); 
}
 
//------------------------------------------------------------------
 
void I2C_SEND(unsigned char REG_ADDRESS, unsigned char DATA) //SEND data to MMA7660
{
 
Wire.beginTransmission(adress_acc);
Wire.write(REG_ADDRESS);
Wire.write(DATA);
Wire.endTransmission();
}
 
//------------------------------------------------------------------
 
void I2C_READ_ACC(int ctrlreg_address) //READ number data from i2c slave ctrl-reg register and return the result in a vector
{
byte REG_ADDRESS[7];
int accel[4];
int i=0; 
Wire.beginTransmission(adress_acc); //=ST + (Device Adress+W(0)) + wait for ACK
Wire.write(ctrlreg_address); // store the register to read in the buffer of the wire library
Wire.endTransmission(); // actually send the data on the bus -note: returns 0 if transmission OK-
Wire.requestFrom(adress_acc,7); // read a number of byte and store them in wire.read (note: by nature, this is called an "auto-increment register adress")
 
for(i=0; i<7; i++) // 7 because on datasheet p.19 if FREAD=0, on auto-increment, the adress is shifted
{
REG_ADDRESS[i]=Wire.read(); //each time you read the write.read it gives you the next byte stored. The couter is reset on requestForm
}
 
for (i=1;i<7;i=i+2)
{
accel[0] = (REG_ADDRESS[i+1]|((int)REG_ADDRESS[i]<<8))>>6; // X
if (accel[0]>0x01FF) {accel[1]=(((~accel[0])+1)-0xFC00);} // note: with signed int, this code is optional
else {accel[1]=accel[0];} // note: with signed int, this code is optional
switch(i){
case 1: axeXnow=accel[1];
break;
case 3: axeYnow=accel[1];
break;
case 5: axeZnow=accel[1];
break;
}
}
 
}
 
//------------------------------------------------------------------
 
void I2C_READ_REG(int ctrlreg_address) //READ number data from i2c slave ctrl-reg register and return the result in a vector
{
unsigned char REG_ADDRESS;
int i=0; 
Wire.beginTransmission(adress_acc); //=ST + (Device Adress+W(0)) + wait for ACK
Wire.write(ctrlreg_address); // register to read
Wire.endTransmission();
Wire.requestFrom(adress_acc,1); // read a number of byte and store them in write received
}

 

 

Output

107;-65281;191;
-65488;511;89;
-65387;15;87;
-65491;511;-65443;
-65364;-65423;-65470;
229;74;-65269;
237;-65511;64;
-65355;-65347;73;
-65360;132;14;
-65481;-65263;-65323;
-65453;228;-65448;
-65354;94;215;
55;-65464;276;

Links

Arduino and HS1011 humidity sensor example

The HS1101 humidity sensor is a cost-effective solution for measuring relative humidity within ±5% accuracy. The sensor’s design is based on a unique capacitive cell; therefore, by using simple RC circuit wiring it is easy to interface with any Parallax microcontroller, including the BASIC Stamp® and Propeller chip.

Specifications

Power requirements: 5 to 10 VDC
Communication: Analog output of varying capacitance in response to change in relative humidity
Humidity Measuring Range: 1 to 99% RH
Operating temperature: -40 to 212 °F (-40 to 100 °C)

Connection

Connect 5v and Gnd to the module

I used Pin 6, you can use any I/O pin you will need to change the code if you do

Code

 

/*
 
Demonstration of the Parallax HS1101 relative humidity sensor (#27920)
 
The HS1101 sensor acts as a capacitor, and uses the circuit described in the 
product documentation to derive an RC (resistor-capacitor) time delay. By
measuring the decay of the capacitor through a resistor, it is possible to
obtain the current relative humidity.
 
This demo shows the relative humidity (accuracy: +/-3.5%, as noted in product 
documentation), along with the RC delay timing. Readings repeat once every ½ 
second, and are displayed in the Arduino Serial Monitor window.
 
This example code is for the Arduino Uno and direct compatible boards, using the
Arduino 1.0 or later IDE software. It has not been tested, nor designed for, other 
Arduino boards, including the Arduino Due.
 
Please note: Environmental factors - including use indoors or outdoors, and
above and below typical room temperature ranges -- may affect the accuracy of 
the readings. The demo includes an RCdelay calibration value that can be 
adjusted against a known working humidity sensor used in the same environment.
 
Important: the result is based on the clock speed of Arduino microcontroller.
Other versions of Arduino (running at faster or slower clocks) will need
recalibration of the RCdelay value. See comment below.
 
Refer to the HS1101 product documentation for the connection diagram and
circuit. The output of the sensor is connected to Arduino pin D4.
 
Tips: The sensor is sensitive to stray capacitance. Keep lead lengths short.
Results may vary when the test circuit is built on a solderless breadboard.
Leads from sensor are slightly undersized for breadboard holes. Make sure
they make adequate contact. When taking readings avoid contact or close
proximity to sensor or bare circuit wires.
 
*/
 
int sensorPin = 4; // RC circuit with HS1101 sesnor connected to digital pin D4
long result = 0;
int const RHconstant = 12169; // RH constant
 
void setup() {
Serial.begin(9600); // Use Serial Monitor window at 9600 baud
Serial.println("Humidiy reading start");
Serial.print("RC delay");
Serial.print("\t");
Serial.println("Humidity");
}
void loop() {
long RCdelay = RCTime(sensorPin); // Take RC time reading of sensor
Serial.print(RCdelay); // Display RC time delay
Serial.print("\t\t"); 
 
RCdelay = RCdelay * 215; // Calibation to RC time delay; experiment with literal value
int humidity = (RCdelay - RHconstant) / 24;
Serial.println(humidity / 100, DEC); 
delay(500); // Wait 1/2 second for the next read
}
 
// Standard RC time function
long RCTime(int sensePin){
long result = 0;
pinMode(sensePin, OUTPUT); // Make pin OUTPUT, and turn HIGH
digitalWrite(sensePin, HIGH); 
delay(1); // Wait 1 ms delay
pinMode(sensePin, INPUT); // Make sensor INPUT
digitalWrite(sensePin, LOW); // Turn off Arduino internal pullup resistor
while(digitalRead(sensePin)){ // Loop until pin goes low
result++;
}
return result;
}

 

Link

https://www.parallax.com/sites/default/files/downloads/27920-Humidity-Sensor-Datasheet.pdf

https://www.parallax.com/sites/default/files/downloads/27920-Humidity-Sensor-Documention-S1101-v1.0.pdf

CJMCU-1101 HS1101 humidity sensor RELATIVE, HUMIDITY, SENSOR

Generate a QR code with an Arduino

In this example we will show how to generate a QR code, all of the hard graft is done in a library

Code

Install https://github.com/ricmoo/QRCode

This is the default example

/**
 *  QRCode
 *
 *  A quick example of generating a QR code.
 *
 *  This prints the QR code to the serial monitor as solid blocks. Each module
 *  is two characters wide, since the monospace font used in the serial monitor
 *  is approximately twice as tall as wide.
 *
 */
 
#include "qrcode.h"
 
void setup() {
    Serial.begin(115200);
 
    // Start time
    uint32_t dt = millis();
 
    // Create the QR code
    QRCode qrcode;
    uint8_t qrcodeData[qrcode_getBufferSize(3)];
    qrcode_initText(&qrcode, qrcodeData, 3, 0, "HELLO WORLD");
 
    // Delta time
    dt = millis() - dt;
    Serial.print("QR Code Generation Time: ");
    Serial.print(dt);
    Serial.print("\n");
 
    // Top quiet zone
    Serial.print("\n\n\n\n");
 
    for (uint8_t y = 0; y < qrcode.size; y++) {
 
        // Left quiet zone
        Serial.print("        ");
 
        // Each horizontal module
        for (uint8_t x = 0; x < qrcode.size; x++) {
 
            // Print each module (UTF-8 \u2588 is a solid block)
            Serial.print(qrcode_getModule(&qrcode, x, y) ? "\u2588\u2588": "  ");
 
        }
 
        Serial.print("\n");
    }
 
    // Bottom quiet zone
    Serial.print("\n\n\n\n");
}
 
void loop() {
 
}

 

Output

Open the serial monitor – this is what you should see

 

 

 

B4R Arduino TM1637 7 segment display example

A few of the code examples and projects on this site use modules containing the Tm1638 driver chip, I was interested in this one which is the TM1637 which appears to be a more basic version which can only control a display, the other one can also control LEDs, buttons and two displays at the same time.

This is a common anode 4-digit tube display module which uses the TM1637 driver chip; Only 2 connections are required to control the 4-digit 8-segment displays

Here is the module

Features of the module

  • Display common anode for the four red LED
  • Powered supply by 3.3V/5V
  • Four common anode tube display module is driven by IC TM1637
  • Can be used for Arduino devices, two signal lines can make the MCU control 4 8 digital tube. Digital tube 8 segment is adjustable

Here is how to hook the module up

 

Code Example

Library is available from here – https://www.b4x.com/android/forum/threads/tm1637-4-digits-display.67733/

This is the examples

Sub Process_Globals
Public Serial1 As Serial
Private tm As TM1637Display
Private timer1 As Timer
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
Log("AppStart")
tm.Initialize(2, 3)
timer1.Initialize("timer1_Tick", 1000)
timer1.Enabled = True
End Sub
Sub Timer1_Tick
tm.ShowNumberDec2(Millis / 1000, True, 4, 0)
End Sub

Links

4 Bits Digital Tube LED Display Module With Clock Display TM1637 for Arduino Raspberry PI FZ1435

B4R Arduino and BH1750 Ambient Light Sensor example

BH1750FVI is an digital Ambient Light Sensor IC for I2C bus interface. This IC is the most suitable to obtain the ambient light data for adjusting LCD and Keypad backlight power of Mobile phone. It is possible to detect wide range at High resolution.  1 – 65535 lux (lx).

Features

1) I2C bus Interface ( f / s Mode Support )
2) Spectral responsibility is approximately human eye response
3) Illuminance to Digital Converter
4) Wide range and High resolution. ( 1 – 65535 lx )
5) Low Current by power down function
6) 50Hz / 60Hz Light noise reject-function
7) 1.8V Logic input interface
8) No need any external parts
9) Light source dependency is little. ( ex. Incandescent Lamp. Fluorescent Lamp. Halogen Lamp. White LED. Sun Light )
10) It is possible to select 2 type of I2C slave-address.
11) Adjustable measurement result for influence of optical window ( It is possible to detect min. 0.11 lx, max. 100000 lx by using this function. )
12) Small measurement variation (+/- 20%)
13) The influence of infrared is very small.

What is lux

The lux (symbol: lx) is the SI unit of illuminance and luminous emittance, measuring luminous flux per unit area. It is equal to one lumen per square metre. In photometry, this is used as a measure of the intensity, as perceived by the human eye, of light that hits or passes through a surface. It is analogous to the radiometric unit watts per square metre, but with the power at each wavelength weighted according to the luminosity function, a standardized model of human visual brightness perception. In English, “lux” is used in both singular and plural

Typical Lux values

These were taken from Wikipedia

Examples
Illuminance Surfaces illuminated by:
0.0001 lux Moonless, overcast night sky (starlight)
0.002 lux Moonless clear night sky with airglow
0.27–1.0 lux Full moon on a clear night[3][4]
3.4 lux Dark limit of civil twilight under a clear sky
50 lux Family living room lights (Australia, 1998)
80 lux Office building hallway/toilet lighting]
100 lux Very dark overcast day
320–500 lux Office lighting
400 lux Sunrise or sunset on a clear day.
1000 lux Overcast day; typical TV studio lighting
1000025000 lux Full daylight (not direct sun)
32000100000 lux Direct sunlight

Typically to use this sensor you will need to purchase a module, here is a picture of one

 

For those that are interested this is a schematic of the module

 

 

Layout

An easy module to connect being an I2C one

 

Code

The library and this code example are available from – https://www.b4x.com/android/forum/threads/rbh1750fvi-digital-ambient-light-sensor.75663/

Sub Process_Globals
Public Serial1 As Serial
Private bh As BH1750FVI
Private Timer1 As Timer
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
Log("AppStart")
'Init the sensor with low I2C address 0x23 and the recommended high resolution mode
bh.Initialize(bh.Device_Address_L, bh.Continuous_H_resolution_Mode)
Timer1.Initialize("Timer1_Tick", 1000)
Timer1.Enabled = True
End Sub
Sub Timer1_Tick
Log(bh.LightIntensity, " lx")
End Sub

 

Testing

108 lx
102 lx
358 lx
357 lx
7 lx
1 lx
1 lx
167 lx

 

Links

BH1750 BH1750FVI light intensity illumination module 3V-5V