之前用MATLAB 做了一个类似的曲线APP,这次尝试一下C#。由于刚入门,在实现过程中走了好一些弯路。
一开始打算用C#的Timer定时采集数据,但是波形失真很严重。
之后又尝试分线程,串口一个线程,将数据存入一个dataQueue中,更新曲线另一个线程,但最终在更新曲线的for 循环过程中,dataQueue进入了一个新的数据,或者还有些什么其他的原因,导致一直报错,最终还是没找到什么好的解决办法。人菜。。
程序测试效果见下。
串口的复杂设置懒得弄了,奇偶检验还有停止位那些一般都是默认设置。
其他的代码都很简单,注意跨线程时要用委托更新非线程创建的控件,不然报错。对于此网上很多资料。
C# 源码,仅供参考:
using System;
using System.Collections.Generic;
//using System.ComponentModel;
//using System.Data;
using System.Drawing;
//using System.Linq;
//using System.Text;
using System.Windows.Forms;
using System.Threading;
//using System.Threading.Tasks;
using System.Windows.Forms.DataVisualization.Charting;
using System.IO.Ports;
namespace ADC_test
{
public partial class Form1 : Form
{
Byte[] receivedData = new byte[2];
int i = 0;
int N = 50; //1s收到的数据点个数,源自MSP430设置
double data;
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
//测试代码运行时长,测试用
public delegate void TextHandler(Label label,string s);
public delegate void ChartHandler(Chart chart1, double data);
public Form1()
{
InitializeComponent();
InitChart();
}
private void button2_Click(object sender, EventArgs e)
{
if (serialport !=null && serialport.IsOpen)
{
timer1.Stop();
serialport.Write("N");
serialport.Close();
}
Application.Exit();
}
private void InitChart()
{
//定义图表区域
chart1.ChartAreas.Clear();
ChartArea chartArea1 = new ChartArea("C1");
chart1.ChartAreas.Add(chartArea1);
//定义存储和显示点的容器
chart1.Series.Clear();
Series series1 = new Series("Data");
series1.ChartArea = "C1";
chart1.Series.Add(series1);
//设置图表显示样式
chart1.ChartAreas[0].AxisY.Minimum = 0; //设置Y轴范围
chart1.ChartAreas[0].AxisY.Maximum = 3.5;
chart1.ChartAreas[0].AxisX.Minimum = 0;
chart1.ChartAreas[0].AxisX.Maximum = 3; //设置X轴范围
chart1.ChartAreas[0].AxisX.Interval = 0.5;
chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.Silver;
chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.Silver;
chart1.Series[0].BorderWidth = 3; //设置线宽
//设置标题
chart1.Titles.Clear();
chart1.Titles.Add("Voltage data");
chart1.Titles[0].Text = "ADC/DAC Test";
chart1.Titles[0].ForeColor = Color.RoyalBlue;
chart1.Titles[0].Font = new Font("Microsoft Sans Serif", 14F);
chart1.ChartAreas[0].AxisX.Title = "Time/s";
chart1.ChartAreas[0].AxisY.Title = "Voltage/V";
//设置图表显示样式
chart1.Series[0].Color = Color.BlueViolet;
chart1.Series[0].ChartType = SeriesChartType.Spline;
chart1.Series[0].Points.Clear();
}
private void button1_Click(object sender, EventArgs e)
{
ThreadStart childref1 = new ThreadStart(SerialPortFunction);
Thread childThread1 = new Thread(childref1);
chart1.ChartAreas[0].AxisX.Minimum = 0;
chart1.ChartAreas[0].AxisX.Maximum = 3;
chart1.Series[0].Points.Clear();
try
{
serialport = new SerialPort(this.comboBox1.Text, Convert.ToInt32(this.comboBox2.Text));
serialport.Open();
serialport.Write("N");
serialport.Write("Y");
label4.ForeColor = Color.Red;
label4.Text = "Running";
}
catch(Exception ex)
{
MessageBox.Show("Can't open the serial port!\n"+ex.Message,"Error");
return;
}
childThread1.Start();
}
public void SerialPortFunction()
{
while (i < N * 10) //测试10秒波形
{
serialport.DiscardInBuffer();
serialport.Write("Y");
while (serialport.BytesToRead < 2) //MSP430分两次发送一个数据
{
};
serialport.Read(receivedData, 0, 2);
Console.WriteLine(string.Join(" ", receivedData));//观察数据
data = (receivedData[0] * 256 + receivedData[1]) * 3.3 / 1024; //计算电压实际值
i++;
chart1.Invoke(new ChartHandler(DrawChart), chart1, data); //更新曲线
label6.Invoke(new TextHandler(ChangeText), label6,data.ToString() + "V"); //更新电压值
}
serialport.Write("N"); //关闭ADC
serialport.Close();
i = 0;
label4.ForeColor = Color.Lime;
label4.Invoke(new TextHandler(ChangeText), label4, "Ready");
MessageBox.Show("Show completed","Message");
}
public void ChangeText(Label label,string s)
{
label.Text = s;
}
public void DrawChart(Chart chart1, double data)
{
chart1.Series[0].Points.AddXY(0.02*i,data);
if (i >= N * 3 && i % N == 0) //更新坐标轴范围
{
chart1.ChartAreas[0].AxisX.Minimum = i / N - 2;
chart1.ChartAreas[0].AxisX.Maximum = i / N + 1;
}
}
}
}
曲线图参考:
另外关于ADC的设置,其采样为每秒等间隔采样50个数据点。
即SMCLK=1MHz,TimerA的CCR0=20000(1M/20000=50),其output用于供ADC采样使用。
其余设置: ADC的UART收到字符Y后开始工作,收到其他字符后停止工作。
DCOCTL = CALDCO_1MHZ; BCSCTL1 = CALBC1_1MHZ;
void TIMERA_Init()
{
TA0CTL= TASSEL_2+MC_1+TACLR;
TA0CCTL1=OUTMOD_3;
CCR0=20000; // T=1/50 s
CCR1=5000; // Set the duty. Can be any value in this project
}
void UART_send(unsigned short data)
{
unsigned short temp1=0,temp2=0;
temp1 = data>>8;
temp2= data-temp1*0x100;
UCA0TXBUF=temp1;
while(UCA0STAT&UCBUSY);
UCA0TXBUF=temp2;
while(UCA0STAT&UCBUSY);
}
void ADC10_Init()
{
ADC10CTL0 &= ~ENC;
ADC10CTL0 = ADC10SHT_1 + ADC10ON +ADC10IE; //SMCLK
ADC10CTL1= CONSEQ_2+ INCH_3 +SHS_1; //TimerA 0_1 output
ADC10AE0 |= BIT3; //Set P1.3 as ADC10 input
// ADC10CTL0 |= ENC+ADC10SC;
_bis_SR_register(CPUOFF+GIE); // MUST NOT PUT IT IN TIMERA_Init()
}
//
#pragma vector=ADC10_VECTOR
__interrupt void ADC10_ISR_HOOK(void)
{
UART_send(ADC10MEM);
__bic_SR_register_on_exit(CPUOFF);
}
#pragma vector=USCIAB0RX_VECTOR
__interrupt void USCI0RX_ISR(void)
{
s=UCA0RXBUF;
if(s=='Y')
{
GPIO_Working(); //绿灯亮
ADC10CTL0 |= ENC+ADC10SC;
}
else
{
GPIO_Reset(); //红灯亮
ADC10CTL0 &= ~ENC;
}
}
2022/4/23更新:
新增STM32部分,实现同样功能。
STM32型号:STM32F103ZET6;
使用资源:
USART1,ADC1,TIM3;
如上图,TIM3挂在APB1总线上,APB1时钟为8MHz
利用TIM3控制ADC采样,如前所述,每秒采样50个点,故实际上应该分频为50Hz
进而确定一些设定的系数。
这里8MHz/8/20000=50Hz;
ADC设置:
USART波特率9600,同样是在在ADC中断中发送数据。
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2022 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
float ADC_ConvertedValueLocal;
uint32_t ADC_ConvertedValue;
uint8_t temp[2];
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_ADC1_Init();
MX_USART1_UART_Init();
MX_TIM3_Init();
/* USER CODE BEGIN 2 */
HAL_ADC_Start_IT(&hadc1); //不要忘记打开ADC和定时器
HAL_TIM_Base_Start(&htim3);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
{
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV2;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/* USER CODE BEGIN 4 */
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc) //ADC中断
{
ADC_ConvertedValue = HAL_ADC_GetValue(hadc);
temp[0]=ADC_ConvertedValue/256;
temp[1]=ADC_ConvertedValue%256;
HAL_UART_Transmit(&huart1,temp,2,10);
}
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
注意到STM32的ADC为12位,所以C#代码中data的值应该除以2^12=4096得到。