⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 demo.m

📁 MatLab图像传感器网络仿真平台WiSNAP
💻 M
字号:
function demo(config);
%Wirless Image Sensor Networks Demo Application.
%   DEMO(CONFIG);
%
%   Input Parameters:
%   ================
%
%      config ------------> Network configuration (positive integer):
%                           1 - Agilent ADCM-1670 camera module on serial port.
%                           2 - Agilent ADNS-3060 mouse sensor on parallel port.
%                           3 - Chipcon CC2420DB wireless mote on serial port,
%                               Agilent ADCM-1670 camera module on serial port, and one
%                               stand-alone Chipcon CC2420DB wireless mote.
%
%   Output Parameters:
%   =================
%
%      NONE.
%
%   See also IMAGE_SENSOR_API, WIRELESS_MOTE_API.
%
%   Instructions:
%   ============
%
%   Press ESC to exit the application.

% Stephan Hengstler
% Stanford Wireless Sensor Networks Lab
% January 11, 2005
%
% Last modified: 03-03-2005

clc, % warning off

%******************* Wireless Image Sensor Networks Demo Application **********************

% parse input arguments (currently not used)
if (exist('arguments') == 1)
   switch arguments(1:2)
   	case '-d'
   		debug 	= 1;
   end
end

%--- Section: System Parameters -----------------------------------------------------------

% choose network configuration
switch (config)
   case 1
      SENSOR					= 'ADCM-1670';		% image sensor device
      SPORT						= 'COM2';			% image sensor port
      Th          			= 256;				% pixel threshold
   case 2
      SENSOR					= 'ADNS-3060';		% image sensor device
      SPORT						= '0378';			% image sensor port
      Th          			= 16;					% pixel threshold
   case 3
      MOTE						= 'CC2420DB';		% wirless mote device
      MPORT						= 'COM1';			% wireless mote port
		PhyInfo.Channel		= 26;					% PHY Layer: ISM channel.
		PhyInfo.Address		= hex2dec('0000');% PHY Layer: Node address.
		PhyInfo.PanId			= hex2dec('2420');% PHY Layer: Personal Area Network (PAN) ID.
      psi         			= 55*pi/180;      % field of view
      SENSOR					= 'ADCM-1670';		% image sensor device
      SPORT						= 'COM2';			% image sensor port
		TxMacPckt.destPanId	= hex2dec('2420');% MAC Layer: Destination PAN ID.
		TxMacPckt.destAddr	= hex2dec('0815');% MAC Layer: Destination node address.
		TxMacPckt.ackRequest	= 1;					% MAC Layer: Acknowledge request.
   otherwise
      disp('ERROR: Invalid network configuration.')
      disp('Type "help main" for more information.')
      return;
end

%--- Section: Application Main ------------------------------------------------------------

% initialize figure (optimal for 1024x768 screen resolution)
figure(1), clf, set(gcf,'Position',[1 29 1024 672])
colormap gray;
release		= version;
if (hex2dec(release(1)) > 5)
   set(gcf,'currentcharacter',' ')
end

%--- Example: Image Sensor - Target Detection ---------------------------------------------

if ((config == 1) | (config == 2))
   
   % open communications session
   shandle		= image_sensor_api(SENSOR,'open',SPORT);
   
   % check for error
   if ~(shandle > 0)
      error('ERROR: Open communications session failed.')
   end
   
   % initialize image sensor
   status		= image_sensor_api(SENSOR,'init',shandle);
   
   % check for error
   if (status < 0)
      status		= image_sensor_api(SENSOR,'close',shandle);
      error('ERROR: Initialize image sensor failed.')
   end
   
   % initialize frame counter
   frame       = 1;
   
   % initialize memory ping-pong
   pong        = 0;
   
   % repeat until break
   while(1)
      
      % capture current frame
      imager		= image_sensor_api(SENSOR,'frame',shandle);
      
      % check for error (this will not work yet; it is just a place holder at this point)
      if (isempty(imager))
         status		= image_sensor_api(SENSOR,'close',shandle);
         error('ERROR: Capture current frame failed.')
      end
      
      % RGB frame?
      if (size(imager,3) == 3)
         
         % rotate image array
         for i = 1:3
            imager(:,:,i)= rot90(imager(:,:,i));
         end
         
      end
      
      % display image array
      figure(1)
      subplot(2,2,1)
      if (size(imager,3) == 1)
         status      = pcolor(imager);
         shading flat
      else
         status      = image(uint8(imager));
         axis equal
      end
      axis([1 size(imager,1) 1 size(imager,2)])
      title(['\bf',SENSOR,' Image Sensor: Frame = ',int2str(frame)])
      xlabel('\bf--- PRESS ESC TO EXIT ---')
      
      % RGB frame?
      if (size(imager,3) == 3)
         
         % convert to gray scale image
         imager      = sum(imager,3);
         
      end
      
      % store image array in correlation memory
      cmem(:,:,pong+1)  = imager;
      
      % perform target detection function
      if (frame > 1)
         
         % compute difference image
         cmem_dif       = abs(cmem(:,:,not(pong)+1)-cmem(:,:,pong+1));
         
         % determine number of pixels above threshold
         N_E(frame)     = sum(sum(cmem_dif > Th));
         
         % display number of pixels
         subplot(2,2,2)
         plot([0:frame-1],N_E,'bx-')
         grid on
         title(['\bfTarget Detection Using Pixel Differences'])
         xlabel('\bfFrame Number')
         ylabel('\bfNumber of Pixels N_E')
         
      end
      
      % increment frame counter
      frame       = frame + 1;
      
      % allow display to update
      pause(1e-3)
      
      % ping-pong correlation memories
      pong        = not(pong);
      
      % check user input
      key         = double(get(gcf,'currentcharacter'));
      
      % exit loop?
      if (~isempty(key) & (key == 27))
         break
      end
      
   end
   
   % close communications session
   status		= image_sensor_api(SENSOR,'close',shandle);
   
   % check for error
   if (status < 0)
      error('ERROR: Close communications session failed.')
   end
   
%--- Example: Wireless Mote with Image Sensor - Network Localization ----------------------

elseif (config == 3)
   
   % open communications session
   mhandle		= wireless_mote_api(MOTE,'open',MPORT);
   
   % check for error
   if ~(mhandle > 0)
      error('ERROR: Open communications session failed.')
   end
   
   % open communications session
   shandle		= image_sensor_api(SENSOR,'open',SPORT);
   
   % check for error
   if ~(shandle > 0)
      error('ERROR: Open communications session failed.')
   end
   
   % initialize wirless mote
   status		= wireless_mote_api(MOTE,'init',mhandle,PhyInfo);
   
   % check for error
   if (status < 0)
      status		= image_sensor_api(SENSOR,'close',shandle);
      status		= wireless_mote_api(MOTE,'close',mhandle);
      error('ERROR: Initialize wireless mote failed.')
   end
   
   % initialize image sensor
   status		= image_sensor_api(SENSOR,'init',shandle);
   
   % check for error
   if (status < 0)
      status		= wireless_mote_api(MOTE,'close',mhandle);
      status		= image_sensor_api(SENSOR,'close',shandle);
      error('ERROR: Initialize image sensor failed.')
   end
   
   % initialize frame counter
   frame       = 1;
   
   % initialize memory ping-pong
   pong        = 0;
   
   % repeat until break
   while(1)
      
      % capture current frame
      imager		= image_sensor_api(SENSOR,'frame',shandle);
      
      % check for error (this will not work yet; it is just a place holder at this point)
      if (isempty(imager))
      	status		= wireless_mote_api(MOTE,'close',mhandle);
         status		= image_sensor_api(SENSOR,'close',shandle);
         error('ERROR: Capture current frame failed.')
      end
      
	   % remotely toggle neighboring node's location led
	   TxMacPckt.pPayload	= sprintf('t\n');
	   TxMacPckt.length	= length(TxMacPckt.pPayload);
      timeout		= 0;
	   while (timeout < 5)
         
         % send transmit packet
         status				= wireless_mote_api(MOTE,'send',mhandle,TxMacPckt);
      
	   	% check for received packet
      	RxMacPckt	= wireless_mote_api(MOTE,'recv',mhandle);
         if (isstruct(RxMacPckt))
            break;
         end
         
      	% increment timeout counter
			timeout		= timeout + 1;
      
	   end
      
      % determine received signal strength indicator
      if (isstruct(RxMacPckt))
         rssi(frame)    = RxMacPckt.rssi;
      else
         rssi(frame)    = -128;
      end
      
      % determine neighboring node's distance
      distance(frame)= 3e3*(1/(rssi(frame)+128)^2);
      
      % RGB frame?
      if (size(imager,3) == 3)
         
         % rotate image array
         for i = 1:3
            imager(:,:,i)= rot90(imager(:,:,i),2);
         end
         
      end
      
      % display image array
      figure(1)
      subplot(2,2,1)
      if (size(imager,3) == 1)
         status      = pcolor(imager);
         shading flat
      else
         status      = image(uint8(imager));
         axis equal
      end
      axis([1 size(imager,1) 1 size(imager,2)])
      title(['\bf',SENSOR,' Image Sensor: Frame = ',int2str(frame)])
      xlabel('\bf--- PRESS ESC TO EXIT ---')
      
      % RGB frame?
      if (size(imager,3) == 3)
         
         % use green color layer only
         imager      = imager(:,:,2);
         
      end
      
      % store image array in correlation memory
      cmem(:,:,pong+1)  = flipud(imager);
      
      % perform node localization function
      if (frame > 1)
         
         % compute difference image
         cmem_dif    = abs(cmem(:,:,not(pong)+1)-cmem(:,:,pong+1));
         
         % determine neighboring node's led position
         threshold   = max(mean(mean(cmem_dif))+(std(std(cmem_dif))),0.5*max(max(cmem_dif)));
         [x,y]       = find(cmem_dif > threshold);
         if ((~isempty(x)) & (~isempty(y)))
            d_i(frame)  = mean(y) + j*mean(x);
         else
            d_i(frame)  = -1 - j;
         end
         
         % compute neighboring node's estimated angular orientation
         D           = size(imager,1);
         phi_i(frame)= -atan(2*(real(d_i(frame))-D/2)/D*tan(psi/2));
         
         % display difference image
         subplot(2,2,3)
         status      = pcolor(cmem_dif);
         shading flat
         axis equal
         axis([1 size(imager,1) 1 size(imager,2)])
         title(['\bf',SENSOR,' Difference Image'])
         
         % display received signal strength and estimated angular orientation
         subplot(2,2,2)
         plot([0:frame-1],rssi,'b-',[0:frame-1],phi_i*180/pi,'r-')
         axis([0 frame-1 -psi/2*180/pi +psi/2*180/pi]), grid on
         title(['\bfReceived Signal Strength and Estimated Angular Orientation'])
         xlabel('\bfFrame Number')
         ylabel('\bfSignal Strength/Angular Orientation')
         
         % display network localization
         subplot(2,2,4)
         plot(0,0,'ko',0,0,'kx',[0 0],[0 0.1],'k-',0,0.1,'k^'), hold on
         circle      = distance(frame)*exp(j*2*pi*[0:0.01:1+0.1]);
         if ((real(d_i(frame)) > 0) & (imag(d_i(frame)) > 0))
            plot(real(circle),imag(circle),'r--')
            secant      = sqrt(2)*[0:1]*exp(j*(phi_i(frame)+pi/2));
            plot(real(secant),imag(secant),'r--')
            location    = distance(frame)*exp(j*(phi_i(frame)+pi/2));
            plot(real(location),imag(location),'bo',real(location),imag(location),'bx')
         else
            plot(real(circle),imag(circle),'b-')
         end
         hold off
         axis([-1 +1 -1 +1]), grid on
         title(['\bfNetwork Localization'])
         xlabel('\bfHorizontal Axis [unit length]')
         ylabel('\bfVertical Axis [unit length]')
         
      end
      
      % increment frame counter
      frame       = frame + 1;
      
      % allow display to update
      pause(1e-3)
      
      % ping-pong correlation memories
      pong        = not(pong);
      
      % check user input
      key         = double(get(gcf,'currentcharacter'));
      
      % exit loop?
      if (~isempty(key) & (key == 27))
         break
      end
      
   end
   
   % close communications session
   status		= image_sensor_api(SENSOR,'close',shandle);
   
   % check for error
   if (status < 0)
      status		= wireless_mote_api(MOTE,'close',mhandle);
      error('ERROR: Close communications session failed.')
   end
   
   % close communications session
   status		= wireless_mote_api(MOTE,'close',mhandle);
   
   % check for error
   if (status < 0)
      error('ERROR: Close communications session failed.')
   end
   
end

% close figure
close(gcf)

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -