AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / user-27169078

c0sx86's questions

Martin Hope
c0sx86
Asked: 2025-04-14 20:02:23 +0800 CST

Arduino Nano não lê dados do UART Shell corretamente

  • 7

Ultimamente, tenho me dedicado à programação bare-metal com o Arduino-Nano e queria brincar com o UART protocool. Criei um "shell" simples usando Rust na minha máquina host que, ao enviar o comando "ledON" ou "ledOFF", ligava ou desligava o LED embutido no nano.

O código C no Nano é o seguinte

Arquivo de cabeçalho (avr-uart.h):

#include <stdint.h>


// Register Defines

#define UBRR0L      (*(volatile uint8_t *)0xC4)
#define UBRR0H      (*(volatile uint8_t *)0xC5)
#define UCSR0A      (*(volatile uint8_t *)0xC0)
#define UCSR0B      (*(volatile uint8_t *)0xC1)
#define UCSR0C      (*(volatile uint8_t *)0xC2)
#define UDR0        (*(volatile uint8_t *)0xC6)


// Register Bit Defines  
#define RXEN0       5                   // USART Receiver
#define TXEN0       4                   // USART Transmitter 
#define USBS0       3                   // Sets number of stop bits 
#define UCSZ00      1                   // Sets Character Size
#define UDRE0       5
#define RXC0        7

// Constant Defines 
#define CLOCK_SPEED     16000000                // MCU Clock Speed 
#define BAUD        115200                  // BAUD rate 
#define MYUBRR      CLOCK_SPEED / 16 / BAUD - 1         // UART Baud Rate 



/*
 * Function Desc: Function to handle Data buffer transfer
 * @param data  => Buffer holding the data to be transmitted 
*/
void USART_Transmit(unsigned char data) {

    // Wait for empty transmit buffer
    while ( !( UCSR0A & (1 << UDRE0)));

    // Puts data in the buffer and sends data 
    UDR0 = data; 
}




/*
 * Function Desc: Function to handle Data Reception 
*/
volatile uint8_t USART_Recieve(void) {
    
    while ( !( UCSR0A & (1 << RXC0)));

    return UDR0;

}

/*
 * Function Desc: Function to handling Printing strings to UART
 * @param *data => Pointer to data buffer
*/
void USART_Print(const char* data) {

    while (*data) {
        USART_Transmit(*data++);
    }
}

/*
 * Function Desc: Function to handle USART setup for Data Transmission and Reception
 * @param ubrr  => BAUD Rate 
*/
void USART_Init(unsigned int ubrr) {

    // This sets BAUD Rate 
    UBRR0H = (unsigned char) (ubrr >> 8);   // Zeroes out higher bit register (according to datasheet) 
    UBRR0L = (unsigned char) ubrr;      // Sets lower bit register baud rate 


    // Enable Receiver and Transmitter 
    UCSR0B = (1 << RXEN0) | (1 << TXEN0);

    // Sets frame format 
    UCSR0C = (1 << USBS0) | (3 << UCSZ00);

}

Arquivo principal:

#include "avr-uart.h"
#include <stdint.h>
#include <string.h>

#define BUFFER_SIZE 50
#define DDRB        (*(volatile uint8_t *)0x24)         // Address of DDRB Register
#define PORTB       (*(volatile uint8_t *)0x25)         // Address of PORTB Register
#define PB5     5                       // PB5 (Port B, bit 5)

int main(void) {

  // Sets the DDRB Register to Output
  DDRB |= (1 << PB5);

  // Initializes UART on the Micro-controller
  USART_Init(MYUBRR);

  char commandBuffer[BUFFER_SIZE];

  uint8_t buffer = 0;

  while (1) {

    // Save the received character in a single char variable
    char received = USART_Recieve();

    // Echo the character
    USART_Transmit(received);

    if (received == '\n' || received == '\r') {

      commandBuffer[buffer] = '\0';

      if (strcmp(commandBuffer, "ledON") == 0) {

        PORTB |= (1 << PB5); // Turns on the LED
        USART_Print("\r\n[NANO] INTERACTED WITH LED\r\n");
      }

      if (strcmp(commandBuffer, "ledOFF") == 0) {

        PORTB &= ~(1 << PB5);   // Turns off the LED
        USART_Print("\r\n[NANO] INTERACTED WITH LED\r\n");
      }

      else {
        USART_Print("\r\n[NANO] INVALID COMMAND\r\n");
      }

      buffer = 0;
    }

    else {
      if (buffer < BUFFER_SIZE - 1) {
        commandBuffer[buffer++] = received;
      }
    }
  }
}

E finalmente o shell simples que escrevi em rust:

use std::io::{self, Write, Read};
use std::time::Duration;
use serialport::SerialPort;

fn main() {


    // Variables for Serial Port name and BAUD rate 
    let port_name = "/dev/ttyUSB1";
    let baud = 115200;

    println!("[!] Initializing Arduino-Nano c0smic Shell! :)\n");


    // Opens a serial port connection to the Arduino
    let mut port = serialport::new(port_name, baud)
        .timeout(Duration::from_millis(1000))
        .open().expect("Failed to open port");

    println!("[!] Successfully connected to serial port /dev/ttyUSB1!\n");
 
    println!("Shell is initialized, you may start sending commands :)\n");

    let mut inputBuffer = String::new();

    loop {

        print!(">> ");
        io::stdout().flush().unwrap();

        inputBuffer.clear();
        // Creates input buffer for commands 

        // Clears reads line 
        io::stdin().read_line(&mut inputBuffer).expect("Failed to read line!");

        // Trims command buffer 
        let inputBuffer: String = inputBuffer.trim().parse().expect("Failed to clean buffer");


        if inputBuffer == "ledON" || inputBuffer == "ledOFF" {
           

            // Sends data as bytes 
            port.write_all(format!("{}\n", inputBuffer).as_bytes()).unwrap();

            // Makes the CPU wait (sleep) for 500 ms 
            std::thread::sleep(Duration::from_millis(500));


            // Creates buffer for receiving data from Nano 
            let mut buffer = [0u8; 128];

            match port.read(&mut buffer) {
                Ok(n) if n > 0 => {
                    let response = String::from_utf8_lossy(&buffer[..n]);
                    println!("{}", response);
                }
    
                // Checks if a response is received or if there is an error 
                Ok(_) => println!("No response receieved"),
                Err(e) => println!("Failed to read: {}", e),
            }

        } else {
            println!("[!] Error ::: Invalid Command!\n");
        }
    }

}

O Makefile para compilação:

default: build

build:
    avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p main.c -o main 

burn: build 
    avr-objcopy -O ihex -R .eeprom main main.hex 

    avrdude -F -V -c arduino -pm328p -P /dev/ttyUSB1 -b 115200 -U flash:w:main.hex 

Consegui confirmar que o shell Rust consegue se conectar ao Arduino e realmente enviar dados (já que o LED RX pisca toda vez que envio o comando), mas sempre que o shell aguarda uma resposta, recebo o erro "Timed Out". Pelo que entendi, o Arduino Nano não consegue ler os dados enviados corretamente. Qualquer ajuda é bem-vinda. Obrigada!

c
  • 1 respostas
  • 83 Views
Martin Hope
c0sx86
Asked: 2025-03-08 03:29:38 +0800 CST

Proxy reverso para backend Golang não funciona (nginx)

  • 5

Tenho trabalhado em um pequeno aplicativo web e queria testar o nginx e o Golang para meu backend. Sou bem novo no Golang, pois este é meu primeiro projeto web Golang. De qualquer forma, estou tendo um problema com proxy reverso para minha página de login HTML:

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="loginStyle.css">
  <title>Cosmic Cloud Login</title>
</head>

<body>

  <div class="loginContainer">
    <h1 class="headerText">Login</h1>
    <p>Please enter your login information</p>
    <form action="/login" method="POST">
      <div class="inputGroup">
        <label for="Username">Username</label>
        <input type="Username" id="Username" name="Username" placeholder="Enter your username" required>
      </div>

      <div class="inputGroup">
        <label for="Password">Password</label>
        <input type="Password" id="Password" name="Password" placeholder="Enter your password" required>
      </div>
      <button type="submit" class="loginButton">Login</button>
    </form>


  </div>

</body>

</html>

O arquivo nginx.conf é o seguinte:

   server {
          listen 80;
   location / {
          root /var/www/html;
          index index.html;
   }

   location /login {
          proxy_pass http://0.0.0.0:8080;
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
   }
   }

e o arquivo Go é o seguinte:

package main 


import (
    "fmt"
    "net/http"
)



var validUsername = "test"
var validPassword = "test1234"

func loginHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        http.Error(w, "Invalid Request method", http.StatusMethodNotAllowed)
        return 
    }

    username := r.FormValue("Username")
    password := r.FormValue("Password")

    if username == validUsername && password == validPassword {
        fmt.Fprint(w, "Login Successfull!")
    } else {
        http.Error(w, "Invalid Username or Password", http.StatusUnauthorized)

    }
}

func main() {
    http.HandleFunc("/login", loginHandler)
    fmt.Println("Server is running on :8080")
    http.ListenAndServe(":8080", nil)
} 

Ao enviar uma solicitação POST, o backend do Golang nunca a recebe, a menos que você especifique a porta 8080. (por exemplo, "http://IP/login" não funciona) ("http://IP:8080/login" funciona) Eu tentei ambos na máquina local e em outra máquina na rede. TLDR: o nginx não está enviando corretamente a solicitação POST do servidor web nginx (porta 80) para a porta onde o backend do Golang está escutando (porta 8080). Qualquer ajuda é muito apreciada, TYIA!

Editar: Provavelmente não é um problema de firewall, pois desabilitei o ufw no ambiente de teste.

go
  • 1 respostas
  • 53 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve