上位机通过usb采集保存电流互感器原始ADC数据
authorkyz <kyz@kyz.pub>
Tue, 27 Feb 2024 07:32:36 +0000 (15:32 +0800)
committerkyz <kyz@kyz.pub>
Tue, 27 Feb 2024 07:32:36 +0000 (15:32 +0800)
tools/welding_curr_disp.py [new file with mode: 0644]
user/user_adc.c
user/user_app.c
user/user_debug.c
user/user_ui.c

diff --git a/tools/welding_curr_disp.py b/tools/welding_curr_disp.py
new file mode 100644 (file)
index 0000000..c29c6b7
--- /dev/null
@@ -0,0 +1,372 @@
+from collections import deque
+from re import L
+import socket
+import sys
+import os
+import ser
+import math
+
+import numpy as np
+import pyqtgraph as pg
+
+from PyQt5.QtCore import *
+from PyQt5.QtGui import *
+from PyQt5.QtWidgets import *
+
+import json
+#import serial
+#import serial.tools
+#import serial.tools.list_ports
+#import serial.serialutil
+#import modbus_tk
+
+import ui_welding
+import time
+
+import crcmod
+import struct
+import intelhex
+
+#生成CRC16-MODBUS校验码
+#crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
+from collections import deque
+
+class App( QDialog, ui_welding.Ui_Dialog ):
+    trigger_rx_pkt = pyqtSignal( bytes )
+    def __init__( self ):
+        super().__init__()
+        self.setupUi(self)
+        self.setWindowTitle( u"焊接电流采集工具 V0.1")
+
+        self.trigger_rx_pkt.connect( self.on_rx_pkt )
+
+        self.connected = False
+        self.btn_connect.setStyleSheet("background-color: lightgray");
+
+        self.btn_connect.released.connect( lambda :self.on_btn_connect() )
+
+        self.io_timer = QTimer()
+        self.io_timer.timeout.connect(self.on_scan_timer)
+        self.io_timer.start(2000)
+        self.crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
+        self.comports = []
+        self.scan_port()
+        self.lineEdit_baud.setText( "9600" )
+        self.connected = False
+        self.ser = ser.ser()
+        self.rx_buf = b''
+        self.generate_image()
+
+        self.btn_current.released.connect( self.on_btn_current )
+
+    def on_btn_current( self ):
+        curr = int( self.lineEdit_current.text() )
+        cmd_str = "I:%d"%( curr*1000 )
+        self.ser.write( cmd_str.encode( "utf-8" )  )           
+
+    def generate_image(self):
+        verticalLayout = QVBoxLayout(self.frame)
+        win = pg.GraphicsLayoutWidget(self.frame)
+        verticalLayout.addWidget(win)
+        p = win.addPlot(title="动态波形图")
+        p.showGrid(x=True,y=True)
+        p.setLabel(axis="left",text="电流 A")
+        p.setLabel(axis="bottom",text="时间 s")
+        p.setTitle(u"焊接电流采集")
+        p.addLegend()
+        #self.curve1 = p.plot(pen="r",name="焊接电流")
+        self.curve11 = p.plot(pen="r",name="焊接电流原始值")
+        self.curve12 = p.plot(pen="green",name="焊接电流平均值")
+        verticalLayout2 = QVBoxLayout(self.frame_2)
+        win2 = pg.GraphicsLayoutWidget(self.frame_2)
+        verticalLayout2.addWidget(win2)
+        p2 = win2.addPlot(title="动态波形图")
+        p2.showGrid(x=True,y=True)
+        p2.setLabel(axis="left",text="气体流量 L/min")
+        p2.setLabel(axis="bottom",text="时间 (s)")
+        p2.setTitle("1.目标流量  2.实际流量")
+        p2.addLegend()
+        self.curve21 = p2.plot(pen="r",name="1.目标流量")
+        self.curve22 = p2.plot(pen="g",name="2.实际流量")
+
+        self.Fs = 1024.0 #采样频率
+        self.N = 1024    #采样点数
+        self.f0 = 4.0    #信号频率
+        self.pha = 0     #初始相位
+        self.t = np.arange(self.N) / self.Fs    #时间向量 1*1024的矩阵
+        self.x_data =  []
+        self.y_data =  []
+        self.y_data_21 = []
+        self.y_data_22 = []
+
+    def on_rx_pkt( self, data ):
+        comments='''
+            item.id = index; //焊接开始第一条记录id为0,后面每条记录id加1
+            item.curr_x10 = g_dev.welding_current*10;
+            item.flow_speed_x10 = g_dev.flowmeter.flow_speed*10;
+            item.pressure_x10   = g_dev.pressure * 10;
+            item.save_factor    = g_dev.cfg.save_gas_factor;
+            item.target_flowspeed_x10 = g_dev.target_flowspeed;
+            item.valve_curr_ma  = g_dev.valve_curr_out*1000;
+            item.valve_temp_x10 = g_dev.valve_temperature*10;
+            item.whelding_method = g_dev.cfg.welding_method;
+typedef struct{
+    uint16_t id;
+    uint16_t curr_x10;
+    uint16_t target_flowspeed_x10;
+    uint16_t flow_speed_x10;
+    uint16_t pressure_x10;
+    uint8_t  valve_curr_ma;
+    uint8_t valve_temp_x10;
+    uint8_t whelding_method;
+    uint8_t save_factor;
+    uint16_t reserved;
+}record_item_t;
+        '''
+        if len( data ) == 1000:
+            self.x_data=range( 500 )
+            self.y_data_22 = []
+            self.y_data_11 = []
+            self.y_data_12 = []
+            curr_sum = 0
+            for i in range( 500 ):
+                raw = (data[i*2]<<0)|(data[i*2+1]<<8)
+                self.y_data_22.append( raw )
+                curr = (raw*2.5*6/0xffff - 2.5)*600/0.625 #(values[i]* VREF*6/0xffff - 2.5)/0.625*600;
+                curr_sum += abs( curr )
+                self.y_data_11.append( curr )
+            #save raw log
+            if not os.path.exists( 'raw_data/' ):
+                os.mkdir( 'raw_data' )
+            file_name = time.strftime( "raw_data/%Y%m%d_%H%M%S" )+'-%d'%self.log_idx
+            self.log_idx += 1
+            with open( file_name, 'wb' ) as fd:
+                fd.write( data )
+            self.y_data_12 = [curr_sum/500]*500
+            self.curve22.setData( np.array( self.x_data), np.array( self.y_data_22))
+            self.curve11.setData( np.array( self.x_data), np.array( self.y_data_11))
+            self.curve12.setData( np.array( self.x_data), np.array( self.y_data_12))
+
+            #self.y_data.append( curr_x10/10.0 )
+            #self.y_data.append( valve_curr_ma*1.0 )
+            #self.y_data_21.append( target_fs_x10/10.0)
+
+            return
+
+        #print( "parse pkt , data:", data.hex(), len(data) )
+        idx,curr_x10,target_fs_x10, fs_x10,  pr_x10, valve_curr_ma, tem_x10, method,factor,  res =struct.unpack("<HHHHHBBBBH", data)
+        #print( "unpack<",idx,curr_x10,fs_x10, pr_x10, factor, target_fs_x10, valve_curr_ma, tem_x10, method, ">" )
+
+        self.tableWidget_devinfo.item(0,0).setText( "%0.0f"%(idx/10.0) )
+        self.tableWidget_devinfo.item(1,0).setText( "%0.1f"%(curr_x10/10.0))
+        self.tableWidget_devinfo.item(2,0).setText( "%0.1f"%(target_fs_x10/10.0))
+        self.tableWidget_devinfo.item(3,0).setText( "%0.1f"%(fs_x10/10.0))
+        self.tableWidget_devinfo.item(4,0).setText( "")
+        self.tableWidget_devinfo.item(5,0).setText( "%0.1f"%(pr_x10/10.0))
+        self.tableWidget_devinfo.item(6,0).setText( "%0.0f"%(valve_curr_ma))
+        self.tableWidget_devinfo.item(7,0).setText( "%d"%(method))
+        self.tableWidget_devinfo.item(8,0).setText( "%d"%(factor))
+        self.tableWidget_devinfo.item(9,0).setText( "%0.1f"%(tem_x10/10.0))
+        if idx == 0:
+                return
+        elif idx == 1:
+                self.x_data=[]
+                self.y_data=[]
+                self.y_data_21=[]
+                self.y_data_22=[]
+        
+        if len( self.x_data)<1000:
+            self.x_data.append( idx/10.0)
+            #self.y_data.append( curr_x10/10.0 )
+            self.y_data.append( valve_curr_ma*1.0 )
+            self.y_data_21.append( target_fs_x10/10.0)
+            self.y_data_22.append( fs_x10/10.0)
+        else:
+            self.x_data = self.x_data[1:]+[ idx/2.0 ]
+            self.y_data = self.y_data[1:]+[ curr_x10/10.0]
+            self.y_data_21 = self.y_data_21[1:]+[ target_fs_x10/10.0]
+            self.y_data_22 = self.y_data_22[1:]+[ fs_x10/10.0]
+        self.pha += 10
+        self.curve1.setData( np.array( self.x_data), np.array( self.y_data))
+        self.curve21.setData( np.array( self.x_data), np.array( self.y_data_21))
+        self.curve22.setData( np.array( self.x_data), np.array( self.y_data_22))
+        #self.curve2.setData(self.t , np.cos(8 * np.pi  * self.t + self.pha * np.pi/180.0))
+
+    def on_serial_rx_cb( self, data ):
+        self.rx_buf += data
+        while len( self.rx_buf) and self.rx_buf[0] != 0xA5:
+            self.rx_buf = self.rx_buf[1:]
+        if len(self.rx_buf) >= 18 and self.rx_buf[1] == 0x10:
+                    #found pkt
+                    pkt_data = self.rx_buf[2:18]
+                    #print( "rx one pkt:", pkt_data.hex() )
+                    #self.parse_pkt( pkt_data )
+                    self.trigger_rx_pkt.emit( pkt_data )
+                    self.rx_buf = self.rx_buf[18:]
+        elif len(self.rx_buf) >= 1024  and self.rx_buf[1] == 0x5A:
+                    print(  "rx data: 1024 Bytes", self.rx_buf[:1024].hex() )
+                    #found pkt
+                    pkt_data = self.rx_buf[4:1004]
+                    #print( "rx one pkt:", pkt_data.hex() )
+                    #self.parse_pkt( pkt_data )
+                    self.trigger_rx_pkt.emit( pkt_data )
+                    self.rx_buf = self.rx_buf[1024:]
+                    self.rx_buf = self.rx_buf[512:]
+        elif len(self.rx_buf) >= 2 and self.rx_buf[1] != 0x5A and self.rx_buf[1] != 0x10:
+            self.rx_buf = []
+
+    def on_connect( self ):
+        self.port = self.cb_serial.currentText()
+        self.baud = self.lineEdit_baud.text()
+
+        #self.on_disconnect()
+        if( self.connected ):
+            self.on_disconnect()
+        else:
+            self.ser.open( port=self.port, baudrate=self.baud, rx_handler=self.on_serial_rx_cb )
+            if( self.ser.ser.is_open):
+                self.connected = True
+                self.btn_connect.setStyleSheet("background-color: green")
+                self.x_data =  []
+                self.y_data =  []
+                self.y_data_21 = []
+                self.y_data_22 = []
+
+                self.ser.write( "REPORT_RAW_CURRENT".encode( "utf-8" )  )   
+                self.log_idx = 0
+            else:
+                print( "open serial fail" )
+
+    def on_disconnect( self ):
+        #self.btn_connect.setText( "connect" )
+        self.ser.close()
+        self.connected = False
+        self.btn_connect.setStyleSheet("background-color: lightgray");
+
+    def on_btn_connect( self ):
+        if self.connected in [ "modbus", "private" ]:
+            self.on_disconnect()
+        else:
+            self.on_connect()
+
+    def log_add( self, log_data ):
+        self.txt_log.append(   log_data  )
+
+    def scan_port( self ):
+        comports=ser.scan()
+        if not self.comports == comports:
+            s = self.cb_serial.currentText()
+            self.cb_serial.clear()
+
+            for com in comports:
+                self.cb_serial.addItem( com )
+            if s in comports:
+                self.cb_serial.setEditText(s)
+            self.comports = comports
+
+    def parse_hex( self, path ):
+        try:
+            #print( "file,check", file, check )
+            self.lineEdit_path.setText( path )
+            ih = intelhex.IntelHex( path )
+            self.lineEdit_image_addr.setText( '%08X'%( ih.minaddr() ) )
+        except:
+            self.on_log( ( u"读取hex文件错误", "error") )
+            self.lineEdit_image_addr.setText( "" )
+            print( "select file error!" )
+            return False
+        return True
+
+    def parse_sensor_data( self, data ):
+        if len(data)!=10:
+            return
+        unit_table={ 0:"ppm", 2:"%LEL", 4:"%VOL", 6:"mg/m3", 8:"ppb"}
+        point_table = { 0:0, 4:1, 8:2, 12:3 }
+        st_table = ["0x00 预热","0x01 正常","0x02 数据错误","0x03 传感器故障",
+                    "0x04 预警","0x05 低报","0x06 高报","0x07 访问故障",
+                    "0x08 超量程","0x09 需要标定","0x0A 超时","0x0B stel报警",
+                    "0x0C twa报警","0x0D 保留","0x0E 保留","0x0F 通信故障" ]
+        unit_str = unit_table[ data[0]>>12 ]
+        point_x = point_table[ (data[0]>>8)&0x0F]
+        conc = (((data[0]>>6)&3)<<16) | data[1]
+        alarm_l =  (((data[0]>>4)&3)<<16) | data[2]
+        alarm_h =  (((data[0]>>2)&3)<<16) | data[3]
+        range_n =  (((data[0]>>0)&3)<<16) | data[4]
+        temperature = data[7]
+        st = st_table[data[5]]
+        return u"浓度 %.2f %s, 量程:%d, 温度:%d, 低报:%.2f, 高报:%.2f, 状态:%s"%( 
+                conc/(10**point_x),
+                unit_str,
+                range_n, #range_n/(10**point_x),
+                temperature,
+                alarm_l/(10**point_x),
+                alarm_h/(10**point_x),
+                st  )
+
+    def on_scan_timer( self ):
+        if self.connected == "modbus":
+            for sensor in [ 0, 1, 2, 3, 4 ]:
+                v = mb.read_regs( sensor*256+0, 10, self.mb )
+                if v:
+                    s = ''
+                    for d in v:
+                        s += '%04X '%(d)
+                    #print( "reg value:", v )
+                    self.tableWidget_snsorinfo.item(sensor,0).setText( gas_name(v[8]>>8))
+                    sensor_data_str = self.parse_sensor_data( v )
+                    self.tableWidget_snsorinfo.item(sensor,1).setText( sensor_data_str )
+        elif self.connected == "private":
+            for sensor in [0, 1, 2, 3, 4]:
+                resp_v = self.tx_cmd( sensor, 0x86 )
+        else:
+            self.scan_port()
+    def tx_cmd( self, sensor, cmd, span=0 ):
+        span_decimal, span_int = math.modf( span )
+        span_int = int( span_int )
+        span_decimal = round( span_decimal*100)
+        print( "span %d.%02d"%(span_int, span_decimal ) )
+        tx_pkt =[0]*9
+        tx_pkt[0] = 0xff
+        tx_pkt[1] = sensor
+        tx_pkt[2] = cmd
+        tx_pkt[3] = (span_int>>8)&0xff
+        tx_pkt[4] = span_int&0xff
+        tx_pkt[7] = span_decimal&0xff
+        sum = tx_pkt[1]+tx_pkt[2]+tx_pkt[3]+tx_pkt[4]+tx_pkt[5]+tx_pkt[6]+tx_pkt[7]
+        tx_pkt[8] = (0x100-sum)&0xff
+        tx_data = bytes( tx_pkt )
+
+        s = ser.ser()
+        s.open( port = self.port, baudrate = self.baud )
+        print( "-------tx data:", tx_data.hex() )
+        s.write( tx_data )
+        time.sleep(0.5)
+        rd_data = s.read()
+        if len( rd_data )==9 and rd_data[0] == 0xff and rd_data[1]==0x86:
+            print( "ser read:", bytes(rd_data).hex() )
+            self.lineEdit_concentration[sensor].setText( "%d"%((rd_data[2]<<8)|rd_data[3]))
+        elif len( rd_data )==9 and rd_data[0] == 0xff and rd_data[1]==0x87:
+            print( "ser read 87:", bytes(rd_data).hex() )
+        elif len( rd_data )==9 and rd_data[0] == 0xff and rd_data[1]==0x88:
+            print( "ser read 88:", bytes(rd_data).hex() )
+        s.close()
+
+    def on_log( self, log_evt ):
+        str, tag = log_evt
+        print( "LOG:", str )
+        if tag == 'error':
+            log_str = '<font color="#FF0000">' + str + '</font>'
+        elif tag == 'warning':
+            log_str = '<font color="orange">' + str + '</font>'
+        elif tag == 'green':
+            log_str = '<font color="green">' + str + '</font>'
+        elif tag == 'info':
+            log_str = '<font color="#000000">' + str + '</font>'
+        else:
+            log_str = '<font color="#000000">' + str + '</font>'
+        self.txt_log.append( log_str )
+
+if __name__ == "__main__":
+    app = QApplication(sys.argv)  # 创建一个QApplication,也就是你要开发的软件app
+    App().show()
+    sys.exit(app.exec_())          # 使用exit()或者点击关闭按钮退出QApplication
index 6faa948a00ed02034dea2b63675b62ef953b0fdc..ef44976c45567318f795d28dc1eadfde77a30342 100644 (file)
@@ -73,7 +73,7 @@ float calc_welding_current( uint16_t *values, uint16_t len )
         }
     }
 
-    if( m_nr > 5 && p_nr > 5 ){
+    if( m_nr > 5 && p_nr > 5 && m_nr > z_nr && p_nr > z_nr ){
         //交流, 采集500次,其中有5次以上正和5次以上负电流,判断为交流电
         float s = 0;
         for( int i=0; i<len; i++ ){
@@ -109,7 +109,15 @@ float calc_welding_current( uint16_t *values, uint16_t len )
         }else{
             //直流,取平均值输出,或有效值输出
             //welding_curr = sqrt( (s_l+s_h)/len );
-            welding_curr = average;
+
+
+            if( p_nr > m_nr )
+                welding_curr = average;
+            else
+                welding_curr = -average;  //加一个负号,用于提醒用户当前电流互感器反接
+            
+            //未接负载,实测电流有-2A左右,暂未实现校准功能,这里直接补偿一下
+            welding_curr += 2.0f; 
         }
     }
     return welding_curr;
@@ -202,7 +210,16 @@ void user_adc_task( void* unused )
                 voltage = raw*VREF/0xffff;  //16bit adc2
                 g_dev.welding_current_raw = raw;
             }
+         {   
+            extern uint32_t dbg_report_raw_current;
+            extern uint8_t CDC_Transmit_HS(uint8_t* Buf, uint16_t Len);
 
+            static  uint8_t dbg_curr_raw[1024] = {0xA5, 0x5A, 0x00, 0x04, };
+            if( dbg_report_raw_current ){
+                memcpy( &dbg_curr_raw[4], adc_raw_copy[1], 1000 );
+                CDC_Transmit_HS( (uint8_t*)dbg_curr_raw, 1024 );
+            }
+        }
             //计算公式:2.5V±0.625V 0V基准
             //正向:2.5+(I/Ipn)*0.625
             //反向:2.5-(I/Ipn)*0.625
index e94de18d8444eca23f99145aab6b280a5bec0377..7d553d7d2856d2f0c614a250a3d7e39b43abc211 100644 (file)
@@ -262,6 +262,8 @@ void welding_record_init( void )
     g_dev.welding_record_number = record_number;
 }
 
+extern uint32_t dbg_report_raw_current;
+
 void welding_data_store( uint32_t index )
 {
     record_item_t item;
@@ -296,7 +298,7 @@ void welding_data_store( uint32_t index )
         }
     }
 
-    {
+    if( !dbg_report_raw_current ){
         //debug 同步发送信息到USB CDC//
         uint8_t buf[ 2+sizeof( record_item_t )];
         buf[0] = 0xA5;
index b4a5a8eccc856429d8f8f284b028666e3c4404f7..72c8fc8beab58812e28442a5eaa6fdd5ae29705e 100644 (file)
@@ -1,6 +1,10 @@
 #include "user.h"
 #include <stdarg.h>
 
+
+float dbg_current = 1000.0f;   //模拟电流数据,用于调试比例阀控制算法
+uint32_t dbg_report_raw_current = 0; //采集上报原始AD值,用于获取交流脉冲等原始数据,调试不同电流算法。
+
 uint8_t CDC_Transmit_HS(uint8_t* Buf, uint16_t Len);
 
 int32_t fputc( int32_t data, FILE *fd )
@@ -17,7 +21,7 @@ void  debug_printf(char* str , ...)
        va_start(aptr, str);
        if ( vsnprintf(dbg_buffer,sizeof(dbg_buffer)-1, str, aptr) > 0)
        {
-        CDC_Transmit_HS( (uint8_t*)dbg_buffer, strlen( dbg_buffer) );
+        ///CDC_Transmit_HS( (uint8_t*)dbg_buffer, strlen( dbg_buffer) );
         HAL_UART_Transmit( &huart2, (uint8_t*)dbg_buffer, strlen( dbg_buffer), strlen( dbg_buffer)*10  );
        }
        va_end(aptr);
@@ -67,7 +71,6 @@ void lcd_uart_rx_cb( void )
     lcd_uart_rx_start();
 #endif
 
-float dbg_current = 1000.0f;
 
 int32_t dbg_current_read( float * curr )
 {
@@ -141,7 +144,8 @@ void user_debug_task( void * unused )
              if((ptr=strstr( (char*)cdc_rx_buf, "I:" ))&& sscanf( ptr, "I:%d\n", &ma )==1){
                          dbg_current = ma/1000.0f;
                         DBG_PRINTF( "I Set:  %0.3fA\n", dbg_current );
-             }else if((ptr=strstr( (char*)cdc_rx_buf, "log_read" )) ){
+             }else if((ptr=strstr( (char*)cdc_rx_buf, "REPORT_RAW_CURRENT" )) ){
+                 dbg_report_raw_current = 1;
                  //printf( "log number:%d\n", g_dev.welding_record_number );
              }else if((ptr=strstr( (char*)cdc_rx_buf, "log_clear" )) ){
                  //printf( "log clear:%d\n", g_dev.welding_record_number );
index f1647cf301669d0602c04a28e9ab99814a5b3280..be8bae5b0932720b2b2945f309ff81f14d229f25 100644 (file)
@@ -217,7 +217,7 @@ void user_ui_task( void* unused )
         }else{
             //500毫秒刷新 ui
             int16_t curr_x10 = g_dev.welding_current*10;
-            if( curr_x10 < 30 && curr_x10 > -30 ){
+            if( curr_x10 < 45 && curr_x10 > -45 ){ //改为按+-4.5A内显示0
                 //传感器采样,未接负载显示 -0.5 到 -2 左右波动,
                 //+3A 到 -3A在屏上暂时按 0A显示 避免影响用户体验
                 curr_x10 = 0;