0

I am writing a Python script, that sends a character to an Arduino and the Arduino prints the received character back. But in this case, the Arduino is always giving a garbage value. Also there is no error while executing the Python script.

I have checked multiple blogs, articles and tutorials and followed the exact steps, but I got no solution.

This is my Python script:

import serial
ser = serial.Serial("/dev/ttyACM0",9600)
ser.write('8')
read=ser.readline()
print(read)

This is the Arduino code:

int temp;
void setup() {
  Serial.begin(9600);
  temp=5;
}

void loop() {
  temp=Serial.read();
  Serial.println(temp);
  delay(1000);
}

Arduino always prints -1 in response.

2 Answers 2

2

Documentation on Serial.read():

Returns

the first byte of incoming serial data available (or -1 if no data is available) - int

So do as Ivan Sheigets suggested or

void setup() {
  Serial.begin(9600);
  Serial.print("You sent: ");
}

void loop() {
  int temp=Serial.read();
  if(temp>=0)
    Serial.print((char)temp);
}

Make sure to cast the incoming value to char (char)temp.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to add Serial.available().

void loop() 
{
    if (Serial.available() > 0)
    {
      temp=Serial.read();
      Serial.print(" I received:");
      Serial.println(temp);
    }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.