什么是串口编程中的回调函数?它是如何工作的? [英] What is actually callback function in serial port programming?How it works?

查看:938
本文介绍了什么是串口编程中的回调函数?它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function DUT_callback(obj, event, DUT_port)
persistent stored_data;

if isempty(stored_data)
    stored_data = [];
end

if ~strcmp(DUT_port.status,'open')
	return;
end

if ~DUT_port.BytesAvailable
	return;
end

try
	new_data = fread(DUT_port,DUT_port.BytesAvailable);
catch exception
	fprintf('ERROR: Failed to read from DUT port.  Shutting down.\n');
	cleanup();
	return;
end
data_array = [stored_data;new_data];

packet.NewPacket = 1;
while packet.NewPacket == 1
	[packet,data_array] = parse_serial_data(data_array);
	% Report bad checksum if appropriate
	if packet.BadChecksum
	end
	
	% If packet was received, do stuff with it
	if packet.NewPacket == 1
		% HANDLE RAW GYRO DATA PACKET
		if packet.Address == 86
			% Extract the gyro data
			gyro_x = typecast( flipud(uint8(packet.data(1:2))), 'int16' );
			gyro_y = typecast( flipud(uint8(packet.data(3:4))), 'int16' );
			gyro_z = typecast( flipud(uint8(packet.data(5:6))), 'int16' );

			got_gyro_data = 1;
% 			fprintf('%d\t%d\t%d\n',gyro_x,gyro_y,gyro_z);
		end 

		% HANDLE TEMPERATURE DATA PACKET
		if packet.Address == 118
			temperature = typecast( flipud(uint8(packet.data(1:4))), 'single' );
			got_temperature_data = 1;
% 			fprintf('%3.2f\n',temperature);
		end

		% If we received gyro and temperature data, log it to
		% the workspace if logging is enabled.
		if got_temperature_data && got_gyro_data
			got_temperature_data = 0;
			got_gyro_data = 0;

if GDATA.logging_data == 1 && GDATA.selected_DUT > 0
		if GDATA.DUT_samples_collected < GDATA.MAX_SAMPLES
		GDATA.DUT_samples_collected = GDATA.DUT_samples_collected + 1;
			GDATA.DUT_data(GDATA.DUT_samples_collected,:) = [single([GDATA.selected_DUT,gyro_x,gyro_y,gyro_z]),temperature];
				else
		fprintf('Maximum datapoints were collected.  Logging disabled.\n');
					GDATA.logging_data = 0;
	end	end	end	end      end

推荐答案

回调是用户提供的功能,但是他/她没有明确地调用。相反,只要有事情发生就会被调用。例如,在串口通信中,可以调用它来处理串行事件(例如数据到达)。
A callback is a function the user provides but he/she doesn't explicitely call. Instead it is called whenever something happens. For instance, in serial port communication, it could be called in order to handle a serial event (e.g. data arrival).


这是本手册中最为出色的解释。



http:// www。 mathworks.com.au/help/matlab/matlab_external/events-and-callbacks.html [ ^ ]



http://www.mathworks.com.au/help/matlab/serial-port-devices.html [ ^ ]
This is all most excellently explained in the manual.

http://www.mathworks.com.au/help/matlab/matlab_external/events-and-callbacks.html[^]

http://www.mathworks.com.au/help/matlab/serial-port-devices.html[^]


这篇关于什么是串口编程中的回调函数?它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆