使用与计算机串行连接的Arduino控制电机

时间:2017-08-09 13:04:23

标签: arduino serial-port electronics

我正在进行自动点胶项目,我打算用Arduino控制十个不同的12V 600mA直流泵。计算机通过usb连接将消息传送到Arduino,格式如下:

lh = pumps off
0h = pump 0 on
1h = pump 1 on
etc.

Arduino通过激活连接到12V 2A直流电源的TIP120 npn电阻为泵供电。在任何给定时间只能运行一台泵。

当我通过为LED供电测试时,串行连接可以正常工作。然而,当我用泵尝试它时,Arduino开始对命令反应缓慢,最终我失去了与Arduino的串行连接。我只能想象有一些电源问题导致Arduino失去联系。我出错的任何想法?

Arduino代码:

#define PUMP5 5 //pin for turning transistor on/off
const byte numChars = 32;
char msg[numChars];

void setup() {
  Serial.begin(9600,SERIAL_8N1);
  Serial.println(msg[0]);
  pinMode(PUMP5, OUTPUT);
}

void loop() {
  read_msg();
  command_pumps();
}

void read_msg() {
  char rc;
  if (Serial.available() > 0) {
    rc = Serial.read();
    msg[0] = rc;
  }
  if(Serial.available() > 0) {
    rc = Serial.read();
    msg[1] = rc;
  }
  Serial.print("msg[0]: ");
  Serial.println(msg[0]);
  Serial.print("msg[1]: ");
  Serial.println(msg[1]);
}

//PUMP5 is used for each of the scenarios since I am only testing with one pump
void command_pumps() {
  if (msg[0] == 'l'||msg[1]=='l') {
    digitalWrite(PUMP5, LOW);
  } else if (msg[1] == 'h') {
    if(msg[0]=='0') digitalWrite(PUMP5, HIGH);
    else if (msg[0]=='1') digitalWrite(PUMP5, LOW);
    else if (msg[0]=='2') digitalWrite(PUMP5, HIGH);
    else if (msg[0]=='3') digitalWrite(PUMP5, HIGH);
    else if (msg[0]=='4') digitalWrite(PUMP5, HIGH);
    else if (msg[0]=='5') digitalWrite(PUMP5, HIGH);
    else if (msg[0]=='6') digitalWrite(PUMP5, HIGH);
    else if (msg[0]=='7') digitalWrite(PUMP5, HIGH);
    else if (msg[0]=='8') digitalWrite(PUMP5, HIGH);
    else if (msg[0]=='9') digitalWrite(PUMP5, HIGH);
  }
  return;
}

My Circuit

0 个答案:

没有答案