[英]How to send int or string from Python over pySerial and turn in to int or String in C
我正在通过串行端口在我的 Arduino UNO 上从 Python 向 C 程序发送一个用 ASCII 编码的字符串 1 和一个字符串 0。
我能够在 C 中接收编码数据,其中 1 为 0x31,2 为 0x30,这是我所期望的,因为它是字符 1 和字符 2 的 ASCII 十六进制。
我可以在它的 ASCII state 中读取/使用它。 但现在我想要这个数据:0x31 被转换成 int 1 或 char 1 和 0x30 成 int 0 或 C 中的 char 0。 我试过atoi(receivedData)
(字面意思是:ASCII to int)但这不起作用,我已经将atoi(receivedData)
结果发回,我在 Python 中得到了 0x00。
我怎么能 go 关于这样做?
这是我的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<<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
receivedDataTemp = receivedData - '0';
Python
myStr1 = b'1'
myStr0 = b'0'
serialC.write(myStr1)
print(int(serialC.read().decode()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.