了解使用操纵杆控制 8x8 点阵的代码背后的逻辑

Understanding the logic behind the code for controlling an 8x8 dot matrix with a joystick

我在网上找到了这段代码,用于使用 Arduino 控制 max7219 8x8 矩阵,我正在努力理解有关代码的一些事情。这是完整的代码:

#include <LedControl.h>

int UD = 0;
int LR = 0; //Setting up controller//
LedControl lc=LedControl(8,10,9,1); //10 is to CLOCK, 9 = CS, 8=DIN//

void setup() {
 Serial.begin(9600);
 lc.shutdown(0,false); // turn off power saving, enables display
 lc.setIntensity(0,1); // sets brightness (0~15 possible values)
 lc.clearDisplay(0); // clear screen
}

void loop() {
 UD = analogRead(A0);
 LR = analogRead(A1);
 char x_translate = map(LR, 1021, 0, 7, 0); //map(value, fromLow, fromHigh, toLow, toHigh)
 char y_translate = map(UD, 1021, 0, 0, 7);

 Serial.print("UD = ");
 Serial.print(UD, DEC);
 Serial.print(", LR = ");
 Serial.print(LR, DEC);
 Serial.print(", x = ");
 Serial.print(x_translate, DEC);
 Serial.print(", y = ");
 Serial.println(y_translate, DEC);
 // not in shutdown mode
 lc.clearDisplay(0);
 lc.setLed(0,x_translate,y_translate,true);
 delay(150); //adjust delay to get your joystick correct//
}

我的第一个问题与 Serial.begin(9600) 的含义有关。

我最大的问题是关于将操纵杆的模拟输入转换为点亮矩阵上的 LED:

char x_translate = map(LR, 1021, 0, 7, 0); //map(value, fromLow, fromHigh, toLow, toHigh)
char y_translate = map(UD, 1021, 0, 0, 7);

1021 从哪里来,为什么它是 fromLow 值,而它似乎是它缩放的任何范围的最大值? 7 是从哪里来的,为什么会出现在现在的位置?

最后,所有 Serial.print() 语句到底发生了什么?什么是Serial,什么是DEC?

如您所知,我是 C++ 的新手,所以如果您能提供帮助,我们将不胜感激。

来自 Arduino 手册:

Serial.begin(baud)

Sets the data rate in bits per second (baud) for serial data transmission.

所以你的情况是 9600 baud

Serial.print()

Prints data to the serial port as human-readable ASCII text. An optional second parameter specifies the base (format) to use; permitted values are BIN(binary, or base 2), OCT(octal, or base 8), DEC(decimal, or base 10), HEX(hexadecimal, or base 16). For floating point numbers, this parameter specifies the number of decimal places to use. For example-

Serial.print(78, BIN) gives "1001110"

Serial.print(78, OCT) gives "116"

Serial.print(78, DEC) gives "78"

Serial.print(78, HEX) gives "4E"

Serial.print(1.23456, 0) gives "1"

Serial.print(1.23456, 2) gives "1.23"

Serial.print(1.23456, 4) gives "1.2345"

map(value, fromLow, fromHigh, toLow, toHigh)

Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc.

value: the number to map. fromLow: the lower bound of the value’s current range.

fromHigh: the upper bound of the value’s current range.

toLow: the lower bound of the value’s target range.

toHigh: the upper bound of the value’s target range.

值 1021 是由编写该代码的人选择的,因为他想将范围 [1021-0] 映射到 [7-0],很可能是因为最大操纵杆伸长产生模拟值 1021。