首页 > 解决方案 > Arduino按钮控制VB6形状填充颜色

问题描述

我正在创建一个程序,如果我单击 Arduino 中的按钮,VB6 中的形状填充颜色将变为红色,如果再次单击按钮,填充颜色将变为绿色。我在读取 Arduino 发送到 VB6 的串行数据时遇到问题。

这是我的 Arduino 代码:

int pbuttonPin = 7;// push button

int LED = 8; // LED

int val = 0; // push value from pin 2

int lightON = 0;//light status

int pushed = 0;//push status

void setup() 
{
Serial.begin(9600);

pinMode(pbuttonPin, INPUT_PULLUP); 

pinMode(LED, OUTPUT);

digitalWrite(LED, HIGH);

}

void loop()
 {

  val = digitalRead(pbuttonPin);// read the push button value


  if(val == HIGH && lightON == LOW){

    pushed = 1-pushed;


    delay(100);

  }    

  lightON = val;

      if(pushed == HIGH)
     {
        Serial.print("Color Red\n");


        digitalWrite(LED, LOW); 


        delay(100);
       
      }
else
      {
        Serial.print("Color Green\n");


        digitalWrite(LED, HIGH);


        delay(100);
      }
   
}

这是我的VB6代码,

Private Sub Form_Load()

    With MSComm1
        .CommPort = 8
        .Settings = "9600,N,8,1"
        .Handshaking = comRTS
        .RTSEnable = True
        .DTREnable = True
        .RThreshold = 1
        .SThreshold = 1
        .InputMode = comInputModeText
        .InputLen = 0
        .PortOpen = True
    End With
    
    Timer1.Enabled = True

End Sub

Private Sub Timer1_Timer()

    If MSComm1.Input = "Color Red" Then
        Shape1.FillColor = vbRed
        Shape1.FillStyle = vbSolid
    End If

    If MSComm1.Input = "Color Green" Then
        Shape1.FillColor = vbGreen
        Shape1.FillStyle = vbSolid
    End If

End Sub

非常感谢您在即将到来的

标签: arduinovb6

解决方案


不能保证来自串行端口的数据不会被分解成多个部分,因此您应该实现一个缓冲区来跟踪接收到的所有部分。此外,由于MSComm1.Input 从接收缓冲区返回和删除字符,您的第二If条语句将永远不会包含任何数据。您应该读取一次数据并将其存储在变量中。这是一些实现此功能的代码:

Dim m_sBuffer As String

Private Sub Form_Load()

    ' Initialize Serial Port
    With MSComm1
        .CommPort = 8
        .Settings = "9600,N,8,1"
        .Handshaking = comRTS
        .RTSEnable = True
        .DTREnable = True
        .RThreshold = 1
        .SThreshold = 1
        .InputMode = comInputModeText
        .InputLen = 0
        .PortOpen = True
    End With
    
    ' Initialize FillStyle
    Shape1.FillStyle = vbSolid
        
    ' Clear buffer
    m_sBuffer = ""
    
    ' Start timer
    Timer1.Enabled = True

End Sub

Private Sub Timer1_Timer()
    Dim sReceivedData As String
    
    ' Read data from serial port
    sReceivedData = MSComm1.Input
    
    ' Append Received Data to buffer
    m_sBuffer = m_sBuffer & sReceivedData
    
    ' Check buffer content
    Select Case m_sBuffer
        Case "Color Red"
            Shape1.FillColor = vbRed
            m_sBuffer = "" ' Clear buffer
        Case "Color Green"
            Shape1.FillColor = vbGreen
            m_sBuffer = "" ' Clear buffer
    End If

End Sub

推荐阅读