1

I need to send data from a processing sketch to an Arduino to pass to a function that takes a uint32_t. How to I send the data in Processing to be run on the Arduino

1

1 Answer 1

1

I recommend studying up on bitwise shifts (<< and >>), along with the bitwise OR and AND. They're what you're going to need, especially since atoi() would only give you a 16 bit, signed integer.

Let's say that your variable's binary is this (split up into 4 segments):

10010010 10110101 01010010 10010100

Sending

uint32_t myVarCopy = myVar;
for(int i = 0; i < 4; i++) {
    Serial.write(myVarCopy & 255);
    myVarCopy = myVarCopy >> 8;
}

The first line in the loop modifies the variable by bitshifting right eight to allow us to read the data eight bits at a time. We have to, whenever sending data through the serial port, "trim" any data that is in the 9th digit or above using the & 255 part. This allows us to split this int up into four bytes.

How the myVarCopy variable would look over the four iterations:

After 1: 00000000 10010010 10110101 01010010 (sent 10010100)
After 2: 00000000 00000000 10010010 10110101 (sent 01010010)
After 3: 00000000 00000000 00000000 10010010 (sent 10110101)
After 4: 00000000 00000000 00000000 00000000 (sent 10010010)

Reading

uint32_t buffer = 0;
for(int i = 0; i < 4; i++) {
    buffer = (buffer >> 8) | (Serial.read() << 24);
}

This code works by adding the newest data onto the digits 25-32 after it moves everything else over eight bits.

This is how the buffer variable would look over the four iterations:

After 1: 10010100 00000000 00000000 00000000
After 2: 01010010 10010100 00000000 00000000
After 3: 10110101 01010010 10010100 00000000
After 4: 10010010 10110101 01010010 10010100

Depending on how Processing works, you might have to worry about little/big endian encoding to ensure that your data is in the right order. Warning: I haven't tested these yet as an IDE isn't installed on the computer I'm typing this on. Also, I don't know the exact function calls for Processing, so it might not compile.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.