How to receive caller number from Arduino SIM800C GSM shield? - arduino

I'm trying to code a GSM caller number receiver. When I (as the phone answerer) answer the phone it should print out the caller number.
I have trouble finding the right AT command for receiving the caller number. I tried AT+CLIP=1\r and on the loop +CLIP, but with no success.
Here is my code:
#include <GSMSim.h>
#include <SoftwareSerial.h>
#define RX 7
#define TX 8
#define RESET 2
#define BAUD 9600
GSMSim gsm;
SoftwareSerial mySerial = SoftwareSerial(RX, TX);
/*
* Also you can this types:
* GSMSim gsm(RX, TX);
* GSMSim gsm(RX, TX, RESET);
* GSMSim gsm(RX, TX, RESET, LED_PIN, LED_FLAG);
*/
void setup() {
Serial.begin(9600);
Serial.println("GSMSim Library - Call Example");
Serial.println("");
delay(1000);
gsm.start(); // baud default 9600
mySerial.read();
mySerial.print("AT+CLIP=1\r");
}
void loop() {
Serial.println(gsm.callStatus());
gsm.callAnswer();
Serial.println("Number:");
Serial.println(mySerial.print("+CLIP"));
delay(1000);
}

I got It working by using mySerial, (ATDevice) read function and using command function to accualy print it out, anyone who looks up how it work, here Is my code
#include <GSMSim.h>
#include <SoftwareSerial.h>
#include <string.h>
#define RX 7
#define TX 8
#define RESET 2
#define BAUD 9600
char outArray;
char inData[20];
char inChar=-1;
byte index = 0;
char * pch;
char* substring(char*, int, int);
GSMSim gsm;
SoftwareSerial ATDevice = SoftwareSerial(RX, TX);
/*
* Also you can this types:
* GSMSim gsm(RX, TX);
* GSMSim gsm(RX, TX, RESET);
* GSMSim gsm(RX, TX, RESET, LED_PIN, LED_FLAG);
*/
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
ATDevice.begin(9600);
command("AT+CLIP=1",1000);
delay(1000);
}
String command(const char *toSend, unsigned long milliseconds) {
String result;
ATDevice.println(toSend);
unsigned long startTime = millis();
Serial.print("Return: ");
while (millis() - startTime < milliseconds) {
if (ATDevice.available()) {
char c = ATDevice.read();
result += c; // append to the result string
}
}
Serial.println(); // new line after timeout.
return result;
}
void loop() {
command("+CLIP",1000);
delay(2000);
}

Related

Working a temprature sensor (LM35) with a GSM module (Sim800L)

I have a temperature sensor set up working with an LCD and a stick to adjust the brightness. I now want the temperature sensor to send a text whenever it reaches a certain temperature. Can somebody please help.
The GSM unit i have is the SIM800L
below is what I have so far :
#include<LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int sensor=A1; // Assigning Analog Pin A1 to variable 'sensor'
float tempc; //variable to store temperature in degree Celsius
float tempf; //variable to store temperature in Fahrenheit
float vout; //temporary variable to hold sensor reading
void setup()
{
pinMode(sensor,INPUT); // Configuring pin A1 as INPUT Pin
Serial.begin(9600);
lcd.begin(16,2);
delay(500);
}
void loop()
{
vout=analogRead(sensor);
vout=(vout*500)/1023;
tempc=vout; // Storing value in degrees Celsius
tempf=(vout*1.8)+32; // Converting Temperature value from degrees Celsius to Fahrenheit
lcd.setCursor(0,0);
lcd.print("DegreeC= ");
lcd.print(tempc);
lcd.setCursor(0,1);
lcd.print("Fahrenheit=");
lcd.print(tempf);
delay(1000); //Delay of 1 second for ease of viewing in serial monitor
}
you could use the library Fona to send SMS with a Sim800L
to send a message you use the command -> fona.sendSMS(sendto, message)
#include <SoftwareSerial.h>
#include "Adafruit_FONA.h"
//This part declares that the RX, TX and RST pins of the SIM800L must be connected
//to pin 2, 3 and 4 of the Arduino.
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
SoftwareSerial fonaSS = SoftwareSerial(FONA_RX, FONA_TX);
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
void setup() {
while (!Serial);
Serial.begin(115200);
Serial.println(F("FONA basic test"));
Serial.println(F("Initializing....(May take 3 seconds)"));
fonaSS.begin(9600);
if (!fona.begin(fonaSS)) {
Serial.println(F("Couldn't find FONA"));
while (1);
}
Serial.println(F("FONA is OK"));
char sendto[21], message[141];
:
:
//initialize sendto and message
:
:
if (!fona.sendSMS(sendto, message)) {
Serial.println(F("error"));
} else {
Serial.println(F("sent!"));
}
}
to adapt the program to your case: i have put some lines of codes from setup to loop (easy to understant sendto and message definitions in loop now)
#include <SoftwareSerial.h>
#include "Adafruit_FONA.h"
//This part declares that the RX, TX and RST pins of the SIM800L must be connected
//to pin 2, 3 and 4 of the Arduino.
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
SoftwareSerial fonaSS = SoftwareSerial(FONA_RX, FONA_TX);
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
void setup() {
fonaSS.begin(9600);
// you initialisation code
}
void loop()
{
vout=analogRead(sensor);
vout=(vout*500)/1023;
tempc=vout; // Storing value in degrees Celsius
tempf=(vout*1.8)+32; // Converting Temperature value from degrees Celsius to Fahrenheit
lcd.setCursor(0,0);
lcd.print("DegreeC= ");
lcd.print(tempc);
lcd.setCursor(0,1);
lcd.print("Fahrenheit=");
lcd.print(tempf);
delay(1000); //Delay of 1 second for ease of viewing in serial monitor
if (tempc > 30.0) {
SendSms();
}
}
void SendSms() {
char sendto[] = "+19999999999"; //put the desired destination phone number for sms here
char message[141];
sprintf(message, "Alert TEMP is %.2f", tempc);// limit to 140
//sends the message via SMS
if (!fona.sendSMS(sendto, message)) {
Serial.println(F("error"));
} else {
Serial.println(F("sent!"));
}
}
another way to send sms
you could test the hayes command: for example
void sendsms(){
Serial.println("Sending text message...");
fonaSS.print("AT+CMGF=1\r"); // SMS MODE
delay(100);
// phone number
fonaSS.print("AT+CMGS=\"+33676171212\"\r"); //indicate your phone number
delay(100);
// message here
fonaSS.print("Message test \r");
// CTR+Z in mode ASCII, to indicate the end of message
fonaSS.print(char(26));
delay(100);
fonaSS.println();
Serial.println("Text send");
}
#include <SoftwareSerial.h>
#include "Adafruit_FONA.h"
//This part declares that the RX, TX and RST pins of the SIM800L must be connected
//to pin 2, 3 and 4 of the Arduino.
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
void setup() {
// you initialisation code
}
void loop()
{
vout=analogRead(sensor);
vout=(vout*500)/1023;
tempc=vout; // Storing value in degrees Celsius
tempf=(vout*1.8)+32; // Converting Temperature value from degrees Celsius to Fahrenheit
lcd.setCursor(0,0);
lcd.print("DegreeC= ");
lcd.print(tempc);
lcd.setCursor(0,1);
lcd.print("Fahrenheit=");
lcd.print(tempf);
delay(1000); //Delay of 1 second for ease of viewing in serial monitor
if (tempc > 30.0) {
SendSms();
}
}
void SendSms() {
char sendto[] = "+19999999999"; //put the desired destination phone number for sms here
char message[141];
sprintf(message, "Alert TEMP is %.2f", tempc);// limit to 140
//sends the message via SMS
if (!fona.sendSMS(sendto, message)) {
Serial.println(F("error"));
} else {
Serial.println(F("sent!"));
}
}

distribute data received from a serial communication with 2 arduino uno

I must send 3 values gave by 3 potentiometers ,connected by an Arduino Uno, and send them to another Arduino Uno whith a serial comunication. The received values must be distributed in 3 servo motors so that each knob able to control the servo motor movement.
the problem with this program is that the values received are not distributed correctly (for example the case that the value of the potentiometer 1 is to be read by the servo motor 3 or other cases). I ask if I could help to synchronize data received with the distribution of them to the servo motors. Thanks in advance.
sketch arduino with potentiometers:
#include <SoftwareSerial.h>
#define RX 2 //Pin tx
#define TX 3 //Pin rx
#define POTPIN A0
#define POTPIN2 A1
#define POTPIN3 A2
SoftwareSerial BTserial(RX, TX);
int lettura_pot;
int lettura_pot2;
int lettura_pot3;
byte val_servo;
byte val_servo2;
byte val_servo3;
void setup()
{
Serial.println("Inizializzazione seriale...");
Serial.begin(9600);
BTserial.begin(9600);
}
void loop()
{
BTserial.write(255); /* synch symbol */
lettura_pot = analogRead(POTPIN);
val_servo=map(lettura_pot,0,1023,0,180);
BTserial.write(val_servo);
Serial.println(val_servo);
lettura_pot2 = analogRead(POTPIN2);
val_servo2=map(lettura_pot2,0,1023,0,180);
BTserial.write(val_servo2);
Serial.println(val_servo2);
lettura_pot3 = analogRead(POTPIN3);
val_servo3=map(lettura_pot3,0,1023,0,180);
BTserial.write(val_servo3);
Serial.println(val_servo3);
}
sketch arduino with servo motors:
#include <SoftwareSerial.h>
#include<Servo.h>
SoftwareSerial BTserial(2, 3);
Servo myservo, myservo2, myservo3;
byte val_servo,val_servo2,val_servo3,a;
void setup() {
Serial.begin(9600);
BTserial.begin(9600);
myservo.attach(9);
myservo2.attach(10);
myservo3.attach(11);
}
void loop() {
if (BTserial.available() > 0) {
if (BTserial.available() == 255) { /* synch */
val_servo = BTserial.read();
val_servo2 = BTserial.read();
val_servo3 = BTserial.read();
}
Serial.print("SERVO1:");
Serial.println(val_servo);
Serial.print("SERVO2:");
Serial.println(val_servo2);
Serial.print("SERVO3:");
Serial.println(val_servo3);
myservo.write(val_servo);
myservo2.write(val_servo2);
myservo3.write(val_servo3);
BTserial.flush();
}
}
master code( no modificated):
#include <SoftwareSerial.h>
#define RX 2 //Pin tx
#define TX 3 //Pin rx
#define POTPIN A0
#define POTPIN2 A1
#define POTPIN3 A2
SoftwareSerial BTserial(RX, TX);
int lettura_pot;
int lettura_pot2;
int lettura_pot3;
byte val_servo;
byte val_servo2;
byte val_servo3;
void setup()
{
Serial.println("Inizializzazione seriale...");
Serial.begin(9600);
BTserial.begin(9600);
}
void loop()
{
BTserial.write(255);
lettura_pot = analogRead(POTPIN);
val_servo=map(lettura_pot,0,1023,0,180);
BTserial.write(val_servo);
Serial.println(val_servo);
lettura_pot2 = analogRead(POTPIN2);
val_servo2=map(lettura_pot2,0,1023,0,180);
BTserial.write(val_servo2);
Serial.println(val_servo2);
lettura_pot3 = analogRead(POTPIN3);
val_servo3=map(lettura_pot3,0,1023,0,180);
BTserial.write(val_servo3);
Serial.println(val_servo3);
}
slave code( modificated):
#include <SoftwareSerial.h>
#include<Servo.h>
SoftwareSerial BTserial(2, 3);
Servo myservo, myservo2, myservo3;
byte val_servo,val_servo2,val_servo3,a;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
BTserial.begin(9600);
myservo.attach(9);
myservo2.attach(10);
myservo3.attach(11);
}
void loop() {
// Read serial input:
if (BTserial.available() > 0) {
byte synch_symbol = BTserial.read();
if (synch_symbol == 255) {
while (BTserial.available() < 3) { }; /* wait for values */
val_servo = BTserial.read();
val_servo2 = BTserial.read();
val_servo3 = BTserial.read();
/* do something with values */
}
Serial.print("SERVO1:");
Serial.println(val_servo);
Serial.print("SERVO2:");
Serial.println(val_servo2);
Serial.print("SERVO3:");
Serial.println(val_servo3);
myservo.write(val_servo);
myservo2.write(val_servo2);
myservo3.write(val_servo3);
BTserial.flush();
}
}

Arduino with two RC522

To pimp up my Carrera I'm going to build a round counter.
It contains an Arduino Nano, a lcd and 2 rc522 rfid-reader.
The readers share the pins for scd, miso, mosi and have own pins for sda and rst.
Actually I'm not able to get the two readers work together at the same time. Only if the one or the other reader is physically plugged (hardcore!) into the breadbord it works (without code changing). But not together.
It has to be an issue with my code, but where?
(The RFID-Communication ist inpired by the example from [addicore][1]http://www.addicore.com/v/vspfiles/downloadables/Product%20Downloadables/RFID_RC522/RFIDQuickStartGuide.pdf)
Is there anyone who has a hint for me?
#include <AddicoreRFID.h>
#include <SPI.h>
#include <LiquidCrystal.h>
#define uchar unsigned char
#define uint unsigned int
// create AddicoreRFID object to control the RFID module
/////////////////////////////////////////////////////////////////////
//set the pins
/////////////////////////////////////////////////////////////////////
//2 - SCK Digital 13
//3 - MOSI Digital 11
//4 - MISO Digital 12
const int SS1 = 8; //RFID1
const int RST1 = 9;
AddicoreRFID myRFID1 (SS1, RST1);
const int SS2 = 10; //RFID2
const int RST2 = A0;
AddicoreRFID myRFID2 (SS2, RST2);
//Maximum length of the array
#define MAX_LEN 16
//LCD init
// * LCD RS pin to digital pin 7
// * LCD Enable pin to digital pin 6
// * LCD D4 pin to digital pin 5
// * LCD D5 pin to digital pin 4
// * LCD D6 pin to digital pin 3
// * LCD D7 pin to digital pin 2
LiquidCrystal lcd1(7, 6, 5, 4, 3, 2);
//Counter
int a = 0;
int b = 0;
void setup() {
Serial.begin(9600);
//LCD init
init_lcd1();
myRFID1.AddicoreRFID_Init();
myRFID2.AddicoreRFID_Init();
}
void loop() {
uchar i, tmp, checksum1;
uchar status;
uchar str1[MAX_LEN];
uchar str2[MAX_LEN];
///////////// RFID1 ///////////////////
// 0x4400 = Mifare_UltraLight -Tag Type
str1[1] = 0x4400;
//Find tags, return tag type
// Manipuliert str1(!);
//AddicoreRFID::AddicoreRFID_Request(byte reqMode, byte *TagType)
status = myRFID1.AddicoreRFID_Request(PICC_REQIDL, str1);
if (status == MI_OK) {
serial_TagDetect(str1, 1);
}
//Anti-collision, return tag serial number 4 bytes
// Manipuliert str1(!);
status = myRFID1.AddicoreRFID_Anticoll(str1);
if (status == MI_OK) {
serial_TagData(str1);
lcd_counter(str1, lcd1);
//delay(500);
}
myRFID1.AddicoreRFID_Halt(); //Command tag into hibernation
///////////// RFID2 ///////////////////
str2[1] = 0x4400;
//Find tags, return tag type
status = myRFID2.AddicoreRFID_Request(PICC_REQIDL, str2);
if (status == MI_OK) {
serial_TagDetect(str2, 2);
}
//Anti-collision, return tag serial number 4 bytes
status = myRFID2.AddicoreRFID_Anticoll(str1);
if (status == MI_OK) {
serial_TagData(str2);
lcd_counter(str2, lcd1);
// liest sonst nonstop die Tags!
//delay(500);
}
myRFID2.AddicoreRFID_Halt(); //Command tag into hibernation
}
void init_lcd1() {
... inits the lcd ...
}
// Zählt das Auftreten der Tags
void lcd_counter (uchar *str, LiquidCrystal lcd ) {
... output to the lcd ....
}
// Meldet gefundenen Tag auf der Konsole
void serial_TagDetect(uchar *str, int reader) {
if (reader == 1) {
Serial.print("RFID1 tag detected: ");
} else {
Serial.print("RFID2 tag detected: ");
}
Serial.print(str[0], BIN);
Serial.print(" , ");
Serial.print(str[1], BIN); Serial.println(" ");
}
// gibt Tagdaten auf der Konsole aus
void serial_TagData(uchar *str) {
uchar checksum1 = str[0] ^ str[1] ^ str[2] ^ str[3];
Serial.print("The tag's number is: ");
//Serial.print(2);
Serial.print(str[0]);
Serial.print(" , ");
Serial.print(str[1], BIN);
Serial.print(" , ");
Serial.print(str[2], BIN);
Serial.print(" , ");
Serial.print(str[3], BIN);
Serial.print(" , ");
Serial.print(str[4], BIN);
Serial.print(" , ");
Serial.println(checksum1, BIN);
}
I wonder about that the same(!!) rfid tag has different values depending it gets read from RFID1 or RFID2:
RFID1 tag detected: 1000100 , 0
The tag's number is: 136 , 100 , 11100 , 1101011 , 11111011 , 11111011
RFID2 tag detected: 1000100 , 0
The tag's number is: 68 , 0 , 0 , 0 , 0 , 1000100
I use 10 RC522 together at the same time with Ardunio mega .
Try this example for 2 ncf reader, its work for me. I tested in Arduino Nano.
The readers share the pins for 3,3V, GND. SCD, MISO, MOSI, RST and have own pins for SDA. I don't use the IRQ pin.
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS1_PIN 10 // Configurable, see typical pin layout above
#define SS2_PIN 8 // Configurable, see typical pin layout above
MFRC522 mfrc522_1(SS1_PIN, RST_PIN); // Create MFRC522 instance
MFRC522 mfrc522_2(SS2_PIN, RST_PIN);
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522_1.PCD_Init(); // Init MFRC522
mfrc522_1.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
mfrc522_2.PCD_Init(); // Init MFRC522
mfrc522_2.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
}
void loop() {
// Look for new cards
if ( mfrc522_1.PICC_IsNewCardPresent() || mfrc522_2.PICC_IsNewCardPresent()) {
Serial.println(F("New card..."));
} else {
return;
}
// Select one of the cards
if ( ! mfrc522_1.PICC_ReadCardSerial() && ! mfrc522_2.PICC_ReadCardSerial()) {
Serial.println(F("Read..."));
return;
}
// Dump debug info about the card; PICC_HaltA() is automatically called
mfrc522_1.PICC_DumpToSerial(&(mfrc522_1.uid));
mfrc522_2.PICC_DumpToSerial(&(mfrc522_2.uid));
}
//Anti-collision, return tag serial number 4 bytes
status = myRFID2.AddicoreRFID_Anticoll(str1); // <<<< needs to be strl2

Arduino: loop function runs only once

I'm trying to request temperatures from my DS18B20 sensor to post on plot.ly, but it seems my loop function is only running once; after connecting to plot.ly and creating the graph, the temperature is printed once in the serial monitor and does not seem to continue! Any help is greatly appreciated. Here is my code:
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <plotly_streaming_cc3000.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define WLAN_SSID "wifi"
#define WLAN_PASS "********"
#define WLAN_SECURITY WLAN_SEC_WPA2
OneWire oneWire(10);
DallasTemperature sensors(&oneWire);
#define nTraces 1
char *tokens[nTraces] = {"token"};
plotly graph("username", "token", tokens, "filename", nTraces);
void wifi_connect(){
/* Initialise the module */
Serial.println(F("\n... Initializing..."));
if (!graph.cc3000.begin())
{
Serial.println(F("... Couldn't begin()! Check your wiring?"));
while(1);
}
// Optional SSID scan
// listSSIDResults();
if (!graph.cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
Serial.println(F("Failed!"));
while(1);
}
Serial.println(F("... Connected!"));
/* Wait for DHCP to complete */
Serial.println(F("... Request DHCP"));
while (!graph.cc3000.checkDHCP())
{
delay(100); // ToDo: Insert a DHCP timeout!
unsigned long aucDHCP = 14400;
unsigned long aucARP = 3600;
unsigned long aucKeepalive = 10;
unsigned long aucInactivity = 20;
if (netapp_timeout_values(&aucDHCP, &aucARP, &aucKeepalive, &aucInactivity) != 0) {
Serial.println("Error setting inactivity timeout!");
}
}
}
void setup() {
graph.maxpoints = 100;
Serial.begin(9600);
sensors.begin();
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
wifi_connect();
bool success;
success = graph.init();
if(!success){while(true){}}
graph.openStream();
}
void loop(void) {
Serial.print("Requesting temperatures...");
sensors.requestTemperatures();
Serial.println("DONE");
Serial.print("Temperature for Device 1 is: ");
Serial.print(sensors.getTempFByIndex(0));
graph.plot(millis(), sensors.getTempFByIndex(0), tokens[0]);
delay(500);
}

Arduino to arduino i2c code

I have an OPT101 connected to a slave arduino to measure light intensity. I want to send the data received from the OPT101 circuit to a master arduino that will print the data on the serial monitor. When I test my code, nothing shows up on the screen. (I know it's not my i2c connection cause I tested it by sending "hello"). I am using an arduino leonardo as the slave and the arduino uno as the master.
The code for the OPT101 circuit is:
#define inPin0 0
void setup() {
Serial.begin(9600);
Serial.println();
}
void loop() {
int pinRead0 = analogRead(inPin0);
double pVolt0 = pinRead0 / 1024.00 * 5.0;
Serial.print(pVolt0, 4 );
Serial.println();
delay(100);
}
I tired to combine the slave code and my OPT101 code to get this:
#include
#define inPin0 0
void setup() {
Wire.begin(2);
}
void loop() {
Wire.beginTransmission(2);
Wire.onRequest(requestEvent);
Wire.endTransmission();
}
void requestEvent()
{
int pinRead0 = analogRead(inPin0);
int pVolt0 = pinRead0 / 1024.0 * 5.0;
Wire.write((byte)pVolt0);
}
And this is my master code:
#include <Wire.h>
void setup()
{
Wire.begin();
Serial.begin(14400);
Wire.requestFrom(2, 8);
while(Wire.available())
{
char c = Wire.read();
Serial.print(c);
}
}
void loop()
{
}
You must follow steps described below to communicate between master and slave I2C devices:
Only master can initiate read or write request.
Read or write requests must be synchronous. It means, slave can only return data after master requests for them and vice versa for write.
Do not use slave address from 0 - 7. They are reserved. Use slave address that ranges between 8 to 127.
On Arduino I2C, you can only send and receive a byte. To send or receive integer, double that have multiple bytes, you need to split them first and on other side, you have to combine them into its equivalent datatype. (Correct me, if I'm wrong.)
Your code should be like this:
Master Sketch:
#include <Wire.h>
#define SLAVE_ADDRESS 0x40
// This macro reads two byte from I2C slave and converts into equivalent int
#define I2C_ReadInteger(buf,dataInteger) \
buf[0] = Wire.read(); \
buf[1] = Wire.read(); \
dataInteger = *((int *)buf);
// Returns light intensity measured by 'SLAVE_ADDRESS' device
int GetLightIntensity()
{
byte Temp[2];
int Result;
// To get integer value from slave, two are required
int NumberOfBytes = 2;
// Request 'NumberOfBytes' from 'SLAVE_ADDRESS'
Wire.requestFrom(SLAVE_ADDRESS, NumberOfBytes);
// Call macro to read and convert bytes (Temp) to int (Result)
I2C_ReadInteger(Temp, Result);
return Result;
}
void setup()
{
// Initiate I2C Master
Wire.begin();
// Initiate Serial communication # 9600 baud or of your choice
Serial.begin(9600);
}
void loop()
{
// Print light intensity at defined interval
Serial.print("Light Intensity = ");
Serial.println(GetLightIntensity());
delay(1000);
}
Slave Sketch:
#include <Wire.h>
#define SLAVE_ADDRESS 0x40
#define inPin0 0
// Preapres 2-bytes equivalent to its int
#define IntegerToByte(buf,intData) \
*((int *)buf) = intData;
// Sends int to Master
void I2C_SendInteger(int Data)
{
byte Temp[2];
// I2C can only send a byte at a time.
// Int is of 2bytes and we need to split them into bytes
// in order to send it to Master.
// On Master side, it receives 2bytes and parses into
// equvivalent int.
IntegerToByte(Temp, Data);
// Write 2bytes to Master
Wire.write(Temp, 2);
}
void setup()
{
// Initiate I2C Slave # 'SLAVE_ADDRESS'
Wire.begin(SLAVE_ADDRESS);
// Register callback on request by Master
Wire.onRequest(requestEvent);
}
void loop()
{
}
//
void requestEvent()
{
// Read sensor
int pinRead0 = analogRead(inPin0);
int pVolt0 = pinRead0 / 1024.0 * 5.0;
// Send int to Master
I2C_SendInteger(pVolt0);
}
This code is tested on Arduino Version: 1.6.7.
For more information regarding I2C communication, refer Arduino
Example: Master Reader
Why are you putting the while loop in the setup() function instead of using the loop() function ?
But more confusing is this line int pVolt0 = pinRead0 / 1024.0 * 5.0;. In the initial code the variable is not int but double. I suggest you try to recode using the original line:
double pVolt0 = pinRead0 / 1024.00 * 5.0;
And only then reduce to int.
In Arduino I2C, you can only send and receive one byte, and it is necessary to combine them in their equivalent data type.

Resources