Unable to receive correct data using i2c serial communication between two Arduino - arduino

I'm using an i2c serial bus for communication between two Arduino (Uno = Master, Due = Slave) and I'm currently experiencing problems while reading data received by the slave.
The master sends some data using Wire.write(command). The slave receives it and the handler function receiveEvent(int howMany) is called thanks the instruction Wire.onReceive(receiveEvent).
Here is the simplified code for the serial communication:
Master's Sketch
#include <Wire.h>
void setup() {
Wire.begin();
Serial.begin(9600);
}
void loop() {
Wire.beginTransmission(8);
byte command[] = {2, 5, 3};
Wire.write(command, 3);
Wire.endTransmission();
Serial.println("command sent...");
delay(1000);
}
Slave's Sketch
#include <Wire.h>
int c = 0;
void setup() {
Serial.begin(9600);
Wire.begin(8);
Wire.onReceive(receiveEvent);
}
void loop() {
delay(1000);
}
void receiveEvent(int howManyBytes){
for(int iter=0; iter<howMany; iter++){
c = Serial.read();
Serial.print("c : ");
Serial.println(c);
}
}
Slave's Output
c : -1
c : -1
c : -1
It appears that three bytes are received but the data are not transmitted correctly. Any idea were there could be a mistake or a bug? Thanks!

Since you expect the data from the Wire, I think your slave should receive the data via Wire.read() instead of Serial.read().

Related

How to send orders from Arduino to Esp32 and make it keypress

I need to send orders from Arduino to ESP32.
I have one joystick button to test.
Arduino nano is sender
Esp32 is receiver
Esp32 receives the joystick button information from Arduino (each time I push the button).
I need the Esp32 to Serial.write according to the data, for example:
If I press the button in Arduino: Send the data to Esp32 and turn bluetooth on (or turn a led on).
These are my codes:
//Arduino NANO sender
byte j = 45;
#define boton_joystick A1
void setup() {
Serial.begin(9600);
pinMode(boton_joystick, INPUT_PULLUP);
}
int boton_joystick_state;
void loop() {
//Serial.println("100");
//Serial.write("BOTON EN GRANDE");
//delay(1500);
if(!digitalRead(boton_joystick)) {
boton_joystick_state = 1;
delay(170);
} else {
boton_joystick_state = 0;
}
if (boton_joystick_state) {
Serial.println(j);
Serial.print(" ");
Serial.write(j);
Serial.println();
}
//ESP-32 receiver
#define RXD2 16
#define TXD2 17
byte j = 45;
int comdata;
void setup() {
Serial.begin(115200);
Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
}
void loop() {
//Serial.print("LEYENDO ARDUINO");
Serial.println(Serial2.readString());
if (Serial2.available() >0) {
char comdata = char(Serial2.read());
if (comdata == 'j') {
Serial.println("joystick activado");
}
}
}
am not sure
but am using Nano 33 BLE with UART and Nano has also Serial1 no need to serial2 no need to Softwearserial. Sensd on serial 1 and recive in Serial 1 but also you have to connect it Via USB. so your serial is USB and your serial 1 is TX RX.
for me it work so you can try it.

ASCII of integer to integer in Arduino

I am working on a project with LoRa and Arduino and I am facing a weird issue where when I transmit a integer the receiver receives at ASCII value which is not good at my case because I wanted to transmit sensor data(3 digits) which is not possible by ASCII. I will also attach my code(converted into a basic integer code for testing) I need a Solution to fix this BTW I am using Arduino UNO for transmitting and Arduino Mega for receiving and SX1278 LoRa Module for both transmitting and receiving.
Transmitter Code(Arduino UNO):
#include <SPI.h>
#include <LoRa.h>
int val = 5;
void setup() {
Serial.begin(9600);
while (!Serial);
Serial.println("LoRa Sender");
if (!LoRa.begin(433E6)) {
Serial.println("Starting LoRa failed!");
while (1);
}
}
void loop() {
Serial.print("Sending packet: ");
// send packet
LoRa.beginPacket();
LoRa.print(val);
LoRa.endPacket();
delay(500);
}
Receiver Code(Arduino Mega):
#include <SPI.h>
#include <LoRa.h>
#define LORA_SS 53
#define LORA_RST 9
#define LORA_DIO0 8
int val;
void setup() {
pinMode(LORA_SS, OUTPUT);
digitalWrite(LORA_SS, HIGH);
LoRa.setPins(LORA_SS, LORA_RST, LORA_DIO0);
Serial.begin(9600);
while (!Serial);
Serial.println("LoRa Receiver");
if (!LoRa.begin(433E6)) {
Serial.println("Starting LoRa failed!");
while (1);
}
}
void loop() {
// try to parse packet
int packetSize = LoRa.parsePacket();
if (packetSize) {
// received a packet
Serial.print("Received packet '");
// read packet
while (LoRa.available()) {
//Serial.print((char)LoRa.read());
int val = LoRa.read();
}
Serial.print(val);
// print RSSI of packet
Serial.print("' with RSSI ");
Serial.println(LoRa.packetRssi());
}
}
Output of the receiver :
Received packet '53' with RSSI -5
To Fix this issue just send the value as an integer, since LoRa receives as char/string same it in a string variable in the receiver and convert it into integer with toInt(); and that will fix it!

Sending Float Data Type from Arduino to ESP32 (NodeMCU)

I am trying to have a NodeMCU(ESP32) receive a floating data type from an Arduino Uno but I do not have any idea how. Can someone please guide me through the process? For now, I have the basic serial communication code sending a single digit Int from the Arduino to the NodeMCU.
Sender (Arduino Uno):
int val = 1;
void setup()
{
Serial.begin(19200);
}
void loop()
{
Serial.write(val);
delay(3000);
}
Receiver (NodeMCU):
#include <HardwareSerial.h>
HardwareSerial receiver(2);
void setup()
{
receiver.begin(19200, SERIAL_8N1, 16, 17);
Serial.begin(9600);
}
void loop()
{
if(receiver.available() > 0)
{
int received = receiver.read();
Serial.println(received); //tried printing the result to the serial monitor
}
delay(3000);
}
Write/read in the form you use it, is for single bytes only. A float in Arduino consists of 4 bytes.
You can use write to send a series of bytes, and you have to read those bytes, arriving one after the other, depending on the serial speed. Synchronization/lost bytes might be a problem, here in this simple solution I assume the best.
Sender:
float val = 1.234;
void setup() {
Serial.begin(19200);
}
void loop() {
Serial.write((byte*)&val,4);
delay(3000);
}
Receiver:
#include <HardwareSerial.h>
HardwareSerial receiver(2);
void setup()
{
receiver.begin(19200, SERIAL_8N1, 16, 17);
Serial.begin(9600);
}
void loop()
{
if(receiver.available() > 0)
{
delay(5); // wait for all 4 bytes
byte buf[4];
byte* bp = buf;
while (receiver.available()) {
*bp = receiver.read();
if (bp - buf < 3) bp++;
}
float received = * (float*)buf;
Serial.println(received, 3); // printing the result to the serial monitor
}
delay(100); // not really required, should be smaller than sender cycle
}

Error connecting an arduino and esp 32 via i2c

I'm having trouble connecting a esp32 with arduino pro mini 3v3. my code is the same arduino tutorial example. I use atom to code and when I open terminal serial write null message
Master code(Run ESP32)
#include <Wire.h>
int i=0;
char c[20
];
#include <Wire.h>
#define I2C_SDA_PIN 21
#define I2C_SCL_PIN 22
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
}
void loop() {
Wire.requestFrom(8, 1); // request 6 bytes from slave device #8
while (Wire.available()>0) { // slave may send less than requested
c[i]=Wire.read(); // receive a byte as character
i++;
Serial.print(c); // print the character
}
}
Run Arduino pro mini
#include <Wire.h>
void setup() {
Wire.begin(8); // join i2c bus with address #8
Wire.onRequest(requestEvent); // register event
}
void loop() {
delay(100);
}
// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
Wire.write('h'); // respond with message of 6 bytes
// as expected by master
}
I did an i2c bus address test and recognized the arduino:screenshot
I do not find anything about it, if anyone can help
p.s sorry for my poor english.

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