Working writing/reading at 0XBF

This commit is contained in:
Wesley Hofman
2025-09-17 12:26:06 +02:00
parent 3eeaa43b3d
commit d1b57db444

View File

@@ -1,31 +1,51 @@
#include <Wire.h>
const int deviceAddress = 0x68; // I2C address of the device (change as needed)
const uint8_t relay1 = 2;
const uint8_t relay2 = 3;
const uint8_t relay1 = 2; // LOW ACTIVE
const uint8_t relay2 = 3; // LOW ACTIVE
const uint8_t oe = 5;
const uint8_t d6 = 6; // Define pin D6
bool actionPerformed = false; // Flag to track if the action has been performed
void relaysOn()
{
//Relays are low active
digitalWrite(relay1,LOW);
digitalWrite(relay2,LOW);
delay(5);
}
void relaysOff()
{
//Relays are low active
digitalWrite(relay1,HIGH);
digitalWrite(relay2,HIGH);
delay(5);
}
// Function to transmit 16-bit data in little-endian format
void transmitData(uint8_t registerAddress, uint16_t data) {
digitalWrite(oe,HIGH);
Wire.beginTransmission(deviceAddress);
Wire.write(registerAddress); // Send the register address
Wire.write(data & 0xFF); // Send the low byte (LSB)
Wire.write((data >> 8) & 0xFF); // Send the high byte (MSB)
Wire.endTransmission();
digitalWrite(oe,LOW);
}
// Function to read back data from the register
uint16_t readData(uint8_t registerAddress) {
uint16_t receivedData = 0;
digitalWrite(oe,HIGH);
// First, send the register address to read from
Wire.beginTransmission(deviceAddress);
Wire.write(registerAddress); // Send the register address
Wire.endTransmission();
if (Wire.endTransmission() != 0) {
Serial.println("Device not found");
digitalWrite(oe,LOW);
return 0; // Return 0 or some error code
}
@@ -35,6 +55,7 @@ uint16_t readData(uint8_t registerAddress) {
receivedData |= Wire.read(); // Read low byte (LSB)
receivedData |= Wire.read() << 8; // Read high byte (MSB)
}
digitalWrite(oe,LOW);
return receivedData;
}
@@ -43,18 +64,15 @@ void setup() {
Wire.begin(); // Initialize I2C
pinMode(relay1, OUTPUT);
pinMode(relay2, OUTPUT);
pinMode(oe, OUTPUT);
pinMode(d6, INPUT); // Set D6 as input
digitalWrite(oe,LOW);
for(int i = 8; i <= 13; i++)
{
pinMode(i,OUTPUT);
digitalWrite(i,LOW);
}
pinMode(oe,OUTPUT);
digitalWrite(relay1,LOW);
digitalWrite(relay2,LOW);
digitalWrite(oe,HIGH);
}
void printHex(uint16_t value) {
@@ -92,19 +110,18 @@ void loop() {
// Only act if the new state is HIGH and the action hasn't been performed yet
if (currentD6State == HIGH && !actionPerformed) {
relaysOn();
uint8_t registerAddress = 0xBF;
uint16_t dataToSend = 0x0000;
// Transmit the data
transmitData(registerAddress, dataToSend); // Transmit data
// Read back data
uint16_t receivedData = readData(registerAddress); // Read back data
// Use the method to print received data in hexadecimal format
relaysOff();
Serial.println("Received data : ");
// Use the method to print received data in hexadecimal format
printHex(receivedData); // Print formatted received data
Serial.println(); // New line for better readability
// Set the action performed flag to true
actionPerformed = true;
}