Вы находитесь на странице: 1из 8

2/19/13

C# | JaycoRobotics

JaycoRobotics Where your best friend is a Robot

Home Simple HUD Software C# Communication Aerial Information Links About Recent Posts
Using Performance Counters C# Add Speach to Your Program Getting CPU Load on Windows Windows Management Information C# Serial Communication New Graphic HUD Serial Communication Protocol Welcome to JaycoRobotics.com

Title

Add Speach to Your Program


Author DJ

Date April 1st, 2012

When making a basestation program for your UAV it can be nice to add voice warnings. There can be used to let the user know when they have reached a waypoint, achieved an objective, and announce a warning or error. With windows programming it is easy to add this voice to the program. To start you will need to add a reference to your the System.Speech. You can then add the using statement in your code like below. 1 using System.Speech.Synthesis; After adding the reference you can use the code below to make the computer speak. 1 SpeechSynthesizer speaker = new SpeechSynthesizer(); 2 Prompt pt = new Prompt("Hello World! You are beautiful today.); 3 speaker.Speak(pt); With this you should hear your computer speak. If you have problems there are a few other options that may need to be set before you system can speak. 1 speaker.Rate = 1; 2 speaker.Volume = 100; 3 speaker.SetOutputToDefaultAudioDevice(); Your speach program should now work to give your users verbal information. Categories C#, Software

Title

Getting CPU Load on Windows


Author DJ

Date March 31st, 2012

When using a robot with a Windows based operating system it is sometimes nice to get the load on the processor so you know how much more processing you can add. If you have a multicore processor it is also nice to see each core individually. If you have direct access to the computer you can just use the task manager to see this information but if you want to see it in your own program you will need to get the information programatically. To get the performance of the processor it is best to use a performance counter. The performance counters are under System.Diagnostics. To get a string array of processors use the code below. 1 PerformanceCounterCategory pcc = new PerformanceCounterCategory("Processor"); 2 string[] cat = pcc.GetInstanceNames(); This will give you a list of all the cores plus one called _total. The _total category is exactly what it sounds like. It is a combination of all the cores. The rest will be labeled as CPU0,CPU1, etc. After you have the list of cores you can choose which one you want or get the total for all. You will need this name in order to create a performance counter. The next step is to choose what you want the performance counter to track. In our case we want to use the % Processor Time. To create the Performance Counter we use the code below. Then all we have to do is call the NextValue method to get the value we want. 1 PerformanceCounter pc = new PerformanceCounter("Processor", "% Processor Time", "_Total"); 2 pc.NextValue(); If you would like to get a list of all the performance counters on the system you can use the code below. This is helpful if there are other metrics that you wish to track on the system. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 PerformanceCounterCategory[] categories = PerformanceCounterCategory.GetCategories(); foreach(PerformanceCounterCategory pcc in categories) { string[] instanceNames = pcc.GetInstanceNames(); foreach (string instanceName in instanceNames) { PerformanceCounter[] counters = pcc.GetCounters(instanceName); foreach (PerformanceCounter counter in counters) { //Do something to list all the performance counters string cn = counter.CounterName; } } }

Links
DIY Drones SDSM&T UAV Team SparkFun Electronics

Performance counters are very helpful in diagnosing a robotic system and for making sure your processor is getting used to its full potential. Categories C#, Software

jaycorobotics.com/category/c/

1/8

2/19/13

C# | JaycoRobotics

Title

Windows Management Information


Author DJ

Date March 28th, 2012

Sometimes when creating a program you will need to know something about the computer inside your program. One way of getting information about the computer is using Windows Management Information. It is relatively simple to get the information and use it to whatever purpose you have. Sometimes it is just fun to show the user the hardware that is on the system. All of the objects that we want to call are Win32 objects. By searching online you can find the names for all of them but I have provided a list at the bottom of this post for ease. To get the information from the object we can use SQL query strings. Below is code for accessing all the properties within the object and adding to a list which can be viewed in a DataGridView or other control. 1 public ArrayList GetInformation(string queryObject) 2 { 3 //Create an array list to return. 4 ArrayList hd = new ArrayList(); 5 6 //Catch any exceptions such as an emtpy or missing object. 7 try 8 { 9 //Retreives a collection of management objects using a SQL type query. 10 ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM " + queryObject); 11 12 //Go thought each object to get its properties. 13 foreach (ManagementObject wmi_HD in searcher.Get()) 14 { 15 //Grab all the properties in the management object. 16 PropertyDataCollection searcherProperties = wmi_HD.Properties; 17 18 //Add each property to the array list. 19 foreach (PropertyData sp in searcherProperties) 20 { 21 //Add the row of property data to the array list. 22 hd.Add(sp); 23 } 24 } 25 } 26 catch (Exception ex) 27 { 28 //Display a message box with any exceptions that occured. 29 MessageBox.Show(ex.ToString()); 30 } 31 32 //Return the array list full or empty. 33 return hd; 34 } Once you have the list of properties for the object you can sort out the ones that you want to display to your user or even modify your SQL statement to quickly get the property you want to show your user. This is a list of all Win32 classes that I know of. Depending on your system not all of these will return information since some systems to not support all objects. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 Win32_1394Controller Win32_1394ControllerDevice Win32_AccountSID Win32_ActionCheck Win32_ActiveRoute Win32_AllocatedResource Win32_ApplicationCommandLine Win32_ApplicationService Win32_AssociatedBattery Win32_AssociatedProcessorMemory Win32_AutochkSetting Win32_BaseBoard Win32_Battery Win32_Binary Win32_BindImageAction Win32_BIOS Win32_BootConfiguration Win32_Bus Win32_CacheMemory Win32_CDROMDrive Win32_CheckCheck Win32_CIMLogicalDeviceCIMDataFile Win32_ClassicCOMApplicationClasses Win32_ClassicCOMClass Win32_ClassicCOMClassSetting Win32_ClassicCOMClassSettings Win32_ClassInforAction Win32_ClientApplicationSetting Win32_CodecFile Win32_COMApplicationSettings Win32_COMClassAutoEmulator Win32_ComClassEmulator Win32_CommandLineAccess Win32_ComponentCategory Win32_ComputerSystem Win32_ComputerSystemProcessor Win32_ComputerSystemProduct Win32_ComputerSystemWindowsProductActivationSetting Win32_Condition Win32_ConnectionShare Win32_ControllerHastHub

jaycorobotics.com/category/c/

2/8

2/19/13
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

C# | JaycoRobotics
Win32_CreateFolderAction Win32_CurrentProbe Win32_DCOMApplication Win32_DCOMApplicationAccessAllowedSetting Win32_DCOMApplicationLaunchAllowedSetting Win32_DCOMApplicationSetting Win32_DependentService Win32_Desktop Win32_DesktopMonitor Win32_DeviceBus Win32_DeviceMemoryAddress Win32_Directory Win32_DirectorySpecification Win32_DiskDrive Win32_DiskDrivePhysicalMedia Win32_DiskDriveToDiskPartition Win32_DiskPartition Win32_DiskQuota Win32_DisplayConfiguration Win32_DisplayControllerConfiguration Win32_DMAChanner Win32_DriverForDevice Win32_DriverVXD Win32_DuplicateFileAction Win32_Environment Win32_EnvironmentSpecification Win32_ExtensionInfoAction Win32_Fan Win32_FileSpecification Win32_FloppyController Win32_FloppyDrive Win32_FontInfoAction Win32_Group Win32_GroupDomain Win32_GroupUser Win32_HeatPipe Win32_IDEController Win32_IDEControllerDevice Win32_ImplementedCategory Win32_InfraredDevice Win32_IniFileSpecification Win32_InstalledSoftwareElement Win32_IP4PersistedRouteTable Win32_IP4RouteTable Win32_IRQResource Win32_Keyboard Win32_LaunchCondition Win32_LoadOrderGroup Win32_LoadOrderGroupServiceDependencies Win32_LoadOrderGroupServiceMembers Win32_LocalTime Win32_LoggedOnUser Win32_LogicalDisk Win32_LogicalDiskRootDirectory Win32_LogicalDiskToPartition Win32_LogicalFileAccess Win32_LogicalFileAuditing Win32_LogicalFileGroup Win32_LogicalFileOwner Win32_LogicalFileSecuritySetting Win32_LogicalMemoryConfiguration Win32_LogicalProgramGroup Win32_LogicalProgramGroupDirectory Win32_LogicalProgramGroupItem Win32_LogicalProgramGroupItemDataFile Win32_LogicalShareAccess Win32_LogicalShareAuditing Win32_LogicalShareSecuritySetting Win32_LogonSession Win32_LogonSessionMappedDisk Win32_MappedLogicalDisk Win32_MemoryArray Win32_MemoryArrayLocation Win32_MemoryDevice Win32_MemoryDeviceArray Win32_MemoryDeviceLocation Win32_MIMEInfoAction Win32_MotherboardDevice Win32_MoveFileAction Win32_NamedJobObject Win32_NamedJobObjectActgInfo Win32_NamedJobObjectLimit Win32_NamedJobObjectLimitSetting Win32_NamedJobObjectProcess Win32_NamedJobObjectSecLimit Win32_NamedJobObjectSecLimitSetting Win32_NamedJobObjectStatistics Win32_NetworkAdapter Win32_NetworkAdapterConfiguration Win32_NetworkAdapterSetting Win32_NetworkClient Win32_NetworkConnection Win32_NetworkLoginProfile Win32_NetworkProtocol Win32_NTDomain Win32_NTEventlogFile Win32_NTLogEvent

jaycorobotics.com/category/c/

3/8

2/19/13
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234

C# | JaycoRobotics
Win32_NTLogEventComputer Win32_NTLogEvnetLog Win32_NTLogEventUser Win32_ODBCAttribute Win32_ODBCDataSourceAttribute Win32_ODBCDataSourceSpecification Win32_ODBCDriverAttribute Win32_ODBCDriverSoftwareElement Win32_ODBCDriverSpecification Win32_ODBCSourceAttribute Win32_ODBCTranslatorSpecification Win32_OnBoardDevice Win32_OperatingSystem Win32_OperatingSystemAutochkSetting Win32_OperatingSystemQFE Win32_OSRecoveryConfiguracin Win32_PageFile Win32_PageFileElementSetting Win32_PageFileSetting Win32_PageFileUsage Win32_ParallelPort Win32_Patch Win32_PatchFile Win32_PatchPackage Win32_PCMCIAControler Win32_PerfFormattedData_ASP_ActiveServerPages Win32_PerfFormattedData_ASPNET_114322_ASPNETAppsv114322 Win32_PerfFormattedData_ASPNET_114322_ASPNETv114322 Win32_PerfFormattedData_ASPNET_2040607_ASPNETAppsv2040607 Win32_PerfFormattedData_ASPNET_2040607_ASPNETv2040607 Win32_PerfFormattedData_ASPNET_ASPNET Win32_PerfFormattedData_ASPNET_ASPNETApplications Win32_PerfFormattedData_aspnet_state_ASPNETStateService Win32_PerfFormattedData_ContentFilter_IndexingServiceFilter Win32_PerfFormattedData_ContentIndex_IndexingService Win32_PerfFormattedData_DTSPipeline_SQLServerDTSPipeline Win32_PerfFormattedData_Fax_FaxServices Win32_PerfFormattedData_InetInfo_InternetInformationServicesGlobal Win32_PerfFormattedData_ISAPISearch_HttpIndexingService Win32_PerfFormattedData_MSDTC_DistributedTransactionCoordinator Win32_PerfFormattedData_NETCLRData_NETCLRData Win32_PerfFormattedData_NETCLRNetworking_NETCLRNetworking Win32_PerfFormattedData_NETDataProviderforOracle_NETCLRData Win32_PerfFormattedData_NETDataProviderforSqlServer_NETDataProviderforSqlServer Win32_PerfFormattedData_NETFramework_NETCLRExceptions Win32_PerfFormattedData_NETFramework_NETCLRInterop Win32_PerfFormattedData_NETFramework_NETCLRJit Win32_PerfFormattedData_NETFramework_NETCLRLoading Win32_PerfFormattedData_NETFramework_NETCLRLocksAndThreads Win32_PerfFormattedData_NETFramework_NETCLRMemory Win32_PerfFormattedData_NETFramework_NETCLRRemoting Win32_PerfFormattedData_NETFramework_NETCLRSecurity Win32_PerfFormattedData_NTFSDRV_ControladordealmacenamientoNTFSdeSMTP Win32_PerfFormattedData_Outlook_Outlook Win32_PerfFormattedData_PerfDisk_LogicalDisk Win32_PerfFormattedData_PerfDisk_PhysicalDisk Win32_PerfFormattedData_PerfNet_Browser Win32_PerfFormattedData_PerfNet_Redirector Win32_PerfFormattedData_PerfNet_Server Win32_PerfFormattedData_PerfNet_ServerWorkQueues Win32_PerfFormattedData_PerfOS_Cache Win32_PerfFormattedData_PerfOS_Memory Win32_PerfFormattedData_PerfOS_Objects Win32_PerfFormattedData_PerfOS_PagingFile Win32_PerfFormattedData_PerfOS_Processor Win32_PerfFormattedData_PerfOS_System Win32_PerfFormattedData_PerfProc_FullImage_Costly Win32_PerfFormattedData_PerfProc_Image_Costly Win32_PerfFormattedData_PerfProc_JobObject Win32_PerfFormattedData_PerfProc_JobObjectDetails Win32_PerfFormattedData_PerfProc_Process Win32_PerfFormattedData_PerfProc_ProcessAddressSpace_Costly Win32_PerfFormattedData_PerfProc_Thread Win32_PerfFormattedData_PerfProc_ThreadDetails_Costly Win32_PerfFormattedData_RemoteAccess_RASPort Win32_PerfFormattedData_RemoteAccess_RASTotal Win32_PerfFormattedData_RSVP_RSVPInterfaces Win32_PerfFormattedData_RSVP_RSVPService Win32_PerfFormattedData_Spooler_PrintQueue Win32_PerfFormattedData_TapiSrv_Telephony Win32_PerfFormattedData_Tcpip_ICMP Win32_PerfFormattedData_Tcpip_IP Win32_PerfFormattedData_Tcpip_NBTConnection Win32_PerfFormattedData_Tcpip_NetworkInterface Win32_PerfFormattedData_Tcpip_TCP Win32_PerfFormattedData_Tcpip_UDP Win32_PerfFormattedData_TermService_TerminalServices Win32_PerfFormattedData_TermService_TerminalServicesSession Win32_PerfFormattedData_W3SVC_WebService Win32_PerfRawData_ASP_ActiveServerPages Win32_PerfRawData_ASPNET_114322_ASPNETAppsv114322 Win32_PerfRawData_ASPNET_114322_ASPNETv114322 Win32_PerfRawData_ASPNET_2040607_ASPNETAppsv2040607 Win32_PerfRawData_ASPNET_2040607_ASPNETv2040607 Win32_PerfRawData_ASPNET_ASPNET Win32_PerfRawData_ASPNET_ASPNETApplications Win32_PerfRawData_aspnet_state_ASPNETStateService

jaycorobotics.com/category/c/

4/8

2/19/13
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

C# | JaycoRobotics
Win32_PerfRawData_ContentFilter_IndexingServiceFilter Win32_PerfRawData_ContentIndex_IndexingService Win32_PerfRawData_DTSPipeline_SQLServerDTSPipeline Win32_PerfRawData_Fax_FaxServices Win32_PerfRawData_InetInfo_InternetInformationServicesGlobal Win32_PerfRawData_ISAPISearch_HttpIndexingService Win32_PerfRawData_MSDTC_DistributedTransactionCoordinator Win32_PerfRawData_NETCLRData_NETCLRData Win32_PerfRawData_NETCLRNetworking_NETCLRNetworking Win32_PerfRawData_NETDataProviderforOracle_NETCLRData Win32_PerfRawData_NETDataProviderforSqlServer_NETDataProviderforSqlServer Win32_PerfRawData_NETFramework_NETCLRExceptions Win32_PerfRawData_NETFramework_NETCLRInterop Win32_PerfRawData_NETFramework_NETCLRJit Win32_PerfRawData_NETFramework_NETCLRLoading Win32_PerfRawData_NETFramework_NETCLRLocksAndThreads Win32_PerfRawData_NETFramework_NETCLRMemory Win32_PerfRawData_NETFramework_NETCLRRemoting Win32_PerfRawData_NETFramework_NETCLRSecurity Win32_PerfRawData_NTFSDRV_ControladordealmacenamientoNTFSdeSMTP Win32_PerfRawData_Outlook_Outlook Win32_PerfRawData_PerfDisk_LogicalDisk Win32_PerfRawData_PerfDisk_PhysicalDisk Win32_PerfRawData_PerfNet_Browser Win32_PerfRawData_PerfNet_Redirector Win32_PerfRawData_PerfNet_Server Win32_PerfRawData_PerfNet_ServerWorkQueues Win32_PerfRawData_PerfOS_Cache Win32_PerfRawData_PerfOS_Memory Win32_PerfRawData_PerfOS_Objects Win32_PerfRawData_PerfOS_PagingFile Win32_PerfRawData_PerfOS_Processor Win32_PerfRawData_PerfOS_System Win32_PerfRawData_PerfProc_FullImage_Costly Win32_PerfRawData_PerfProc_Image_Costly Win32_PerfRawData_PerfProc_JobObject Win32_PerfRawData_PerfProc_JobObjectDetails Win32_PerfRawData_PerfProc_Process Win32_PerfRawData_PerfProc_ProcessAddressSpace_Costly Win32_PerfRawData_PerfProc_Thread Win32_PerfRawData_PerfProc_ThreadDetails_Costly Win32_PerfRawData_RemoteAccess_RASPort Win32_PerfRawData_RemoteAccess_RASTotal Win32_PerfRawData_RSVP_RSVPInterfaces Win32_PerfRawData_RSVP_RSVPService Win32_PerfRawData_Spooler_PrintQueue Win32_PerfRawData_TapiSrv_Telephony Win32_PerfRawData_Tcpip_ICMP Win32_PerfRawData_Tcpip_IP Win32_PerfRawData_Tcpip_NBTConnection Win32_PerfRawData_Tcpip_NetworkInterface Win32_PerfRawData_Tcpip_TCP Win32_PerfRawData_Tcpip_UDP Win32_PerfRawData_TermService_TerminalServices Win32_PerfRawData_TermService_TerminalServicesSession Win32_PerfRawData_W3SVC_WebService Win32_PhysicalMedia Win32_PhysicalMemory Win32_PhysicalMemoryArray Win32_PhysicalMemoryLocation Win32_PingStatus Win32_PNPAllocatedResource Win32_PnPDevice Win32_PnPEntity Win32_PnPSignedDriver Win32_PnPSignedDriverCIMDataFile Win32_PointingDevice Win32_PortableBattery Win32_PortConnector Win32_PortResource Win32_POTSModem Win32_POTSModemToSerialPort Win32_Printer Win32_PrinterConfiguration Win32_PrinterController Win32_PrinterDriver Win32_PrinterDriverDll Win32_PrinterSetting Win32_PrinterShare Win32_PrintJob Win32_Process Win32_Processor Win32_Product Win32_ProductCheck Win32_ProductResource Win32_ProductSoftwareFeatures Win32_ProgIDSpecification Win32_ProgramGroup Win32_ProgramGroupContents Win32_Property Win32_ProtocolBinding Win32_Proxy Win32_PublishComponentAction Win32_QuickFixEngineering Win32_QuotaSetting Win32_Refrigeration Win32_Registry

jaycorobotics.com/category/c/

5/8

2/19/13
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428

C# | JaycoRobotics
Win32_RegistryAction Win32_RemoveFileAction Win32_RemoveIniAction Win32_ReserveCost Win32_ScheduledJob Win32_SCSIController Win32_SCSIControllerDevice Win32_SecuritySettingOfLogicalFile Win32_SecuritySettingOfLogicalShare Win32_SelfRegModuleAction Win32_SerialPort Win32_SerialPortConfiguration Win32_SerialPortSetting Win32_ServerConnection Win32_ServerSession Win32_Service Win32_ServiceControl Win32_ServiceSpecification Win32_ServiceSpecificationService Win32_SessionConnection Win32_SessionProcess Win32_Share Win32_ShareToDirectory Win32_ShortcutAction Win32_ShortcutFile Win32_ShortcutSAP Win32_SID Win32_SoftwareElement Win32_SoftwareElementAction Win32_SoftwareElementCheck Win32_SoftwareElementCondition Win32_SoftwareElementResource Win32_SoftwareFeature Win32_SoftwareFeatureAction Win32_SoftwareFeatureCheck Win32_SoftwareFeatureParent Win32_SoftwareFeatureSoftwareElements Win32_SoundDevice Win32_StartupCommand Win32_SubDirectory Win32_SystemAccount Win32_SystemBIOS Win32_SystemBootConfiguration Win32_SystemDesktop Win32_SystemDevices Win32_SystemDriver Win32_SystemDriverPNPEntity Win32_SystemEnclosure Win32_SystemLoadOrderGroups Win32_SystemLogicalMemoryConfiguration Win32_SystemNetworkConnections Win32_SystemOperatingSystem Win32_SystemPartitions Win32_SystemProcesses Win32_SystemProgramGroups Win32_SystemResources Win32_SystemServices Win32_SystemSlot Win32_SystemSystemDriver Win32_SystemTimeZone Win32_SystemUsers Win32_TapeDrive Win32_TCPIPPrinterPort Win32_TemperatureProbe Win32_Terminal Win32_TerminalService Win32_TerminalServiceSetting Win32_TerminalServiceToSetting Win32_TerminalTerminalSetting Win32_Thread Win32_TimeZone Win32_TSAccount Win32_TSClientSetting Win32_TSEnvironmentSetting Win32_TSGeneralSetting Win32_TSLogonSetting Win32_TSNetworkAdapterListSetting Win32_TSNetworkAdapterSetting Win32_TSPermissionsSetting Win32_TSRemoteControlSetting Win32_TSSessionDirectory Win32_TSSessionDirectorySetting Win32_TSSessionSetting Win32_TypeLibraryAction Win32_UninterruptiblePowerSupply Win32_USBController Win32_USBControllerDevice Win32_USBHub Win32_UserAccount Win32_UserDesktop Win32_UserInDomain Win32_UTCTime Win32_VideoController Win32_VideoSettings Win32_VoltageProbe Win32_VolumeQuotaSetting Win32_WindowsProductActivation

jaycorobotics.com/category/c/

6/8

2/19/13

C# | JaycoRobotics
429 Win32_WMIElementSetting 430 Win32_WMISetting

Categories

C#, Software

Title

C# Serial Communication
Author DJ

Date February 26th, 2011

The C# langauge and the embedded processors that can harness the programs created by it are growing every year. This post will teach making a simple serial program. Sample Project Files

The first thing we need to do is create a serial port using the code below. 1 SerialPort serialport = new SerialPort(); //Declare the serial port object.

The code below shows how to fill combo boxes with the possible selections for each of the settings required to create a serial port. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 //Get Serial Port Names foreach (string serialname in SerialPort.GetPortNames()) { cmbSerialPort.Items.Add(serialname); } if (cmbSerialPort.Items.Count > 0) cmbSerialPort.SelectedIndex = 0; //Tie Enum Types to combo boxes for selection. cmbStopBits.DataSource = Enum.GetValues(typeof(StopBits)); cmbParity.DataSource = Enum.GetValues(typeof(Parity)); //Put all the Possible Baud rates into the combo box for selection. cmbBaud.Items.Add("1200"); cmbBaud.Items.Add("2400"); cmbBaud.Items.Add("4800"); cmbBaud.Items.Add("9600"); cmbBaud.Items.Add("19200"); cmbBaud.Items.Add("38400"); cmbBaud.Items.Add("57600"); cmbBaud.Items.Add("115200"); cmbBaud.Items.Add("230400"); cmbBaud.SelectedIndex = 3; //Set all the possible data bit values. cmbDataBits.Items.Add("4"); cmbDataBits.Items.Add("5"); cmbDataBits.Items.Add("6"); cmbDataBits.Items.Add("7"); cmbDataBits.Items.Add("8"); cmbDataBits.SelectedIndex = 4;

To create the serial port we need to set several variables. 1 2 3 4 5 6 7 8 9 //Set the minimum values we need to create a link serialport.PortName = cmbSerialPort.SelectedItem.ToString(); serialport.BaudRate = Convert.ToInt16(cmbBaud.SelectedItem); serialport.DataBits = Convert.ToInt16(cmbDataBits.SelectedItem); serialport.Parity = (Parity)cmbParity.SelectedItem; serialport.StopBits = (StopBits)cmbStopBits.SelectedItem; //Open the Serial Port serialport.Open();

The next thing we need to do is set up an event handler so we can catch when new information is transmitted to us. 1 serialport.DataReceived += new SerialDataReceivedEventHandler(DataReceived); Since the event handler does not come back on the same thread as the UI we need to invoke and delegate the information to our UI thread for displaying. 1 rtbReceived.Invoke(new EventHandler(delegate 2 { 3 rtbReceived.AppendText(serialport.ReadExisting()); 4 })); To send data over the serial link all we need to do is call the WriteLine method. The serial port also allows for sending character or byte strings.

jaycorobotics.com/category/c/

7/8

2/19/13

C# | JaycoRobotics
1 serialport.WriteLine(rtbSend.Text); Putting the parts learned here together I created a simple serial communication program that sends text from one computer to another. This is a perfect start to developing communication between computers and components. With a few changes to the above code you can send data in byte streams specific to your needs or stay in Ascii characters and make your communication easy for humans to read and interpret. Have fun with your newly learned skills. Categories C#, Communication

jaycorobotics.com/category/c/

8/8

Вам также может понравиться