如何通过pySerial从Python发送int或字符串,并在C语言中转换为int或String

问题描述 投票:0回答:1

我正在通过串行端口从Python向Arduino UNO上的C程序发送用ASCII编码的字符串1和字符串0。

我能够在C中接收1的0x31和2的0x30的编码数据,这是我期望的,因为char 1和char 2是ASCII十六进制。

我可以以ASCII状态读取/使用它。但是现在我想要这些数据:0x31转换为int 1或char 1,0x30转换为int 0或char 0(在C语言中)。工作,我将atoi(receivedData)结果发送回去,并且在Python中得到了0x00。

我该怎么做?

这是我的C代码:

atoi(receivedData)

这是我的Python代码:

uint8_t receivedData;

void uart_init()
{
    // set the baud rate
    UBRR0H = 0;
    UBRR0L = UBBRVAL;
    // disable U2X mode
    UCSR0A = 0;
    // enable receiver & transmitter
    UCSR0B = (1<<RXEN0) | (1<<TXEN0); // Turn on the transmission and reception circuitry
    // set frame format : asynchronous, 8 data bits, 1 stop bit, no parity
    UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);
}

void receive(void)
{
    loop_until_bit_is_set(UCSR0A, RXC0);
    receivedData = UDR0;
}

void transmit(uint8_t dataa)
{
    loop_until_bit_is_set(UCSR0A, UDRE0);
    UDR0 = dataa
}

void processData() {
    cleanUDR0();

    // 0x31 is ascii code for 1, 0x30 is 0
    // led turns on if input == 1 (0x31) and turns off if led == 0 (0x30)
    receive();

    transmit(receivedData);

    int temporary = atoi(receivedData);

    if (temoraray == 1){
        PORTD = 0xff; // Turning LEDs on
    }
    else if (temporary == 0){
        PORTD = 0x00; // Turning LEDs off
    }
}

void cleanUDR0(void) {
    unsigned char y;
    while (UCSR0A & (1<<RXC0)) y=UDR0;
}

int main(void)
{
   DDRD = 0xFF;
   uart_init();

   While(1) {
      processData();
   }
}
python c arduino ascii pyserial
1个回答
0
投票

检查答案的注释。

C

import time
import threading
import serial


class SerialT(threading.Thread):
    connected = False

    serialC = serial.Serial("COM4", 19200)

    while not connected:
        serin = serialC.read()
        connected = True

    while True:
        myStr1 = '1'
        myStr0 = "0"

        serialC.write(myStr1.encode('ascii'))
        print(int(chr(ord(serialC.read()))))

        time.sleep(2)

        serialC.write(myStr0.encode('ascii'))
        print(int(chr(ord(serialC.read()))))

        time.sleep(2)

Python

receivedDataTemp = receivedData - '0';
© www.soinside.com 2019 - 2024. All rights reserved.