I'm using an Arduino Due to make a feedback loop using python, but this does not seem to function. The python code I'm using is the following:
from serial import Serial
board = Serial('COM11',9600)
board.write('100'.encode()) # 100 is taken as an example
In fact, if I just use Arduino to measure the sensor voltage, it succeeds. It's the same if the voltage is sent without measuring the sensor. But, as soon as I put both simultaneously, the sensor is good but nothing is read by the Arduino. However, if I send the voltage not using Python but using the Arduino IDE, everything is okay.
It seems that the Arduino can't do the two operations at the same time, but this is weird. Here is my Arduino code:
int const controller = DAC0; // Set the controller output pin
int const sensor = A1; // Set the sensor pin
double MeanNumber = 500;
void setup() {
Serial.begin(9600);
pinMode(controller, OUTPUT);
analogReadResolution(12);
}
double get_voltage(int Measure)
{
double voltage;
voltage = Measure * 3.3 / 4095.0;
return voltage;
}
void loop() {
double Measure = 0;
double voltage;
for (int i = 0; i < int(MeanNumber); i++) // Realize an average each MeanNumber value
{
Measure = Measure + analogRead(sensor) / MeanNumber;
delay(1);
}
// Send the averaged measure to python
voltage = get_voltage(Measure);
Serial.println(voltage,4);
// Get the feedback from python
if (Serial.available() > 0)
{// Verify if data are available
String receivedData = Serial.readString(); // Read the voltage value from bytes to string
float value = receivedData.toFloat(); // Convert the voltage into float
analogWrite(controller,value); // Send the signal via the Arduino
}
}
Do you have an idea of what is wrong with my job?
-
Whenever Python opens a port, the Arduino will get reset. What usually helps is right after you open a port in Python, sleep for a couple of seconds (time.sleep(3)).Fahad– Fahad2023年06月12日 02:40:05 +00:00Commented Jun 12, 2023 at 2:40
1 Answer 1
Opening a Serial connection will reset the Arduino. The python code may be doing that when it creates the port. Put a Serial.print("Starting") line in your setup function to see if that's what is happening.