I have an STM32 connected to a thermal sensor which indicate the temperature of the room and i worte this program to read this temperatur from my com port. Now i need a program to read multiple value from my com port. thank you for helping me to solve this problem.
import serial
serport = 'COM3'
serbaudrate = 38400
ser = serial.Serial(port = serport, baudrate = serbaudrate, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, timeout=2)
try:
ser.isOpen()
except:
print("Error")
exit()
if ser.isOpen():
try:
while 1:
if ser.inWaiting() > 0:
#print(ser.readline())
response = ser.readline()
print(response.decode("utf-8"))
else:
ser.write(b"1")
except Exception as e:
print(e)
@Tarmo thank you for answering my question. This is the code i wrote for programming th microcontroller:
while (1)
{
// Test: Set GPIO pin high
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_SET);
// Get ADC value
HAL_ADC_Start(&hadc1);
HAL_ADC_PollForConversion(&hadc1, HAL_MAX_DELAY);
raw = HAL_ADC_GetValue(&hadc1);
raw = ((raw*0.000244*3.3) - 0.25)/0.028;
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_RESET);
// Convert to string and print
sprintf(msg, "%hu\r\n", raw);
HAL_UART_Transmit(&huart2, (uint8_t*)msg, strlen(msg), HAL_MAX_DELAY);
// Pretend we have to do something else for a while
HAL_Delay(100);
}
in this case i am reading just one value because the thermal sensor gives only one value. if i have more than one value how can i delimit them with a semicolon?
If you've already gone the way of sending a numeric value as text, you can extend that. Assuming you want to send 3 integer values at the same time, just delimit them with a semicolon. E.g. 123;456;789\n
.
Your microcontroller should then output data in this format and your Python program can read the entire line just like it does now. The you can parse this line into individual values using regex:
import re
...
response = ser.readline()
needles = re.match("(\d+);(\d+);(\d+)", response)
if needles:
print("Got: {} {} {}".format(needles[0], needles[1], needles[2]))