我正在通过串行端口从Python向Arduino UNO上的C程序发送用ASCII编码的字符串1和字符串0。
我能够接收C中的编码数据,其中1表示0x31,2表示0x30,这是我期望的,因为char 1和char 2是ASCII十六进制。
我可以在ASCII状态下读取/使用它。 但是现在我想要这些数据:在C中将0x31转换为int 1或char 1,将0x30转换为int 0或atoi(receivedData) 。我已经尝试过atoi(receivedData) (字面意思是:将ASCII转换为int),但这没有。工作时,我已将atoi(receivedData)结果发送回去,并且在Python中得到了0x00。
我该怎么做呢?
这是我的C代码:uint8_t receivedData;
void uart_init()
{
// set the baud rate
UBRR0H = 0;
UBRR0L = UBBRVAL;
// disable U2X mode
UCSR0A = 0;
// enable receiver & transmitter
UCSR0B = (1<
// 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<
}
int main(void)
{
DDRD = 0xFF;
uart_init();
While(1) {
processData();
}
}
这是我的Python代码: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)