I have arduino uno with simple firmware which provides simple API over serial port:
Command "read" returns the current state
Command "on" sets the state to "on"
Command "off" sets the state to "off"
Now I want to implement a client for this device.
If I use Arduino IDE serial monitor, this API works as expected.
If I use python with pySerial library, API works.
But whenever I try to read data from the serial port using golang and go-serial, my read calls hangs (but works fine with /dev/pts/X created by socat, for example)
Python client
import serial
s = serial.Serial("/dev/ttyACM0")
s.write("read\n")
resp = []
char = None
while char != "\r":
char = s.read()
resp.append(char)
print "".join(resp)
Go client (hangs on Read call forever):
package main
import "fmt"
import "github.com/jacobsa/go-serial/serial"
func check(err error) {
if err != nil {
panic(err.Error())
}
}
func main() {
options := serial.OpenOptions{
PortName: "/dev/ttyACM0",
BaudRate: 19200,
DataBits: 8,
StopBits: 1,
MinimumReadSize: 4,
}
port, err := serial.Open(options)
check(err)
n, err := port.Write([]byte("read\n"))
check(err)
fmt.Println("Written", n)
buf := make([]byte, 100)
n, err = port.Read(buf)
check(err)
fmt.Println("Readen", n)
fmt.Println(string(buf))
}
Firmware code:
String inputString = ""; // a String to hold incoming data
boolean stringComplete = false; // whether the string is complete
String state = "off";
void setup() {
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
pinMode(13, OUTPUT);
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
blink();
if (inputString == "on\n") {
state = "on";
} else if (inputString == "off\n") {
state = "off";
} else if (inputString == "read\n") {
Serial.println(state );
}
// clear the string:
inputString = "";
stringComplete = false;
}
}
void blink() {
digitalWrite(13, HIGH); // set the LED on
delay(1000); // wait for a second
digitalWrite(13, LOW); // set the LED off
delay(1000); // wait for a second
}
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag so the main loop can
// do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
Python code
You have set the baud rate for the Go lang function to 19200, but in the arduino you have used 9600.
In the python code, the baud rate is not set, so it takes the default of 9600.
Just set the right baud rate in your go lang program, and it should work.
Related
I'm trying to send a string from a C++ client on one computer to a Python server on another computer.
My error is send: Bad file descriptor
The Python server is killed if it is contacted by the client but it doesn't receive a string. While the Python server is running it does end the program when I attempt to send the string from the C++ client. So I know the server is being reached by the client when I execute it.
I am able to send strings to the server from the C++ client's computer with a Python client script. Since it's not a basic problem with the server I don't think this and other answers apply to my problem.
On the Python script I have tried changing this number.
s.listen(11)
Here is the Python server
import os
import sys
import socket
s=socket.socket()
host='192.168.0.101'
port=12003
s.bind((host,port))
s.listen(11)
while True:
c, addr=s.accept()
content=c.recv(1024).decode('utf-8')
print(content)
if not content:
break
Here is the C++ client
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <unistd.h>
#define ADDR "192.168.0.101"
#define PORT "12003"
void sendall(int socket, char *bytes, int length)
{
int n = 0, total = 0;
while (total < length) {
n = send(socket, bytes + total, total-length, 0);
if (n == -1) {
perror("send");
exit(1);
}
total += n;
}
}
int main()
{
struct addrinfo hints = {0}, *addr = NULL;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
int status = getaddrinfo(ADDR, PORT, &hints, &addr);
if (status != 0) {
fprintf(stderr, "getaddrinfo()\n");
exit(1);
}
int sock = -1;
{
struct addrinfo *p = NULL;
for (p = addr; p != NULL; p = addr->ai_next) {
int sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sock == -1) {
continue;
}
if (connect(sock, p->ai_addr, p->ai_addrlen) != -1) {
break;
}
close(sock);
}
if (p == NULL) {
fprintf(stderr, "connect(), socket()\n");
exit(1);
}
freeaddrinfo(addr);
/* Do whatever. */
sendall(sock, "Hello, World", 12);
/* Do whatever. */
}
close(sock);
return 0;
}
UPDATE:
In the client there was an unessacary int in front of sock = socket...
I removed it and now I'm getting an error on the server side when I send the string that reads..
$ python server.py
Traceback (most recent call last):
File "/home/computer/server.py", line 35, in <module>
content=c.recv(1024).decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfc in position 29: invalid start byte
You're redeclaring the sock variable in the for loop, so the value of sock when you call sendall() is the original -1. Change
int sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
to
sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
so it assigns the outer variable.
I want the Arduino to send information to the python script only when the Arduino receives the correct command from the python script. There seems to be a miscommunication somewhere.
Arduino code:
char inChar;
bool serial_ready;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
while (!Serial) {
;
}
}
void loop() {
// put your main code here, to run repeatedly:
while (Serial.available()) {
// read the incoming byte:
inChar = Serial.read();
if (inChar == 'r') {
Serial.print('L');
} else {
Serial.print(inChar);
}
serial_ready = false;
}
}
Python script:
import serial
if __name__ == '__main__':
ser = serial.Serial('COM4',115200,timeout=0)
# send signal to arduino
ser.reset_input_buffer()
ser.reset_output_buffer()
try:
ser.write(b'r')
while (ser.inWaiting() <= 0):
print('waiting')
byte_wait = ser.inWaiting()
ard_in = ser.read(byte_wait)
print(ard_in)
except KeyboardInterrupt:
print('KeyboardInterrupt')
ser.close()
Sometimes I get b'\xf0' after a few waiting are printed out (which is not what I'm looking for) and sometimes it gets stuck in the loop and just prints waiting until I stop it. Why does it return b'\xf0' instead of L or r? Why does it sometimes not return anything?
Thanks in advance!
Here a test with the onboard LED and a flushing the buffer (works only if you are not hammering data from the phyton side);
// Open a serial connection and flash LED when input is received
int ledRed = 13; // Onboard LED connected to digital pin 13
char inChar;
bool serial_ready;
void setup() {
pinMode(ledRed, OUTPUT);
Serial.begin(115200);
while (!Serial) {
;
}
}
void loop() {
// put your main code here, to run repeatedly:
while (Serial.available()) {
// read the incoming byte:
digitalWrite(ledRed, HIGH);
inChar = Serial.read();
if (inChar == 'r') {
Serial.print('L');
} else {
Serial.print(inChar);
}
digitalWrite(ledRed, LOW);
Serial.flush();
}
}
I've some problem writing serial bytes from a python code to arduino.
The python code had to write to serial port a number that the arduino receive.
Python3 code:
import serial
import time
ser = serial.Serial ('/dev/ttyACM0',)
ser.baudrate = 115200
ser.write(str(3).encode()) #or (b'3')
ser.write(str('\n').encode())
Arduino code:
void setup(){
Serial.begin (115200); //Comunicazione seriale 115200 bit
servomotore.attach(3);
pinMode(2,OUTPUT);
pinMode(12,OUTPUT);
pinMode(13,OUTPUT);
digitalWrite(2,HIGH);
digitalWrite(12,HIGH);
servomotore.write(180);
}
/*Il loop comprende due funzioni; sensori e Mappa, attivate ogni 15 gradi di movimento del servomotore,
sensori rileva le distanze, Mappa invia i valori al seriale, ogni ciclo del radar produce 24 valori in centimetri*/
void loop() {
char buffer[] = {' ',' '};
if (Serial.available() > 0) {
Serial.readBytesUntil('n', buffer, 2);
int incremento = atoi(buffer);
If I run this code I can't see output, no error or print, I need to exit with ctrl+c. Arduino doesn't receive nothing.
The Arduino code is longer, this is the only part that I can't understand in this moment, it's only a part of a most complex project
I cannot reproduce your problem. Here is how I tested it. On the Arduino Uno setup the following program:
void setup()
{
Serial.begin(115200);
Serial.println(F("Serial test"));
}
char buffer[80] = { 0 };
void loop()
{
if (Serial.available() > 0)
{
Serial.readBytesUntil('\n', buffer, sizeof(buffer));
Serial.print(F("read: ["));
Serial.print(buffer);
Serial.println("]");
memset(buffer, 0, sizeof(buffer));
}
}
The following python3 script successfully reads and writes to this Arduino firmware:
#!/usr/bin/env python3
import sys
from serial import Serial
def main():
ser = Serial('/dev/ttyACM0',)
ser.baudrate = 115200
print(ser.readline())
ser.write(str(3).encode())
ser.write(str('\n').encode())
print(ser.readline())
return 0
if __name__ == '__main__':
sys.exit(main())
I get the following output once the device is programmed and plugged in:
~ $ python3 so-check-serial.py
b'Serial test\r\n'
b'read: [3]\r\n'
Alternative interrupt based serial input
I'd like to add that I would not normally write a serial handler like this in Arduino. The following uses the serial interrupt to buffer the input and set a flag when the line is read completely. In this example we can wait or do other things until a whole line has been receivied (ie: keep blinking at the right times):
#include <Arduino.h>
volatile String buffer;
volatile bool inputComplete = false;
void serialEvent()
{
while (Serial.available())
{
char c = (char)Serial.read();
if (c == '\n')
inputComplete = true;
else
buffer += c;
}
}
void setup()
{
Serial.begin(115200);
Serial.println(F("Serial test"));
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
}
void loop()
{
if (inputComplete) {
inputComplete = false;
Serial.println(buffer.c_str());
buffer = "";
}
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
delay(500);
}
I'm trying to read lines from an Arduino board with a very simple code (for the sake of showcasing the problem) on Linux.
Python code:
# arduino.py
import serial
arduino = serial.Serial('/dev/ttyACM0')
with arduino:
while True:
print(arduino.readline())
Arduino code:
// simpleWrite.ino
long ii = 0;
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}
void loop() {
Serial.println(ii);
ii++;
}
As the board auto-resets when the serial connection is opened, the first bytes are likely garbage. After a second or two everything works fine.
This is a typical output:
$ python arduino.py
b'09\r\n'
b'540\r\n'
b'541\r\n'
b'542\r\n'
b'543\r\n'
b'544\r\n'
b'545\r\n'
b'546\r\n'
b'547\r\n'
b'548\r\n'
b'549\r\n'
b'550\r\n'
b'551\r\n'
b'552\r\n'
b'553\r\n'
b'554\r\n'
b'555\r\n'
b'556\r\n'
b'557\r\n'
b'55\xfe0\r\n' # <---- Here the board restarted
b'1\r\n'
b'2\r\n'
b'3\r\n'
b'4\r\n'
b'5\r\n'
b'6\r\n'
b'7\r\n'
b'8\r\n'
b'9\r\n'
b'10\r\n'
However, I see the Arduino IDE Serial Monitor doesn't have this problem, and properly shows a delay (while restarting) and then prints all the lines starting from the first one.
Is there a way to emulate this behaviour in Python using pySerial? That is, discarding all the output before restarting and nothing more? Perhaps through some low-level functions?
I tried looking at the relevant Arduino source code, but I don't know Java and it didn't help.
Note: Of course I could sleep for, say, three seconds, discard everything and start from there, but I would probably discard some of the first lines too.
Edit: Apparently, this problem doesn't exist on Windows and the accepted solution was not necessary.
The Arduino IDE's monitor toggle's the assigned DTR pin of the port when connected. Where this toggling causes a reset on the Arduino. Noting that the DTR is toggled after the Monitor has opened the Serial port and is ready to receive data. In your case the below example should do the same.
Import serial
arduino = serial.Serial('/dev/ttyS0',
baudrate=9600,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=1,
xonxoff=0,
rtscts=0
)
# Toggle DTR to reset Arduino
arduino.setDTR(False)
sleep(1)
# toss any data already received, see
# http://pyserial.sourceforge.net/pyserial_api.html#serial.Serial.flushInput
arduino.flushInput()
arduino.setDTR(True)
with arduino:
while True:
print(arduino.readline())
I would also add the compliment to the DTR for the Arduino's with AVR's using built-in USB, such as the Leonoardo, Esplora and alike. The setup() should have the following while, to wait for the USB to be opened by the Host.
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
}
It will have no effect for FTDI's based UNO's and such.
I realize this is an old question, but hopefully this can be useful to somebody else out there with the same problem.
I had an issue where if I used any baudrates other than 9600, the serial connection in python would just receive gibberish all the time, even if Serial.begin(...) is properly set on the arduino and matches the value used in the python code.
I read online that the bootloader or watchdog may take a second to load (when the board is power-cycled) and it may send stuff over serial at some specific baudrate (for chip programming possibly). I'm guessing that this is what messes up the serial communication in python.
Here's the piece of code that gives me reliable results:
import serial
from time import sleep
arduino = serial.Serial('/dev/ttyACM0') # dummy connection to receive all the watchdog gibberish (unplug + replug) and properly reset the arduino
with arduino: # the reset part is actually optional but the sleep is nice to have either way.
arduino.setDTR(False)
sleep(1)
arduino.flushInput()
arduino.setDTR(True)
# reopen the serial, but this time with proper baudrate. This is the correct and working connection.
arduino = serial.Serial('/dev/ttyACM0',baudrate=57600)
with arduino:
while True:
print(arduino.readline())
The code used on the arduino side for testing is as simple as this:
void setup() {
Serial.begin(57600);
Serial.println("setup");
}
void loop() {
Serial.println("hello");
delay(200);
}
Please follow this link for a reliable PC-Arduino USB serial communication using python.
Python code simply sends a short message to the Arduino and prints the reply it receives.
// This is very similar to Example 3 - Receive with start- and end-markers
// in Serial Input Basics http://forum.arduino.cc/index.php?topic=396450.0
const byte numChars = 64;
char receivedChars[numChars];
boolean newData = false;
byte ledPin = 13; // the onboard LED
//===============
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
delay(200);
digitalWrite(ledPin, LOW);
delay(200);
digitalWrite(ledPin, HIGH);
Serial.println("<Arduino is ready>");
}
//===============
void loop() {
recvWithStartEndMarkers();
replyToPython();
}
//===============
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
}
}
else if (rc == startMarker) {
recvInProgress = true;
}
}
}
//===============
void replyToPython() {
if (newData == true) {
Serial.print("<This just in ... ");
Serial.print(receivedChars);
Serial.print(" ");
Serial.print(millis());
Serial.print('>');
// change the state of the LED everytime a reply is sent
digitalWrite(ledPin, ! digitalRead(ledPin));
newData = false;
}
}
//===============
Python Code
import serial
import time
startMarker = '<'
endMarker = '>'
dataStarted = False
dataBuf = ""
messageComplete = False
#========================
#========================
# the functions
def setupSerial(baudRate, serialPortName):
global serialPort
serialPort = serial.Serial(port= serialPortName, baudrate = baudRate, timeout=0, rtscts=True)
print("Serial port " + serialPortName + " opened Baudrate " + str(baudRate))
waitForArduino()
#========================
def sendToArduino(stringToSend):
# this adds the start- and end-markers before sending
global startMarker, endMarker, serialPort
stringWithMarkers = (startMarker)
stringWithMarkers += stringToSend
stringWithMarkers += (endMarker)
serialPort.write(stringWithMarkers.encode('utf-8')) # encode needed for Python3
#==================
def recvLikeArduino():
global startMarker, endMarker, serialPort, dataStarted, dataBuf, messageComplete
if serialPort.inWaiting() > 0 and messageComplete == False:
x = serialPort.read().decode("utf-8") # decode needed for Python3
if dataStarted == True:
if x != endMarker:
dataBuf = dataBuf + x
else:
dataStarted = False
messageComplete = True
elif x == startMarker:
dataBuf = ''
dataStarted = True
if (messageComplete == True):
messageComplete = False
return dataBuf
else:
return "XXX"
#==================
def waitForArduino():
# wait until the Arduino sends 'Arduino is ready' - allows time for Arduino reset
# it also ensures that any bytes left over from a previous message are discarded
print("Waiting for Arduino to reset")
msg = ""
while msg.find("Arduino is ready") == -1:
msg = recvLikeArduino()
if not (msg == 'XXX'):
print(msg)
#====================
#====================
# the program
setupSerial(115200, "/dev/ttyACM0")
count = 0
prevTime = time.time()
while True:
# check for a reply
arduinoReply = recvLikeArduino()
if not (arduinoReply == 'XXX'):
print ("Time %s Reply %s" %(time.time(), arduinoReply))
# send a message at intervals
if time.time() - prevTime > 1.0:
sendToArduino("this is a test " + str(count))
prevTime = time.time()
count += 1
you need to set your var , try:
unsigned long ii = 0;
but pay attention that this is a 32 bit var and when it is full ,cause overflow and reboot.
for me work.
As suggested by #Kobi K add a minimal delay time, for load real data at 9600 boud each char has a duration of 2 ms,
void loop() {
Serial.println(ii);
delay(20);
ii++;
}
And in python you need to declare a Pyserial like this:
arduino=serial.Serial('/dev/ttyACM0',9600,timeout=0.0001)
hope this help you
I would like to set up a serial communication between a Python daemon and an Arduino.
At first, the Python daemon sets up a serial connection that will last for the whole lifetime of the daemon. Through this connection, I would like to send data to the Arduino and receive back data in the acks variable every time the Python daemon receives commands.
The problem is that while the first time the communication goes well, nothing is sent through serial afterwards. If I make the a new connection for every request it works, but it makes the program very slow, which I'd like to avoid.
edit: the real issue is when send a correct string to the arduio evrything goes well but when i send a wrong one the serial port block and it will never reconize corrct strings again( the problem is in the arduino code)
Python code:
import serial
import time
import sys
from socket import *
import threading
import thread
def handler(clientsock,addr):
while 1:
#arduino.flush()
data = clientsock.recv(BUFSIZ)
if not data:
break
print data
print data
#time.sleep(3)
arduino.write(data)
#time.sleep(3)
ack = arduino.readline(1)
arduino.flush()
clientsock.send(ack+"\n")
clientsock.close()
if __name__=='__main__':
HOST = '0.0.0.0'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
arduino = serial.Serial('/dev/ttyACM0',9600,timeout=6)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR)
serversock.listen(2)
while 1:
print 'waiting for connection...'
clientsock, addr = serversock.accept()
print '...connected from:', addr
thread.start_new_thread(handler, (clientsock, addr))
Arduino code:
int relayPinCH1 = 7; // pin de commande du relais 1
char inData[20]; // Allocate some space for the string
char inChar=-1; // Where to store the character read
byte index = 0; // Index into array; where to store the character
void setup()
{
pinMode(relayPinCH1, OUTPUT);
Serial.begin(9600);
}
char Comp(char* This) {
while (Serial.available() > 0) // Don't read unless
// there you know there is data
{
if(index < 19) // One less than the size of the array
{
inChar = Serial.read(); // Read a character
inData[index] = inChar; // Store it
index++; // Increment where to write next
inData[index] = '\0'; // Null terminate the string
}
}
Serial.flush();
if (strcmp(inData,This) == 0) {
for (int i=0;i<19;i++) {
inData[i]=0;
}
index=0;
return(0);
}
else {
return(1);
}
}
void loop()
{
//Serial.println("Hello Pi");
if (Comp("l11\n")==0)
{
Serial.flush();
digitalWrite(relayPinCH1, HIGH);
Serial.println("y");
}
if (Comp("l10\n")==0)
{
Serial.flush();
digitalWrite(relayPinCH1, LOW);
Serial.println("n");
}
delay(1000);
}
In your Arduino code, your logic is kind of funky - so, I'm not sure, but are you clearing index to 0 before you start the loop again? It looks like once index == 19, it may or may not get reset to 0 depending upon later logic. If you enter Comp() a second time and index >= 19 then you'll never read the serial port again.
I think #Zeus is entirely right (and hence I upvoted that answer), but there are also other problems. To reiterate what #Zeus is saying:
index is only reset to 0 if the comparison succeeds. So your buffer is full, the string you are looking for isn't there, and index never goes back to 0 again.
Once index reaches 19, no more reading is done. As a result, whatever is in inData stays in inData and all the future comparisons will fail, meaning index will never get reset to 0.
There are a number of other problems in the code, but the main issue is that the design is very fragile, and prone to exactly the sort of error you are experiencing. For instance if the newlinews your Python script is sending are CR+LF for newlines, but you are expecting CR only, you'll have the same sort of failure you have now: first time communications work, but never again.
I would suggest reorganizing your code like this:
Your function for reading serial port reads a line from a serial port and returns that to the caller (without the newlines), regardless of the content of the communications.
The caller compares the line received from the serial port with the list of known commands and executes them accordingly.
This might look rougly as follows
char strCommand[0xFF];
int idxCommandChar;
// Read a command from serial, returning the command size
// This function BLOCKS, i.e., doesn't return until a command is available
int readSerialCommand() {
// We reset the index to zero on every read: the command is overwritten every time
idxCommandChar = 0;
// Read serial characters and store them in strCommand
// until we get a newline
int in = Serial.read();
while (in!='\n') {
strCommand[idxCommandChar++] = in;
in = Serial.read();
}
// Add the string terminator
strCommand[idxCommandChar++] = '\0';
// Return command size
return idxCommandChar;
}
// Get command from serial, and process it.
void processCommand() {
readSerialCommand();
if (strcmp(strCommand, "CMD1")==0) {
// do something
} else if (strcmp(strCommand, "CMD2")==0) {
// do something else
} else {
// Unknown command
Serial.println("Unknown command");
}
}
void loop() {
processCommand();
delay(1000);
}
This code blocks on serial, i.e. doesn't return until a newline is detected. You could easily modify the code to be non-blocking, perhaps like this:
/* Read serial characters, if available and store them in strCommand
until we get a newline
Returns 0 if no command is available */
int readSerialCommand() {
idxCommandChar = 0;
while (Serial.available()) {
int in = Serial.read();
while (in!='\n') {
strCommand[idxCommandChar++] = in;
in = Serial.read();
}
strCommand[idxCommandChar++] = '\0';
return idxCommandChar;
}
return 0;
}
// Get command from serial (if available), and process it.
void processCommand() {
if (readSerialCommand()) {
....
In either case you might loose serial characters while you are waiting, so you may want to rethink that strategy.