如何解决单片机线性电位器输出
| 好的,下一个问题是:如果我在数字输入上添加了一个按钮,那么我可以使用它来将电位计校准为零吗? 当我按下按钮时,无论底盘处于什么位置,所有值都从零开始?之后我打算在Excel中执行此操作,但是今天下午似乎可以尝试执行此操作。您将使用switch语句还是某种if语句?float ZPot = 0;
float YPot = 1;
float XPot = 2;
byte Reset = 10;
void setup()
{
pinMode(XPot,INPUT);
pinMode(YPot,INPUT);
pinMode(ZPot,INPUT);
pinMode(Reset,INPUT);
Serial.begin(9600);
}
void loop()
{
ZPot = analogRead(0)/ 1023.0 * 105.0;
YPot = analogRead(1)/ 1023.0 * 105.0;
XPot = analogRead(2)/ 1023.0 * 105.0;
Reset = digitalRead(10);
Serial.print(\"X Pot [mm] = \");
Serial.print(XPot );
delay(500);
Serial.print(\" Y Pot [mm] = \");
Serial.print(YPot );
delay(500);
Serial.print(\" Z Pot [mm] = \");
Serial.println (ZPot );
delay(500);
}
解决方法
您已经快到了。您只需要更改两件事:
float ZPot = 0;
float YPot = 1;
float XPot = 2;
int Reset = 10;
float ZCalibration = 0;
float YCalibration = 0;
float XCalibration = 0;
和
Reset = digitalRead(10);
ZPot = (analogRead(0) / 1023.0 * 105.0) - ZCalibration;
YPot = (analogRead(1) / 1023.0 * 105.0) - YCalibration;
XPot = (analogRead(2) / 1023.0 * 105.0) - XCalibration;
if (Reset == HIGH) {
ZCalibration = ZPot;
YCalibration = YPot;
XCalibration = XPot;
}
,尝试添加功能
float convertToMM(float reading)
{
return reading/1023.0*105.0;
}
然后当您阅读时,改为
ZPot = convertToMM(analogRead(0));
,为了增加答案,您还可以使用map()函数:
ZPot = map(analogRead(0),1023.0,105);
YPot = map(analogRead(1),105);
XPot = map(analogRead(2),105);
进行手动操作可能比调用map()更快,但是如果您的程序不是很复杂,那应该没问题。否则,您可以考虑仅使用乘法写表达式(analogRead(0) / 1023.0f * 105.0f)
:(analogRead(0) * 0.000977517107f * 105.0f)
高温超导
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。