我正在通过一个串行端口将一个字符串1和一个用ASCII编码的字符串0从Python发送到Arduino UNO上的一个C程序
我能够接收编码数据在C是0x31为1和0x30为2,这是我所期望的,因为它是ASCII十六进制字符1和字符2
我可以在ASCII状态下读取/使用它。但现在我想把这个数据:0x31转换成int 1或char 1,0x30转换成int 0或char 0。我试过atoi(receivedData)
(字面意思是:ASCII到int),但这不起作用,我已经将atoi(receivedData)
结果发送回来,在Python中得到一个0x00
我该怎么做呢
这是我的代码:
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代码:
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)
检查注释以获得答案
C
Python
相关问题 更多 >
编程相关推荐