Skip to content

Instantly share code, notes, and snippets.

@ShawnHymel
Created December 13, 2017 23:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShawnHymel/ff4114f1bc05a96ea30a4f4169963de6 to your computer and use it in GitHub Desktop.
Save ShawnHymel/ff4114f1bc05a96ea30a4f4169963de6 to your computer and use it in GitHub Desktop.
H3LIS331 Ball Demo
/**
* H3LIS331 Ball Demo
*
* Date: December 13, 2017
* Author: Shawn Hymel (SparkFun Electronics)
*
* Moves a ball around the OLED.
*
* Connect the H3LIS331 breakout board to the Arduino's I2C port
* (A4 and A5 on most boards). Connect Micro OLED board to SPI
* port as per the connections found here:
* https://learn.sparkfun.com/tutorials/micro-oled-breakout-hookup-guide#hardware-hookup
*
* This sketch was written by SparkFun Electronics, with lots of
* help from the Arduino community. This code is completely free
* for any use.
*/
#include "SparkFun_LIS331.h"
#include <Wire.h>
#include <SFE_MicroOLED.h>
// Constants
const int FRAME_DELAY = 33; // Target ms per frame (1/fps)
const int RADIUS = 3; // Radius of ball (pixels)
const int THRESH = 4; // Acceleration needs to be over this
const float SCALE = 0.15; // Scale acceleration for ball
const int I2C_ADDR = 0x19; // I2C address for accelerometer
const int PIN_RESET = 9; // Reset pin on OLED
const int PIN_DC = 8; // DC pin on OLED
const int PIN_CS = 10; // CS pin on OLED
const int OLED_WIDTH = 64; // Number of pixels in X
const int OLED_HEIGHT = 48; // Number of pixels in Y
// Globals
LIS331 accel;
MicroOLED oled(PIN_RESET, PIN_DC, PIN_CS);
unsigned long timestamp = 0;
float ball_x = 32.0;
float ball_y = 24.0;
void setup() {
// Initialize the accelerometer
Wire.begin();
accel.setI2CAddr(I2C_ADDR);
accel.begin(LIS331::USE_I2C);
// Initialize the OLED
oled.begin();
oled.clear(ALL);
oled.display();
// Debug
Serial.begin(9600);
}
void loop() {
int16_t x, y, z;
// Try to hit the target FPS by waiting to update each frame
if ( millis() > timestamp + FRAME_DELAY ) {
timestamp = millis();
// Read acceleration in each axis
accel.readAxes(x, y, z);
// Debug
Serial.print(x);
Serial.print(" ");
Serial.println(y);
// Update x,y of ball. Note x,y are swapped on accelerometer
if ( abs(x) >= THRESH ) {
ball_y -= SCALE * (float)x;
}
if ( abs(y) >= THRESH ) {
ball_x -= SCALE * (float)y;
}
// Don't let ball fall off edge
if ( ball_x - RADIUS < 0 ) {
ball_x = RADIUS;
}
if ( ball_x + RADIUS + 1 > OLED_WIDTH ) {
ball_x = OLED_WIDTH - RADIUS - 1;
}
if ( ball_y - RADIUS < 0 ) {
ball_y = RADIUS;
}
if ( ball_y + RADIUS + 1 > OLED_HEIGHT ) {
ball_y = OLED_HEIGHT - RADIUS - 1;
}
// Clear screen
oled.clear(PAGE);
// Draw outline box
oled.rect(0, 0, OLED_WIDTH, OLED_HEIGHT);
// Draw ball
oled.circleFill(round(ball_x), round(ball_y), RADIUS);
// Show everything on the screen
oled.display();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment