目的
c#初学者です.
現在,C#を用いてセンサ値を400Hzで取得するプログラムを作成しています.
現在は,マイコン側から9bytesのデータをシリアルを通じてc#側で取得するようなプログラムを作成しています.
現在
9bytesの内,はじめの1byteは0xFFを送り,c#側では読み込んだ初めの1byteが0xFFであれば,センサ値を配列に入れ替えるようなプログラムを組んでおります.
c#側では,button1が押された場合に,データの読み取りを行うようにして,別のボタンによってfragを入れ替えるようなプログラムを書いております.
また,マイコン側ではfloat型のデータをシリアルで送るために,共用体を用いてfloat型をint型として送信しています.
質問
質問は,c#側でのserial.Readのタイミングや方法を教えていただきたいです.
現在のプログラムでは,全く異なるデータが取得されてしまいます.
ただ,マイコン側がデータを正しく送信していることは別のプログラムで確認しましたので,特にc#について改善点を教えていただきたいです.
以下にコードを示します.
c#
1//一部抜粋です. 2public static class Condition 3 { 4 public static string[,] condition = new string[6, 2];// Modifiable 5 public static int clicked_num = 0; 6 public static int[] index_num = new int[6]; 7 public static bool frag = false; 8 9 } 10public static class Data_t 11 { 12 public static float[,] data = new float[50000, 2]; 13 } 14 15private void button1_Click(object sender, EventArgs e) 16 { 17 button3.Enabled = true; 18 button1.Enabled = false; 19 Condition.frag = true; 20 if (Condition.clicked_num < 6) 21 { 22 23 int count = 0; 24 while (Condition.frag) 25 { 26 //dataの読み取りと配列に値渡し 27 //System.Console.WriteLine("test_now1"); 28 byte[ ] buffer = new byte[9]; 29 //System.Console.WriteLine("test_now2"); 30 serialPort1.Read(buffer, 0, buffer.Length); 31 //System.Console.WriteLine("test_now3"); 32 if (buffer[0] == 0xff) 33 { 34 float tmp1 = BitConverter.ToSingle(buffer,0); 35 float tmp2 = BitConverter.ToSingle(buffer, 4); 36 //System.Console.WriteLine("get_value"); 37 Data_t.data[count, 0] = tmp1; 38 Data_t.data[count, 1] = tmp2; 39 System.Console.WriteLine(tmp1.ToString() + ","+tmp2.ToString()); 40 count++; 41 } 42 43 Application.DoEvents(); 44 } 45 } 46 else 47 { 48 label1.Text = "FINISH"; 49 button3.Enabled = false; 50 serialPort1.DiscardOutBuffer(); 51 serialPort1.DiscardInBuffer(); 52 serialPort1.Close(); 53 } 54 } 55 56 private void button3_Click(object sender, EventArgs e) 57 { 58 Condition.frag = false; 59 button1.Enabled = true; 60 button3.Enabled = false; 61 }
またマイコン側のプログラムは以下です.
arduino
1#include <Arduino.h> 2#include <rhio-LIS2HH12.h> 3#define ODR 200 4float x, y, z; 5float mx,mz; 6//https://gitlab.com/rhombio/rhio-libraries/rhio-LIS2HH12 7LIS2HH12 lis = LIS2HH12(); 8 9bool frag = false; 10 11union float2int{ 12 float value; 13 int i; 14}; 15 16void setup() { 17 // put your setup code here, to run once: 18 19 Serial.begin(115200); 20 Serial.println("LIS2HH12 example"); 21 lis.begin(); 22 lis.setBasicConfig(); 23 lis.setFrequency(80);//400Hz 24} 25 26void loop() { 27 unsigned long pre = micros(); 28 29 lis.getAccelmG(&x,&y,&z); 30 union float2int X; 31 union float2int Z; 32 X.value = x; 33 Z.value = z; 34 35 Serial.write(0xFF); 36 Serial.write(X.i>>24 |0x00); 37 Serial.write(X.i>>16 |0x00); 38 Serial.write(X.i>>8 | 0x00); 39 Serial.write(X.i&0xFF); 40 Serial.write(Z.i>>24|0x00); 41 Serial.write(Z.i>>16|0x00); 42 Serial.write(Z.i>>8|0x00); 43 Serial.write(Z.i&0xFF); 44 45 while(micros()-pre<2500); 46}
お手数ですがご確認お願いいたします。


回答3件
あなたの回答
tips
プレビュー