首页 > 解决方案 > sending a string like "111#013" in python

问题描述

i have written a code for my microcontroller using the c language and it functions in a way that when i send a 111#013 using the Hercules 3.2.8 app by HW group an led on my board lights up , but i dont know how to send the same thing using python here is my code:

import tkinter as tk
import serial
port=serial.Serial(port='COM3',baudrate=115200,timeout=0)
def led1_on():
    port.write("111".encode(encoding="ascii"))
    print("111".encode(encoding="ascii"))
    port.write(13)

after this when i call led1_on() it doesn't work explanation:the "111#013" means it sends a string 111 and then the number 13 , and the C code uses uart

This is the c code

int i=0,j=0,k=100,len=0;
float v;
char buffer[100];
char Tem[32];
char Rx_data[2],Rx_indx,Rx_Buffer[100],Transfer_cplt;

'

void chartoint(char *str)
{
  j=0;
  while (*str != 0)
  {
    if(*str <= '9' && *str >= '0')
    {j = j*10+(*str - '0');}
    str++;
  }
}

void HAL_UART_RxCpltCallback (UART_HandleTypeDef *huart)
{
  uint8_t i;
  if(huart->Instance==USART1)
  {
    chartoint(buffer);
    
    if(Rx_indx==0)
    {for(i=0;i<100;i++)
      Rx_Buffer[i]=0;}
    if(Rx_data[0]!=13)
    {Rx_Buffer[Rx_indx++]=Rx_data[0];}
    else
    {Rx_indx=0;
    Transfer_cplt=1;}
    HAL_UART_Receive_IT(&huart1,Rx_data,1);
  }
}

'

if(Transfer_cplt)
{
  sprintf(buffer,"%s\r\n",Rx_Buffer);
  chartoint(buffer);
  //LED on-off
  if(j == 103)
    HAL_GPIO_WritePin(GPIOC,1<<8,GPIO_PIN_RESET);
  if(j == 113)
    HAL_GPIO_WritePin(GPIOC,1<<8,GPIO_PIN_SET);
  if(j == 102)
    HAL_GPIO_WritePin(GPIOC,1<<7,GPIO_PIN_RESET);
  if(j == 112)
    HAL_GPIO_WritePin(GPIOC,1<<7,GPIO_PIN_SET);
  if(j == 101)
    HAL_GPIO_WritePin(GPIOB,1<<15,GPIO_PIN_RESET);
  if(j == 111)
    HAL_GPIO_WritePin(GPIOB,1<<15,GPIO_PIN_SET);
  //LED on-off
  if(j<=100)
    k=j*2;
  Transfer_cplt=0;
}

this isnt the latest version of the code and i've changed it a bit and it turns on more than one led, but this is probably useful, the changed version works just fine when using the hercules app

标签: pythonc

解决方案


推荐阅读