Problems with Decode and Arduino

0

Hello, People

I have the following code in Arduino

if((digitalRead(4) != 1)||(digitalRead(5) != 1))
  {
      Serial.print("\t");
      Serial.print(analogRead(A0));
      Serial.print(",");
      Serial.print(millis());
      Serial.print("\n");
  }

And with it, I read in Python with the following code:

def leituraSerial():
    tempo_leitura = time.time() + (TIMER + 1.6) # Contador de TIMER segundos
    k = 0

    while(time.time() <= tempo_leitura):  

        print("\n Leitura Iniciada!")

        aux = entrada.readline()
        str(aux)
        print(aux.decode('ascii'))

I tried several encodings of cp1252, windows-1250, utf-8, latin_1 and so on .. some return \ x00 with the value I wanted, others give error, the way code is above, it runs, however I add, for example:

ts, tp = aux.split(",")

I already get the following error:

'ascii' codec can't decode byte 0xfe in position 8: ordinal not in range(128) 

If you use utf-8:

'utf-8' codec can't decode byte 0xfd in position 6: invalid start byte

So what the heck is going on?

    
asked by anonymous 17.04.2018 / 05:38

1 answer

2

The problem is not on the Python side -

Your C functions should not be returning strings, and yes, numbers - meaning that the number that is going to the communicated string is garbage (the integer returned by its functions is interpreted as a memory address - the print goes there and reads the contents of that address until it finds a value of 0x00 and puts whatever it found in the string.

If instead of Arduino, at the other end, you had run your program under an operating system with process memory access management, your program would stop with a segmentation fault. But on an 8-bit machine, any C program has equivalent powers to that of the system kernel.

To solve this, if you want to send your data as text, use the function itoa on the side of C- should be something like:

<include stdlib.h>
...
   char tmp[20];
...
if((digitalRead(4) != 1)||(digitalRead(5) != 1))
  {

      Serial.print("\t");
      Serial.print(itoa(analogRead(A0), tmp, 10));
      Serial.print(",");
      Serial.print(itoa(millis(), tmp, 10));
      Serial.print("\n");
  }

So that's your answer.

To complete the encoding information: you do not have to worry about encoding unless you are using accented characters in your Arduino program. If it is - suppose you were sending a complete table and the first line of the header was "analog read, milliseconds \ n" - in that case it would just use the same encoding used in the C file in which you wrote this string, before to compile. The C language does not "know" text, only "bytes" - so if your original C file was in utf-8, the analog "o" would be in the program object, inside the arduino as the string '\ xc3 \ xb3 "- which when received in Python, and treated with" .decode ('utf-8') ", would turn back the letter" o ".

    
17.04.2018 / 14:28