I2C sending data from arduino to python gives gibberish data

It's my first time working with SMBUS and I've read the docs of arduino and the Wire object. It states that I can send a string. To quote the docs: string: a string to send as a series of bytes. write() - Arduino Reference

When I convert my int to a String type and pass it along to Wire.write, I can't read it with Python.

Slave address: `0x8`

    void setup() {
      Serial.begin(BaudRate); delay(10);
      Wire.begin(SLAVE_ADDRESS); 0x8
      Wire.onRequest(sendData); 
    }
    
    void loop() {
       sendData(1272); // right now hard-coded for testing purposes
    }
    // callback for sending data
    void sendData(int data) {
        String dataString = String(data);
        int len = dataString.length() + 1;
        char charDataString[len];
        dataString.toCharArray(charDataString, len);
        for (int i = 0; i < len; i++) {
            Serial.println(charDataString[i]); -> SHOWS THE CORRECT VALUES
            Wire.write(charDataString[i]);
        }
        delay(1000);
    }

My python code (how I read the data):

    import smbus
    import time
    bus = smbus.SMBus(1)
    address = 0x8
    while True:
        data = ""
        for (i in range(0, 10))
            ##BOTH VARIANTS DO NOT WORK
            data = bus.read_i2c_block_data(address, 99, 3)
            data += chr(bus.read_byte(address));

        print(data)
        time.sleep(1)

I can't wrap my head around what I am doing wrong here. If there is a way to immediately send it over instead of each value individually I'd prefer that as well.

That seems like a silly thing to do. There is never a need for Strings with Arduino, especially when you turn right around and convert the String to a character data array.
dataString.toCharArray(charDataString, len);

To convert integers to C-strings (zero terminated character arrays), use the function itoa() and its relatives.

On the AVR-based Arduinos, use of Strings often causes program crashes or malfunction.

What computer is running python, and how is that an Arduino problem?

The pi is running python and my problem is that I cannot convert the values I send back to the correect values.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.