XIAO BLE with MAX30100 and BLE - arduino

When I run MAX30100 by itself on SEEED XIAO BLE SENSE module everything works fine. But when I add BLE into code, MAX30100 stops getting beats when BLE begins. I am guessing this is to do with pox.update() not updating in time. If someone has any idea what I can do please share. Thank you.
My code is here:
//MAX30100 BPM + SPO2 header
#include <MAX30100_PulseOximeter.h>
//BLE header
#include <Arduino.h>
#include <ArduinoBLE.h>
//Communication header
#include <Wire.h>
//MAX30100
PulseOximeter pox;
uint8_t hearty = 0;
uint8_t oxy = 0;
//MAX timer
unsigned long max_prev_millis = 0;
//BLE timer
unsigned long ble_prev_millis = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
if (!pox.begin()) Serial.println(F("MAX30100 error"));
else Serial.println(F("MAX30100 OK!"));
pox.setOnBeatDetectedCallback(onBeatDetected);
// setting the registers for the bluetooth transmit power
uint32_t *TXPOWER = (uint32_t *)0x4000150C;
*TXPOWER &= 0x0;
*TXPOWER |= 0x08;
uint32_t *MODE = (uint32_t *)0x40001510;
*MODE &= 0x0;
*MODE |= 0x05;
BLE.setLocalName("IT'S ME, BLE");
}
void loop() {
// put your main code here, to run repeatedly:
pox.update();
//Heart rate reading every 1 second
if (millis() - max_prev_millis >= 1000){
readMax30100();
}
//Bluetooth upload every 15 seconds
if (millis() - ble_prev_millis >= 15 * 1000) {
BLEUpload();
}
}
void readMax30100(){
hearty = pox.getHeartRate();
oxy = pox.getSpO2();
Serial.print(F("Heart rate:"));
Serial.print(hearty);
Serial.print(F("bpm / SpO2:"));
Serial.print(oxy);
Serial.println(F("%"));
max_prev_millis = millis();
}
void BLEUpload(){
BLE.begin();
BLE.stopAdvertise();
BLEAdvertisingData advData;
advData.setFlags(BLEFlagsBREDRNotSupported | BLEFlagsGeneralDiscoverable);
unsigned char send_data[2]
{
(unsigned char) (hearty),
(unsigned char) (oxy)
};
advData.setAdvertisedServiceData(0x2ACA, send_data, sizeof(send_data));
BLE.setAdvertisingData(advData);
BLE.advertise();
BLE.end();
ble_prev_millis = millis();
}
void onBeatDetected(){
Serial.println(F("Beat!"));
}

Related

How to Send Float/Double over SPI Arduino (SAMD21 Based Board)

I am trying to send a double/float over SPI from my SAMD21 based board, with chip select on pin A1/A2. I have copied some code from the internet, but I don't really understand it, plus it only works for sending data between two Arduino Unos. Here is my master:
#include <SPI.h>
float a = 3.14159;
float b = 2.252332;
uint8_t storage [12];
float buff[2] = {a, b};
void setup()
{
digitalWrite(SS, HIGH);
SPI.begin();
Serial.begin(9600);
SPI.setClockDivider(SPI_CLOCK_DIV8);
}
void loop()
{
digitalWrite(SS, LOW);
memcpy(storage, &buff, 8);
SPI.transfer(storage, sizeof storage ); //SPI library allows a user to
//transfer a whole array of bytes and you need to include the size of the
//array.
digitalWrite(SS, HIGH);
delay(1000);
}
And here is my slave:
#include <SPI.h>
byte storage [8];
volatile byte pos;
volatile boolean process;
float buff[2];
void setup()
{
pinMode(MISO,OUTPUT);
SPCR |= _BV(SPE);
SPCR |= _BV(SPIE);
pos = 0;
process = false;
Serial.begin(9600);
}
ISR(SPI_STC_vect)
{
byte gathered = SPDR;
if( pos < sizeof storage)
{
storage[pos++] = gathered;
}
else
process = true;
}
void loop()
{
if( process )
{
memcpy(buff,&storage,8);
Serial.print("This is val1:");Serial.println(buff[0], 5);
Serial.print("This is val2:");Serial.println(buff[1], 6);
storage[pos] = 0;
pos = 0;
process = false;
}
}
Any help would be aprreciated, and please understand that I am a newb in this subject.

Trying to send a float value over SPI between 2 Arduinos

I am currently trying to send a float value across two Arduinos via SPI. Currently I am working to send a static value of 2.25 across and then read it via the Serial.println() command. I would then want to pass a float value from a linear displacement sensor. My end goal is to be able to have the master ask for information, the slave gathers the appropriate data and packages it and then master receives said data and does what it needs with it.
Currently I am getting an error "call of overloaded 'println(byte [7])' is ambiguous" and I am not to sure why I am getting this error. I am currently a mechanical engineering student and I am crash-coursing myself through C/C++. I am not entirely positive about what I am doing. I know that a float is 4 bytes and I am attempting to create a buffer of 7 bytes to store the float and the '\n' char with room to spare. My current code is below.
Master:
#include <SPI.h>
void setup() {
pinMode(SS,OUTPUT);
digitalWrite(SS,HIGH);
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV4);
}
void loop() {
digitalWrite(SS,LOW);
float a = 2.25;
SPI.transfer(a);
SPI.transfer('\n');
digitalWrite(SS,HIGH);
}
My slave code is as follows:
#include <SPI.h>
byte buf[7];
volatile byte pos = 0;
volatile boolean process_it = false;
void setup() {
Serial.begin(9600);
pinMode(MISO,OUTPUT);
digitalWrite(MISO,LOW);
SPCR |= _BV(SPE); // SPI Enable, sets this Arduino to Slave
SPCR |= _BV(SPIE); // SPI interrupt enabled
}
ISR(SPI_STC_vect) {
// Interrupt Service Routine(SPI_(SPI Transfer Complete)_vector)
byte c = SPDR;
// SPDR = SPI Data Register, so you are saving the byte of information in that register to byte c
if (pos < sizeof buf) {
buf[pos++] = c;
if (c == '\n') {
process_it = true;
}
}
}
void loop() {
if (process_it = true) {
Serial.println(buf);
pos = 0;
process_it = false;
}
}
I figured out what I needed to do and I wanted to post my finished code. I also added an ability to transfer more than one float value.
Master:
#include <SPI.h>
float a = 3.14;
float b = 2.25;
uint8_t storage [12];
float buff[2] = {a, b};
void setup()
{
digitalWrite(SS, HIGH);
SPI.begin();
Serial.begin(9600);
SPI.setClockDivider(SPI_CLOCK_DIV8);
}
void loop()
{
digitalWrite(SS, LOW);
memcpy(storage, &buff, 8);
Serial.print("storage[0] = "); Serial.println(storage[0]); // the
following serial prints were to check i was getting the right decimal
numbers for the floats.
Serial.print("storage[1] = "); Serial.println(storage[1]);
Serial.print("storage[2] = "); Serial.println(storage[2]);
Serial.print("storage[3] = "); Serial.println(storage[3]);
Serial.print("storage[4] = "); Serial.println(storage[4]);
Serial.print("storage[5] = "); Serial.println(storage[5]);
Serial.print("storage[6] = "); Serial.println(storage[6]);
Serial.print("storage[7] = "); Serial.println(storage[7]);
SPI.transfer(storage, sizeof storage ); //SPI library allows a user to
transfer a whole array of bytes and you need to include the size of the
array.
digitalWrite(SS, HIGH);
delay(1000);
}
For my Slave code:
#include <SPI.h>
byte storage [8];
volatile byte pos;
volatile boolean process;
float buff[2];
void setup()
{
pinMode(MISO,OUTPUT);
SPCR |= _BV(SPE);
SPCR |= _BV(SPIE);
pos = 0;
process = false;
Serial.begin(9600);
}
ISR(SPI_STC_vect)
{
byte gathered = SPDR;
if( pos < sizeof storage)
{
storage[pos++] = gathered;
}
else
process = true;
}
void loop()
{
if( process )
{
Serial.print("storage[0] = "); Serial.println(storage[0]);
Serial.print("storage[1] = "); Serial.println(storage[1]);
Serial.print("storage[2] = "); Serial.println(storage[2]);
Serial.print("storage[3] = "); Serial.println(storage[3]);
Serial.print("storage[4] = "); Serial.println(storage[4]);
Serial.print("storage[5] = "); Serial.println(storage[5]);
Serial.print("storage[6] = "); Serial.println(storage[6]);
Serial.print("storage[7] = "); Serial.println(storage[7]);
memcpy(buff,&storage,8);
Serial.print("This is buff[0]");Serial.println(buff[0]);
Serial.print("This is buff[1]");Serial.println(buff[1]);
storage[pos] = 0;
pos = 0;
process = false;
}
}
The immediate problem is that Serial.print doesn't know what to do with a byte array. Either declare it as a char array or cast it in the print statement:
char buf[7];
OR
Serial.print((char*) buf);
Either way, though, it's not going to show up as a float like you want.
An easier way to do all this is to use memcpy or a union to go back and forth between float and bytes. On the master end:
uint8_t buf[4];
memcpy(buf, &a, 4);
Then use SPI to send 4 bytes. Reverse it on the peripheral end.
Note that sending '\n' as the termination byte is a bad idea because it can lead to weird behavior, since one of the bytes in the float could easily be 0x0a, the hexadecimal equivalent of '\n'.

microphone sph0645 with I2S less sensitive after watchdog sleep with Adafruit Feather M0

I am using the Adafruit Feather M0 RFM69 with the Adafruit I2S MEMS Microphone Breakout SPH0645. Every second I take a reading (sampleRate = 16000, bits per sample = 32) using the I2S library and send it over the radio. This all works fine.
My problem is that, when I want to save power, I am getting weird readings after I wake the board from sleep (using Adafruit_SleepyDog library). The microphone somewhat still works, although it is much less sensitive, only picks up loud sounds and also returns 60dB in a quiet room. When I don't put it to sleep, in the same sound setting, I get 40dB. However, if I put a delay of 250ms after waking up, the microphone works fine again, like before, but this is obviously not saving energy then.
I wonder why this is happening. Is there something I can do to get the microphone to work quicker? I checked the datasheet, but it only says: "When Vdd is applied the microphone senses the
CLOCK line, if the frequency is greater than 900KHz, the microphone enters the normal mode of operation." This should not even take a few ms though?
Thanks in advance
#include <I2S.h>
#include <Adafruit_SleepyDog.h>
#include <SPI.h>
#include <RH_RF69.h>
/************ Radio Setup ***************/
#define RF69_FREQ 433.0
#define SLEEP
//#if defined(ARDUINO_SAMD_FEATHER_M0) // Feather M0 w/Radio
#define RFM69_CS 8
#define RFM69_INT 3
#define RFM69_RST 4
#define LED 13
//#endif
// radio
// Singleton instance of the radio driver
RH_RF69 rf69(RFM69_CS, RFM69_INT);
int transmit_interval = 1000;
int time_counter = 0;
int packetnum = 0;
// MIC
#define SAMPLES 1024//2048 // make it a power of two for best DMA performance
int samples[SAMPLES];
int measurementsdB = 0;
int current_measure;
#define ADC_SOUND_REF 65
#define DB_SOUND_REF 41
int sampleRate1 = 16000;
int bitsPerSample1 = 32;
typedef struct
{
uint8_t measurementdB = 123;
uint8_t battery = 111;
uint8_t test = 222;
} RadioMessage;
RadioMessage struct_message;
void setup()
{
delay(2000); // Wait so its easier to program
Serial.begin(115200);
//while (!Serial) { delay(1); } // wait until serial console is open, remove if not tethered to computer
// Init Mic
if (!I2S.begin(I2S_PHILIPS_MODE, sampleRate1, bitsPerSample1)) {
while (1); // do nothing
}
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
pinMode(RFM69_RST, OUTPUT);
digitalWrite(RFM69_RST, LOW);
Serial.println("Feather RFM69 TX Test!");
Serial.println();
// manual reset
digitalWrite(RFM69_RST, HIGH);
delay(10);
digitalWrite(RFM69_RST, LOW);
delay(10);
if (!rf69.init()) {
Serial.println("RFM69 radio init failed");
while (1);
}
Serial.println("RFM69 radio init OK!");
// Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM (for low power module)
// No encryption
if (!rf69.setFrequency(RF69_FREQ)) {
Serial.println("setFrequency failed");
}
// If you are using a high power RF69 eg RFM69HW, you *must* set a Tx power with the
// ishighpowermodule flag set like this:
rf69.setTxPower(20, true); // range from 14-20 for power, 2nd arg must be true for 69HCW
// The encryption key has to be the same as the one in the server
uint8_t key[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
rf69.setEncryptionKey(key);
Serial.print("RFM69 radio #"); Serial.print((int)RF69_FREQ); Serial.println(" MHz");
//GCLK->GENCTRL.bit.RUNSTDBY=1; // !! can go
}
void loop() {
Serial.println("START");
///// MIC
//PM->APBCMASK.reg |= PM_APBCMASK_I2S;
int a = 0;
while (a == 0) a = I2S.available();
uint8_t current_measure = sample_audio_signal(samples);
///// RADIO
if (true)//((time_counter + transmit_interval) < millis())
{
struct_message.measurementdB = current_measure;
//struct_message.battery = measuredvbat;
// Send a message!
/*
Serial.print("Array content: ");
uint8_t* bla = (uint8_t*) &struct_message;
for (int i = 0; i < 3; i++)
{
Serial.println(bla[i]);
}*/
rf69.send((const uint8_t*) &struct_message, sizeof(struct_message));
rf69.waitPacketSent();
Serial.print("Wait for reply");
// Now wait for a reply
uint8_t buf[RH_RF69_MAX_MESSAGE_LEN];
uint8_t len = sizeof(buf);
if (rf69.waitAvailableTimeout(100)) {
// Should be a reply message for us now
if (rf69.recv(buf, &len)) {
Serial.print("Got a reply: ");
Serial.println((char*)buf);
} else {
Serial.println("Receive failed");
}
} else {
Serial.println("No reply, is another RFM69 listening?");
}
Serial.println("Radio sleeping");
rf69.sleep();
time_counter = millis();
}
// sleep time
#ifdef SLEEP
int sleepMS = Watchdog.sleep(10);
delay(250);
#else
delay(1000);
#endif
Serial.println("loop ended");
}
void Blink(byte PIN, byte DELAY_MS, byte loops) {
for (byte i=0; i<loops; i++) {
digitalWrite(PIN,HIGH);
delay(DELAY_MS);
digitalWrite(PIN,LOW);
delay(DELAY_MS);
}
}
float sample_audio_signal(int samples[])
{
for (int i=0; i<SAMPLES; i++) {
int sample = 0;
while ((sample == 0) || (sample == -1) ) {
sample = I2S.read();
}
// convert to 18 bit signed
sample >>= 14;
samples[i] = sample;
}
// ok we have the samples, get the mean (avg)
float meanval = 0;
for (int i=0; i<SAMPLES; i++) {
meanval += samples[i];
}
meanval /= SAMPLES;
// subtract it from all samples to get a 'normalized' output
for (int i=0; i<SAMPLES; i++) {
samples[i] -= meanval;
}
// find the 'peak to peak' max
float maxsample, minsample;
minsample = 100000;
maxsample = -100000;
for (int i=0; i<SAMPLES; i++) {
minsample = min(minsample, samples[i]);
maxsample = max(maxsample, samples[i]);
}
int newdB = 20 * log10((float)maxsample / (float)ADC_SOUND_REF) + DB_SOUND_REF;
return newdB;
Ok, the best I got it down to is 3.8mA. I only got so far by leaving the voltage regulator and the internal oscillator (DFLL) on during sleeping.
After adding the following code to my setup routine, when board goes to sleep, the microphone still works after waking up:
SYSCTRL->DFLLCTRL.bit.RUNSTDBY=1;
SYSCTRL->VREG.bit.RUNSTDBY=1;
However, ideally I would like to get much less than that, but then the mic doesn't work...

Simulating RSSI with Cheap RF Modules

My goal is to essentially spoof RSSI (Received Signal Strength Indicator) using a system of counting received packets. The idea is to have something where:
A specific number of packets is sent in a specific time from the transmitter.
Then are received at another unit and the number of packets received is counted.
The number in the counter of the receiver indicates the number of packets received at that time specific in the transmitter.
The fewer packages (counter value) that are received, the farther the sender will be.
I'm having a little trouble implementing the logic in my code however so I'd really appreciate the help. I am using Arduino Pro Mini 5V with NRF24L01+ radios and the RF24 Network library. My code is as follows:
Transmitter:
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>
#include <Wire.h>
RF24 radio(8,9);
RF24Network network(radio);
const uint16_t home_node = 00;
const uint16_t distant_node = 01;
struct payload_t { // Structure of our payload
byte ID;
};
void setup(void) {
Serial.begin(115200);
SPI.begin();
radio.begin();
network.begin(/*channel*/ 92, /*node address*/ distant_node);
}
void loop(void) {
byte ID = 1;
for (int i = 0; i < 50; i++)
{
payload_t payload = {ID};
RF24NetworkHeader header(/*to node*/ home_node);
bool ok = network.write(header,&payload,sizeof(payload));
if (ok)
Serial.println("ok.");
else
Serial.println("failed.");
delay (300);
}
delay(15000);
}
Receiver:
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>
#include <Wire.h>
RF24 radio(8,9);
RF24Network network(radio);
const uint16_t home_node = 00;
const uint16_t distant_node = 01;
struct payload_t {
byte ID;
};
//const unsigned long interval = 3000;
//unsigned long last_sent;
int count = 0;
void setup(void)
{
Serial.begin(115200);
SPI.begin();
radio.begin();
network.begin(/*channel*/ 92, /*node address*/ home_node);
}
void loop(void)
{
RF24NetworkHeader header;
payload_t payload;
network.update();
while ( network.available() ) { // Is there anything ready for us?
bool ok = network.read(header, &payload, sizeof(payload));
if (ok) // Non-blocking
{
count++;
Serial.println ("count=");
Serial.println (count);
}
else
Serial.println ("Failed");
}
}

serial output anomaly in atmega2560

I am facing a problem with atmega2560 serial outport port. When I connect AVRISPmkII programmer to atmega2560, all serial port gives output data at specified baud rate but when I disconnect programmer, there is no output but 1 second led blinks. I don't think that this is the code proble!m. I have not tried it with other programmer as that is all I have. The code is very simple anyway - blink led at 1 second and give output through RS232 port.
Voltage at reset pin is 5V and at sck is about 1.19V whether or not programmer is connected.
What is the problem here ?
The figure shows ISP and serial port circuits.
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include <string.h>
void USART0_init(void) /*************** USART 0 ***********************/
{
UCSR0A = 0x00;
UCSR0B = 0b00011000;
UCSR0C = 0b00000110;
UBRR0H = 0x00;
UBRR0L = 103; //baud rate: 9600, right - rx, tx, gnd - left
}
void USART0_putc(char data)
{
while(!(UCSR0A&0x20));
UDR0=data;
}
void USART0_puts(char* str){
while(*str) {USART0_putc(*str++);}
}
void USART1_init(void) /*************** USART 1 ***********************/
{
UCSR1A = 0x00;
UCSR1B = 0b10011000;
UCSR1C = 0b00000110;
UBRR1H = 0x00;
UBRR1L = 103; //baudrate: 9600
}
void USART1_putc(char data)
{
while(!(UCSR1A&0x20));
UDR1=data;
}
void USART1_puts(char* str){
while(*str) {USART1_putc(*str++);}
}
char t = 0;
char rx_buf1[50];
ISR(USART1_RX_vect)
{
cli();
t = UDR1;
rx_buf1[cnt1++] = t;
if (t == 0x0a){ // detect EOL \n FOR NOW
rx_buf1[cnt1] = '\0';
sprintf(out_buf1, "\r\nS1, ");
strcat(out_buf1, (const char*)rx_buf1);
sprintf(out_buf1, ", /");
USART0_puts(out_buf1);
cnt1 = 0;
rx_complete1 = 1;
}
if (cnt1 >= 50){
cnt1 = 0;
}
sei();
}
void timer_init(void)
{
cli();
TCCR1B = (1<<WGM12); //CTC mode
OCR1A = 1561; //100 ms
TIMSK1 |= (1<<OCIE1A);
TCCR1B |= (1<<CS12)|(0<<CS11)|(1<<CS10);
}
void dev_init(void)
{
DDRA = 0x0F;
PORTA = 0x00;
timer_init();
stdout = &uart0_str;
stderr = &uart1_str;
USART0_init();
USART1_init();
sei();
}
int main(void)
{
dev_init();
while(1)
{
process();
}
return 0;
}
volatile unsigned char tick_100ms;
char out_buf[100];
float speed = 4.3;
void process(void){
static unsigned char lc=1;
static uint8_t tick_cnt = 0;
if (tick_100ms){
tick_100ms = 0;
tick_cnt++;
if (tick_cnt == 10){
tick_cnt = 0;
PORTA = ~lc; /* this code is for blinking 4 LEDS */
lc = lc*2; /* very 1 seconds alternately*/
if (lc >8) lc = 1;
sprintf(out_buf, "S1, speed: %05.2f/\r\n", (double)speed);
USART0_puts(out_buf);
USART1_puts(out_buf);
}
}
}
I gave posted my code below.
The uart 1 interrupt code is not needed because there is no incoming data. Disabling them made no difference.

Resources