I want to control a 220/250 V , 1.04A AC emergency bell through computer and arduino. I have arduino uno and 5 volt relay for this purpose. I manage to write asimple arduino program which turns HIGH a digital pin when receives character 'a' from serial port. After two seconds delay, it turns LOW that pin.
I wrote the computer program in c#. All works as expected when we use a 100W/200W electric bulb instead of emergency alarm. But when we connect the alarm, after 1 execution, the program hangs, and computer failed to connect to the serial port. To make it work again, I have to replug all power cords.
Here is my arduino code,
int received = 0;
void setup()
{
pinMode(12,OUTPUT);
Serial.begin(115200);
}void loop(){
if(Serial.available() == 1)
{
received = Serial.read();
switch (received)
{case 97: // Received ASCII a
digitalWrite(12, HIGH);
delay(2000);
digitalWrite(12, LOW);
received=0;
Serial.flush();
break; //Move ondefault:
digitalWrite(12, LOW);
break;
}
}
}
And here is my c# code,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports; // Serial stuff in here.namespace Serial
{
class Program
{
static SerialPort port;
static void Main(string[] args)
{
int baud;
string name;
string output=String.Empty;
Console.WriteLine(args);
Console.WriteLine("Welcome, enter parameters to begin");
Console.WriteLine(" ");
Console.WriteLine("Available ports:");
if (SerialPort.GetPortNames().Count() >= 0)
{
foreach (string p in SerialPort.GetPortNames())
{
Console.WriteLine(p);
}
}
else
{
Console.WriteLine("No Ports available, press any key to exit.");
Console.ReadLine();
// Quit
return;
}
Console.WriteLine("Port Name:");
name = Console.ReadLine();
Console.WriteLine(" ");
Console.WriteLine("Baud rate:");
baud = GetBaudRate();Console.WriteLine(" ");
Console.WriteLine("Beging Serial...");
BeginSerial(baud, name);
// port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
port.Open();
Console.WriteLine("Serial Started.");
Console.WriteLine(" ");
Console.WriteLine("Ctrl+C to exit program");
Console.WriteLine("Send:");for (; ; )
{
Console.WriteLine(" ");
Console.WriteLine("> ");
try
{
port.WriteLine(Console.ReadLine());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}}
}static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
for (int i = 0; i < (10000 * port.BytesToRead) / port.BaudRate; i++)
; //Delay a bit for the serial to catch up
Console.Write(port.ReadExisting());}
static void BeginSerial(int baud, string name)
{
port = new SerialPort(name, baud);
}static int GetBaudRate()
{
try
{
return int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid integer. Please try again:");
return GetBaudRate();
}
}
}
}
I am really frustrated with this project. If required, I can upload all connection image. Please help me if you can identify any problem in my code. Once more, this code works fine when I use bulbs, but fails in alarm.