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

我正在通过串行端口从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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值