首页 > 解决方案 > 如何将变量的值从一个arduino传输到另一个

问题描述

我正在设置一个触摸屏界面来控制我正在建造的微型注塑机上的步进电机。我已经能够使用按钮控件来控制大多数开关/按钮,但我想尝试使用触摸屏来选择电机转速以及电机应完成的转数的值。不需要启动或方向功能,因为这些功能由 Master arduino 通过按钮控制。

我正在尝试做的事情:

  1. 主站:从站中保存的变量“CV_Num_Rotations_Output”的请求值
  2. 从站:发送值
  3. 主:将值写入“CV_Num_Rotations”

  4. 主站:从站中保存的变量“CV_Speed_Rotations_Output”的请求值

  5. 从站:发送值
  6. Master:将接收到的值写入“CV_Speed_rotations”

在查看了可以通过 I2C 传输的数据类型后,我了解到发送浮点数并不容易,因此我将这两个变量转换为整数,稍后将由 Master 解释。

我也尝试过使用 struct 来保存值的想法,但是由于我只是在传输数字并且已经编写了转换函数,所以我宁愿坚持在 Slave 之后用它们的新值覆盖变量送他们过去。

现在我在主/从上的两个变量中使用 int:

int CV_Num_Rotations_Output = 1; // Pre-conversion value ready to be transmitted (can't be a float/decimal)
int CV_Speed_Rotations_Output = 1;

但我愿意使用另一种变量类型。

主 Arduino 代码:

#include <Wire.h>

int CV_Num_Rotations = 1;
int CV_Speed_Rotations = 1;
int CV_Num_Rotations_Output = 1; // Pre-conversion value ready to be transmitted (can't be a float/decimal)
int CV_Speed_Rotations_Output = 1;

void setup() {
  Serial.begin(9600);
  Wire.begin();   // Join i2c bus (address optional for master [becomes master by default])

void loop() {
  Wire.requestFrom(8,2)  // Request 2 bytes from slave device #8

  while (Wire.available()) {

    Wire.write(CV_Num_Rotations_Output);
    Wire.write(CV_Speed_Rotations_Output);
  }
  Serial.print("CV_Num_Rotations: ");
  Serial.println(CV_Num_Rotations_Output);
  Serial.print("CV_Speed_Rotations: ");
  Serial.println(CV_Speed_Rotations_Output);
  delay(150);
}

从 Arduino 代码:

#include <Wire.h>

int CV_Num_Rotations_Output = 5; // Values range from 1-20
int CV_Speed_Rotations_Output = 10; // Values range from 10-30

void setup() {
  Serial.begin(9600);
  Wire.begin(8);
  Wire.onRequest(requestEvent);
}

void requestEvent() {
  Wire.write(CV_Num_Rotations_Output);
  Wire.write(CV_Speed_Rotations_Output);
}

由于 Master 的两个 CV_Rotation 变量的初始值为“1”,因此打印输出应分别从 1 --> 5 和 1 --> 10 更改。

我的结果是:我一无所获。没有任何东西打印到串行监视器...

请帮忙。我不敢相信做这样一个简单的操作有多么困难,比如传递一个变量的值......

先感谢您

标签: variablesarduinointegeri2cserial-communication

解决方案


推荐阅读