Conectando ESP8266 con Arduino nano “I2C” 2da parte

Conexion ESP8266 con Arduino y DS18B20

Introducción:

En este proyecto utilizaremos:
1- 1 NODEMCU (ESP12E).
2- 1 Arduino Nano
3- 2 DS18B20
4- breadboard
5- Cables de conexion

Introducción

En este ocasión presento como es la transferencia de datos mediante el protocolo I2C, entre un ESP8266 como maestro y un Arduino Nano como esclavo pero transfiriendo los datos de dos sensores de temperatura DS18B20, este es un sensor que contiene una dirección única que permite identificarlo individualmente, lo que lo hace propicio para el uso del protocolo OnWire que permite enviar y recibir datos utilizando un solo cable.

Click aquí para ver la primera parte

Para Saber sobre el sensor DS1820 click aqui

El código

Presentare la codificación del esclavo ya que la del maestro(ESP8266) es básicamente  la misma que en la primera parte.

En este vídeo explico su funcionamiento:

1- Añadimos las librerías relacionadas con el sensor
OneWire y DallarTemperture

2- Definimos el pin 2 del arduino nano
#One_WIRE_BUS

3- Instanciamos y asociamos el pin 2 del arduino al protocolo OneWire y la librería DallasTemperarute
OneWire oneWire(ONE_WIRE_BUS)
DallasTemperature sensors(&oneWire)

#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices 
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
 
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

4- Definimos la direccion del esclavo y asignamos los nombres a las variables

const byte MY_ADDRESS = 42;
int Temp1,Temp2;
// various commands we might get

enum {
    CMD_ID = 1,
    CMD_READ_Temp1  = 2,
    CMD_READ_Temp2 = 3
    };

5- iniciamos los sensores

 sensors.begin();

6- Creamos uns subrutina que lee las medidas del los sensores.

void sendSensorTemp ()
  {
  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus
  Serial.print(" Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  Serial.println("DONE");
  
  Temp1 = sensors.getTempCByIndex(0);
  Temp2 = sensors.getTempCByIndex(1);
  delay(500);
  
  }  // end of sendSensor

8- llamamos la subrutina infinitamente en el loop

void loop() 
  {
   sendSensorTemp ();
  }  // end of loop

A continucion los codigos completos tanto del master como el esclavo

/Master
/*These examples illustrate how a master can request data from a slave).
First, the master, which asks the slave for information:
*/
#include <Wire.h>

const int SLAVE_ADDRESS = 42;
int Temp1,Temp2;
// various commands we might send
enum {
    CMD_ID = 1,
    CMD_READ_Temp1  = 2,
    CMD_READ_Temp2 = 3
    };

void sendCommand (const byte cmd, const int responseSize)
  {
  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write (cmd);
  //Wire.endTransmission ();
  if (Wire.endTransmission () == 0)
  {
  Serial.println("Data Sent OK");  
  }
  else{
    Serial.println("Error Sending Data");
    }
  Wire.requestFrom (SLAVE_ADDRESS, responseSize);  
  }  // end of sendCommand
  
void setup ()
  {
  Wire.begin (0,2);   
  Serial.begin (115200);  // start serial for output
  
  sendCommand (CMD_ID, 1);
  
  if (Wire.available ())
    {
    Serial.println("");  
    Serial.print ("Slave is ID: ");
    Serial.println (Wire.read (), DEC);
    }
  else
    Serial.println ("No response to ID request");
  
  }  // end of setup

void loop()
  {
  
  
  sendCommand (CMD_READ_Temp1, 1);
  Temp1 = Wire.read ();
  Serial.print ("Value of Temp1: ");
  Serial.println (Temp1);

  sendCommand (CMD_READ_Temp2, 1);
  Temp2= Wire.read ();
  Serial.print ("Value of Temp2: ");
  Serial.println (Temp2);

  delay (500);   
  }  // end of loop
Master
// Slave
/*It has to be able to reply to any request without even knowing the address of the device 
 making the request.
It does this by setting up an interrupt handler (by calling Wire.onRequest).
This gets called any time a master wants a response.
We also need the Wire.onReceive handler, to get the initial "command" - that is,
we need to know what data is wanted.
The example above assumes a single-byte command, which we save in the variable "command".
Then when the requestEvent handler is called, we check what the most-recent command was,
and send an appropriate response.
Warning - because of the way the Wire library is written, the requestEvent handler can 
only (successfully) do a single send. The reason is that each attempt to send a reply resets
the internal buffer back to the start. Thus in your requestEvent, if you need to send multiple bytes,
you should assemble them into a temporary buffer, and then send that buffer using a single Wire.write. 
For example:
*/
#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices 
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
 
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

const byte MY_ADDRESS = 42;
int Temp1,Temp2;
// various commands we might get

enum {
    CMD_ID = 1,
    CMD_READ_Temp1  = 2,
    CMD_READ_Temp2 = 3
    };

char command;

void setup() 
  {
  command = 0;
  
  Serial.begin(115200);
  Serial.println("Dallas Temperature IC Control Library Demo");

  // Start up the library
  sensors.begin();
  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveEvent);  // interrupt handler for incoming messages
  Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted

  }  // end of setup

void sendSensorTemp ()
  {
  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus
  Serial.print(" Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  Serial.println("DONE");
  
  Temp1 = sensors.getTempCByIndex(0);
  Temp2 = sensors.getTempCByIndex(1);
  delay(500);
  
  }  // end of sendSensor

void loop() 
  {
   sendSensorTemp ();
  }  // end of loop

void receiveEvent (int howMany)
  {
  command = Wire.read ();  // remember command for when we get request
  } // end of receiveEvent


void requestEvent ()
  {
  switch (command)
     {
     
    case CMD_ID:      Wire.write (0x55); break;   // send our ID 
    case CMD_READ_Temp1: Wire.write(Temp1); break;  // send Temp1 value
    case CMD_READ_Temp2: Wire.write(Temp2); break;   // send Temp2 value
    
     }  // end of switch
  
  }  // end of requestEvent
ESCLAVO

Deja un comentario