Sending string to serial.to_bytes not working
<p>I am trying to send a string variable contains the command.</p>

<p>Like this:</p>

<pre><code>value="[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]"
self.s.write(serial.to_bytes(value))
</code></pre>

<p>The above one fails. Won't give any error.</p>

<p>But it's working when I send a value like this:</p>

<pre><code>self.s.write(serial.to_bytes([0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]))
</code></pre>

<p>I also tried sending string like this:</p>

<pre><code>self.s.write(serial.to_bytes(str(value)))
</code></pre>

<p>Still not working. Can someone please let me know how to send the value by storing in string?</p>

<p>I want to do this thing:</p>

<pre><code>value="[0x"+anotherstring+",0x"+string2+"0x33, 0x0a]"
</code></pre>

<p>and send the value.</p>

<p>Thanks!</p>

<p><a href="https://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.to_bytes" rel="nofollow">serial.to_bytes</a> takes a sequence as input. You should remove double quotes around <code>value</code> to pass a sequence of integers instead of a <code>str</code> representing the sequence you want to pass:</p>

<pre><code>value = [0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]
self.s.write(serial.to_bytes(value))  # works now
</code></pre>

<p>In the first case, you sent a sequence of bytes representing <code>"[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]"</code>. Now, you will send the sequence <code>[0x31, 0x0a, 0x32, 0x0a, 0x33, 0x0a]</code> as expected.</p>

<hr>

<p>If you want to send a string, just send it as <code>bytes</code>:</p>

<pre><code># Python 2
self.s.write('this is my string')
text = 'a string'
self.s.write(text)

# Python 3
self.s.write(b'this is my string')
text = 'a string'
self.s.write(text.encode())
</code></pre>

<p>And for a sequence:</p>

<pre><code>for value in values:
    # Python 2
    self.s.write(value)

    # Python 3
    self.s.write(value.encode())
</code></pre>

python pyserial