title: Simple 2-way serial communication between Raspberry Pi and Arduino
body: <p>I want to do simple 2-way serial communication between my Raspberry Pi and my Arduino. This is for a project in which I will replace the Arduino with another serial device which I don't yet have.</p>
  
  <p>I've done 1-way communication (<a href="https://maker.pro/raspberry-pi/tutorial/how-to-connect-and-interface-raspberry-pi-with-arduino" rel="nofollow noreferrer">https://maker.pro/raspberry-pi/tutorial/how-to-connect-and-interface-raspberry-pi-with-arduino</a>) from the Arduino to the Raspberry Pi, but am having a little trouble with 2-way. The Arduino code I use is from this example: <a href="https://www.arduino.cc/en/Serial/Read" rel="nofollow noreferrer">https://www.arduino.cc/en/Serial/Read</a>: </p>
  
  <pre><code>int incomingByte = 0;   // for incoming serial data
  
  void setup() {
          Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
  }
  
  void loop() {
  
          // send data only when you receive data:
          if (Serial.available() &gt; 0) {
                  // read the incoming byte:
                  incomingByte = Serial.read();
  
                  // say what you got:
                  Serial.print("I received: ");
                  Serial.println(incomingByte, DEC);
          }
  }
  </code></pre>
  
  <p>And the Python code I use is this:</p>
  
  <pre><code>import serial
  import time
  ser = serial.Serial('/dev/ttyACM1',9600)
  var1 = "3"
  while True:
      ser.write(var1.encode())
      time.sleep(0.2)
      read_serial=ser.readline()
      print read_serial
  </code></pre>
  
  <p>After looking through the net I have changed the value to be sent from just ser.write('3') to a string 'var1' and put '.encode()' after in order to encode to bytes. No errors come, but nothing happens/is being written out.</p>
  
  <p>The goal for this is for Raspberry Pi to send a '3' to the Arduino and the Arduino to respond with 'I've received: 3' which should be printed in the Raspberry Pi/Python's terminal window. From there I imagine that I can make it more complex towards my goal of sending a command like this: '0 30 50 100' which the device I don't have would respond to.</p>
  
  <p>I appreciate any help. Thank you.</p>