Sie sind auf Seite 1von 13

1.

Introduction popular with people just starting out with


To demonstrate the ease with which you can electronics, and for good reason. Unlike
control an Arduino project using a C# most previous programmable circuit boards,
Application running on your computer, we the Arduino does not need a separate piece
will be equipping this project with the of hardware (called a programmer) in order
ability to receive commands from the to load new code onto the board – you can
application to control its IO pins to perform simply use a USB cable. Additionally, the
actions like turning on or off an LED, Arduino IDE uses a simplified version of
displaying information on an LCD amongst C++, making it easier to learn to program.
others. The main ingredient which makes Finally, Arduino provides a standard form
communication between the Arduino and factor that breaks out the functions of the
the c# software we will be building possible micro-controller into a more accessible
is the Serial communication protocol. package.
Applications and programs (including the
Arduino IDE) running on a computer are
able to interact with the Arduino due to the
presence of the onboard USB to Serial
converter (FTDI chip) on the Arduino. So
whenever a command is sent from the C#
program either via the click of a button or
any other action on the GUI, the C#
program sends the corresponding
instruction to the Arduino via a previously
established serial communication port. The
Arduino receives the command and takes
the related action.

2. Components Required
The following components are required to
build this project:
• Arduino Uno
• LCD 16x2 Display
• Light Emitting Diode
• Resistor
• Wires
• Bread Board

3. Arduino Uno
Arduino is an open-source platform used for
building electronics projects. Arduino
consists of both a physical programmable
circuit board (often referred to as a
microcontroller) and a piece of software, or
IDE (Integrated Development Environment)
that runs on your computer, used to write The Arduino hardware and software was
and upload computer code to the physical designed for artists, designers, hobbyists,
board. hackers, newbies, and anyone interested in
The Arduino platform has become quite creating interactive objects or environments.
Arduino can interact with buttons, LEDs,
motors, speakers, GPS units, cameras, the is 7 to 12 volts.
internet, and even your smart-phone or your The power pins are as follows:
TV! This flexibility combined with the fact • VIN. The input voltage to the
that the Arduino software is free, the hardware Arduino board when it's using an
boards are pretty cheap, and both the software external power source (as opposed to
and hardware are easy to learn 5 volts from the USB connection or
other regulated power source). You
can supply voltage through this pin,
The Arduino Uno is a microcontroller board or, if supplying voltage via the power
based on the ATmega328 (datasheet). It has jack, access it through this pin.
14 digital input/output pins (of which 6 can • 5V.This pin outputs a regulated 5V
be used as PWM outputs), 6 analog inputs, a from the regulator on the board. The
16 MHz ceramic resonator, a USB board can be supplied with power
connection, a power jack, an ICSP header, either from the DC power jack (7 -
and a reset button. It contains everything 12V), the USB connector (5V), or
needed to support the microcontroller; simply the VIN pin of the board (7-12V).
connect it to a computer with a USB cable or Supplying voltage via the 5V or 3.3V
power it with a AC-to-DC adapter or battery pins bypasses the regulator, and can
to get started. The Uno differs from all damage your board. We don't advise
preceding boards in that it does not use the it
FTDI USB-to-serial driver chip. Instead, it • 3V3. A 3.3 volt supply generated by
features the Atmega16U2 (Atmega8U2 up to the on-board regulator. Maximum
version R2) programmed as a USB-to-serial current draw is 50 mA.
converter. • GND. Ground pins.
"Uno" means one in Italian and is named to
mark the upcoming release of Arduino 1.0. Memory
The Uno and version 1.0 will be the reference The ATmega328 has 32 KB (with 0.5 KB
versions of Arduino, moving forward. The used for the bootloader). It also has 2 KB of
Uno is the latest in a series of USB Arduino SRAM and 1 KB of EEPROM (which can
boards be read and written with the EEPROM
library).
Power
The Arduino Uno can be powered via the Input and Output
USB connection or with an external power Each of the 14 digital pins on the Uno can be
supply. The power source is selected used as an input or output, using pinMode(),
automatically. External (non-USB) power digitalWrite(), and digitalRead() functions.
can come either from an AC-to-DC adapter They operate at 5 volts. Each pin can provide
(wall-wart) or battery. The adapter can be or receive a maximum of 40 mA and has an
connected by plugging a 2.1mm center- internal pull-up resistor (disconnected by
positive plug into the board's power jack. default) of 20-50 kOhms. In addition, some
Leads from a battery can be inserted in the pins have specialized functions:
Gnd and Vin pin headers of the POWER • Serial: 0 (RX) and 1 (TX). Used to
connector. The board can operate on an receive (RX) and transmit (TX) TTL
external supply of 6 to 20 volts. If supplied serial data. These pins are connected
with less than 7V, however, the 5V pin may to the corresponding pins of the
supply less than five volts and the board ATmega8U2 USB-to-TTL Serial
may be unstable. If using more than 12V, chip.
the voltage regulator may overheat and
• External Interrupts: 2 and 3. These
damage the board. The recommended range
pins can be configured to trigger an The Arduino software includes a serial
interrupt on a low value, a rising or monitor which allows simple textual data to
falling edge, or a change in value. See be sent to and from the Arduino board. The
the attachInterrupt() function for RX and TX LEDs on the board will flash
details. when data is being transmitted via the USB-
• PWM: 3, 5, 6, 9, 10, and 11. Provide to-serial chip and USB connection to the
8-bit PWM output with the computer (but not for serial communication
analogWrite() function. on pins 0 and 1).
• SPI: 10 (SS), 11 (MOSI), 12 (MISO), A SoftwareSerial library allows for serial
13 (SCK). These pins support SPI communication on any of the Uno's digital
communication using the SPI library. pins. The ATmega328 also supports I2C
• LED: 13. There is a built-in LED (TWI) and SPI communication. The
connected to digital pin 13. When the Arduino software includes a Wire library to
pin is HIGH value, the LED is on, simplify use of the I2C bus; see the
when the pin is LOW, it's off. documentation for details. For SPI
The Uno has 6 analog inputs, labeled A0 communication, use the SPI library.
through A5, each of which provide 10 bits of Programming
resolution (i.e. 1024 different values). By The Arduino Uno can be programmed with
default they measure from ground to 5 volts, the Arduino software (download). Select
though is it possible to change the upper end "Arduino Uno from the Tools > Board menu
of their range using the AREF pin and the (according to the microcontroller on your
analogReference() function. board). For details, see the reference and
Additionally, some pins have specialized tutorials.
functionality: The ATmega328 on the Arduino Uno comes
• TWI: A4 or SDA pin and A5 or SCL preburned with a bootloader that allows you
pin. Support TWI communication to upload new code to it without the use of
using the Wire library an external hardware programmer. It
• AREF. Reference voltage for the communicates using the original STK500
analog inputs. Used with protocol (reference, C header files). You can
analogReference(). also bypass the bootloader and program the
microcontroller through the ICSP (In-Circuit
• Reset. Bring this line LOW to reset
Serial Programming) header.
the microcontroller. Typically used to
The ATmega16U2 (or 8U2 in the rev1 and
add a reset button to shields which
rev2 boards) firmware source code is
block the one on the board.
available . The ATmega16U2/8U2 is loaded
Communication
with a DFU bootloader, which can be
The Arduino Uno has a number of facilities
activated by:
for communicating with a computer, another
Arduino, or other microcontrollers. The • On Rev1 boards: connecting the
ATmega328 provides UART TTL (5V) serial solder jumper on the back of the
communication, which is available on digital board (near the map of Italy) and then
pins 0 (RX) and 1 (TX). resetting the 8U2.
An ATmega16U2 on the board channels this • On Rev2 or later boards: there is a
serial communication over USB and appears resistor that pulling the 8U2/16U2
as a virtual com port to software on the HWB line to ground, making it easier
computer. The '16U2 firmware uses the to put into DFU mode.
standard USB COM drivers, and no external Automatic (Software) Reset
driver is needed. However, on Windows, a Rather than requiring a physical press of the
.inf file is required. reset button before an upload, the Arduino
Uno is designed in a way that allows it to be
reset by software running on a connected The maximum length and width of the Uno
computer. One of the hardware flow control PCB are 2.7 and 2.1 inches respectively, with
lines (DTR) of the ATmega8U2/16U2 is the USB connector and power jack extending
connected to the reset line of the ATmega328 beyond the former dimension. Four screw
via a 100 nanofarad capacitor. When this line holes allow the board to be attached to a
is asserted (taken low), the reset line drops surface or case. Note that the distance
long enough to reset the chip. between digital pins 7 and 8 is 160 mil
The Arduino software uses this capability to (0.16"), not an even multiple of the 100 mil
allow you to upload code by simply pressing spacing of the other pins.
the upload button in the Arduino
environment. This means that the bootloader ATMEGA 328 :
can have a shorter timeout, as the lowering Features
of DTR can be well-coordinated with the • High Performance, Low Power AVR® 8-
start of the upload. This setup has other Bit Microcontroller
implications. When the Uno is connected to • Advanced RISC Architecture – 131
either a computer running Mac OS X or Powerful Instructions – Most Single Clock
Linux, it resets each time a connection is Cycle Execution – 32 x 8 General
made to it from software (via USB). For the Purpose Working Registers – Fully Static
following halfsecond or so, the bootloader is Operation – Up to 20 MIPS Throughput at 20
running on the Uno. MHz – On-chip 2-cycle Multiplier
While it is programmed to ignore • High Endurance Non-volatile Memory
malformed data (i.e. anything besides an Segments
upload of new code), it will intercept the first – 4/8/16/32K Bytes of In-System
few bytes of data sent to the board after a Self-Programmable Flash progam memory
connection is opened. If a sketch running on (ATmega48PA/88PA/168PA/328P)
the board receives one-time configuration or – 256/512/512/1K Bytes EEPROM
other data when it first starts, make sure that (ATmega48PA/88PA/168PA/328P)
the software with which it communicates – 512/1K/1K/2K Bytes Internal SR
waits a second after opening the connection AM (ATmega48PA/88PA/168PA/328P)
and before sending this data. – Write/Erase Cycles: 10,000
The Uno contains a trace that can be cut to Flash/100,000 EEPROM – Data retention: 20
disable the auto-reset. The pads on either side years at 85°C/100 years at 25°C(1)
of the trace can be soldered together to re- – Optional Boot Code Section with
enable it. It's labeled "RESET-EN". You may Independent Lock Bits In-System
also be able to disable the auto-reset by Programming by On-chip Boot Program True
connecting a 110 ohm resistor from 5V to the Read-While-Write Operation
reset line; see this forum thread for details. – Programming Lock for Software
Security
USB Overcurrent Protection • Peripheral Features
The Arduino Uno has a resettable polyfuse – Two 8-bit Timer/Counters with
that protects your computer's USB ports Separate Prescaler and Compare Mode
from shorts and overcurrent. Although most – One 16-bit Timer/Counter with
computers provide their own internal Separate Prescaler, Compare Mode, and
protection, the fuse provides an extra layer of Capture Mode
protection. If more than 500 mA is applied to – Real Time Counter with Separate
the USB port, the fuse will automatically Oscillator
break the connection until the short or – Six PWM Channels
overload is removed. – 8-channel 10-bit ADC in TQFP and
Physical Characteristics QFN/MLF package Temperature
Measurement Block Diagram
– 6-channel 10-bit ADC in PDIP
Package Temperature Measurement
– Programmable Serial USART
– Master/Slave SPI Serial Interface
– Byte-oriented 2-wire Serial Interface
(Philips I2 C compatible)
– Programmable Watchdog Timer with
Separate On-chip Oscillator
– On-chip Analog Comparator
– Interrupt and Wake-up on Pin
Change
• Special Microcontroller Features
– Power-on Reset and Programmable
Brown-out Detection
– Internal Calibrated Oscillator
– External and Internal Interrupt
Sources
– Six Sleep Modes: Idle, ADC Noise
Reduction, Power-save, Power-down,
Standby, and Extended Standby
• I/O and Packages
– 23 Programmable I/O Lines
– 28-pin PDIP, 32-lead TQFP, 28-pad
QFN/MLF and 32-pad QFN/MLF The AVR core combines a rich instruction
• Operating Voltage: – 1.8 - 5.5V set with 32 general purpose working
• Temperature Range: – -40°C to 85°C registers. All the 32 registers are directly
Speed Grade: – 0 - 20 MHz @ 1.8 - 5.5V connected to the Arithmetic Logic Unit
• Low Power Consumption at 1 MHz, 1.8V, (ALU), allowing two independent registers
25°C for ATmega48PA/88PA/168PA/328P: to be accessed in one single instruction
– Active Mode: 0.2 Ma executed in one clock cycle. The resulting
– Power-down Mode: 0.1 µA architecture is more code efficient while
– Power-save Mode: 0.75 µA (Including achieving throughputs up to ten times
32 kHz RTC) faster than conventional CISC
– microcontrollers.
The ATmega48PA/88PA/168PA/328P
provides the following features:
4/8/16/32K bytes of InSystem
Programmable Flash with Read-While-
Write capabilities, 256/512/512/1K bytes
EEPROM, 512/1K/1K/2K bytes SRAM,
23 general purpose I/O lines, 32 general
purpose working registers, three flexible
Timer/Counters with compare modes,
internal and external interrupts, a serial
programmable USART, a byte-oriented 2-
wire Serial Interface, an SPI serial port, a
6-channel 10-bit ADC (8 channels in
TQFP and QFN/MLF packages), a
programmable Watchdog Timer with 4. Liquid Crystal Display (LCD)
internal Oscillator, and five software
selectable power saving modes. The Idle
mode stops the CPU while allowing the
SRAM, Timer/Counters, USART, 2-wire
Serial Interface, SPI port, and interrupt
system to continue functioning. The
Power-down mode saves the register
contents but freezes the Oscillator,
disabling all other chip functions until the
next interrupt or hardware reset. In Power-
save mode, the asynchronous timer
continues to run, allowing the user to
maintain a timer base while the rest of the Liquid crystal display screen is the
device is sleeping. The ADC Noise electronic display module and find a wide
Reduction mode stops the CPU and all I/O ranges of applications. A 16*2 LCD display
modules except asynchronous timer and is very basic module and it is very
ADC, to minimize switching noise during commonly use in various devices and
ADC conversions. In Standby mode, the circuit. These modules are preferred to
crystal/resonator Oscillator is running seven segments and other multi segments
while the rest of the device is sleeping. LEDs. The reason being: LCDs are
This allows very fast start-up combined economical; easily programmable; have no
with low power consumption. limitation of displaying special and even
Technical Specification custom characters (unlike in 7 segments),
·Microcontroller- Atmega328 animations and so on. A 16*2 LCD means it
·Operating Voltage- 5V can display 16 characters per line and there
·Input Voltage (recommended) 7- are 2 such lines. In this LCD each character
12V is displayed in 5*7 pixel matrix. This LCD
·Input Voltage (limits) 6-20V has 2 registers , namely command and data.
·Digital I/O Pins- 14 (of which 6 LCD Display The command registers stores
provide PWM output) the command instructions given to the
·Analog Input Pins- 6 LCD. A command is an instruction given to
·DC Current per I/O Pin- 40 mA LCD to do a predefined task like initializing
·DC Current for 3.3V Pin- 50 mA it, clearing its screen, setting the cursor
·Flash Memory- 32 KB position, controlling display etc. the data
(ATmega328) of which 0.5 KB used by registers stores the data to be display on the
bootloader LCD . the data is the ASCII value of the
·SRAM- 2 KB (ATmega328) character to be displayed on the LCD.
·EEPROM- 1 KB (Atmega328) Features of 16×2 LCD module
·Clock Speed- 16 MHz  Operating Voltage is 4.7V to 5.3V
 Current consumption is 1mA
without backlight
 Alphanumeric LCD display module,
meaning can display alphabets and
numbers
 Consists of two rows and each row
can print 16 characters.
 Each character is build by a 5×8 Data Pin
pixel box 9
2
 Can work on both 8-bit and 4-bit Data Pin
mode 10
3
 It can also display any custom
Data Pin
generated characters 11
4
 Available in Green and Blue
Backlight Data Pin Microcontroller to send 8-
12
5 bit data.
Data Pin These LCD’s can also
13 operate on 4-bit mode in
6
such case Data pin 4,5,6
Data Pin
14 and 7 will be left free.
7
LED Backlight LED pin
15
Positive positive terminal
LED Backlight LED pin
16
Negative negative terminal

LCD modules are vey commonly used in


Pin Configuration most embedded projects, the reason being
its cheap price, availability and programmer
Pin Pin
Description friendly. Most of us would have come
No: Name:
across these displays in our day to day life,
Vss Ground pin connected to either at PCO’s or calculators. The
1
(Ground) system ground appearance and the pinouts have already
Vdd (+5 Powers the LCD with +5V been visualized above now let us get a bit
2
Volt) (4.7V – 5.3V) technical.
VE Decides the contrast level 16×2 LCD is named so because; it has 16
3 (Contrast of display. Grounded to Columns and 2 Rows. There are a lot of
V) get maximum contrast. combinations available like, 8×1, 8×2,
10×2, 16×1, etc. but the most used one is
Connected to the 16×2 LCD. So, it will have (16×2=32)
Register Microcontroller to shit 32 characters in total and each character
4
Select between command/data will be made of 5×8 Pixel Dots. A Single
register character with all its Pixels is shown in the
Used to read or write data. below picture.
Read/Wri
5 Normally grounded to 2D model of 16×2 LCD module
te
write data to LCD
Connected to
Microcontroller Pin and
6 Enable
toggled between 1 and 0
for data acknowledgement
Data Pin
7
0 Data pins 0 to 7 forms a 8-
Data Pin bit data line. They can be
8 connected to
1
7. Light Emitting Diode

A light emitting diode is a two lead


semiconductor light source. It is a p-n
junction diode, which emits light when
activated. When a suitable voltage is applied
to the leads, electrons are able to recombine
with electron holes within the device,
6. Resistors
releasing energy in the form of photons.
This effect is called electroluminescence,
and the colour of the light is determined by
the energy band gap of the semiconductor.
An LED is often small in area and
integrated optical components may be used
to shape its radiation pattern.
Early LEDs were often used as indicator
lamps for electronic devices, replacing small
incandescent bulbs. They were soon
packaged into numeric readouts in the form
of seven-segment displays, and were
The resistor is a passive electrical commonly seen in digital clocks.
component to create resistance in the flow
of electric current. In almost all electrical
networks and electronic circuits they can be
found. The resistance is measured in ohms. 8. Potentiometer (POT)
An ohm is the resistance that occurs when a
current of one ampere passes through a
resistor with a one volt drop across its
terminals. The current is proportional to the
voltage across the terminal ends.
Resistors are used for many purposes. A few
examples include delimit electric current,
voltage division, heat generation, matching
and loading circuits, control gain, and fix A potentiometer is a three terminal resistor
time constants. They are commercially with sliding or rotating contact that forms an
available with resistance values over a range adjustable voltage divider. If only two
of more than nine orders of magnitude. They contacts are used, it acts as variable resistor
can be used to as electric brakes to dissipate or rheostat. Here we have used an 2K POT.
kinetic energy from trains, or be smaller So it has varying resistance up to 10K.
than a square millimeter for electronics.
9. Program Code #STAR\n to the serial port. Then we change
The code for this project is divided into two: the button text and we enable all the
The C# Application and the Arduino code to controls on the user interface. Now if we
run on the hardware. We have created a write a text on the textbox and press the
simple communication protocol for this write button, we get the text from the
project which consists of 6 commands. Each textbox and write it to the Serial port with
command is 4 characters long and it can be the command TEXT. Also, when the state
followed by some data. Each command one of the checkboxes changes we send the
starts with the # character and it is command LED1 for example with the state,
terminated by the \n symbol. This symbol on or off. Lastly, when we press the connect
will tell the Arduino that the command is button and we are already connected to
complete so it can act. So we have the Arduino we send the STOP command.
following commands: Now let’s take a quick look at the Arduino
•STAR for Start code. At first, we initialize the display. Then
•STOP we wait for serial data. When we receive
•TEXT data on the serial port we save them in the
•LED1 variable inputString until we receive the \n
•LED2 character. When we receive this character
we know that command is complete, so we
•LED3
have to act. If we receive the TEXT
The STAR command tells the Arduino to
command for example, we know that we
wait for commands from the computer. The
have to print something on the LCD
STOP command tells the Arduino that the
display. So, we remove the first five
computer has disconnected from it. The
characters from the inputString variable,
TEXT command is followed by the text we
because that’s the command, we delete then
want to display on the LCD. For example, if
last 2 character which is the \n symbol and
we write #TEXTYOUTUBE\n on the serial
we print the remaining characters on the
port the word YOUTUBE will appear on the
display. We do something similar when we
display.
receive an LED command. We read the next
The LED1, LED2 and LED3 commands
two characters after the command to see if
control the state of each LED. So if we
we need to turn the LED on or off and we
want to turn on the first LED we write the
act accordingly. As you can see the Arduino
following command to the serial port:
code is very simple, we just use so if
#LED1ON\n . If we want to turn off the
statements to respond to the commands sent
second LED we send the command
by the computer..
#LED2OF . The same thing applies to the
If we program the Arduino, we can see, that
third LED as well.That’s the very basic
the LCD display shows the message
protocol we use in this project. Of course,
“Ready to connect”, which means the
we can design many more commands. In
Arduino is programmed successfully and it
the code now at first, after the User
is waiting for commands from the
Interface is initialized we disable all the
computer. Then we open the Computer
controls. Then we get the available serial
application, we select the serial port that
ports on the computer and we load them on
the Arduino is connected to and we press
the combox. When we press the Connect
connect.
button, the button1_Click method is called
Now we can control the Arduino from the
and we try to connect to Arduino if we are
computer! How cool is that! Let’s now see
not already connected. In order to connect
how to develop the computer software to
to Arduino, we open the Serial port, and we
send commands to the Arduino.
send a command to it. We simply write
{
Arduino Code:- turnLedOff(led1Pin);
#include <LiquidCrystal.h> }
String inputString = ""; // a string to }
hold incoming data else if(commandString.equals("LED2"))
boolean stringComplete = false; // whether {
the string is complete boolean LedState = getLedState();
String commandString = ""; if(LedState == true)
int led1Pin = 10; {
int led2Pin = 11; turnLedOn(led2Pin);
int led3Pin = 12; }else
boolean isConnected = false; {
LiquidCrystal lcd(8,9,4,5,6,7); turnLedOff(led2Pin);
void setup() { }
Serial.begin(9600); }
pinMode(led1Pin,OUTPUT); else if(commandString.equals("LED3"))
pinMode(led2Pin,OUTPUT); {
pinMode(led3Pin,OUTPUT); boolean LedState = getLedState();
initDisplay(); if(LedState == true)
} {
void loop() { turnLedOn(led3Pin);
if(stringComplete) }else
{ {
stringComplete = false; turnLedOff(led3Pin);
getCommand(); }
if(commandString.equals("STAR")) }
{ inputString = "";
lcd.clear(); }
} }
if(commandString.equals("STOP")) void initDisplay()
{ {
turnLedOff(led1Pin); lcd.begin(16, 2);
turnLedOff(led2Pin); lcd.print("Ready to connect");
turnLedOff(led3Pin); }
lcd.clear(); boolean getLedState()
lcd.print("Ready to connect"); {
} boolean state = false;
else if(commandString.equals("TEXT"))
{ if(inputString.substring(5,7).equals("ON"))
String text = getTextToPrint(); {
printText(text); state = true;
} }else
else if(commandString.equals("LED1")) {
{ state = false;
boolean LedState = getLedState(); }
if(LedState == true) return state;
{ }
turnLedOn(led1Pin); void getCommand()
}else {
if(inputString.length()>0) stringComplete = true;
{ }
commandString = }
inputString.substring(1,5); }
}
}
void turnLedOn(int pin) C# Code:-
{ using System;
digitalWrite(pin,HIGH); using System.Collections.Generic;
} using System.ComponentModel;
void turnLedOff(int pin) using System.Data;
{ using System.Drawing;
digitalWrite(pin,LOW); using System.Text;
} using System.Windows.Forms;
using System.IO.Ports;
namespace ComputerToArduino
String getTextToPrint() {
{ public partial class Form1 : Form
String value =
inputString.substring(5,inputString.length() {
-2); bool isConnected = false;
return value; String[] ports;
} SerialPort port;

void printText(String text) public Form1()


{ {
lcd.clear(); InitializeComponent();
lcd.setCursor(0,0); disableControls();
if(text.length()<16) getAvailableComPorts();
{
lcd.print(text); foreach (string port in ports)
}else {
{ comboBox1.Items.Add(port);
lcd.print(text.substring(0,16)); Console.WriteLine(port);
lcd.setCursor(0,1); if (ports[0] != null)
lcd.print(text.substring(16,32)); {
} comboBox1.SelectedItem =
} ports[0];
void serialEvent() { }
while (Serial.available()) { }
// get the new byte: }
char inChar = (char)Serial.read(); private void button1_Click(object
// add it to the inputString: sender, EventArgs e)
inputString += inChar; {
// if the incoming character is a newline, if (!isConnected)
set a flag {
// so the main loop can do something connectToArduino();
about it: } else
if (inChar == '\n') { {
disconnectFromArduino(); }
} }
} private void
void getAvailableComPorts() Led3CheckboxClicked(object sender,
{ EventArgs e)
ports = SerialPort.GetPortNames(); {
} if (isConnected)
private void connectToArduino() {
{ if (checkBox3.Checked)
isConnected = true; {
string selectedPort = port.Write("#LED3ON\n");
comboBox1.GetItemText(comboBox1.Sele }
ctedItem); else
port = new SerialPort(selectedPort, {
9600, Parity.None, 8, StopBits.One); port.Write("#LED3OF\n");
port.Open(); }
port.Write("#STAR\n"); }
button1.Text = "Disconnect"; }
enableControls(); private void disconnectFromArduino()
} {
private void isConnected = false;
Led1CheckboxClicked(object sender, port.Write("#STOP\n");
EventArgs e) port.Close();
{ button1.Text = "Connect";
if(isConnected) disableControls();
{ resetDefaults();
if(checkBox1.Checked) }
{ private void button2_Click(object
port.Write("#LED1ON\n"); sender, EventArgs e)
}else {
{ if (isConnected)
port.Write("#LED1OF\n"); {
} port.Write("#TEXT" +
} textBox1.Text + "#\n");
} }
private void }
Led2CheckboxClicked(object sender, private void enableControls()
EventArgs e) {
{ checkBox1.Enabled = true;
if (isConnected) checkBox2.Enabled = true;
{ checkBox3.Enabled = true;
if (checkBox2.Checked) button2.Enabled = true;
{ textBox1.Enabled = true;
port.Write("#LED2ON\n"); groupBox1.Enabled = true;
} groupBox3.Enabled = true;
else }
{ private void disableControls()
port.Write("#LED2OF\n"); {
} checkBox1.Enabled = false;
checkBox2.Enabled = false; {
checkBox3.Enabled = false;
button2.Enabled = false; }
textBox1.Enabled = false; }
groupBox1.Enabled = false; }
groupBox3.Enabled = false;
} Conclusion
private void resetDefaults() Thus we have learned to control Arduino
{ Uno using simple application made using
checkBox1.Checked = false; C# code using USB cable. Now we use our
checkBox2.Checked = false; own protocol for controlling other things
checkBox3.Checked = false; such as motors, lighting, pump, fan,
textBox1.Text = ""; industrial instruments etc. We have studied
} LCD, LED interfacing with Arduino Uno.
private void groupBox3_Enter(object Also we have studied how to use serial
sender, EventArgs e) communication.

Das könnte Ihnen auch gefallen