image.png

image.png

I wrote several pieces of code according to the requirements of the code

按道理来说:millis()是全局时间,所以当分两次引用millis()即便只有一行之隔也会有所变化。

但此处的pressTime = mills()是时间戳的概念,类似给现在的全局时间做了“截屏”或者打上关键帧,后面在引用此时的pressTime则会固定。

I wrote a few snippets of code based on the code requirements.

In theory, millis() is a global time, so if you reference it twice, even if it's only one line apart, it will change.

However, here, pressTime = mills() is a timestamp, like taking a screenshot or marking a keyframe for the current global time. Subsequent references to pressTime at that point will fix it.

if (buttonState != lastButtonState) { // 如果按钮被按下,就记录时间 if (buttonState == HIGH) { pressTime = millis(); // 这里保存“按下时刻” } // 如果按钮松开,就计算持续时间 if (buttonState == LOW) { long holdTime = millis() - pressTime; // 这里再读一次“当前时间” } }

This is an experiment to control the volume of a speaker based on FSR. A conditional statement to control the noise is used to map sensor values greater than 50 and less than 1023 to a range of 200 and 1000.

int fsrPin = A1;       // FSR 接在 A1
int speakerPin = 8;    // 蜂鸣器接在 D8

void setup() {
  Serial.begin(9600);
  pinMode(speakerPin, OUTPUT);
}

void loop() {
  int fsrValue = analogRead(fsrPin);  // 读 FSR 值(0~1023)
  Serial.println(fsrValue);           // 打印调试用

  if (fsrValue > 50) {  // 设置一个阈值,避免松开时乱响
    // 把 FSR 值映射到频率范围(200Hz~1000Hz)
    int freq = map(fsrValue, 50, 1023, 200, 1000);
    tone(speakerPin, freq, 100);   // 发声 100ms
  } else {
    noTone(speakerPin);  // 松开时不发声
  }

  delay(50);  // 小延时,避免刷屏太快
}