我想寫我自己的庫,通過UART0發送消息從我的Arduino UNO到我的電腦。Arduino通過UART0接收字符串的問題UNO
除了我想要接收字符串的部分以外,庫成功工作。該庫的代碼是:
#define F_CPU 16000000
#define EVEN_P 0
#define ODD_P 1
#define BAUD_RATE 57600
#include <avr/io.h>
#include <math.h>
#include <avr/io.h>
#include <string.h>
#include <util/delay.h>
// Initialize UART0 communication
void UART0_Init_Custom(unsigned long BaudRate, char AsyncDoubleSpeed, char DataSizeInBits, char ParityEVENorODD, char StopBits)
{
uint16_t UBBR_Value = lrint (F_CPU/16/BaudRate - 1); // maybe 16L??
// Setting the U2X bit to 1 for double speed asynchronous (default = 0, normal speed)
if (AsyncDoubleSpeed == 1) UCSR0A = (1 << U2X0);
// Upper part of the baud number (bits 8 to 11)
UBRR0H = (unsigned char)(UBBR_Value >> 8);
// Rest of the baud number
UBRR0L = (unsigned char)(UBBR_Value);
// Enable the receiver and transmitter
UCSR0B = (1 << RXEN0) | (1 << TXEN0);
// Set 2 stop bits (default = 1)
if (StopBits == 2) UCSR0C = (1 << USBS0);
// Set parity
if (ParityEVENorODD == EVEN_P) UCSR0C |= (1 << UPM01);
if (ParityEVENorODD == ODD_P) UCSR0C |= (3 << UPM00);
// Set data length (default = 5 bits)
if (DataSizeInBits == 6) UCSR0C |= (1 << UCSZ00); // 6-bit
if (DataSizeInBits == 7) UCSR0C |= (2 << UCSZ00); // 7-bit
if (DataSizeInBits == 8) UCSR0C |= (3 << UCSZ00); // 8-bit
if (DataSizeInBits == 9) UCSR0C |= (7 << UCSZ00); // 9-bit
}
void UART0_Init(unsigned long BaudRate)
{
if (BaudRate == 115200)
{
UART0_Init_Custom((BaudRate/2),1,8,0,2);
}
else
{
UART0_Init_Custom(BaudRate,0,8,0,2);
}
}
// Receive Data UART0
char UART0_GET(void)
{
while (!(UCSR0A & (1 << RXC0)));
return UDR0;
}
// Transmit Data UART0
void UART0_PUT(char data)
{
while (!(UCSR0A & (1 << UDRE0)));
UDR0 = data;
}
// Transmit Data-String UART0
void UART0_PRINT(char* String)
{
while(*String)
{
UART0_PUT(*String++);
}
}
// Receive Data-String UART0
char* UART0_READ(void)
{
char* ReceivedString;
char ReceivedBit;
int StringBit = 0;
memset(&ReceivedString,0,sizeof(ReceivedString));
while ((ReceivedBit=UART0_GET())!=13)
{
UART0_PUT(ReceivedBit);
ReceivedString[StringBit] = ReceivedBit;
StringBit++;
}
ReceivedString[StringBit] = 13;
ReceivedString[StringBit++] = 10;
UART0_PUT(10);
strncpy(ReceivedString, ReceivedString, StringBit+1);
return(ReceivedString);
}
char* Input;
int main(void)
{
UART0_Init(BAUD_RATE);
UART0_PRINT((char*)"Give a message and I will return it\r\n");
while(1)
{
Input = UART0_READ();
UART0_PRINT((char*)"The message was:");
UART0_PRINT(Input);
}
}
運行此代碼時,PuTTY會顯示一些隨機令牌並停止。我不能再插入任何東西了。
「PuTTY顯示一些隨機標記並停止」 - 哪個隨機標記?你能給我們輸出嗎? –
此外,儘可能縮小您的問題,給出[最小化,完整和可驗證的示例](http://stackoverflow.com/help/mcve),也許通過** Divide and conquer **方法幫助頁面建議。 –
「PuTTY顯示一些隨機令牌並停止」 - 聽起來像波特率設置錯誤 – Gravell