我无法从Arduino到mDot LoRa节点的i2c总线检索数据。基于ARMBed i2c库,尝试使用以下代码从Arduino(从站)获取数据:
/**
* Copyright (c) 2017, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include "lorawan/LoRaWANInterface.h"
#include "lorawan/system/lorawan_data_structures.h"
#include "events/EventQueue.h"
// Application helpers
#include "DummySensor.h"
#include "trace_helper.h"
#include "lora_radio_helper.h"
using namespace events;
// documentacion de i2c
// https://os.mbed.com/docs/mbed-os/v5.12/apis/i2c.html
#include "mbed.h"
mbed::I2C i2c(I2C_SDA, I2C_SCL);
const int addr7bit = 0x29; // 7-bit I2C address (del ARDUINO)
const int addr8bit = addr7bit << 1; // 8-bit I2C address (shift a izquierda para el MDOT)
// Max payload size can be LORAMAC_PHY_MAXPAYLOAD.
// This example only communicates with much shorter messages (<30 bytes).
// If longer messages are used, these buffers must be changed accordingly.
uint8_t tx_buffer[30];
uint8_t rx_buffer[30];
/*
* Sets up an application dependent transmission timer in ms. Used only when Duty Cycling is off for testing
*/
#define TX_TIMER 10000
/**
* Maximum number of events for the event queue.
* 10 is the safe number for the stack events, however, if application
* also uses the queue for whatever purposes, this number should be increased.
*/
#define MAX_NUMBER_OF_EVENTS 10
/**
* Maximum number of retries for CONFIRMED messages before giving up
*/
#define CONFIRMED_MSG_RETRY_COUNTER 3
/**
* Dummy pin for dummy sensor
*/
#define PC_9 0
/**
* Dummy sensor class object
*/
DS1820 ds1820(PC_9);
/**
* This event queue is the global event queue for both the
* application and stack. To conserve memory, the stack is designed to run
* in the same thread as the application and the application is responsible for
* providing an event queue to the stack that will be used for ISR deferment as
* well as application information event queuing.
*/
static EventQueue ev_queue(MAX_NUMBER_OF_EVENTS *EVENTS_EVENT_SIZE);
/**
* Event handler.
*
* This will be passed to the LoRaWAN stack to queue events for the
* application which in turn drive the application.
*/
static void lora_event_handler(lorawan_event_t event);
/**
* Constructing Mbed LoRaWANInterface and passing it the radio object from lora_radio_helper.
*/
static LoRaWANInterface lorawan(radio);
/**
* Application specific callbacks
*/
static lorawan_app_callbacks_t callbacks;
/**
* Entry point for application
*/
int main(void)
{
// setup tracing
setup_trace();
// stores the status of a call to LoRaWAN protocol
lorawan_status_t retcode;
// Initialize LoRaWAN stack
if (lorawan.initialize(&ev_queue) != LORAWAN_STATUS_OK) {
printf("\r\n LoRa initialization failed! \r\n");
return -1;
}
printf("\r\n Mbed LoRaWANStack initialized \r\n");
// prepare application callbacks
callbacks.events = mbed::callback(lora_event_handler);
lorawan.add_app_callbacks(&callbacks);
// Set number of retries in case of CONFIRMED messages
if (lorawan.set_confirmed_msg_retries(CONFIRMED_MSG_RETRY_COUNTER)
!= LORAWAN_STATUS_OK) {
printf("\r\n set_confirmed_msg_retries failed! \r\n\r\n");
return -1;
}
printf("\r\n CONFIRMED message retries : %d \r\n",
CONFIRMED_MSG_RETRY_COUNTER);
// Enable adaptive data rate
if (lorawan.enable_adaptive_datarate() != LORAWAN_STATUS_OK) {
printf("\r\n enable_adaptive_datarate failed! \r\n");
return -1;
}
printf("\r\n Adaptive data rate (ADR) - Enabled \r\n");
retcode = lorawan.connect();
if (retcode == LORAWAN_STATUS_OK ||
retcode == LORAWAN_STATUS_CONNECT_IN_PROGRESS) {
} else {
printf("\r\n Connection error, code = %d \r\n", retcode);
return -1;
}
printf("\r\n Connection - In Progress ...\r\n");
// make your event queue dispatching events forever
ev_queue.dispatch_forever();
return 0;
}
/**
* Sends a message to the Network Server
*/
static void send_message()
{
uint16_t packet_len;
int16_t retcode;
float sensor_value;
// esta sería la variable que guardará el "paquete" leido del ARDUINO
char cmd[28];
// inicializamos en 0 cada valor del arreglo
for (size_t i = 0; i < 28; i++)
{
cmd[i] = 0x00;
}
if (ds1820.begin()) {
ds1820.startConversion();
sensor_value = ds1820.read();
printf("\r\n Esto es console log = %3.1f \r\n", sensor_value);
ds1820.startConversion();
packet_len = sprintf((char *) tx_buffer, "Esto es lo que se manda: %3.1f", sensor_value); //28 bytes
} else {
// printf("\r\n No sensor found \r\n");
// return;
// basicamente tengo que mandar cualquier cosa para que el maestro me conteste con los datos
// de los sensores.
i2c.write(addr8bit, cmd, 28);
printf("%d\n", addr7bit);
printf("%d\n", addr8bit);
wait(5); // 5 segundos
// y ahora leo los 28 bytes recibidos, el paquete enviado desde arduino deberia ser de 28 bytes
i2c.read(addr8bit, cmd, 28);
printf("%s\r\n", cmd);
packet_len = sprintf((char *) tx_buffer, "%s", cmd);
}
retcode = lorawan.send(MBED_CONF_LORA_APP_PORT, tx_buffer, packet_len, MSG_UNCONFIRMED_FLAG);
if (retcode < 0) {
retcode == LORAWAN_STATUS_WOULD_BLOCK ? printf("send - WOULD BLOCK\r\n")
: printf("\r\n send() - Error code %d \r\n", retcode);
if (retcode == LORAWAN_STATUS_WOULD_BLOCK) {
//retry in 3 seconds
if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
ev_queue.call_in(3000, send_message);
}
}
return;
}
printf("\r\n %d bytes scheduled for transmission \r\n", retcode);
memset(tx_buffer, 0, sizeof(tx_buffer));
}
/**
* Receive a message from the Network Server
*/
static void receive_message()
{
uint8_t port;
int flags;
int16_t retcode = lorawan.receive(rx_buffer, sizeof(rx_buffer), port, flags);
if (retcode < 0) {
printf("\r\n receive() - Error code %d \r\n", retcode);
return;
}
printf(" RX Data on port %u (%d bytes): ", port, retcode);
for (uint8_t i = 0; i < retcode; i++) {
printf("%02x ", rx_buffer[i]);
}
printf("\r\n");
memset(rx_buffer, 0, sizeof(rx_buffer));
}
/**
* Event handler
*/
static void lora_event_handler(lorawan_event_t event)
{
switch (event) {
case CONNECTED:
printf("\r\n Connection - Successful \r\n");
if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
send_message();
} else {
ev_queue.call_every(TX_TIMER, send_message);
}
break;
case DISCONNECTED:
ev_queue.break_dispatch();
printf("\r\n Disconnected Successfully \r\n");
break;
case TX_DONE:
printf("\r\n Message Sent to Network Server \r\n");
if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
send_message();
}
break;
case TX_TIMEOUT:
case TX_ERROR:
case TX_CRYPTO_ERROR:
case TX_SCHEDULING_ERROR:
printf("\r\n Transmission Error - EventCode = %d \r\n", event);
// try again
if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
send_message();
}
break;
case RX_DONE:
printf("\r\n Received message from Network Server \r\n");
receive_message();
break;
case RX_TIMEOUT:
case RX_ERROR:
printf("\r\n Error in reception - Code = %d \r\n", event);
break;
case JOIN_FAILURE:
printf("\r\n OTAA Failed - Check Keys \r\n");
break;
case UPLINK_REQUIRED:
printf("\r\n Uplink required by NS \r\n");
if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
send_message();
}
break;
default:
MBED_ASSERT("Unknown Event");
}
}
// EOF
这是我的Arduino草图:
#include <DHT.h>
#include <Wire.h>
// Sensor temperatura, humedad DHT11 (test).
#define DHTPIN 10
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
// Comunicacion i2c con nodo lora.
#define SLAVE_ADDRESS 0x29
// Variables globales de sensores
float h;
float t;
void setup() {
Serial.begin(9600);
Wire.begin(SLAVE_ADDRESS);
Wire.onReceive(receiveEvent);
dht.begin();
}
void loop() {
delay(5000);
h = dht.readHumidity();
t = dht.readTemperature();
// Comprobamos si ha habido algún error en la lectura
if (isnan(h) || isnan(t)) {
Serial.println("Error obteniendo los datos del sensor DHT11");
return;
}
Serial.print("Humedad: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperatura: ");
Serial.print(t);
Serial.println(" *C ");
}
// Total de bytes del arreglo de datos a transmitir: 28 bytes.
void receiveEvent(int howMany) {
Serial.println("Recibido paquete desde MDOT LoRa Node");
Wire.beginTransmission(SLAVE_ADDRESS);
Wire.write("/Humedad:");
char hum[3];
String(h).toCharArray(hum, 3);
Wire.write(hum);
Wire.write("/Temperatura:");
char temp[3];
String(t).toCharArray(temp, 3);
Wire.write(temp);
Wire.endTransmission();
}
我将当前使用的所有代码留在仓库中:https://github.com/cipiasentini/lorai2c