Hi all,
I'm working on learning how to interface PC software with embedded devices at the moment, working on my own board based around the SAM3X8E - but I'm using both my Due & Uno to test code snippets.
I've made a simple Windows app in Visual Studio 2010, with three buttons - one to switch on the onboard LED, one to switch off and another to flash the LED. I found some VB code online which I added to to make this work.
Imports System.IO
Imports System.IO.Ports
Imports System.Threading
Public Class Form1
Shared _continue As Boolean
Shared _serialPort As SerialPort
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SerialPort1.Close()
SerialPort1.PortName = "com4"
SerialPort1.BaudRate = 9600
SerialPort1.DataBits = 8
SerialPort1.Parity = Parity.None
SerialPort1.StopBits = StopBits.One
SerialPort1.Handshake = Handshake.None
SerialPort1.Encoding = System.Text.Encoding.Default
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SerialPort1.Open()
SerialPort1.Write("1")
SerialPort1.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SerialPort1.Open()
SerialPort1.Write("0")
SerialPort1.Close()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
SerialPort1.Open()
SerialPort1.Write("2")
SerialPort1.Close()
End Sub
End Class
I then wrote the Arduino code which simply takes the value sent over serial, and does something with it, as below.
int led_state = 0;
byte led = 13;
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop() {
if (Serial.available() > 0){
led_state = Serial.read();
}
if (led_state == 49){ // 49 == ASCII for 1
digitalWrite(led, HIGH);
}
else if (led_state == 48){ // 48 == ASCII for 0
digitalWrite(led, LOW);
}
else if (led_state == 50){ // 50 == ASCII for 2
digitalWrite(led, HIGH);
delay(500);
digitalWrite(led, LOW);
delay(500);
}
}
// program works, although any value high than 2 switches LED off, why?
However, what I want to be able to achieve - is to send multiple values over serial, and have the Arduino decide what's what. For example, currently I'm just sending one byte of data and doing something based on the ASCII character.
Say I want to be able to switch the LED on and off, but also control the delay times for the flash - I guess I need a way to tell the Arduino "use this bit of data to do that".
I was thinking, perhaps - send the value of 1, and if the value of 1 is recieved, the next piece of data is regarding to that, if it were 2 for example, then it would be related to something else.
Tips anybody? Thanks