I would like to establish a communication between my C# program and my Arduino Duemilanove. I tried lot of different tutorials, but none of them were the same, and I'm a little bit confused.
Actually my code is:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace InterfaceArduinoWindowsFOrm {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
serialPort1.PortName = "COM3";
serialPort1.BaudRate = 9600;
serialPort1.Open();
}
private void pictureBox1_Click(object sender, EventArgs e) {
}
private void tabPage2_Click(object sender, EventArgs e) {
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
}
private void toolTip1_Popup(object sender, PopupEventArgs e) {
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) {
Console.WriteLine("test");
}
private void button1_Click_1(object sender, EventArgs e) {
serialPort1.Write("5");
Console.WriteLine(serialPort1.IsOpen);
}
}
}
Arduino:
/* Sweep
by BARRAGAN <http://barraganstudio.com>
This example code is in the public domain.
modified 8 Nov 2013
by Scott Fitzgerald
http://arduino.cc/en/Tutorial/Sweep
*/
#include <Servo.h>
Servo myservo; // Create servo object to control a servo.
// Twelve servo objects can be created on most boards.
int pos = 0;
int message = 0; // This will hold one byte of the serial message
// variable to store the servo position.
void setup() {
Serial.begin(9600);
myservo.attach(9); // Attaches the servo on pin 9 to the servo object
}
void loop() {
if (Serial.available()) {
// Check to see if there is a new message
message = Serial.read();
// Put the serial input into the message
Serial.print(message);
if (message == '5') {
Serial.print("test");
for(pos = 0; pos <= 180; pos += 1) {
// Goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos);
// Tell servo to go to position in variable 'pos'
delay(15);
// Waits 15 ms for the servo to reach the position
}
for(pos = 180; pos>=0; pos-=1) {
// Goes from 180 degrees to 0 degrees
myservo.write(pos);
// Tell servo to go to position in variable 'pos'
delay(15);
// Waits 15 ms for the servo to reach the position
}
}
}
}
The problem is, when I click my button, nothing happens, but obviously if I remove the if
statement, the servo motor code works.