ESP32 serial communucation between 2 of them - c++

I'm trying to do a small project between which involves measuring temperature with an ESP32, send it through a serial connection to another ESP32, and make the latter write on the the Serial connection with my computer. I am using some LEDs for monitoring.
The code for the sender is:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "DHT.h"
#include <HardwareSerial.h>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set Global variables
/////////////////////////////////////////////////////////////////////////////////////
// set the LCD number of columns and rows
#define LED1 32
#define RXD2 16
#define TXD2 17
#define DHTPIN 33 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11
int lcdColumns = 16;
int lcdRows = 2;
LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows);
/////////////////////////////////////////////////////////////////////////////////////
// Serial Communication
HardwareSerial Sender(2); // use Sender
/////////////////////////////////////////////////////////////////////////////////////
DHT dht(DHTPIN, DHTTYPE);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Setup function
void setup() {
Wire.begin();
Sender.begin(19200,SERIAL_8N1, RXD2, TXD2);
lcd.init();
lcd.backlight();
lcd.print("Finished loading");
pinMode(LED1, OUTPUT);
dht.begin();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Loop function
void loop() {
float t1 = dht.readTemperature();
float h = dht.readHumidity();
Sender.print(String(t1));
lcd.setCursor(0,0);
lcd.print("Temp1(C): " + String(t1) + "\n");
lcd.setCursor(0,1);
lcd.print("Humid: " + String(h));
//lcd.print("Temp2(C): " + String(t2) + "\n");
digitalWrite(LED1, HIGH);
delay(200);
digitalWrite(LED1, LOW);
delay(200);
}
The code for the receiver is:
#include <HardwareSerial.h>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Set Global variables
/////////////////////////////////////////////////////////////////////////////////////
// set the Serial Port Data
#define RXD2 16
#define TXD2 17
HardwareSerial Receiver(2); // use Receiver
/////////////////////////////////////////////////////////////////////////////////////
// set other relevant variables
#define LED 33
String message;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Setup function
void setup() {
// Setup the Serial communication
Receiver.begin(19200,SERIAL_8N1, RXD2, TXD2);
// LED check
pinMode(LED,OUTPUT);
digitalWrite(LED, HIGH);
delay(200);
digitalWrite(LED,LOW);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Loop function
void loop() {
while(Receiver.available())
{
message = Receiver.read();
Serial.println("Message received: " + message);
digitalWrite(LED, HIGH);
delay(200);
digitalWrite(LED,LOW);
delay(200);
}
}
I checked that the sensor is correctly measuring and changing, but the receiver is not receiving correctly the information, or at least it isn't able to send it to the Serial connection.

By initializing the communication with the computer with another HardwareSerial instance instead of the default Serial instance the message was sent.

Related

How to control a linear actuator with an ESP32 and a BME280 sensor

I'm trying to program an EPS32 board to open and close a linear actuator depending of the temperature a BME 280 sensor gets. It is for an automated gardening project :)
My code is functional but I would like to perfect it.
The actuator is currently connected with two GPIO pin, one to open and he other to close.
GOALS:
Switch off relays when not used.
Replace the use of delay() with millis()
Currently, the actuator is opening when temperature is above 27c°. Relay is on for 7 seconds which let the time to the actuator to go full course. Then, the relay is switch off.
But if the temperature stay above 27, the "if" part of the loop is going on an on, meaning it turn on for 7 seconds, switch off for 7 seconds and so on... I would like to switch all relays off when not needed to save energy and extend components life.
I suppose there might be something to do with && or even the analogRead() function to get the state of the actuator and apply actions from that but it is too complicated for me.
To open the actuator, I decided to time the course of the actuator and let the relay on for that timing with a delay() function. There is probably a different approach to this ( with analogRead() I suppose) but I find it simple and working. I would like to replace delay() with millis() function in order not to block the rest of the script (I plan to add fans, water valves, a float switch sensor...).
May you show me the way ?
#include <Adafruit_BME280.h>
#include <WiFi.h>
const char* ssid = "#####"; // ESP32 and ESP8266 uses 2.4GHZ wifi only
const char* password = "#####";
//MQTT Setup Start
#include <PubSubClient.h>
#define mqtt_server "####.###.##.##"
WiFiClient espClient;
PubSubClient client(espClient);
#define mqttActuator "growShed/Acuator"
#define mqttTemp1 "growShed/temp1"
int actuatorUp = 15; //GPIO de l'actuator
int actuatorDown = 2; //GPIO de l'actuator
int actuatorUpread = (!digitalRead(actuatorUp)); //read state of gpio : on or off
int actuatorDownread = (!digitalRead(actuatorDown)); //read state of gpio : on or off
//MQTT Setup End
Adafruit_BME280 bme1; // I2C
//utiliser les virgules sur les capteurs suivants
float temp1, hum1, pres1;
//gestion des délais entre chaque captations de data
unsigned long millisNow1 = 0; //for delay purposes (laisser 0)
unsigned int sendDelay1 = 2000; //delay before sending sensor info via MQTT
//gestion des délais entre chaque captations de data
unsigned long millisNow3 = 0; //for delay purposes (laisser 0)
unsigned int sendDelay3 = 7000; //delay before sending sensor info via MQTT
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
// begin Wifi connect
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(2000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address (wifi RaspPi) : ");
Serial.println(WiFi.localIP());
//end Wifi connect
client.setServer(mqtt_server, 1883);
//BME
delay(5000);
unsigned status;
status = bme1.begin(0x76);
if (!status) {
Serial.println("Could not find a valid BME280 sensor, check wiring, address, sensor ID!");
Serial.print("SensorID was: 0x"); Serial.println(bme1.sensorID(),16);
Serial.print(" ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n");
Serial.print(" ID of 0x56-0x58 represents a BMP 280,\n");
Serial.print(" ID of 0x60 represents a BME 280.\n");
Serial.print(" ID of 0x61 represents a BME 680.\n");
while (1);
}
//Acuator
pinMode(actuatorUp, OUTPUT);
digitalWrite(actuatorDown, HIGH); //Begin with actuator switched off
pinMode(actuatorDown, OUTPUT);
digitalWrite(actuatorUp, HIGH); //Begin with actuator switched off
//End Actuator
}
bool getValues() {
temp1 = round(bme1.readTemperature()); //rounded values
actuatorUpread = (digitalRead(actuatorUp)); //inverted value as the relay is inverted
Serial.print("BME 1 Temperature = ");
Serial.print(temp1);
Serial.println(" °C");
Serial.print("État de l'actuator haut = ");
Serial.println(actuatorUpread);
Serial.print("État de l'actuator bas = ");
Serial.print(actuatorDownread);
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
int counter = 0;
while (!client.connected()) {
if (counter==5){
ESP.restart();
}
counter+=1;
Serial.println("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("growTentController")) {
Serial.println("connected");
} else {
Serial.println("failed, rc=");
Serial.println(client.state());
Serial.println(" try again in 5 seconds");
// Wait 10 seconds before retrying
delay(5000);
}
}
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()){
reconnect();
}
if (millis() > millisNow1 + sendDelay1){
if (getValues()) {
client.publish(mqttTemp1, String(temp1).c_str(),true);
client.publish(mqttActuator, String(actuatorUpread).c_str(),true);
millisNow1 = millis();
}
}
//Acuator moving according to BME280 temperature sensor
temp1 = bme1.readTemperature();
if (millis() > millisNow3 + sendDelay3){
if ((temp1 > 27)){
digitalWrite(actuatorUp, LOW);
delay(7000); // approx the time it take to execute the full course of the acuator.
digitalWrite(actuatorUp, HIGH);
}
else {
digitalWrite(actuatorDown, LOW);
delay(7000); // approx the time it take to execute the full course of the acuator
digitalWrite(actuatorDown, HIGH);
}
millisNow3 = millis();
}
}
I think this is what you want to do. This uses a state variable to keep track of what state the actuator is in.
When the actuator is closed, the loop will check the temperature and, if the temperature goes above 27 degrees, it will start opening the actuator. Then the loop will simply monitor the time using millis() until the actuator is open - so you can put other code in the loop for other sensors.
The same happens if the actuator is open, it will close the actuator when the temperature is lower than 26 degrees (kept a degree difference here to stop the code constantly triggering if the temperature hovers around 27 degrees).
Currently this will read the temperature on every iteration of the loop whilst the actuator is either open or closed - so I've put a small delay at the end of the loop to restrict this.
Please note - I have not tested any of the changes in the code as I don't have the hardware to hand. But it compiles, and should give you an idea of how you can use a state model with millis() to handle this sort of thing without delaying the loop.
#include <Adafruit_BME280.h>
#include <WiFi.h>
const char* ssid = "#####"; // ESP32 and ESP8266 uses 2.4GHZ wifi only
const char* password = "#####";
//MQTT Setup Start
#include <PubSubClient.h>
#define mqtt_server "####.###.##.##"
WiFiClient espClient;
PubSubClient client(espClient);
#define mqttActuator "growShed/Acuator"
#define mqttTemp1 "growShed/temp1"
int actuatorUp = 15; //GPIO de l'actuator
int actuatorDown = 2; //GPIO de l'actuator
int actuatorUpread = (!digitalRead(actuatorUp)); //read state of gpio : on or off
int actuatorDownread = (!digitalRead(actuatorDown)); //read state of gpio : on or off
//MQTT Setup End
Adafruit_BME280 bme1; // I2C
//utiliser les virgules sur les capteurs suivants
float temp1, hum1, pres1;
//gestion des délais entre chaque captations de data
unsigned long millisNow1 = 0; //for delay purposes (laisser 0)
unsigned int sendDelay1 = 2000; //delay before sending sensor info via MQTT
//gestion des délais entre chaque captations de data
unsigned long millisNow3 = 0; //for delay purposes (laisser 0)
unsigned int sendDelay3 = 7000; //delay before sending sensor info via MQTT
// The states the actuator can be in.
enum ActuatorState
{
OPENING,
OPEN,
CLOSING,
CLOSED
};
ActuatorState actuatorState;
// When opening or closing the actuator - this is the time to stop.
unsigned long actuatorEndTime = 0 ;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
// begin Wifi connect
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(2000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address (wifi RaspPi) : ");
Serial.println(WiFi.localIP());
//end Wifi connect
client.setServer(mqtt_server, 1883);
//BME
delay(5000);
unsigned status;
status = bme1.begin(0x76);
if (!status) {
Serial.println("Could not find a valid BME280 sensor, check wiring, address, sensor ID!");
Serial.print("SensorID was: 0x"); Serial.println(bme1.sensorID(),16);
Serial.print(" ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n");
Serial.print(" ID of 0x56-0x58 represents a BMP 280,\n");
Serial.print(" ID of 0x60 represents a BME 280.\n");
Serial.print(" ID of 0x61 represents a BME 680.\n");
while (1);
}
//Acuator
pinMode(actuatorUp, OUTPUT);
digitalWrite(actuatorDown, HIGH); //Begin with actuator switched off
pinMode(actuatorDown, OUTPUT);
digitalWrite(actuatorUp, HIGH); //Begin with actuator switched off
actuatorState = CLOSED ;
//End Actuator
}
bool getValues() {
temp1 = round(bme1.readTemperature()); //rounded values
actuatorUpread = (digitalRead(actuatorUp)); //inverted value as the relay is inverted
Serial.print("BME 1 Temperature = ");
Serial.print(temp1);
Serial.println(" °C");
Serial.print("État de l'actuator haut = ");
Serial.println(actuatorUpread);
Serial.print("État de l'actuator bas = ");
Serial.print(actuatorDownread);
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
int counter = 0;
while (!client.connected()) {
if (counter==5){
ESP.restart();
}
counter+=1;
Serial.println("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("growTentController")) {
Serial.println("connected");
} else {
Serial.println("failed, rc=");
Serial.println(client.state());
Serial.println(" try again in 5 seconds");
// Wait 10 seconds before retrying
delay(5000);
}
}
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()){
reconnect();
}
if (millis() > millisNow1 + sendDelay1){
if (getValues()) {
client.publish(mqttTemp1, String(temp1).c_str(),true);
client.publish(mqttActuator, String(actuatorUpread).c_str(),true);
millisNow1 = millis();
}
}
//Acuator moving according to BME280 temperature sensor
switch ( actuatorState ) {
case OPEN:
// Does it need closing (use value lower than 27 so we're not constantly opening and
// closing the actuator if the temperature is floating around 27)
temp1 = bme1.readTemperature();
if ( temp1 < 26 ) {
digitalWrite(actuatorDown, LOW);
actuatorState = CLOSING;
actuatorEndTime = millis() + 7000 ;
}
break;
case CLOSED:
// Does it need opening?
temp1 = bme1.readTemperature();
if ( temp1 > 27 ) {
digitalWrite(actuatorUp, LOW);
actuatorState = OPENING;
actuatorEndTime = millis() + 7000;
}
break ;
case OPENING:
// Is it fully open?
if ( millis() >= actuatorEndTime ) {
digitalWrite(actuatorUp, HIGH);
actuatorState = OPEN ;
}
break ;
case CLOSING:
// Is it fully closed?
if ( millis() >= actuatorEndTime ) {
digitalWrite(actuatorDown, HIGH);
actuatorState = CLOSED ;
}
break ;
}
// small delay to run the loop - and do the temperature check 5 times per second.
delay(200);
}

NRF24L01 modules not connecting - hardware or coding issue?

I am trying to transmit data from an ultrasonic sensor to an LCD screen using two NRF24L01 modules connected to two separate Arduino UNOs for a distance sensor for a bike. As I am relatively new to Arduino and initially did not know how to use the NRF24L01 module, I followed a tutorial from https://www.electroniclinic.com/nrf24l01-multiple-transmitters-and-single-receiver-for-sensor-monitoring-using-arduino/
, implemented it into my code, and it is not working. I ensured on multiple occasions that the wiring for the NRF24L01 is correct for the Arduino UNOs and attempted to change radio channels, and no use. For others from the website it appeared to be working, but for me it is not. Both programs compile just fine. Is there an issue with my code or is it possible that my NRF24L01 is nonfunctional?
Here is my code:
Transmitter:
#include <RF24Network.h>
#include <RF24Network_config.h>
#include <Sync.h>
#include <RF24.h>
#include <SPI.h>
RF24 radio(5, 4); // radio module, pins 5,4 for (CE, CSN)
RF24Network network(radio);
const uint16_t this_node = 01; //address of arduino
const uint16_t node00 = 00;
//setting up pins for each device
const int buzzerPin = 10;
const int aheadTrigPin = 9;
const int aheadEchoPin = 8;
//initialize variables for ultrasonic sensor and data
unsigned long data[3];
unsigned long aheadDistance;
unsigned long aheadDuration;
void setup() {
Serial.begin(9600);
SPI.begin();
radio.begin();
network.begin(69, this_node);
radio.setDataRate(RF24_2MBPS);
pinMode(buzzerPin, OUTPUT);
pinMode(aheadTrigPin, OUTPUT);
pinMode(aheadEchoPin, INPUT);
}
void loop() {
//clears the "trig" condition for ultrasonic sensor
digitalWrite(aheadTrigPin, LOW);
delayMicroseconds(2);
//releases sound waves from ultrasonic sensor for 10 microseconds
digitalWrite(aheadTrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(aheadTrigPin, LOW);
//reads "echo" pin to return sound wave travel time in microseconds
aheadDuration = pulseIn(aheadEchoPin, HIGH);
//calculating distance of ultrasonic sensor, in inches (distance = velocity * time)
aheadDistance = (aheadDuration * 0.034 / 2) * 2.54;
Serial.println(aheadDistance);
//activates buzzer to alert rider if danger values are met
if(aheadDistance <= 100) {
tone(buzzerPin, 255);
}
else {
noTone(buzzerPin);
}
//send data to main component
network.update();
data[0] = aheadDistance;
RF24NetworkHeader header(node00);
bool ok = network.write(header, &data, sizeof(data)); // send data
Serial.println("sent to NRF24 server");
delay(200);
}
The reason I am sending an array as the data is because I am currently working on having another transmitter to send data to a single receiver.
Receiver:
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <RF24Network.h>
#include <RF24Network_config.h>
#include <Sync.h>
#include <RF24.h>
#include <SPI.h>
//sets up timer for the LCD display to constantly run
//sets up OLED screen
LiquidCrystal_I2C display(0x27,20,4);
RF24 radio (10, 9); // CE, CSN, defines new RF24 radio
RF24Network network(radio);
const uint64_t this_node = 00;
//data variables that will be collected from other arduinos
unsigned long data[3];
unsigned long aheadDistance;
unsigned long groundDistance;
unsigned long backAheadDistance;
void setup()
{
Serial.begin(9600);
display.init(); // intialize lcd
display.backlight(); //open backlight of lcd
display.clear();
//initialize starting screen
display.setCursor(0, 0);
//set up radio module (reciever)
SPI.begin();
radio.begin();
network.begin(69, this_node);
radio.setDataRate(RF24_2MBPS);
}
//method to update screen with current data values
void displayDistance() {
display.setCursor(0, 0);
display.print("Bike Sensor");
display.setCursor(0, 1);
display.print("Front: ");
display.print(aheadDistance);
display.print(" in");
display.setCursor(0, 2);
display.print("Ground: ");
display.print(groundDistance);
display.print(" in");
display.setCursor(0, 3);
display.print("Back: ");
display.print(backAheadDistance);
display.print(" in");
display.display();
}
void connectionLost() // activates when main component is unable to connect to others
{
display.clear();
display.setCursor(0, 1);
display.print("Connection");
display.setCursor(0, 2);
display.print("Lost");
display.display();
}
void loop()
{
network.update();
while(network.available()) {
RF24NetworkHeader header;
Serial.println("connection found");
network.read(header, &data, sizeof(data));
Serial.println("data recieved");
if(header.from_node == 01) {
backAheadDistance = data[0];
}
if(header.from_node == 02) {
aheadDistance = data[1];
groundDistance = data[2];
}
displayDistance();
delay(100);
}
connectionLost();
Serial.println("no connection found");
delay(200);
}
//updates OLED screen and actually displays it on the module
It’s possible that your nRF24L01 is dead. I’ve had many. Some fail. I recommend those from EByte especially ML01DP5 and ML01SP4. These are good.
Also there’s a little known hardware issue: never let the FIFO buffers remain full for over 4ms. Of course it’s hard to know. So simply flush them often as a precaution. I have fixed my code this way and now it’s robust.
Good luck!
Malcolm

Set up loop keeps looping (Adurino)

I am currently troubleshooting a code in Arduino for a temperature and humidity project. There is a line in the void setup(), Serial.println("Feather LoRa TX Test!");, which keeps popping up. My ideal code is to run that particular line once in the output and that will be it. However, the current code keeps repeating that line again, and again. May I know how do I rectify this issue (The whole code is below)? Thanks in advance!!
#include <RH_RF95.h>
#include <DHT.h>
#define DHTPIN 7 // what digital pin we're connected to
#define DHTTYPE DHT22 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
#define RFM95_CS 10
#define RFM95_RST 9
#define RFM95_INT 3
// Change to 434.0 or other frequency, must match RX's freq!
#define RF95_FREQ 915.0
// Singleton instance of the radio driver
RH_RF95 rf95(RFM95_CS, RFM95_INT);
int node = 3; // to change based on node deployment
void setup()
{
pinMode(RFM95_RST, OUTPUT);
digitalWrite(RFM95_RST, HIGH);
while (!Serial);
Serial.begin(9600);
delay(100);
Serial.println("Feather LoRa TX Test!");
digitalWrite(RFM95_RST, LOW);
delay(100);
digitalWrite(RFM95_RST, HIGH);
delay(100);
while (!rf95.init()) {
Serial.println("LoRa radio init failed");
while (1);
}
Serial.println("LoRa radio init OK!");
// Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM
if (!rf95.setFrequency(RF95_FREQ)) {
Serial.println("setFrequency failed");
while (1);
}
Serial.print("Set Freq to: "); Serial.println(RF95_FREQ);
dht.begin();
rf95.setTxPower(23, false);
}
void loop()
{
float t = dht.readTemperature();
float h = dht.readHumidity();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
delay(1000);
return;
}
String d = "{\"Node\":"+ String (node) +",";
d += "\"Temp\":"+ String (t)+",";
d += "\"Hum\":"+ String (h);
d += "} "; // Add a trailing space is necessary
Serial.println("Transmitting...");
char data[d.length()];
d.toCharArray(data,d.length());
Serial.println(d);
rf95.send((uint8_t*)data, sizeof(data));
Serial.println("Waiting for packet to complete...");
delay(1000);
rf95.waitPacketSent();
Serial.println(" complete...");
delay(57000); // delay 1 minute
}
You have an infinite loop before you do any initialization. This will be detected because Arduino have a watchdog timer, and the system will reset.
And on reset setup is called again, and you again enter the infinite loop.
The loop it's about:
while (!Serial);
You must call Serial.begin(...) before that loop:
Serial.begin(9600);
while (!Serial);
Something is resetting your MCU before the code reaches the loop function. Therefore the setup function gets executed again and again. You can add more print messages in between lines so you'll know where it breaks.

Read Received via SPI data with arduino mega

There
I am working on one of the project, in that i am trying to read 16-bit data from ADS8681. Currently i get the correct waveform of SCk,MISO,MOSI and SCK on oscilloscope. But I am not able to print data on alphanumeric LCD. With readRegister(long thisRegister, long bytesToRead) also unable to print data. Can anyone suggest me how i print received data?
References which i am using:
1] https://www.arduino.cc/en/Tutorial/LibraryExamples/BarometricPressureSensor#code
Source Code :
#include <SPI.h>
#include <LiquidCrystal.h>
#define SS 53 // CS/CONVST
LiquidCrystal lcd (38,37,36,35,34,33);
void setup()
{
lcd.begin(16,4);
SPI.begin();
digitalWrite(SS,OUTPUT);
digitalWrite(SS, HIGH);
delay(10);
digitalWrite(SS,LOW);
writeRegister(0x14, 0x0001); //Write data range selection
digitalWrite(SS, HIGH);
delay(10);
digitalWrite(SS,LOW);
writeRegister(0x10, 0x4100); //Write Data_OUT_CTRL
lcd.setCursor(0,0);
lcd.print ("Data");
}
void loop()
{
digitalWrite(SS, HIGH);
delay(10);
digitalWrite(SS,LOW);
writeRegister(0x14, 0x0001); //Write data range selection
delay(100);
}
void readRegister(long thisRegister, long bytesToRead)
{
}
void writeRegister(word thisRegister, word thisValue)
{
}

Entering multiple SPI interfaces

I am having a problem with my code for arduino m0 (using microchip SAMD21). There are two SPI interfaces, first classic and second with int variable in front of the pin name, int MISO, for instance. Does someone know, how to control this classic SPI interface?
I have also attached my code.
PS: Code stucks in begin function of OZONE2CLICK sensor...
#include "Arduino.h"
#include <MQ131.h>
// include RFM69 library
#include <SPI.h>
// Local
#define PC_BAUDRATE 56700
#define MS_DELAY 0 // Number of milliseconds between data sending and LED signalization
#define LED_DELAY 100
#define Serial SerialUSB
// SD card
#define sd_cs_pin 35 // set SD's chip select pin (according to the circuit)
float PPMO2;
float PPBO2;
float MGM3O2;
float UGM3O2;
const byte pinSS = 2; //cs pin
const byte pinRDY = 12;
const byte pinSCK = 13;
const byte O2Pin = 10;
#define DcPin 8
// SD card file
File file; // SD library variable
// LEDS
#define D13_led_pin 42 // D13 LED
#define M_led_pin 36 // MLED
// Local variables
int idCounter = 1;
bool isBmeOk = true;
bool isSdOk = true;
bool isRadioOk = true;
bool isGpsConnected = true;
void OZONE2CLICKCalibrate ()
{
Serial.println("2");
//MQ131.begin(pinSS, pinRDY, O2Pin, LOW_CONCENTRATION, 10000); //(int _pinCS, int _pinRDY, int _pinPower, MQ131Model _model, int _RL)
Serial.println("99");
Serial.println("Calibration in progress...");
MQ131.calibrate();
Serial.println("Calibration done!");
Serial.print("R0 = ");
Serial.print(MQ131.getR0());
Serial.println(" Ohms");
Serial.print("Time to heat = ");
Serial.print(MQ131.getTimeToRead());
Serial.println(" s");
}
void OZONE2CLICKMeasure ()
{
Serial.println("Sampling...");
MQ131.sample();
Serial.print("Concentration O3 : ");
PPMO2 = MQ131.getO3(PPM);
Serial.print(PPMO2);
Serial.println(" ppm");
Serial.print("Concentration O3 : ");
PPBO2 = MQ131.getO3(PPB);
Serial.print(PPBO2);
Serial.println(" ppb");
Serial.print("Concentration O3 : ");
MGM3O2 = MQ131.getO3(MG_M3);
Serial.print(MGM3O2);
Serial.println(" mg/m3");
Serial.print("Concentration O3 : ");
UGM3O2 = MQ131.getO3(UG_M3);
Serial.print(UGM3O2);
Serial.println(" ug/m3");
}
void setup()
{
Serial.begin(PC_BAUDRATE);
// wait for the Arduino serial (on your PC) to connect
// please, open the Arduino serial console (right top corner)
// note that the port may change after uploading the sketch
// COMMENT OUT FOR USAGE WITHOUT A PC!
// while(!Serial);
Serial.println("openCanSat PRO");
Serial.print("Node ");
Serial.print(MYNODEID,DEC);
Serial.println(" ready");
// begin communication with the BME280 on the previously specified address
// print an error to the serial in case the sensor is not found
if (!bme.begin(BME280_ADDRESS_OPEN_CANSAT))
{
isBmeOk = false;
Serial.println("Could not find a valid BME280 sensor, check wiring!");
return;
}
// begin communication with the INA219
ina219.begin();
// check of Gps is connected
Wire.beginTransmission(0x42); // 42 is addres of GPS
int error = Wire.endTransmission();
if (error != 0)
{
isGpsConnected = false;
}
// begin communication with gps
gps.begin();
// Uncomment when you want to see debug prints from GPS library
// gps.debugPrintOn(57600);
if(!radio.initialize(FREQUENCY, MYNODEID, NETWORKID))
{
isRadioOk = false;
Serial.println("RFM69HW initialization failed!");
}
else
{
radio.setFrequency(FREQUENCYSPECIFIC);
radio.setHighPower(true); // Always use this for RFM69HW
}
pinMode(D13_led_pin, OUTPUT);
}
void loop()
{
pinMode(SS, OUTPUT);
digitalWrite(SS, HIGH);
pinMode(DcPin, OUTPUT);
pinMode(O2Pin, OUTPUT);
digitalWrite(DcPin, HIGH);
digitalWrite(O2Pin, HIGH);
delay(10000);
OZONE2CLICKCalibrate();
OZONE2CLICKMeasure();
}
It looks the code opening the SPI connection is commented out:
MQ131.begin(pinSS, pinRDY, O2Pin, LOW_CONCENTRATION, 10000);
You need to configure the SPI connection to get any data from your device.
Refer to reference code from the manufacturer or library you're using to make sure your programming against it correctly.
Please format your code with predictable spacing. This is pretty hard to read.
Since you're using C++, prefer to use:
constexpr <type> NAME = <value>;
rather than macros:
#define NAME (<value>)
Since this is a bare metal compilation, using return in the setup() or loop() functions does not stop them. You probably want something more like while (true) {}. This will loop the code indefinitely, rather than proceed in a bad state.
i.e.:
void stop_forever() {
Serial.println("fatal error detected, stoping forever.");
while (true) {}
}
// then, use it later:
// ...
if (error) {
stop_forever();
}
// ...