Hi,
I’m beginning in Arduino programming, and I’m having some trouble with the Serial.write() command>
I have a arduino programm that works fine in the arduino IDE’s Serial terminal. I can write commands and it returns me some text.
Now I’m trying to use python to do this, I can read data from the port (for example I can read “begin” at the beginning of the programm).
Here is my arduino code :
#include <BMDSDIControl.h>
#include <stdlib.h>
const int shieldAddress = 0x6E;
BMD_SDICameraControl_I2C sdiCameraControl(shieldAddress);
String inString = "";
boolean error = false;
void setup() {
sdiCameraControl.begin();
sdiCameraControl.setOverride(true);
Serial.begin(9600);
Serial.println("debut");
}
void loop() {
if (Serial.available() > 0) { // is a character available?
int inChar = Serial.read();
error = false;
//loop();
if (inChar != '\n') {
// As long as the incoming byte
// is not a newline,
// convert the incoming byte to a char
// and add it to the string
inString += (char)inChar;
}
else {
if(inString.substring(0,1) != "f" && inString.substring(0,1) != "a" || inString.substring(0) == "f" || inString.substring(0) == "a") {
Serial.println("Write 'f<value>' to set focus and 'a<value>' to set aperture");
error = true;
//return 0;
}
if (inString.substring(1) > "1"){
Serial.println("Value can't exceed 1.");
error = true;
}
if (inString.substring(1) < "0"){
Serial.println("Value can't be less than 0.");
error = true;
}
if(inString.substring(0,1) == "f" && error == false){
Serial.print("Input string: ");
Serial.print(inString + ".");
Serial.print("\t Focus value is: ");
inString.remove(0,1);
Serial.println(inString);
sdiCameraControl.writeCommandFixed16(
4, // Destination: Camera 4
0, // Category: Lens
0, // Param: Instantaneous Autofocus;
0,
inString.toFloat()
);
inString = "";
}
if(inString.substring(0,1) == "a" && error == false){
Serial.print("Input string: ");
Serial.print(inString + ".");
Serial.print("\t Aperture value is: ");
inString.remove(0,1);
Serial.println(inString);
sdiCameraControl.writeCommandFixed16(
4, // Destination: Camera 4
0, // Category: Lens
3, // Param: Aperture;
0,
inString.toFloat()
);
inString = "";
}
// clear the string for new input:
inString = "";
}
}
}
And here is my python code:
import serial
import time
arduino = serial.Serial("COM3",baudrate = 9600, timeout = 2)
#arduino.open()
print(arduino.is_open)
time.sleep(2)
def sendCommand(command):
arduino.write(b"command")
done = arduino.readline()
doneDecoded = done.decode('ascii')
print(doneDecoded)
print(done)
print('done')
pass
while True:
command = input(" Write your command : ")
sendCommand(command)
I have also tried using the python interpretor, and also using putty but the same happens, I have this response :
Write your command : f0
b’’
done
I have seen a bunch of people having the same problem but I have never found a solution to this.