unresolved overloaded function type error - c++

I see a lot of discussion on this error, but I can't seem to find a format that works. I am getting the following error:
In member function 'void radarClass::ping()':
error: no matching function for call to 'NewPing::ping_timer(<unresolved overloaded function type>)'
note: candidates are: void NewPing::ping_timer(void (*)())
My full code is attached below, the error is at line 198:
sonar->ping_timer(echoCheck);
I have also unsuccessfully tried:
sonar->ping_timer((void* ) &radarClass::echoCheck));
sonar->ping_timer(&radarClass::echoCheck);
Full code here:
#ifndef RADAR_CLASS
#define RADAR_CLASS
#include <NewPing.h>
#include <Servo.h>
#include <PString.h>
/*
**
** MOVING AVERAGE CLASS
** Special volatile impelentation, fixed Int type
**
*/
template <int N> class volatileMovingAverage
{
public:
volatileMovingAverage(int def = 0) : sum(0), p(0)
{
for (int i = 0; i < N; i++) {
samples[i] = def;
sum += samples[i];
}
}
int add(int new_sample)
{
sum = sum - samples[p] + new_sample;
samples[p++] = new_sample;
if (p >= N)
p = 0;
return sum / N;
}
int inline getAverage(void)
{
return sum / N;
}
private:
volatile int samples[N];
volatile int sum;
volatile int p;
}; // Class volatileMoving Average
/* *************************************************************** */
// RadarClass
//
// USAGE:
// ----------------------
// NewPing mySonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
// Servo myServo;
// radarClass myRadar(&myServo, &mySonar);
// myRadar.attachServo(pinNumber);
// myRadar.setServoSpeed(200); // 0.2 seconds/60 degrees of rotation
// myRadar.run(); etc.
#define RADAR_DEBUG_MODE YES // for testing only, comment out otherwise
#define NO_ANGLES 9 // number of angles, i.e. positions at which to take measurements
class radarClass
{
private:
int maxAngle; // 9 values, positions 0 - 8
int angles[NO_ANGLES]; // values: {0, 22, 44, 67, 90, 112, 135, 157, 180}
volatileMovingAverage<4> sonarAverage[NO_ANGLES]; // array of moving average distances (one per angle)
volatile uint8_t pos; // current position within angle array
unsigned long int servoArrivalTime; // time (millis) when servo will complete its rotation and arrive at next position
int direction; // direction traversing the angle array (+1 or -1)
Servo *radarServo; // pointer to the servo
NewPing *sonar; // point to the NewPing sensor
int maxDist; // max distance (used by NewPing sensor)
int servoSpeed; // servo peed in milli-seconds to move 60 degrees (e.g. 0.15 seconds to move 60 degrees of rotation = 0.15 x 1000 = 150)
volatile bool waitingForPing; // flag to mark when ping result received
bool pingStarted; // flag to keep track of ping loop status
volatile int pingValue; // used to pass ping result between the two routines/ISRs
void nextPosition(void);
void ping(void);
int getMinDistance(int start_pos, int end_pos);
void commonInit(void);
void echoCheck(void);
public:
radarClass(Servo *svr, NewPing *snr);
radarClass(NewPing *snr, Servo *svr);
int getMinDistanceLeft(void);
int getMinDistanceRight(void);
int getMinDistasnceFront(void);
void run(void);
void attachServo(int pin);
void setServoSpeed(int);
void setMaxDistance(int d) {maxDist = d;};
#ifdef RADAR_DEBUG_MODE
void printAllValues(void);
void printInt(int val, int len);
#endif
//int getCurrentAngle(void) {return angles[pos];}
//int getDistance(int p) {return sonarAverage[p].getAverage();}
}; // radarClass
/* ********************************************************** */
// constructor
radarClass::radarClass(Servo *svr, NewPing *snr)
{
// save the passed pointers
radarServo = svr;
sonar = snr;
// run common initialization routine
commonInit();
} // radarClass::radarClass constructor
/* ********************************************************** */
// constructor
radarClass::radarClass(NewPing *snr, Servo *svr)
{
// save the passed pointers
radarServo = svr;
sonar = snr;
// run common initialization routine
commonInit();
} // radarClass::radarClass constructor
/* ********************************************************** */
// constructor common initialization routine
void radarClass::commonInit(void)
{
// initialize variables
maxAngle = NO_ANGLES - 1;
pos = 0;
direction = 1;
servoSpeed = 100; // default to 0.10 s/60 degrees (x 1000 per millisecond) for TowerPro SG-90
maxDist = 100; // max distance usable by NewPing IN INCHES
pingStarted = false;
waitingForPing = false;
// initialize the angle array...not elegant but it works
// angles[] = {0, 22, 44, 67, 90, 112, 135, 157, 180};
angles[0] = 0;
angles[1] = 22;
angles[2] = 44;
angles[3] = 67;
angles[4] = 90;
angles[5] = 112;
angles[6] = 135;
angles[7] = 157;
angles[8] = 180;
// move servo to initial position
radarServo->write(angles[0]);
// set arrival time (estimated)
servoArrivalTime = millis() + (abs(angles[0] - angles[maxAngle]) * servoSpeed / 60 / 2);
}
/* ********************************************************** */
// main external program loop...call continually, moves servo & reads values
void radarClass::run(void)
{
unsigned long int t = millis();
// has the servo arrived at target angle yet?
if (t < servoArrivalTime)
return;
// read distance at current location, wait for result, and advance to next location
ping();
}
/* ********************************************************** */
// get ping distance at current servo position
void radarClass::ping(void)
{
if (!pingStarted) // send new ping, echoCheck will be called by interrupt Timer2 until result received
{
pingStarted = true;
waitingForPing = true;
sonar->ping_timer(echoCheck);
return;
}
else // pingStarted loop is true, already called ping timer...
{
if (!waitingForPing) // have we received the result back?
{
if (pingValue == 0) // NewPing returns 0 for undetactable ranges...
pingValue = maxDist;
sonarAverage[pos].add( pingValue );
pingStarted = false; // toggle flag to mark that we are ot of hte loop
nextPosition(); // advance to the next position
}
}
}
/* ********************************************************** */
// function called by NewPing ISR to check for ping result;
// Timer2 interrupt calls this function every 24uS where you can check the ping status.
void radarClass::echoCheck(void)
{
// Don't do anything here!
if (sonar->check_timer()) // Check to see if the ping was received.
{
pingValue = (sonar->ping_result / US_ROUNDTRIP_IN); // Ping returned, uS result in ping_result, convert to inches with US_ROUNDTRIP_IN.
waitingForPing = false; // toggle flag so we know result is complete
}
// Don't do anything here!
}
/* ********************************************************** */
// move servo to the next position
void radarClass::nextPosition(void)
{
// if at either end, change direction
if (pos == 0)
direction = 1;
else if (pos == maxAngle)
direction = -1;
// advance to next position
pos += direction;
radarServo->write(angles[pos]);
// calculate arrival time at next position
servoArrivalTime = millis() + ( (abs(angles[pos] - angles[pos + direction]) * servoSpeed ) / 60);
}
/* ********************************************************** */
// set the servo speed, in milliseconds per 60 degrees
void radarClass::setServoSpeed(int spd)
{
servoSpeed = spd;
}
/* ********************************************************** */
// Attach servo to specified pin
void radarClass::attachServo(int pin)
{
radarServo->attach(pin);
}
/* ********************************************************** */
// return the longest distance for given array entries (inclusive)
int radarClass::getMinDistance(int start_pos, int end_pos)
{
// to make sure underlying data isn't changed by ISR routine, briefly turn off interrupts
//noInterrupts();
// calculate the min value
int smallest = sonarAverage[start_pos].getAverage();
for (int t = start_pos + 1; t <= end_pos; t++)
{
int curr = sonarAverage[t].getAverage();
if (curr < smallest)
smallest = curr;
}
// turn interrupts back on
//interrupts();
// return the calculated value
return (smallest);
}
/* ********************************************************** */
// return closest distance to left (positions 0, 1 & 2)
int radarClass::getMinDistanceLeft(void)
{
return getMinDistance(0, 2);
}
/* ********************************************************** */
// return closest distance to right (positions 6, 7 & 8)
int radarClass::getMinDistanceRight(void)
{
return getMinDistance(6, 8);
}
/* ********************************************************** */
// return closest distance to front (positions 3, 4 & 5)
int radarClass::getMinDistasnceFront(void)
{
return getMinDistance(3, 5);
}
// code for debugging; prints all values in neat format
#ifdef RADAR_DEBUG_MODE
void radarClass::printAllValues(void)
{
static bool firstEntry = true;
if (firstEntry) // only print the header row once
{
Serial.println(" ");
Serial.println(F("Angle 1 Angle 2 Angle 3 Angle 4 Angle 5 Angle 6 Angle 7 Angle 8 Angle 9"));
for (int i = 0; i <= maxAngle; i++) // print the angles
{
printInt(angles[i], 7);
Serial.print(" ");
}
Serial.println("");
Serial.println(F("------- ------- ------- ------- ------- ------- ------- ------- -------"));
firstEntry = false;
}
// print the distances
for (int i = 0; i <= maxAngle; i++)
{
printInt(sonarAverage[i].getAverage(), 7);
Serial.print(" ");
}
Serial.println("");
} // void printAllValues(void)
/* ********************************************************** */
// Print integer, padded for alignment
void radarClass::printInt(int val, int len)
{
int strLen;
char buffer[30];
PString str(buffer, sizeof(buffer));
// Find the length of the printed value
str.begin();
str.print(val);
strLen = str.length();
str.begin();
// Pad string with leading spaces
for (int t = len - strLen; t > 0; t--)
{
str += " ";
}
// then print the string
str.print(val);
//str += " ";
// print result
Serial.print(str);
} // void printInt(int val, int len)
#endif // RADAR_DEBUG_MODE
#endif // RADAR_CLASS
/* ****************************************************************************************** */
/*
** TEST CODE HERE
********************************
*/
//#include <TimerOneThree.h>
#include <TimerOne.h>
#define RADAR_INT_TIME 100000 // 100,000 microseconds = 10x/second = 1 sweep of 9 angles per sceond
Servo myServo;
NewPing mySonar(10, 11, 250);
radarClass myRadar(&myServo, &mySonar);
// function to be called by the interrupt timer; will run the Radar code
void intRunRadar(void)
{
myRadar.run();
} // void intRunRadar()
void setupRadarInterrupt(void)
{
// Timer1.initialize(RADAR_INT_TIME); // set how often to run the interrupt (in microseconds)
// Timer1.attachInterrupt(intRunRadar);
} // void setupRadarInterrupt(void)
void setup()
{
Serial.begin(9600);
myRadar.attachServo(3);
myRadar.setServoSpeed(150);
delay(500);
//setupRadarInterrupt();
}
void loop()
{
unsigned long int t1, t2;
t1 = millis();
Serial.println("Starting test");
while (1)
{
myRadar.run();
t2 = millis();
if (t2 >= t1 + 1000)
{
t1 = t2;
myRadar.printAllValues();
}
} // while
} // loop()
I have apparently reached the limit of my knowledge here.

Add constructors to the sketch:
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); //

Related

Time dependent data acquisition from DHT22 - problem with initial loops

I'm trying to gather the data from DHT22 Humidity and Temperature sensor based on millis() function to avoid the buffer overload and due to how fast the sensor is itself. The point is, that the project has to manage the 72h constant routines, to control the air valve. Because of that 2 actions to be handled, delay is out of range. The problem is, that after setup() and filling in the buffer for average, the loop starts from 12 readings one after another, and eventually after these 12 readings it starts to perform 2 sec. interval readings.
#include <DHT.h>
#include <Adafruit_Sensor.h>
#include <CircularBuffer.h>
#include <time.h>
#define DHTPIN 2
#define DHTTYPE DHT22
using namespace std;
const int sample_rate = 4; // Defining how many samples are gathered to calculate the average
const int temper_low = -3; // Defining lower range of temperature
const int temper_high = 20;// Defining high range for temperature
float sum_temper, sum_humid, avg_temp, avg_humid = 0; // variables to calculate the Simple Moving Average
int pre_fill_count = 0; // iterator used for preFill buffer, goes up to 9 and then gets cleared
float test = -255.0;
int mins = 0; //Next 3 vars used for valve control timer
int hours = 0;
int days = 0;
DHT dht(DHTPIN, DHTTYPE); // Defining the dht object
CircularBuffer<float, sample_rate> temper_buffer; // Defining the CircularBuffer for FILO with Moving Average
CircularBuffer<float, sample_rate> humid_buffer; // Same as above
const unsigned long DHT_reads_interval = 2000; //interval used to perform reading action considering the speed of DHT sensor
unsigned long currentMillis = 0; //stores the value of millis() in each iteration of loop()
unsigned long previous_sens_readout = 0; //last time temperature was readed
//State machine for humidity readouts
enum state{
preFill,
measure,
fail
};
state sensorState = preFill;
bool measurmentFlag = false;
//Functions definitions
void calculateAverageTemperature(
const int& sample_rate,
float& sum_temper,
float& sum_humid,
float& avg_temp,
float& avg_humid
);
void getSensorReadings(
DHT &sensor,
CircularBuffer<float, sample_rate> &temper_buffer,
CircularBuffer<float, sample_rate> &humid_buffer
);
float readTemperature
(
state &sensorState,
DHT &dht
);
float readHumidity
(
state &sensorState,
DHT &dht
);
void setup() {
// Setup, runs once after uC boot
Serial.begin(9600);
Serial.println(F("DHTxx test!"));
dht.begin();
Serial.println("test value ");
Serial.println(test);
// Wait a few seconds between measurements.
currentMillis = millis();
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
///////////////////////////////////////////////////////////////////////////
//////////////////////////////INIT BUFFER FILL SECTION////////////////////
/////////////////////////////////////////////////////////////////////////
Serial.println("INITIALISING THE BUFFER, PLEASE WAIT... ");
while(sensorState == preFill && (pre_fill_count <=9)) {
//PUSHING READINGS TO THE BUFFER
//DUE TO BUFFER INIT ACTION, IT TAKES C.A. 20 SECS TO MOVE FROM preFill TO measure state!!!
if(currentMillis - previous_sens_readout >= DHT_reads_interval){
temper_buffer.push(readTemperature(sensorState, dht));
Serial.print(pre_fill_count);
Serial.print(" it Temperature measurement from temper buffer: ");
Serial.println(temper_buffer[pre_fill_count]);
humid_buffer.push(readHumidity(sensorState, dht));
Serial.print(pre_fill_count);
Serial.print(" it Humidity measurement from temper buffer: ");
Serial.println(humid_buffer[pre_fill_count]);
previous_sens_readout = previous_sens_readout + DHT_reads_interval;
pre_fill_count++;
}
currentMillis = millis();
}
sensorState = measure;
previous_sens_readout = 0;
currentMillis = millis();
Serial.print("Program time on the exit of preFill: ");
Serial.print(int(currentMillis/1000));
Serial.println(" seconds");
measurmentFlag = true;
}
void loop() {
///////////////////////////////////////////////////////////////////////////////////
////////////////////////////MAIN STATE MACHINE OF PROGRAM/////////////////////////
/////////////////////////////////////////////////////////////////////////////////
Serial.println("--------------------HELLO THERE------------------------");
currentMillis = millis();
//TOTO - IMPLEMENT ACTUAL USE OF THE calculateAverageTemperature function
if(sensorState == measure && measurmentFlag == true){
calculateAverageTemperature(
sample_rate,
sum_temper,
sum_humid,
avg_temp,
avg_humid
);
if(currentMillis - previous_sens_readout >= DHT_reads_interval){
getSensorReadings(dht,
temper_buffer,
humid_buffer
);
previous_sens_readout = previous_sens_readout + DHT_reads_interval;
}
if(sensorState == fail){
Serial.println("FAKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP!");
delay(2000);
//TODO: RETRY MEASUREMENT AND RAISE LED INDICATOR OF FAIL!
}
}
}
void calculateAverageTemperature(
const int& sample_rate,
float& sum_temper,
float& sum_humid,
float& avg_temp,
float& avg_humid
){
//iter to gather the sum of 10 values
for (int k = 0; k < sample_rate; k++) {
Serial.println("-----------------HERE I AM!---------------------");
sum_temper = sum_temper + temper_buffer[k];
sum_humid = sum_humid + humid_buffer[k];
}
//calculate the sum of values
avg_temp = sum_temper / sample_rate;
avg_humid = sum_humid / sample_rate;
sum_temper = sum_humid = 0;
measurmentFlag = false;
}
void getSensorReadings(
DHT &sensor,
CircularBuffer<float, sample_rate> &temper_buffer,
CircularBuffer<float, sample_rate> &humid_buffer
){
//get next measurings
temper_buffer.push(readTemperature(sensorState, dht));
humid_buffer.push(readHumidity(sensorState, dht));
Serial.print(F("Avg Humidity: "));
Serial.print(avg_humid);
Serial.print(F("% Temperature: "));
Serial.print(avg_temp);
Serial.print(F("°C \n"));
measurmentFlag = true;
}
//GATHERING TEMPERATURE MEASUREMENT
float readTemperature
(
state &sensorState,
DHT &dht
){
float t = 0;
bool readed = false;
for (int r = 0; r < 4; r++) {
if ((!readed) && (!isnan(t = dht.readTemperature()))) {
Serial.print("Temperature readed on iteration: ");
Serial.println(r);
readed = true;
break;
}
else if ((r == 3) && (!readed)) {
Serial.println("Something went wrong with temperature");
sensorState = fail;
return -255;
}
}
return t;
}
//GATHERING HUMIDITY MEASUREMENT
float readHumidity
(
state &sensorState,
DHT &dht
){
float h = 0;
bool readed = false;
for (int o = 0; o < 4; o++) {
if (!readed && !isnan(h = dht.readHumidity())) {
Serial.print("Humidity readed on iteration: ");
Serial.println(o);
readed = true;
break;
}
else if ((o == 3) && (!readed)) {
//raise error, blink LED, Kill software
Serial.println("Something went wrong with Humidity");
sensorState = fail;
return -255;
}
}
return h;
}
I've tried many times using some extra flags inside code, nothing seem to really help.
DHT_reads_interval is defined as 2000. It should be expected that
(currentMillis - previous_sens_readout >= DHT_reads_interval)
is satisfied approximately every 2000 ms, which is 2 seconds.
Regarding the first 12 readings coming one after another, ask yourself what is currentMillis, and what is previous_sens_readout after setup completes?
In fact, currentMillis retains its value, but previous_sens_readout = 0; is spelled loud and clear. Do you see the consequences?

How do I generate a tone using SDL_audio?

I am trying to generate a simple, constant sine tone using SDL_audio. I have a small helper class that can be called to turn the tone on/off, change the frequency, and change the wave shape. I have followed some examples I could find on the web and got the following:
beeper.h
#pragma once
#include <SDL.h>
#include <SDL_audio.h>
#include <cmath>
#include "logger.h"
class Beeper {
private:
//Should there be sound right now
bool soundOn = true;
//Type of wave that should be generated
int waveType = 0;
//Tone that the wave will produce (may or may not be applicable based on wave type)
float waveTone = 440;
//Running index for sampling
float samplingIndex = 0;
//These are useful variables that cannot be changed outside of this file:
//Volume
const Sint16 amplitude = 32000;
//Sampling rate
const int samplingRate = 44100;
//Buffer size
const int bufferSize = 1024;
//Samples a sine wave at a given index
float sampleSine(float index);
//Samples a square wave at a given index
float sampleSquare(float index);
public:
//Initializes SDL audio, audio device, and audio specs
void initializeAudio();
//Function called by SDL audio_callback that fills stream with samples
void generateSamples(short* stream, int length);
//Turn sound on or off
void setSoundOn(bool soundOnOrOff);
//Set timbre of tone produced by beeper
void setWaveType(int waveTypeID);
//Set tone (in Hz) produced by beeper
void setWaveTone(int waveHz);
};
beeper.cpp
#include <beeper.h>
void fillBuffer(void* userdata, Uint8* _stream, int len) {
short * stream = reinterpret_cast<short*>(_stream);
int length = len;
Beeper* beeper = (Beeper*)userdata;
beeper->generateSamples(stream, length);
}
void Beeper::initializeAudio() {
SDL_AudioSpec desired, returned;
SDL_AudioDeviceID devID;
SDL_zero(desired);
desired.freq = samplingRate;
desired.format = AUDIO_S16SYS; //16-bit audio
desired.channels = 1;
desired.samples = bufferSize;
desired.callback = &fillBuffer;
desired.userdata = this;
devID = SDL_OpenAudioDevice(SDL_GetAudioDeviceName(0,0), 0, &desired, &returned, SDL_AUDIO_ALLOW_FORMAT_CHANGE);
SDL_PauseAudioDevice(devID, 0);
}
void Beeper::generateSamples(short *stream, int length) {
int samplesToWrite = length / sizeof(short);
for (int i = 0; i < samplesToWrite; i++) {
if (soundOn) {
if (waveType == 0) {
stream[i] = (short)(amplitude * sampleSine(samplingIndex));
}
else if (waveType == 1) {
stream[i] = (short)(amplitude * 0.8 * sampleSquare(samplingIndex));
}
}
else {
stream[i] = 0;
}
//INFO << "Sampling index: " << samplingIndex;
samplingIndex += (waveTone * M_PI * 2) / samplingRate;
//INFO << "Stream input: " << stream[i];
if (samplingIndex >= (M_PI*2)) {
samplingIndex -= M_PI * 2;
}
}
}
void Beeper::setSoundOn(bool soundOnOrOff) {
soundOn = soundOnOrOff;
//if (soundOnOrOff) {
// samplingIndex = 0;
//}
}
void Beeper::setWaveType(int waveTypeID) {
waveType = waveTypeID;
//samplingIndex = 0;
}
void Beeper::setWaveTone(int waveHz) {
waveTone = waveHz;
//samplingIndex = 0;
}
float Beeper::sampleSine(float index) {
double result = sin((index));
//INFO << "Sine result: " << result;
return result;
}
float Beeper::sampleSquare(float index)
{
int unSquaredSin = sin((index));
if (unSquaredSin >= 0) {
return 1;
}
else {
return -1;
}
}
The callback function is being called and the generateSamples function is loading data into the stream, but I cannot hear anything but a very slight click at irregular periods. I have had a look at the data inside the stream and it follows a pattern that I would expect for a scaled sine wave with a 440 Hz frequency. Is there something obvious that I am missing? I did notice that the size of the stream is double what I put when declaring the SDL_AudioSpec and calling SDL_OpenAudioDevice. Why is that?
Answered my own question! When opening the audio device I used the flag SDL_AUDIO_ALLOW_FORMAT_CHANGE which meant that SDL was actually using a float buffer instead of the short buffer that I expected. This was causing issues in a couple of places that were hard to detect (the stream being double the amount of bytes I was expecting should have tipped me off). I changed that parameter in SDL_OpenAudioDevice() to 0 and it worked as expected!

Arduino NRF24l01 RC sends nothing

I'm trying to execute following source on my RC transmitter and receiver which uses NRF24 module. Today i uploaded same sketch as i did half year ago and it stopped receiving any data from transmitter, nothing is printed in DEBUG_PRINT sections.
On transmitter NRF24 is connected to 7, 8.
On receiver NRF24 is connected to 9, 10.
Wiring checked 7 times, correct, power supply of the receiver is 7.4V to the VIN, power supply for the transmitter is USB source.
Running on the arduino nano.
Source for transmitter is:
// Flash for self-diy NRF24lo* transmiter controller.
// 6 buttons, 4-way sticks, based on CX-10c controller.
#include <EEPROM.h>
#include <SPI.h>
#include "RF24.h"
#define DEBUG_PRINT
// #define DEBUG_PRINT_RAW
#ifdef DEBUG_PRINT
#include <printf.h>
#endif
// IO mappings
#define STICK0 A3
#define STICK1 A2
#define STICK2 A0
#define STICK3 A1
#define BTN0 3
#define BTN1 6
#define BTN2 5
#define BTN3 4
#define BTN4 9
#define BTN5 A4
#define STLED 2
// Optional moddings
#define BTN_LONG_PRESS 1000
#define LED_ST_OFF 0
#define LED_ST_CONST 1
#define LED_ST_FLASH 2
#define LED_ST_FAST_FLASH 3
#define LED_ST_FLASH_TIME 250
#define LED_ST_FAST_FLASH_TIME 100
#define LED_POWER 150
// Package types
#define PACKAGE_STICKS 3
#define PACKAGE_BUTTON 5
#define PACKAGE_PING 7
#define PACKAGE_TIMEOUT 100
// Amount of packages should be dropped sequently to detect disconnect
#define TX_DROP_EDGE 16
// Long press stick 0 to start calibration, long press to stop
// Struct with min/max calibration values
struct STICK_CALIBRATION {
int stmx[4];
int stmn[4];
};
// Struct with info of button presses
struct BTN_STATE {
int press[6];
unsigned long time[6];
// Used in long press to avoid multiple pressing
int acted[6];
};
// Struct with state of flashing/idle/working LED
// FLASH --> CONST/OFF
// FAST_FLASH --> CONST/OFF
struct LED_STATE {
// Previous type (for FLASH return to OFF/CONST state)
int ptype;
// Type of operation
int type;
// ON/OFF
int state;
// Time since action
unsigned long time;
// Count of flashes
int count;
};
// Sender package type.
// Contains type and values for button or values for sticks
struct Package {
int type;
union {
struct {
int number;
int lpress;
int dummy[2];
} button;
struct {
int sticks[4];
} sticks;
} data;
};
// Info of sticks calibration
STICK_CALIBRATION calibration;
bool calibration_mode = 0;
int sticks[4];
// When entering lock mode, stick data is not updating from input
bool lock_mode = 0;
// info of buttons states
BTN_STATE buttons;
LED_STATE led_state;
// Use NRF24lo1 transmitter on pins 7, 8
RF24 radio(7, 8);
byte addresses[][6] = { "TRAAA", "REEEE" };
// Amount of sequently dropped packages. Used to detect disconnect
int tx_dropped = 0;
// Used to prevent longpress repeat
// On long press button could be used as sticky press function,
// to avoid button sticking and long press act once during while push down,
// use this function to mark button as acted
void btn_act(int nubmer);
// Called on button press/longpress
void btn_action(int number, int lpress);
// Set led ON/OFF with change of state flag
void led_set_state(int state);
// Set led action type (FLAST, CONST, e.t.c.)
void led_set(int type, int count);
// Sends single package with given amount of attempts.
// Allows waiting for responce of receiver. The response should be 0.
// Returns 1 on success, 0 on failture.
int send_package(byte* pack, int size);
void setup() {
#ifdef DEBUG_PRINT
Serial.begin(115200);
#endif
// Set up transmitter
radio.begin();
radio.setChannel(77);
radio.enableAckPayload();
radio.setPALevel(RF24_PA_MAX);
radio.openWritingPipe(addresses[1]);
radio.openReadingPipe(1, addresses[0]);
#ifdef DEBUG_PRINT
printf_begin();
radio.printDetails();
#endif
// Read calibration values
byte* cal_struct = (byte*) &calibration;
for (int i = 0; i < sizeof(STICK_CALIBRATION); ++i)
cal_struct[i] = EEPROM.read(i);
#ifdef DEBUG_PRINT
Serial.println("CALIBRATION: ");
for (int i = 0; i < 4; ++i) {
Serial.print('(');
Serial.print(calibration.stmn[i]);
Serial.print(", ");
Serial.print(calibration.stmx[i]);
Serial.print(") ");
}
Serial.println();
#endif
buttons = {{0,0,0,0,0,0}, {0,0,0,0,0,0}, {0,0,0,0,0,0}};
// Clear LED state
led_state.ptype = 0;
led_state.type = 0;
led_state.state = 0;
led_state.time = 0;
led_state.count = 0;
// Prepare pinout
pinMode(STLED, OUTPUT);
pinMode(STICK0, INPUT_PULLUP);
pinMode(STICK1, INPUT_PULLUP);
pinMode(STICK2, INPUT_PULLUP);
pinMode(STICK3, INPUT_PULLUP);
pinMode(BTN0, INPUT_PULLUP);
pinMode(BTN1, INPUT_PULLUP);
pinMode(BTN2, INPUT_PULLUP);
pinMode(BTN3, INPUT_PULLUP);
pinMode(BTN4, INPUT_PULLUP);
pinMode(BTN5, INPUT_PULLUP);
}
void loop() {
// Read sticks & map to calibration
if (!lock_mode) {
sticks[0] = analogRead(STICK0);
sticks[1] = analogRead(STICK1);
sticks[2] = 1024 - analogRead(STICK2);
sticks[3] = 1024 - analogRead(STICK3);
}
// Read stick buttons
int rbtn[6];
rbtn[0] = !digitalRead(BTN0);
rbtn[1] = !digitalRead(BTN1);
// read optional buttons
rbtn[2] = !digitalRead(BTN2);
rbtn[3] = !digitalRead(BTN3);
rbtn[4] = !digitalRead(BTN4);
rbtn[5] = !digitalRead(BTN5);
#ifdef DEBUG_PRINT
#ifdef DEBUG_PRINT_RAW
// Debug out
Serial.print(sticks[0]); Serial.print(' ');
Serial.print(sticks[1]); Serial.print(' ');
Serial.print(sticks[2]); Serial.print(' ');
Serial.print(sticks[3]); Serial.print(' ');
Serial.print(rbtn[0]); Serial.print(' ');
Serial.print(rbtn[1]); Serial.print(' ');
Serial.print(rbtn[2]); Serial.print(' ');
Serial.print(rbtn[3]); Serial.print(' ');
Serial.print(rbtn[4]); Serial.print(' ');
Serial.print(rbtn[5]); Serial.print(' ');
Serial.println();
#endif
#endif
// Map to calibration
if (!calibration_mode && !lock_mode) {
sticks[0] = map(sticks[0], calibration.stmn[0], calibration.stmx[0], 0, 1023);
sticks[1] = map(sticks[1], calibration.stmn[1], calibration.stmx[1], 0, 1023);
sticks[2] = map(sticks[2], calibration.stmn[2], calibration.stmx[2], 0, 1023);
sticks[3] = map(sticks[3], calibration.stmn[3], calibration.stmx[3], 0, 1023);
}
// Check buttons states and update timings
for (int i = 0; i < 6; ++i) {
if (buttons.press[i] && !rbtn[i]) { // Button released
if (!buttons.acted[i])
btn_action(i, (millis() - buttons.time[i]) > BTN_LONG_PRESS);
buttons.press[i] = 0;
buttons.time[i] = 0;
} else if (buttons.press[i]) { // Button keeps down
if ((millis() - buttons.time[i]) > BTN_LONG_PRESS && !buttons.acted[i]) { // Toggle long press
btn_action(i, 1);
// buttons.press[i] = 0;
buttons.time[i] = 0;
}
} else if (rbtn[i]) { // Button pressed
buttons.press[i] = 1;
buttons.acted[i] = 0;
buttons.time[i] = millis();
}
}
// Update LED
if (led_state.type == LED_ST_FLASH && (led_state.time + LED_ST_FLASH_TIME) < millis()
||
led_state.type == LED_ST_FAST_FLASH && (led_state.time + LED_ST_FAST_FLASH_TIME) < millis()) { // Flash period done
if (!led_state.state) { // Count cycle as finished, try to begin another one
--led_state.count;
if (led_state.count <= 0) { // Flashing cycles is done
led_state.type = led_state.ptype;
led_set_state(led_state.type == LED_ST_CONST);
} else { // Turn led ON again, begin next flash cycle
led_state.time = millis();
led_set_state(1);
}
} else { // Just turn the led OFF
led_state.time = millis();
led_set_state(0);
}
}
// Update led flashing
if (led_state.type != LED_ST_FLASH && led_state.type != LED_ST_FAST_FLASH) {
if (calibration_mode)
led_set(LED_ST_FAST_FLASH, 4);
else {
// Update led lighting
if (lock_mode)
led_set(LED_ST_CONST, 0);
else
led_set(LED_ST_OFF, 0);
}
}
// If !paired
if (calibration_mode) {
for (int i = 0; i < 4; ++i) {
if (calibration.stmn[i] > sticks[i])
calibration.stmn[i] = sticks[i];
if (calibration.stmx[i] < sticks[i])
calibration.stmx[i] = sticks[i];
}
} else {
// Sending package with sticks
Package pack;
pack.type = PACKAGE_STICKS;
pack.data.sticks.sticks[0] = sticks[0];
pack.data.sticks.sticks[1] = sticks[1];
pack.data.sticks.sticks[2] = sticks[2];
pack.data.sticks.sticks[3] = sticks[3];
bool result = send_package((byte*) &pack, sizeof(Package));
if (!result) {
if (tx_dropped > TX_DROP_EDGE && led_state.type != LED_ST_FLASH && led_state.type != LED_ST_FAST_FLASH)
led_set(LED_ST_FLASH, 4);
#ifdef DEBUG_PRINT
Serial.println("TX failed");
#endif
}
}
}
int send_package(byte* pack, int size) {
if (!radio.write(pack, size)) {
++tx_dropped;
return 0;
} else {
byte payload;
if (radio.isAckPayloadAvailable()) {
radio.read(&payload, sizeof(byte));
tx_dropped = 0;
return 1;
}
++tx_dropped;
return 0;
}
};
void led_set_state(int state) {
if (led_state.state && !state) {
digitalWrite(STLED, 0);
led_state.state = !led_state.state;
} else if (!led_state.state && state) {
analogWrite(STLED, LED_POWER);
led_state.state = !led_state.state;
}
};
void led_set(int type, int count) {
if (type == LED_ST_CONST || type == LED_ST_OFF) {
led_set_state(type == LED_ST_CONST);
led_state.type = type;
} else {
// if was flashing --> rewrite
// if was constant --> move type to ptype & do flashing
if (led_state.type == LED_ST_CONST || led_state.type == LED_ST_OFF)
led_state.ptype = led_state.type;
led_state.type = type;
led_state.count = count;
led_state.time = millis();
led_set_state(1);
}
};
void btn_act(int number) {
buttons.acted[number] = 1;
};
// Override calls for button presses
void btn_action(int number, int lpress) {
#ifdef DEBUG_PRINT
Serial.print("Press for "); Serial.println(number);
#endif
switch(number) {
// calibration
case 0: {
// press = ?
// Lpress = calibration mode
if (lpress) {
if (calibration_mode && !lock_mode) {
// Write calibration values
byte* cal_struct = (byte*) &calibration;
for (int i = 0; i < sizeof(STICK_CALIBRATION); ++i)
EEPROM.write(i, cal_struct[i]);
calibration_mode = 0;
#ifdef DEBUG_PRINT
Serial.println("NEW CALIBRATION: ");
for (int i = 0; i < 4; ++i) {
Serial.print('(');
Serial.print(calibration.stmn[i]);
Serial.print(", ");
Serial.print(calibration.stmx[i]);
Serial.print(") ");
}
Serial.println();
#endif
} else {
for (int i = 0; i < 4; ++i) {
calibration.stmn[i] = 1024;
calibration.stmx[i] = 0;
}
calibration_mode = 1;
}
}
break;
}
case 1: {
// press = ?
// Lpress = lock mode
if (lpress) {
lock_mode = !lock_mode;
}
break;
}
}
led_set(LED_ST_FAST_FLASH, 2);
btn_act(number);
Package pack;
pack.type = PACKAGE_BUTTON;
pack.data.button.number = number;
pack.data.button.lpress = lpress;
bool result = send_package((byte*) &pack, sizeof(Package));
#ifdef DEBUG_PRINT
if (!result)
Serial.println("Button TX failed");
#endif
};
Source for receiver is:
// Flash for self-diy NRF24lo* receiver controller.
// 6 buttons, 4-way sticks.
#include <Servo.h>
#include <SPI.h>
#include "RF24.h"
#define DEBUG_PRINT
#ifdef DEBUG_PRINT
#include <printf.h>
#endif
// IO mappings
#define CONNECT_0 2
#define CONNECT_1 3
#define CONNECT_2 4
#define CONNECT_3 5
#define CONNECT_4 6
#define CONNECT_5 7
#define CONNECT_6 8
#define CONNECT_A0 A0
#define CONNECT_A1 A1
#define CONNECT_A2 A2
#define CONNECT_A3 A3
#define CONNECT_A4 A4
#define CONNECT_A5 A5
// A6, A7 on nano are only analog input
#define CONNECT_A6 A6
#define CONNECT_A7 A7
// Inverters for sticks
#define INVERT_STICK0 0
#define INVERT_STICK1 0
#define INVERT_STICK2 0
#define INVERT_STICK3 0
// Mappings for sticks
#define SERVO_MAP_STICK0 0, 180
#define SERVO_MAP_STICK1 0, 180
#define SERVO_MAP_STICK2 0, 180
#define SERVO_MAP_STICK3 60, 120
#define ANALOG_MAP_STICK0 0, 255
#define ANALOG_MAP_STICK1 0, 255
#define ANALOG_MAP_STICK2 0, 255
#define ANALOG_MAP_STICK3 0, 255
// Optional moddings
// Package types
#define PACKAGE_STICKS 3
#define PACKAGE_BUTTON 5
#define PACKAGE_PING 7
// Used to detect disconnect from the controller
#define CONNECTION_TIMEOUT 100
// Mpdes for output of the motor
// #define MODE_2_DIGITAL_1_ANALOG
#define MODE_2_ANALOG
// Receiver package struct.
// Contains type and values for button or values for sticks
struct Package {
int type;
union {
struct {
int number;
int lpress;
// Used to complete size of the package.
// Without it, payload is not sending for sticks.
int dummy[2];
} button;
struct {
int sticks[4];
} sticks;
} data;
};
// Describes state of a single buttons on controller
// Single press -> 1
// Second press -> 0
struct Button {
bool state;
bool lstate;
};
// Use NRF24lo1 transmitter on pins 7, 8
RF24 radio(9, 10);
byte addresses[][6] = { "TRAAA", "REEEE" };
// Used to detect timed disconnection from the controller
unsigned long last_receive_time;
bool disconnected;
// Servos mapped to sticks
Servo servo[4];
// Buttons states
Button buttons[6];
// Called on connection restored after drop
void on_connection();
// Called on connection dropped
void on_disconnection();
// Called on button state received
void button_action(int button, int lpress);
// Called on sticks state received
void sticks_action(int sticks[4]);
void setPWMNanofrequency(int freq) {
TCCR2B = TCCR2B & 0b11111000 | freq;
TCCR1B = TCCR1B & 0b11111000 | freq;
}
void setup() {
#ifdef DEBUG_PRINT
Serial.begin(115200);
#endif
// Set up receiver
radio.begin();
radio.setChannel(77);
//radio.setAutoAck(1);
//radio.setRetries(0, 8);
radio.enableAckPayload();
radio.setPALevel(RF24_PA_MAX);
//radio.setCRCLength(RF24_CRC_8);
radio.openWritingPipe(addresses[0]);
radio.openReadingPipe(1, addresses[1]);
#ifdef DEBUG_PRINT
// Debugger output
printf_begin();
radio.printDetails();
#endif
radio.startListening();
// Init buttons with 0
buttons[0] = { 0, 0 };
buttons[1] = { 0, 0 };
buttons[2] = { 0, 0 };
buttons[3] = { 0, 0 };
buttons[4] = { 0, 0 };
buttons[5] = { 0, 0 };
// Set up pinout
pinMode(CONNECT_0, OUTPUT);
pinMode(CONNECT_2, OUTPUT);
pinMode(CONNECT_3, OUTPUT);
pinMode(CONNECT_4, OUTPUT);
pinMode(CONNECT_5, OUTPUT);
pinMode(CONNECT_6, OUTPUT);
pinMode(CONNECT_A0, OUTPUT);
pinMode(CONNECT_A1, OUTPUT);
pinMode(CONNECT_A2, OUTPUT);
pinMode(CONNECT_A3, OUTPUT);
pinMode(CONNECT_A4, OUTPUT);
pinMode(CONNECT_A5, OUTPUT);
pinMode(CONNECT_A6, INPUT);
pinMode(CONNECT_A7, INPUT);
// setPWMNanofrequency(0x02);
// Set up servos
servo[0].attach(CONNECT_A4); // Remapped servos to leave three PWM pins
servo[1].attach(CONNECT_A5);
servo[2].attach(CONNECT_5);
servo[3].attach(CONNECT_6);
// Clear disconnect trigger
last_receive_time = millis();
disconnected = 0;
// Reset outputs
digitalWrite(CONNECT_0, LOW);
digitalWrite(CONNECT_2, LOW);
digitalWrite(CONNECT_3, LOW);
digitalWrite(CONNECT_4, LOW);
digitalWrite(CONNECT_5, LOW);
digitalWrite(CONNECT_6, LOW);
digitalWrite(CONNECT_A0, LOW);
digitalWrite(CONNECT_A1, LOW);
digitalWrite(CONNECT_A2, LOW);
digitalWrite(CONNECT_A3, LOW);
digitalWrite(CONNECT_A4, LOW);
digitalWrite(CONNECT_A5, LOW);
// digitalWrite(CONNECT_A6, LOW);
// digitalWrite(CONNECT_A7, LOW);
}
void loop() {
byte payload = 13;
radio.writeAckPayload(1, &payload, sizeof(byte));
if (radio.available()) {
Package pack;
radio.read((byte*) &pack, sizeof(Package));
// Update trigger
last_receive_time = millis();
if (disconnected)
on_connection();
disconnected = 0;
switch(pack.type) {
case PACKAGE_STICKS: {
#ifdef DEBUG_PRINT
Serial.print(pack.data.sticks.sticks[0]); Serial.print(' ');
Serial.print(pack.data.sticks.sticks[1]); Serial.print(' ');
Serial.print(pack.data.sticks.sticks[2]); Serial.print(' ');
Serial.print(pack.data.sticks.sticks[3]); Serial.println();
#endif
if (INVERT_STICK0) pack.data.sticks.sticks[0] = 1024 - pack.data.sticks.sticks[0];
if (INVERT_STICK1) pack.data.sticks.sticks[1] = 1024 - pack.data.sticks.sticks[1];
if (INVERT_STICK2) pack.data.sticks.sticks[2] = 1024 - pack.data.sticks.sticks[2];
if (INVERT_STICK3) pack.data.sticks.sticks[3] = 1024 - pack.data.sticks.sticks[3];
int ssticks[4];
ssticks[0] = map(pack.data.sticks.sticks[0], 0, 1023, SERVO_MAP_STICK0);
ssticks[1] = map(pack.data.sticks.sticks[1], 0, 1023, SERVO_MAP_STICK1);
ssticks[2] = map(pack.data.sticks.sticks[2], 0, 1023, SERVO_MAP_STICK2);
ssticks[3] = map(pack.data.sticks.sticks[3], 0, 1023, SERVO_MAP_STICK3);
int asticks[4];
asticks[0] = map(pack.data.sticks.sticks[0], 0, 1023, ANALOG_MAP_STICK0);
asticks[1] = map(pack.data.sticks.sticks[1], 0, 1023, ANALOG_MAP_STICK1);
asticks[2] = map(pack.data.sticks.sticks[2], 0, 1023, ANALOG_MAP_STICK2);
asticks[3] = map(pack.data.sticks.sticks[3], 0, 1023, ANALOG_MAP_STICK3);
#ifdef DEBUG_PRINT
Serial.print("Servo data: ");
Serial.print(ssticks[0]); Serial.print(' ');
Serial.print(ssticks[1]); Serial.print(' ');
Serial.print(ssticks[2]); Serial.print(' ');
Serial.print(ssticks[3]); Serial.println();
Serial.print("Analog data: ");
Serial.print(asticks[0]); Serial.print(' ');
Serial.print(asticks[1]); Serial.print(' ');
Serial.print(asticks[2]); Serial.print(' ');
Serial.print(asticks[3]); Serial.println();
#endif
sticks_action(pack.data.sticks.sticks, ssticks, asticks);
break;
}
case PACKAGE_BUTTON: {
#ifdef DEBUG_PRINT
Serial.print(pack.data.button.number); Serial.print(' ');
Serial.print(pack.data.button.lpress); Serial.println();
#endif
// Update states of the buttons
if (pack.data.button.lpress)
buttons[pack.data.button.number].lstate = !buttons[pack.data.button.number].lstate;
else
buttons[pack.data.button.number].state = !buttons[pack.data.button.number].state;
button_action(pack.data.button.number, pack.data.button.lpress);
break;
}
}
} else if (!disconnected && millis() - last_receive_time > CONNECTION_TIMEOUT) {
disconnected = 1;
on_disconnection();
}
}
void on_connection() {
};
void on_disconnection() {
// servo[0].write(0);
// servo[1].write(0);
// servo[2].write(0);
// servo[3].write(0);
// analogWrite(CONNECT_A0, 0);
// analogWrite(CONNECT_A1, 0);
// analogWrite(CONNECT_A2, 0);
// analogWrite(CONNECT_A3, 0);
#ifdef MODE_2_DIGITAL_1_ANALOG
digitalWrite(CONNECT_1, LOW);
digitalWrite(CONNECT_2, LOW);
digitalWrite(CONNECT_3, LOW);
#endif
#ifdef MODE_2_ANALOG
digitalWrite(CONNECT_3, LOW);
digitalWrite(CONNECT_4, LOW);
digitalWrite(CONNECT_0, LOW);
#endif
};
void button_action(int button, int lpress) {
switch (button) {
case 0:
case 1:
break;
case 2: {
digitalWrite(CONNECT_A0, buttons[button].state);
break;
}
case 3: {
digitalWrite(CONNECT_A1, buttons[button].state);
break;
}
case 4: {
digitalWrite(CONNECT_A2, buttons[button].state);
break;
}
case 5: {
digitalWrite(CONNECT_A3, buttons[button].state);
break;
}
}
};
void sticks_action(int sticks[4], int ssticks[4], int asticks[4]) {
servo[0].write(ssticks[0]);
servo[1].write(ssticks[1]);
servo[2].write(ssticks[2]);
servo[3].write(ssticks[3]);
// analogWrite(CONNECT_A0, asticks[0]);
// analogWrite(CONNECT_A1, asticks[1]);
// analogWrite(CONNECT_A2, asticks[2]);
// analogWrite(CONNECT_A3, asticks[3]);
// Control H-Bridge over 3, 4 outputs with right stick
int value = (sticks[2] > 500) ? (sticks[2] - 500) : (sticks[2] < 480) ? (480 - sticks[2]) : (0);
if (value < 500)
value = map(value, 0, 480, 0, 255);
else
value = map(value, 0, 1023 - 500, 0, 255);
value = (value > 255) ? 255 : (value < 0) ? 0 : value;
// connecting 2 digital pins as HIGH,LOW / LOW,HIGH and analog as speed value (used in bts79603 bridge)
#ifdef MODE_2_DIGITAL_1_ANALOG
if (sticks[2] > 500) {
digitalWrite(CONNECT_1, HIGH);
digitalWrite(CONNECT_2, LOW);
analogWrite(CONNECT_3, value);
} else if (sticks[2] < 480) {
digitalWrite(CONNECT_1, LOW);
digitalWrite(CONNECT_2, HIGH);
analogWrite(CONNECT_3, value);
} else {
digitalWrite(CONNECT_1, LOW);
digitalWrite(CONNECT_2, LOW);
analogWrite(CONNECT_3, 0);
}
#endif
// connecting 2 analog pins to simple H-Bridge
#ifdef MODE_2_ANALOG
analogWrite(CONNECT_3, sticks[2] > 500 ? value : 0);
analogWrite(CONNECT_4, sticks[2] < 480 ? value : 0);
analogWrite(CONNECT_0, sticks[2] > 500 || sticks[2] < 480);
#endif
};
Transmitter printDetails output:
STATUS = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1 = 0x4141415254 0x4545454552
RX_ADDR_P2-5 = 0xc3 0xc4 0xc5 0xc6
TX_ADDR = 0x4141415254
RX_PW_P0-6 = 0x20 0x20 0x00 0x00 0x00 0x00
EN_AA = 0x3f
EN_RXADDR = 0x03
RF_CH = 0x4d
RF_SETUP = 0x07
CONFIG = 0x0e
DYNPD/FEATURE = 0x00 0x00
Data Rate = 1MBPS
Model = nRF24L01+
CRC Length = 16 bits
PA Power = PA_MAX
Receiver printDetails output:
STATUS = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1 = 0x4545454552 0x4141415254
RX_ADDR_P2-5 = 0xc3 0xc4 0xc5 0xc6
TX_ADDR = 0x4545454552
RX_PW_P0-6 = 0x20 0x20 0x00 0x00 0x00 0x00
EN_AA = 0x3f
EN_RXADDR = 0x02
RF_CH = 0x4d
RF_SETUP = 0x07
CONFIG = 0x0e
DYNPD/FEATURE = 0x00 0x00
Data Rate = 1MBPS
Model = nRF24L01+
CRC Length = 16 bits
PA Power = PA_MAX
Code used
Following code on receiver caused IO break.
pinMode(CONNECT_A6, INPUT);
pinMode(CONNECT_A7, INPUT);
A6, A7 pins DOES NOT support mode change and this issue made NRF24 connection to fail.

LIS3DH accelerometer outputting null values when using Arduino

I'm using an Arduino Uno with an Adafruit Motor Shield (v2) in order to power and control a motor and a LIS3DH accelerometer. With a simpler code in which the motor just goes forward for a certain number of pulses (output by the encoder), the identical function for the accelerometer outputs correct values. The code is shown below.
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_LIS3DH.h>
#include <Adafruit_MotorShield.h>
#include <Adafruit_Sensor.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
#define pi 3.14159
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
float distance = 30;
Adafruit_LIS3DH lis = Adafruit_LIS3DH();
//
const byte encoder0pinA = 2;//A pin -> the interrupt pin 0
unsigned int pulsesperturn = 56 * 64 / 2 ;
float circumference = 5.25 * 3.14159;
int pulses;
//int count = 0;
#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
#define Serial SerialUSB
#endif
void setup(void) {
#ifndef ESP8266
while (!Serial); // will pause Zero, Leonardo, etc until serial console opens
#endif
Serial.begin(9600);
AFMS.begin();
Serial.println("LIS3DH test!");
if (! lis.begin(0x19)) { // change this to 0x19 for alternative i2c address
Serial.println("Couldnt start");
while (1);
}
Serial.println("LIS3DH found!");
lis.setRange(LIS3DH_RANGE_4_G); // 2, 4, 8 or 16 G!
//
}
void loop() {
// // }
// myMotor->setSpeed(255); // this will end up changing but is constant for testing validation purposes
// myMotor->run(FORWARD);
// delay(2500);
// myMotor->setSpeed(0);
// // right = 0;
// delay(1000);
// // right = 1;
// myMotor->run(BACKWARD);
// myMotor->setSpeed(255);
// delay(2500);
// myMotor->setSpeed(0);
// // right = 0;
// delay(1000);
// // right = 1;
myMotor->run(FORWARD);
myMotor->setSpeed(255); // this will end up changing but is constant for testing validation purposes
if (pulsesperturn <= pulses ) {
myMotor->run(RELEASE);
myMotor->run(RELEASE);
myMotor->setSpeed(0);
stoppedAccel();
pulses = 0;
}
// Then print out the raw data
// Serial.print("X: "); Serial.print(lis.x);
// Serial.print(" \tY: "); Serial.print(lis.y);
// Serial.print(" \tZ: "); Serial.print(lis.z);
// for (int a = 1; a < 20; a = a + 1) {
// lis.read(); // get X Y and Z data at once
// sensors_event_t event;
// lis.getEvent(&event);
//
// /* Display the results (acceleration is measured in m/s^2) */
// // Serial.print(" \tAngle: "); Serial.print(angle);
// //
// // Serial.print("\t\tX: "); Serial.print(event.acceleration.x);
// Serial.print(" \tY: "); Serial.print(event.acceleration.y);
// Serial.print(" \tZ: "); Serial.print(event.acceleration.z);
// // Serial.println(" m/s^2 ");
//
// Serial.println();
// //
// // char buffer[5];
// // Serial.print("#S|WRITEDATA|[");
// // Serial.print(angle); // accels
// // Serial.println("]#");
//
// // WriteAccel();
// delay(10);
// }
// myMotor->run(FORWARD);
//
// myMotor->run(RELEASE);
// myMotor->setSpeed(255);
// if (distance / circumference * pulsesperturn <= pulses) {
// myMotor->setSpeed(0);
// delay(2500);
// }
// myMotor->setSpeed(255);
// myMotor->run(FORWARD);
// pulses = 0;
Serial.print("pulses = ");
Serial.println(pulses);
attachInterrupt(digitalPinToInterrupt(encoder0pinA), counter, RISING);
/* Or....get a new sensor event, normalized */
}
void counter()
{
pulses++;
}
void stoppedAccel()
{
for (int a = 1; a < 150; a = a + 1) {
lis.read(); // get X Y and Z data at once
sensors_event_t event;
lis.getEvent(&event);
float angle = asin(event.acceleration.z / 9.81) * 180 / pi ;
Serial.print(" \tAngle: "); Serial.print(angle);
//
// Serial.print("\t\tX: "); Serial.print(event.acceleration.x);
// Serial.print(" \tY: "); Serial.print(event.acceleration.y);
// Serial.print(" \tZ: "); Serial.print(event.acceleration.z);
// Serial.println(" m/s^2 ");
Serial.println();
//
// char buffer[5];
// Serial.print("#S|WRITEDATA|[");
// Serial.print(angle); // accels
// Serial.println("]#");
delay(10);
}
}
In this code, which runs the motor forward for a distance 6 times and then runs it backward for the same distance it went forward, the motor runs correctly and the accelerometer says that it has been found but it outputs exclusively null values.
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
#include <SPI.h>
#include <Adafruit_LIS3DH.h>
#include <Adafruit_Sensor.h>
Adafruit_LIS3DH lis = Adafruit_LIS3DH();
//The sample code for driving one way motor encoder
const byte encoder0pinA = 2;//A pin -> the interrupt pin 0
//byte encoder0PinALast;
int duration;//the number of the pulses
//unsigned long timeold;
unsigned int pulsesperturn = 56 * 64 / 2;
float widthDetector = 10; //distance needed, in cm
float circumference = 5.25 * 3.14159;
float pulses;
int count = 0;
#define pi 3.14159
//bool answered = 0;
//float distanceTotal = 100;
//float waitTime = 0.01;
//unsigned int pulsesper100forward = 56 * 64 ;
//unsigned int pulsesper100back = 56 * 64 ;
int b = 0;
float conversion = 171 / 169;
#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
#define Serial SerialUSB
#endif
void setup(void)
{
#ifndef ESP8266
while (!Serial); // will pause Zero, Leonardo, etc until serial console opens
#endif
Serial.begin(9600);
AFMS.begin();
Serial.println("LIS3DH test!");
if (! lis.begin(0x19)) { // change this to 0x19 for alternative i2c address
Serial.println("Couldnt start");
while (1);
}
Serial.println("LIS3DH found!");
lis.setRange(LIS3DH_RANGE_4_G); // 2, 4, 8 or 16 G!
// myMotor->run(FORWARD);
myMotor->setSpeed(255); // this will end up changing but is constant for testing validation purposes
}
void loop() {
motorDirection();
}
void counter()
{
pulses++;
}
void bcounter()
{
b++;
}
void motorDirection()
{
while (b < 6) {
myMotor->run(FORWARD);
readInt();
if (500 * conversion <= pulses) {
myMotor->run(RELEASE);
myMotor->run(RELEASE);
pulses = 0;
bcounter();
if (b == 6) {
stoppedAccel();
}
delay(1500);
}
// break;
}
while (b == 6) {
myMotor->run(BACKWARD);
readInt();
if (500 * b <= pulses) {
myMotor->run(RELEASE);
myMotor->run(RELEASE);
bcounter();
stoppedAccel();
pulses = 0;
delay(500);
break;
}
}
while (b > 6) {
b = 0;
break;
}
}
// 169 forward per 1000, 171 backward
void stoppedAccel()
{
for (int a = 1; a < 150; a = a + 1) {
lis.read(); // get X Y and Z data at once
sensors_event_t event;
lis.getEvent(&event);
float angle = asin(event.acceleration.z / 9.81) * 180 / pi ;
Serial.print(" \tAngle: "); Serial.print(angle);
//
// Serial.print("\t\tX: "); Serial.print(event.acceleration.x);
// Serial.print(" \tY: "); Serial.print(event.acceleration.y);
// Serial.print(" \tZ: "); Serial.print(event.acceleration.z);
// Serial.println(" m/s^2 ");
Serial.println();
//
// char buffer[5];
// Serial.print("#S|WRITEDATA|[");
// Serial.print(angle); // accels
// Serial.println("]#");
delay(100);
}
}
void readInt()
{
attachInterrupt(digitalPinToInterrupt(encoder0pinA), counter, RISING);
Serial.print("pulses = ");
Serial.println(pulses);
}
I have tried various things but I have little background in CS, especially in C++, so my attempts haven't been fruitful. Any advice would be helpful.
The issue was using delay(). How exactly the hardware works, I'm not sure, but I believe blocking it in such a way threw off the hardware so that it was outputting null. Below is the corrected code using millis().
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
#include <SPI.h>
#include <Adafruit_LIS3DH.h>
#include <Adafruit_Sensor.h>
Adafruit_LIS3DH lis = Adafruit_LIS3DH();
//The sample code for driving one way motor encoder
const byte encoder0pinA = 2;//A pin -> the interrupt pin 0
//byte encoder0PinALast;
int duration;//the number of the pulses
//unsigned long timeold;
unsigned int pulsesperturn = 56 * 64 / 2;
float widthDetector = 10; //distance needed, in cm
float circumference = 5.25 * 3.14159;
float pulses;
int count = 0;
#define pi 3.14159
float angle;
const long interval = 1000;
unsigned long previousMillis;
//bool answered = 0;
//float distanceTotal = 100;
//float waitTime = 0.01;
//unsigned int pulsesper100forward = 56 * 64 ;
//unsigned int pulsesper100back = 56 * 64 ;
int b = 0;
float conversion = 171 / 169;
#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
#define Serial SerialUSB
#endif
void setup(void)
{
#ifndef ESP8266
while (!Serial); // will pause Zero, Leonardo, etc until serial console opens
#endif
Serial.begin(9600);
AFMS.begin();
Serial.println("LIS3DH test!");
if (! lis.begin(0x19)) { // change this to 0x19 for alternative i2c address
Serial.println("Couldnt start");
while (1);
}
Serial.println("LIS3DH found!");
lis.setRange(LIS3DH_RANGE_4_G); // 2, 4, 8 or 16 G!
// myMotor->run(FORWARD);
myMotor->setSpeed(255); // this will end up changing but is constant for testing validation purposes
}
void loop() {
motorDirection();
// stoppedAccel();
}
void counter()
{
pulses++;
}
void bcounter()
{
b++;
}
void motorDirection()
{
//serial.write
while (b < 6) {
myMotor->run(FORWARD);
readInt();
if (500 * conversion <= pulses) {
myMotor->run(RELEASE);
bcounter();
previousMillis = millis();
timing();
// previousMillis = currentMillis;
pulses = 0;
if (b == 6) {
stoppedAccel();
}
}
break;
}
while (b == 6) {
myMotor->run(BACKWARD);
readInt();
if (500 * b <= pulses) {
myMotor->run(RELEASE);
pulses = 0;
bcounter();
stoppedAccel();
break;
}
}
while (b > 6) {
b = 0;
break;
}
}
// 169 forward per 1000, 171 backward
void stoppedAccel()
{
for (int a = 1; a < 200; a = a + 1) {
lis.read(); // get X Y and Z data at once
sensors_event_t event;
lis.getEvent(&event);
angle = asin(event.acceleration.z / 9.81) * 180 / pi ;
Serial.print(" \tAngle: "); Serial.print(angle);
//
// Serial.print("\t\tX: "); Serial.print(event.acceleration.x);
// Serial.print(" \tY: "); Serial.print(event.acceleration.y);
// Serial.print(" \tZ: "); Serial.print(event.acceleration.z);
// Serial.println(" m/s^2 ");
Serial.println();
//
// char buffer[5];
// Serial.print("#S|WRITEDATA|[");
// Serial.print(angle); // accels
// Serial.println("]#");
delay(10);
}
}
void readInt()
{
attachInterrupt(digitalPinToInterrupt(encoder0pinA), counter, RISING);
Serial.print("pulses = ");
Serial.println(pulses);
}
void timing()
{
while (millis() - previousMillis <= interval) {
myMotor->run(RELEASE);
}
}

SD.h not compatible with other libraries in Arduino/C++ environment

I'm having some very weird issues using the following hardware elements:
Arduino Uno
Wi-Fi shield
GPS receiver
Accelerometer
Barometer
I wanted to off-load the sensor readings to an SD card as needed, but before I can even code the SD functions, the mere inclusion of the SD.h library renders my code useless.
My code is as follows:
#include <SoftwareSerial.h>
#include <TinyGPS.h>
#include <SD.h>
/* This sample code demonstrates the normal use of a TinyGPS object.
It requires the use of SoftwareSerial, and assumes that you have a
4800-baud serial GPS device hooked up on pins 3(rx) and 4(tx).
*/
//For baraometer
#include <Wire.h>
#define BMP085_ADDRESS 0x77 // I2C address of BMP085
const unsigned char OSS = 2; // Oversampling Setting
// Calibration values
int ac1;
int ac2;
int ac3;
unsigned int ac4;
unsigned int ac5;
unsigned int ac6;
int b1;
int b2;
int mb;
int mc;
int md;
// b5 is calculated in bmp085GetTemperature(...), this variable is also used in bmp085GetPressure(...)
// So ...Temperature(...) must be called before ...Pressure(...).
long b5;
//End of baraometer
//ACcelerometer
// These constants describe the pins. They won't change:
const int xpin = A1; // x-axis of the accelerometer
const int ypin = A2; // y-axis
const int zpin = A3; // z-axis (only on 3-axis models)
//end of accel
TinyGPS gps;
SoftwareSerial nss(3, 4);
static void gpsdump(TinyGPS &gps);
static bool feedgps();
static void print_float(float val, float invalid, int len, int prec);
static void print_int(unsigned long val, unsigned long invalid, int len);
static void print_date(TinyGPS &gps);
static void print_str(const char *str, int len);
void setup()
{
//Make sure the analog-to-digital converter takes its reference voltage from
// the AREF pin
analogReference(EXTERNAL);
pinMode(xpin, INPUT);
pinMode(ypin, INPUT);
pinMode(zpin, INPUT);
//Barometer
Wire.begin();
bmp085Calibration();
//GPS
Serial.begin(115200);
nss.begin(57600);
Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
Serial.println("by Mikal Hart");
Serial.println();
Serial.print("Sizeof(gpsobject) = "); Serial.println(sizeof(TinyGPS));
Serial.println();
Serial.println("Sats HDOP Latitude Longitude Fix Date Time Date Alt Course Speed Card Distance Course Card Chars Sentences Checksum");
Serial.println(" (deg) (deg) Age Age (m) --- from GPS ---- ---- to London ---- RX RX Fail");
Serial.println("--------------------------------------------------------------------------------------------------------------------------------------");
}
void loop()
{
//Accelerometer
Serial.print( analogRead(xpin));
Serial.print("\t");
//Add a small delay between pin readings. I read that you should
//do this but haven't tested the importance
delay(1);
Serial.print( analogRead(ypin));
Serial.print("\t");
//add a small delay between pin readings. I read that you should
//do this but haven't tested the importance
delay(1);
Serial.print( analogRead(zpin));
Serial.print("\n"); // delay before next reading:
bool newdata = false;
unsigned long start = millis();
// Every second we print an update
while (millis() - start < 1000)
{
if (feedgps())
newdata = true;
}
//barometer
float temperature = bmp085GetTemperature(bmp085ReadUT()); //MUST be called first
float pressure = bmp085GetPressure(bmp085ReadUP());
float atm = pressure / 101325; // "standard atmosphere"
float altitude = calcAltitude(pressure); //Uncompensated caculation - in Meters
Serial.print("Temperature: ");
Serial.print(temperature, 2); //display 2 decimal places
Serial.println(" C");
Serial.print("Pressure: ");
Serial.print(pressure, 0); //whole number only.
Serial.println(" Pa");
Serial.print("Standard Atmosphere: ");
Serial.println(atm, 4); //display 4 decimal places
Serial.print("Altitude: ");
Serial.print(altitude, 2); //display 2 decimal places
Serial.println(" M");
Serial.println();//line break
//end of barometer
gpsdump(gps);
}
static void gpsdump(TinyGPS &gps)
{
float flat, flon;
unsigned long age, date, time, chars = 0;
unsigned short sentences = 0, failed = 0;
static const float LONDON_LAT = 51.508131, LONDON_LON = -0.128002;
print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
gps.f_get_position(&flat, &flon, &age);
print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 9, 5);
print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 10, 5);
print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
print_date(gps);
print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 8, 2);
print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0UL : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : TinyGPS::course_to(flat, flon, 51.508131, -0.128002), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);
gps.stats(&chars, &sentences, &failed);
print_int(chars, 0xFFFFFFFF, 6);
print_int(sentences, 0xFFFFFFFF, 10);
print_int(failed, 0xFFFFFFFF, 9);
Serial.println();
}
static void print_int(unsigned long val, unsigned long invalid, int len)
{
char sz[32];
if (val == invalid)
strcpy(sz, "*******");
else
sprintf(sz, "%ld", val);
sz[len] = 0;
for (int i=strlen(sz); i<len; ++i)
sz[i] = ' ';
if (len > 0)
sz[len-1] = ' ';
Serial.print(sz);
feedgps();
}
static void print_float(float val, float invalid, int len, int prec)
{
char sz[32];
if (val == invalid)
{
strcpy(sz, "*******");
sz[len] = 0;
if (len > 0)
sz[len-1] = ' ';
for (int i=7; i<len; ++i)
sz[i] = ' ';
Serial.print(sz);
}
else
{
Serial.print(val, prec);
int vi = abs((int)val);
int flen = prec + (val < 0.0 ? 2 : 1);
flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
for (int i=flen; i<len; ++i)
Serial.print(" ");
}
feedgps();
}
static void print_date(TinyGPS &gps)
{
int year;
byte month, day, hour, minute, second, hundredths;
unsigned long age;
gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
if (age == TinyGPS::GPS_INVALID_AGE)
Serial.print("******* ******* ");
else
{
char sz[32];
sprintf(sz, "%02d/%02d/%02d %02d:%02d:%02d ",
month, day, year, hour, minute, second);
Serial.print(sz);
}
print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
feedgps();
}
static void print_str(const char *str, int len)
{
int slen = strlen(str);
for (int i=0; i<len; ++i)
Serial.print(i<slen ? str[i] : ' ');
feedgps();
}
static bool feedgps()
{
while (nss.available())
{
if (gps.encode(nss.read()))
return true;
}
return false;
}
// Stores all of the bmp085's calibration values into global variables
// Calibration values are required to calculate temp and pressure
// This function should be called at the beginning of the program
void bmp085Calibration()
{
Serial.write("\n\nCalibrating ... ");
ac1 = bmp085ReadInt(0xAA);
ac2 = bmp085ReadInt(0xAC);
ac3 = bmp085ReadInt(0xAE);
ac4 = bmp085ReadInt(0xB0);
ac5 = bmp085ReadInt(0xB2);
ac6 = bmp085ReadInt(0xB4);
b1 = bmp085ReadInt(0xB6);
b2 = bmp085ReadInt(0xB8);
mb = bmp085ReadInt(0xBA);
mc = bmp085ReadInt(0xBC);
md = bmp085ReadInt(0xBE);
Serial.write("Calibrated\n\n");
}
// Calculate temperature in deg C
float bmp085GetTemperature(unsigned int ut){
long x1, x2;
x1 = (((long)ut - (long)ac6)*(long)ac5) >> 15;
x2 = ((long)mc << 11)/(x1 + md);
b5 = x1 + x2;
float temp = ((b5 + 8)>>4);
temp = temp /10;
return temp;
}
// Calculate pressure given up
// calibration values must be known
// b5 is also required so bmp085GetTemperature(...) must be called first.
// Value returned will be pressure in units of Pa.
long bmp085GetPressure(unsigned long up){
long x1, x2, x3, b3, b6, p;
unsigned long b4, b7;
b6 = b5 - 4000;
// Calculate B3
x1 = (b2 * (b6 * b6)>>12)>>11;
x2 = (ac2 * b6)>>11;
x3 = x1 + x2;
b3 = (((((long)ac1)*4 + x3)<<OSS) + 2)>>2;
// Calculate B4
x1 = (ac3 * b6)>>13;
x2 = (b1 * ((b6 * b6)>>12))>>16;
x3 = ((x1 + x2) + 2)>>2;
b4 = (ac4 * (unsigned long)(x3 + 32768))>>15;
b7 = ((unsigned long)(up - b3) * (50000>>OSS));
if (b7 < 0x80000000)
p = (b7<<1)/b4;
else
p = (b7/b4)<<1;
x1 = (p>>8) * (p>>8);
x1 = (x1 * 3038)>>16;
x2 = (-7357 * p)>>16;
p += (x1 + x2 + 3791)>>4;
long temp = p;
return temp;
}
// Read 1 byte from the BMP085 at 'address'
char bmp085Read(byte address)
{
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(address);
Wire.endTransmission();
Wire.requestFrom(BMP085_ADDRESS, 1);
while(!Wire.available()) {};
return Wire.read();
}
// Read 2 bytes from the BMP085
// First byte will be from 'address'
// Second byte will be from 'address'+1
int bmp085ReadInt(byte address)
{
unsigned char msb, lsb;
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(address);
Wire.endTransmission();
Wire.requestFrom(BMP085_ADDRESS, 2);
while(Wire.available()<2)
;
msb = Wire.read();
lsb = Wire.read();
return (int) msb<<8 | lsb;
}
// Read the uncompensated temperature value
unsigned int bmp085ReadUT(){
unsigned int ut;
// Write 0x2E into Register 0xF4
// This requests a temperature reading
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write((byte)0xF4);
Wire.write((byte)0x2E);
Wire.endTransmission();
// Wait at least 4.5 ms
delay(5);
// Read two bytes from registers 0xF6 and 0xF7
ut = bmp085ReadInt(0xF6);
return ut;
}
// Read the uncompensated pressure value
unsigned long bmp085ReadUP(){
unsigned char msb, lsb, xlsb;
unsigned long up = 0;
// Write 0x34+(OSS<<6) into register 0xF4
// Request a pressure reading w/ oversampling setting
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(0xF4);
Wire.write(0x34 + (OSS<<6));
Wire.endTransmission();
// Wait for conversion, delay time dependent on OSS
delay(2 + (3<<OSS));
// Read register 0xF6 (MSB), 0xF7 (LSB), and 0xF8 (XLSB)
msb = bmp085Read(0xF6);
lsb = bmp085Read(0xF7);
xlsb = bmp085Read(0xF8);
up = (((unsigned long) msb << 16) | ((unsigned long) lsb << 8) | (unsigned long) xlsb) >> (8-OSS);
return up;
}
void writeRegister(int deviceAddress, byte address, byte val) {
Wire.beginTransmission(deviceAddress); // Start transmission to device
Wire.write(address); // Send register address
Wire.write(val); // Send value to write
Wire.endTransmission(); // End transmission
}
int readRegister(int deviceAddress, byte address){
int v;
Wire.beginTransmission(deviceAddress);
Wire.write(address); // Register to read
Wire.endTransmission();
Wire.requestFrom(deviceAddress, 1); // Read a byte
while(!Wire.available()) {
// waiting
}
v = Wire.read();
return v;
}
float calcAltitude(float pressure){
float A = pressure/101325;
float B = 1/5.25588;
float C = pow(A,B);
C = 1 - C;
C = C /0.0000225577;
return C;
}
Granted, right now, it is merely a conglomeration of multiple example sketches, but they work. I get a sampled reading from the accelerometer, the GPS unit and the barometer once a second. However once I simply add the line #include <SD.h> to the sketch, it fails to run correctly. The serial monitor does not display anything. I have similar versions of the above sketch (omitted as they are much lengthier), but I get the same result: either jumbled text or nothing on the Serial monitor. If I comment out the line that include the SD.h library, everything works fine....
Are there known issues with the SD.h library or conflicts? And yes, I am NOT using the necessary pins for the SD access (digital pin #4) for my sensor connections....
UPDATE:
I at least figured out it has something to do with the SoftSerial (SoftSerial.h) library and the use of the SoftSerial object (which I called nss). I can load all libraries and get everything to work if I do not call nss.begin. Is there a reason why that would conflict?
Turns out I was out of memory. Having the Serial go unresponsive like that is a common symptom. This link ultimately is what I used to trace and conclude my memory issue.
First thing would be to check the Arduino site, on the SD documentation (here) there's a mention that the communication between the microcontroller and the SD card uses SPI (documentation here) which takes place on digital pins 11, 12 and 13. I wouldn't be surprised if this was the source of your problems with the Serial monitor.
Reading some comments in Sd2Card.h, it might be tricky to get your setup to work properly:
/**
* Define MEGA_SOFT_SPI non-zero to use software SPI on Mega Arduinos.
* Pins used are SS 10, MOSI 11, MISO 12, and SCK 13.
*
* MEGA_SOFT_SPI allows an unmodified Adafruit GPS Shield to be used
* on Mega Arduinos. Software SPI works well with GPS Shield V1.1
* but many SD cards will fail with GPS Shield V1.0.
*/
Even if you put MEGA_SOFT_SPI to a non 0 value, you'd probably still fail to pass the (defined(__AVR_ATmega1280__)||defined(__AVR_ATmega2560__)) check.
I would suggest trying your same sketch without the TinyGPS to try to pinpoint the issue.
Also, check out this sketch it seems to be doing something similar to what you're doing, maybe you can fix yours based on what's done here.
Use pin 4 for CS and change the MOSI, MISO and SCK pins in the library SD in Sd2card.h, hope you will get rid of the problem