質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Visual Studio

Microsoft Visual StudioはMicrosoftによる統合開発環境(IDE)です。多種多様なプログラミング言語に対応しています。

Q&A

解決済

3回答

2200閲覧

C#でシリアル通信を行いその値をint型に変換する方法

yakoumori

総合スコア12

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Visual Studio

Microsoft Visual StudioはMicrosoftによる統合開発環境(IDE)です。多種多様なプログラミング言語に対応しています。

0グッド

0クリップ

投稿2018/12/18 15:54

編集2018/12/18 16:37

こんばんは。

現在ArduinoとC#を連携させて画面の明るさを変更するためのプログラムの作成を行っています。
Ardiunoから圧力センサの値を受信して、C#にて画面の明るさを変更しようとしています。

C#の開発環境はVisualStudio2013でシリアル通信をさせることはできたのですが、
シリアル通信によって得た圧力センサの値を画面の明るさへの値として入れようとしてもうまくいきません。

今の状態はArduinoからfloat型にしている圧力センサの平均値を読み取り、listBoxに表示するところまでできています。
イメージ説明

画面の明るさを変更するにはint型を要求されていることはわかったのですが、
肝心の変換のやり方がわからなくて困っています。

1度Convertを利用して、

C#

1private void AddLog(String text) 2 { 3      int t = Convert.ToInt32(text); 4 listBox1.Items.Insert(0, text); 5 } 6

と入力してみたのですが実行途中にて次のようなエラーが起きました。起きました
どのように変換すればint型になり明るさを変更できるのかがわかりません。

ソースコード

C#

1using System; 2using System.Collections.Generic; 3using System.ComponentModel; 4using System.Data; 5using System.Drawing; 6using System.Linq; 7using System.Runtime.InteropServices; 8using System.Text; 9using System.Threading.Tasks; 10using System.Windows.Forms; 11using System.IO.Ports; 12 13namespace display 14{ 15 public partial class Form1 : Form 16 { 17 18 19 #region Constants 20 /// <summary> 21 /// Settings in this subgroup control configuration of the video power management features. 22 /// </summary> 23 Guid GUID_VIDEO_SUBGROUP = new Guid("7516b95f-f776-4464-8c53-06167f40cc99"); 24 25 /// <summary> 26 /// Guid for display brightness setting. 27 /// </summary> 28 Guid DisplayBrightnessGuid = new Guid("aded5e82-b909-4619-9949-f5d71dac0bcb"); 29 #endregion 30 31 #region Methods 32 /// <summary> 33 /// Retrieves the AC index of the specified power setting. 34 /// </summary> 35 /// <param name="RootPowerKey">This parameter is reserved for future use and must be set to NULL.</param> 36 /// <param name="SchemeGuid">The identifier of the power scheme.</param> 37 /// <param name="SubGroupOfPowerSettingsGuid">The subgroup of power settings. This parameter can be one of the following values defined in WinNT.h. Use NO_SUBGROUP_GUID to refer to the default power scheme.</param> 38 /// <param name="PowerSettingGuid">The identifier of the power setting</param> 39 /// <param name="AcValueIndex">A pointer to a variable that receives the AC value index.</param> 40 /// <returns>Returns ERROR_SUCCESS (zero) if the call was successful, and a nonzero value if the call failed.</returns> 41 [DllImport("powrprof.dll", EntryPoint = "PowerReadACValueIndex", CharSet = CharSet.Auto, SetLastError = true)] 42 public static extern uint PowerReadACValueIndex(IntPtr RootPowerKey, ref Guid SchemeGuid, ref Guid SubGroupOfPowerSettingsGuid, ref Guid PowerSettingGuid, out uint AcValueIndex); 43 44 45 /// <summary> 46 /// Sets the AC value index of the specified power setting. 47 /// </summary> 48 /// <param name="RootPowerKey">This parameter is reserved for future use and must be set to NULL.</param> 49 /// <param name="SchemeGuid">The identifier of the power scheme.</param> 50 /// <param name="SubGroupOfPowerSettingsGuid">The subgroup of power settings. This parameter can be one of the following values defined in WinNT.h. Use NO_SUBGROUP_GUID to refer to the default power scheme.</param> 51 /// <param name="PowerSettingGuid">The identifier of the power setting</param> 52 /// <param name="AcValueIndex">The AC value index.</param> 53 /// <returns>Returns ERROR_SUCCESS (zero) if the call was successful, and a nonzero value if the call failed.</returns> 54 [DllImport("powrprof.dll", EntryPoint = "PowerWriteACValueIndex", CharSet = CharSet.Auto, SetLastError = true)] 55 public static extern uint PowerWriteACValueIndex(IntPtr RootPowerKey, ref Guid SchemeGuid, ref Guid SubGroupOfPowerSettingsGuid, ref Guid PowerSettingGuid, uint AcValueIndex); 56 57 /// <summary> 58 /// Retrieves the AC index of the specified power setting. 59 /// </summary> 60 /// <param name="RootPowerKey">This parameter is reserved for future use and must be set to NULL.</param> 61 /// <param name="SchemeGuid">The identifier of the power scheme.</param> 62 /// <param name="SubGroupOfPowerSettingsGuid">The subgroup of power settings. This parameter can be one of the following values defined in WinNT.h. Use NO_SUBGROUP_GUID to refer to the default power scheme.</param> 63 /// <param name="PowerSettingGuid">The identifier of the power setting</param> 64 /// <param name="AcValueIndex">A pointer to a variable that receives the AC value index.</param> 65 /// <returns>Returns ERROR_SUCCESS (zero) if the call was successful, and a nonzero value if the call failed.</returns> 66 [DllImport("powrprof.dll", EntryPoint = "PowerReadDCValueIndex", CharSet = CharSet.Auto, SetLastError = true)] 67 public static extern uint PowerReadDCValueIndex(IntPtr RootPowerKey, ref Guid SchemeGuid, ref Guid SubGroupOfPowerSettingsGuid, ref Guid PowerSettingGuid, out uint AcValueIndex); 68 69 70 /// <summary> 71 /// Sets the AC value index of the specified power setting. 72 /// </summary> 73 /// <param name="RootPowerKey">This parameter is reserved for future use and must be set to NULL.</param> 74 /// <param name="SchemeGuid">The identifier of the power scheme.</param> 75 /// <param name="SubGroupOfPowerSettingsGuid">The subgroup of power settings. This parameter can be one of the following values defined in WinNT.h. Use NO_SUBGROUP_GUID to refer to the default power scheme.</param> 76 /// <param name="PowerSettingGuid">The identifier of the power setting</param> 77 /// <param name="AcValueIndex">The AC value index.</param> 78 /// <returns>Returns ERROR_SUCCESS (zero) if the call was successful, and a nonzero value if the call failed.</returns> 79 [DllImport("powrprof.dll", EntryPoint = "PowerWriteDCValueIndex", CharSet = CharSet.Auto, SetLastError = true)] 80 public static extern uint PowerWriteDCValueIndex(IntPtr RootPowerKey, ref Guid SchemeGuid, ref Guid SubGroupOfPowerSettingsGuid, ref Guid PowerSettingGuid, uint AcValueIndex); 81 82 83 /// <summary> 84 /// Sets the active power scheme for the current user. 85 /// </summary> 86 /// <param name="UserRootPowerKey">This parameter is reserved for future use and must be set to NULL.</param> 87 /// <param name="SchemeGuid">The identifier of the power scheme.</param> 88 /// <returns>Returns ERROR_SUCCESS (zero) if the call was successful, and a nonzero value if the call failed.</returns> 89 [DllImport("powrprof.dll", EntryPoint = "PowerSetActiveScheme", CharSet = CharSet.Auto, SetLastError = true)] 90 public static extern uint PowerSetActiveScheme(IntPtr UserRootPowerKey, ref Guid SchemeGuid); 91 92 #endregion 93 94 public Form1() 95 { 96 InitializeComponent(); 97 } 98 99 100 private delegate void AddLogDelegate(String text); 101 string str; 102 Guid MY_POWER_MANAGEMENT_POLICY = new Guid("a83ffe77-647e-45df-899e-cd3f4e2835a1"); // 今回は<SCHEME_GUID>をベタ指定 103 104 105 //コマンドプロンプトでの実行をここで行う 106 bool SetACBrightness(int bright_ac) 107 { 108 if (bright_ac < 0 || bright_ac > 100) 109 return false; 110 111 uint ret = PowerWriteACValueIndex(IntPtr.Zero, ref MY_POWER_MANAGEMENT_POLICY, ref GUID_VIDEO_SUBGROUP, ref DisplayBrightnessGuid, (uint)bright_ac); 112 if (ret != 0) 113 return false; 114 115 ret = PowerSetActiveScheme(IntPtr.Zero, ref MY_POWER_MANAGEMENT_POLICY); 116 if (ret != 0) 117 return false; 118 119 return true; 120 } 121 122 private void serialPort1_DataReceived_1(object sender, SerialDataReceivedEventArgs e) 123 { 124 str = serialPort1.ReadLine(); 125 AddLogDelegate dlg1 = new AddLogDelegate(AddLog); 126 BeginInvoke(dlg1, new object[] { str }); 127 } 128 private void AddLog(String text) 129 { 130 int t = Convert.ToInt32(text); 131 listBox1.Items.Insert(0, text); 132 } 133 134 135 136 //ボタンによる実行 137 private void button1_Click_1(object sender, EventArgs e) 138 { 139 140 //Ardinoの設定 141 try 142 { 143 this.serialPort1.PortName = "COM3"; 144 this.serialPort1.BaudRate = 9600; 145 this.serialPort1.Parity = System.IO.Ports.Parity.None; 146 this.serialPort1.DataBits = 8; 147 this.serialPort1.StopBits = System.IO.Ports.StopBits.One; 148 serialPort1.Open(); 149 } 150 catch (Exception ex) 151 { 152 MessageBox.Show(ex.Message, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); 153 return; 154 } 155 /* 156 Random rb_ac = new System.Random(); 157 //画面の明るさ変更を乱数で1~100の値を設定 158 int b_ac = rb_ac.Next(100); 159 //labelにランダムの値を表示 160 label1.Text = b_ac.ToString(); 161 */ 162 163 164 //徐々にスクリーンの明るさの変更を行うソースコード 165 int c_ac = 1; 166 for (int i = 100; i >1; i--) 167 { 168 c_ac = i; 169 170 //boolの実行 171 if (SetACBrightness(c_ac) == true) 172 { 173 } 174 } 175 for (int i = 0; i <= 100; i++) 176 { 177 c_ac = i; 178 //boolの実行 179 if (SetACBrightness(c_ac) == true) 180 { 181 } 182 } 183 184 } 185 186 187 188 189 190 private void button2_Click(object sender, EventArgs e) 191 { 192 serialPort1.Close(); 193 } 194 195 } 196} 197

よろしくお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

TakafumiYuasa

2018/12/18 16:14

恐らくシリアル通信で送られくる文字列が数字だけのものではない、あるいは16進数の値(0〜F)ではないでしょうか? シリアル通信で送られてきている文字列をそのままデバッグ表示したらどのような文字列が表示されるか追記願えますか?
guest

回答3

0

小数点付きの文字列であれば、
「C# 文字列 float 変換」でぐぐれば変換方法は出てきます
小数点以下2桁、と決まってるなら、floatにしたあと100掛けて、intにしてしまい、あとの換算に使えばいいでしょう
(最終的に100で割るのを忘れずに)

投稿2018/12/18 23:19

y_waiwai

総合スコア87747

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

ベストアンサー

追記ありがとうございました。
テキストは浮動小数点数という事で、少なくとも以下のようにすれば整数値で値が得られると思います。

C#

1private void AddLog(String text) 2{ 3 double value = double.Parse(text); 4 int t = (int)value; 5 listBox1.Items.Insert(0, text); 6}

さらに言えば、小数点数の扱いですが、

C#

1private void AddLog(String text) 2{ 3 double value = double.Parse(text); 4 double value_ceiling = Math.Ceiling(value); // 切り上げ 5 double value_floor = Math.Floor(value); // 切り捨て 6 double value_round = Math.Round(value, MidpointRounding.AwayFromZero); // 四捨五入 7 int t = (int)value; 8 listBox1.Items.Insert(0, text); 9}

といった形で処理することが出来るので、目的に合わせて切り上げたり、切り捨てたり、四捨五入してください。

投稿2018/12/18 18:31

TakafumiYuasa

総合スコア124

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

yakoumori

2018/12/19 01:16

回答ありがとうございます。 実行してみたのですが、アプリケーションのコンポーネントで、ハンドルされていない例外が発生しているという画面が表示されました。 また、double.Parseで設定した入力文字列の形式が正しくないとの表記が出ています。
TakafumiYuasa

2018/12/19 01:37

これで出来ないとなると、もしかすると送られてきている文字列が全角だったりしますか? "100.00"ではなく"100.00"だったりしますかね? 半角であれば前後に空白(スペース)が挟まっていてもdouble.Parse()は正常に動いたので、前後空白とかはないと思いますので、全角の可能性あるかもです。 C#で全角/半角変換は面倒っぽいので、送信側で半角にできるなら半角にした方が良さそうだと思います。
YAmaGNZ

2018/12/19 02:00

質問に貼られている画像を見る限り、全角というのは考えにくい気がします。 何かしらの勘違いを防ぐために、質問者さんの実行したコードを書いていただくのがよろしいかと
TakafumiYuasa

2018/12/19 02:06

すみません、ありがとうございます。 確かにそうですね。 思い浮かぶ原因がそれくらいしかなく軽率でした。
yakoumori

2018/12/19 02:16

Arduinoではfloatによって求められた平均値をSerial.printlnで送信しているだけなのですが、送信で半角が全角になることがあるのですか? 圧力センサの値の読み込みはint型、平均値はfloatで読み込んでいます。
ozwk

2018/12/19 02:46

例外発生時にdouble.Parse()に何が渡されているか確認してください。
yakoumori

2018/12/19 03:02

解決しました。自分で設定したものがあったのでそれを利用しました。
guest

0

ソースコードにstring str;を設定し、

C#

1 private void serialPort1_DataReceived_1(object sender, SerialDataReceivedEventArgs e) 2 { 3 str = serialPort1.ReadLine(); 4 AddLogDelegate dlg1 = new AddLogDelegate(AddLog); 5 BeginInvoke(dlg1, new object[] { str }); 6 }

の中でstrにシリアルポートの値を読み込んでいた場所がありました。
その文字列をParseにて変換することでSetACBrightness(t);にて読み込むことができました。

C#

1 private void AddLog(String text) 2 { 3 double val = double.Parse(str); 4 t = (int)val; 5 SetACBrightness(t); 6 }

回答やコメントをしてくれた方々ありがとうございます。

投稿2018/12/19 03:13

yakoumori

総合スコア12

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問