首页 > 解决方案 > 我似乎无法从我的串行 COM11(我正在使用 atmega328p)获取数据到我的 python 代码

问题描述

我正在跟踪机器人。我从 PORTC 引脚中的 ir 传感器获得数字信号。这辆车工作正常。现在我需要通过从我正在使用的 C 代码向我的 python 代码发送一个变量来绘制一个图表。我尝试过使用 USART_transmit 和使用读取功能。我似乎无法将数据获取到我的 python 代码中。这是我的代码。

#define F_CPU 16000000UL
#define BAUD 9600
#define MYUBRR F_CPU/16/BAUD-1
#include <avr/io.h>
#include <util/delay.h>

void USART_Init( unsigned int ubrr);
unsigned char USART_Read();
void USART_Transmit( unsigned char data );

int main(void){
    USART_Init(MYUBRR);
    initIRSensor();
    int check = 0;
    while(1){

        if(PINC == 0b00000001){
            USART_Transmit(1);

        }

    }

    return 0;
}

void USART_Init( unsigned int ubrr)
{
    /*Set baud rate */
    /* UBRR0H contains the 4 most significant bits of the
    baud rate. UBRR0L contains the 8 least significant
    bits.*/  
    UBRR0H = (unsigned char)(ubrr>>8);
    UBRR0L = (unsigned char)ubrr;


    /*Enable transmitter */
    UCSR0B = (1<<RXEN0)  |(1<<TXEN0);

    /* Set frame format: 8data */
    UCSR0C = (1<<USBS0)|(3<<UCSZ00);
}
void USART_Transmit( unsigned char data )
{
    /* Wait for empty transmit buffer */
    while ( !( UCSR0A & (1<<UDRE0)) );

    /* Put data into buffer, sends the data */
    UDR0 = data;
}

unsigned char USART_Read()
{
    /* Wait for empty transmit buffer */
    while ( !( UCSR0A & (1<<RXC0)) );

    /* Put data into buffer, sends the data */
    //UDR0 = data;
    return UDR0;
}

我希望将值 '1' 发送到我的 python 代码,以便我可以制作绘图。这是我的python代码。每当灯泡 1 高时,我都会给出一个增量。我遇到的问题是读取功能无法正常工作。串行通信工作正常,因为我使用了 ser.write 函数并且它运行良好。我遇到的问题是读取函数。希望任何人都可以提供帮助:)

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import serial
import keyboard

bulb1=0
ser = serial.Serial('COM11')
print(ser.name)
while 1:
    if(ser.read() == 1):
        bulb1+=1

标签: pythoncserial-portpyserialusart

解决方案


推荐阅读