Jump to content
BatMan22

Arduino Serial Communication (Send and Receive - Simple Example)

Recommended Posts

BatMan22
Posted (edited)

Hey guys, the code that I've written/borrowed below is mostly an example of using the commUDF listed at the bottom, just applied to an Arduino with accompanying Arduino code. Uses Serial communication to turn on a LED, then reads a response from the arduino and prints it in the console. I hope it helps :) 

Autoit Code:

#include <CommMG.au3>
#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

Global $CMPort = 3
Global $CmBoBaud = 9600
Global $sportSetError = ''
Global $CmboDataBits = 8
Global $CmBoParity = "none"
Global $CmBoStop = 1
Global $setflow = 2

_CommSetPort($CMPort, $sportSetError, $CmBoBaud, $CmboDataBits, $CmBoParity, $CmBoStop, $setflow)

If @error Then
    MsgBox(16, "Error!", "Can't connect to Arduino on port - " & $CMPort)
    Exit
EndIf

_CommSetRTS(0)
_CommSetDTR(0)

While 1 ; Just use to call function, doesn't need to be a loop.
    LED_ON()
    Sleep(100)
    LED_OFF()
    Sleep(100)
WEnd

Func LED_ON()
    _CommSendString("1") ;Sends the Arduino a string of "1" to turn on LED
    Local $ret = _CommGetLine(@CR, 100, 100) ; Waits for up to 100 for a carriage return response from Arduino.
    ConsoleWrite($ret & @CRLF) ;Print to Console.
EndFunc   ;==>LED_ON_OFF

Func LED_OFF()
    _CommSendString("0") ;Sends Arduino string of "0" to turn off the LED
    Local $ret = _CommGetLine(@CR, 100, 100) ; Waits for up to 100 for a carriage return response from Arduino.
    ConsoleWrite($ret & @CRLF) ;Print to Console.
EndFunc   ;==>LED_BLINK_10

 Arduino Code:

int led = 12;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available())
  {
    int data = Serial.read();
    if (data == '1') //On
    {
      digitalWrite(led, HIGH);
      //writeslow();
      Serial.print("The LED is on!");
    }
    if (data == '0') //Off
    {
      digitalWrite(led, LOW);
      Serial.print("The LED is OFF!");
    }
  }
}

Serial/Com port UDF this is all based on :)

 

Edited by BatMan22
  • Like 2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×