Skip to content

Instantly share code, notes, and snippets.

@bkutil
Created April 7, 2014 08:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bkutil/10016434 to your computer and use it in GitHub Desktop.
Save bkutil/10016434 to your computer and use it in GitHub Desktop.
Arduino sketch for duinode reporting voltage and temperature
#include <SPI.h>
#include <avr/sleep.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"
RF24 radio(8, 7);
int led = 3;
int temp = A2;
int voltage = A3;
int node_id = 1;
uint64_t addresses[3] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0E1LL, 0xF0F0F0F0A2LL };
const short sleep_cycles_per_transmission = 35;
volatile short sleep_cycles_remaining = sleep_cycles_per_transmission;
float readMCP9700(const int pin)
{
// http://ww1.microchip.com/downloads/en/AppNotes/01001a.pdf
int v = analogRead(pin);
float t = ( (v * 1.1 / 1024.0 ) - 0.5 ) * 100;
float t_e = 244e-6 * (125.0 - t) * (t - -40.0) + 2e-12 * (t - -40.0) - 2.0;
return t - t_e;
}
float readBatteryVoltage(const int pin)
{
int v = analogRead(pin);
return (v * 3.3 / 1024.0);
}
void setup_watchdog(uint8_t prescalar)
{
prescalar = min(9,prescalar);
uint8_t wdtcsr = prescalar & 7;
if ( prescalar & 8 )
wdtcsr |= _BV(WDP3);
MCUSR &= ~_BV(WDRF);
WDTCSR = _BV(WDCE) | _BV(WDE);
WDTCSR = _BV(WDCE) | wdtcsr | _BV(WDIE);
}
ISR(WDT_vect)
{
--sleep_cycles_remaining;
}
void do_sleep(void)
{
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_mode();
sleep_disable();
}
void setup() {
analogReference(INTERNAL);
Serial.begin(57600);
radio.begin();
radio.setRetries(15, 15);
radio.setPALevel(RF24_PA_MAX);
radio.setDataRate(RF24_1MBPS);
radio.setChannel(76);
radio.setPayloadSize(32);
radio.openWritingPipe(addresses[node_id]);
setup_watchdog(9);
}
void loop() {
double v, t;
char buf[32];
radio.powerUp();
v = readBatteryVoltage(voltage);
t = readMCP9700(temp);
snprintf(buf, 32, "N=%d;V=%d;T=%d", node_id, (int) (v * 100), (int) (t * 100));
Serial.println(buf);
radio.write(buf, 32);
radio.powerDown();
while (sleep_cycles_remaining) {
do_sleep();
}
sleep_cycles_remaining = sleep_cycles_per_transmission;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment