code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_arith.all; use ieee.std_logic_unsigned.all; entity CRA is port( A : In std_logic_vector (7 downto 0); B : In std_logic_vector (7 downto 0); Cin : In std_logic; Cout : Out std_logic; Y : Out std_logic_vector (7 downto 0) ); end CRA; architecture RTL of CRA is begin process(A,B,Cin) variable tempC : std_logic_vector (8 downto 0); variable P : std_logic_vector (7 downto 0); variable G : std_logic_vector (7 downto 0); begin tempC(0):= Cin; for i in 0 to 7 loop P(i):= A(i) XOR B(i); G(i):= A(i) AND B(i); Y(i)<= P(i) xor tempC(i); tempC(i+1):=G(i) OR (tempC(i) AND P(i)); end loop; Cout<=tempC(8); end process; end RTL;
02207-work-groupdt07
trunk/Project/code/archive/CRA.vhd
VHDL
lgpl
1,065
library IEEE; use IEEE.std_logic_1164.all; entity reg_ld is GENERIC(n : integer); Port ( AS : In std_logic_vector (n downto 0); RESET : In std_logic; CLOCK : In std_logic; LOAD : In std_logic; ZS : Out std_logic_vector (n downto 0) ); end reg_ld; architecture BEHAVIORAL of reg_ld is begin process(reset,clock) begin if ( reset = '0' ) then ZS <= (others => '0'); elsif (( clock = '1' ) and (clock'EVENT)) then if ( load = '1' ) then ZS <= AS ; end if; end if; end process; end BEHAVIORAL; configuration CFG_reg_ld_BEHAVIORAL of gl_dualreg_ld is for BEHAVIORAL end for; end CFG_reg_ld_BEHAVIORAL;
02207-work-groupdt07
trunk/Project/code/archive/reg_ld.vhd
VHDL
lgpl
839
library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_arith.all; use ieee.std_logic_unsigned.all; entity chargue is port( clock: In std_logic; reset: In std_logic; loa: In std_logic; QF: Out std_logic_vector(71 downto 0) ); end chargue; architecture SCHEMATIC of chargue is signal AD: std_logic_vector(15 downto 0); signal re: std_logic; signal CLK: std_logic; signal RES: std_logic; signal D1 : std_logic_vector(7 downto 0); signal end1: std_logic; signal w : std_logic; signal WA : std_logic_vector(15 downto 0); signal QKau : std_logic_vector(71 downto 0); signal WD : std_logic_vector(7 downto 0); signal en_sh : std_logic; signal en : std_logic; component REG Port ( D : In std_logic_vector (7 downto 0); Reset : In std_logic; Clock : In std_logic; Q : Out std_logic_vector (7 downto 0) ); end component; component Memory Port ( Clock: in std_logic; Enable: in std_logic; Read: in std_logic; Write: in std_logic; Read_Addr: in std_logic_vector(15 downto 0); Write_Addr: in std_logic_vector(15 downto 0); Data_in: in std_logic_vector(7 downto 0); Data_out: out std_logic_vector(7 downto 0) ); end component; component FSM_in_3 port ( clock: in std_logic; reset: in std_logic; address: out std_logic_vector(15 downto 0); can_read: out std_logic ); end component; component SHIFTREG is Port ( CLOCK : In std_logic; RESET : In std_logic; ENABLE : In std_logic; QK : In std_logic_vector (7 downto 0); Q : InOut std_logic_vector (71 downto 0) ); end component; begin w<='0'; if (reset = '1') then end if; if (end1='1') then FSM_INIC1: FSM_in_3 Port Map(clock=>CLOCK,reset=>RESET, address=>AD(15 downto 0), can_read=>re); Mem_load1: Memory Port Map (clock=>CLOCK, enable=>en,read=>re,write=>w, Read_addr=>AD, Write_Addr=>WA,Data_in=>WD,Data_out=>D1); Reg_IN1: REG Port Map(D=>D1, Reset=>RESET,Clock=>CLOCK, Q=>QKau(7 downto 0)); FSM_INIC2: FSM_in_3 Port Map(clock=>CLOCK,reset=>RESET, address=>AD(15 downto 0), can_read=>re); Mem_load2: Memory Port Map (clock=>CLOCK, enable=>en,read=>re,write=>w, Read_addr=>AD, Write_Addr=>WA,Data_in=>WD,Data_out=>D1); Reg_IN2: REG Port Map(D=>D1, Reset=>RESET,Clock=>CLOCK, Q=>QKau(15 downto 8)); FSM_INIC3: FSM_in_3 Port Map(clock=>CLOCK,reset=>RESET, address=>AD(15 downto 0), can_read=>re); Mem_load3: Memory Port Map (clock=>CLOCK, enable=>en,read=>re,write=>w, Read_addr=>AD, Write_Addr=>WA,Data_in=>WD,Data_out=>D1); Reg_IN3: REG Port Map(D=>D1, Reset=>RESET,Clock=>CLOCK, Q=>QKau(23 downto 16)); FSM_INIC4: FSM_in_3 Port Map(clock=>CLOCK,reset=>RESET, address=>AD(15 downto 0), can_read=>re); Mem_load4: Memory Port Map (clock=>CLOCK, enable=>en,read=>re,write=>w, Read_addr=>AD, Write_Addr=>WA,Data_in=>WD,Data_out=>D1); Reg_IN4: REG Port Map(D=>D1, Reset=>RESET,Clock=>CLOCK, Q=>QKau(31 downto 24)); FSM_INIC5: FSM_in_3 Port Map(clock=>CLOCK,reset=>RESET, address=>AD(15 downto 0), can_read=>re); Mem_load5: Memory Port Map (clock=>CLOCK, enable=>en,read=>re,write=>w, Read_addr=>AD, Write_Addr=>WA,Data_in=>WD,Data_out=>D1); Reg_IN5: REG Port Map(D=>D1, Reset=>RESET,Clock=>CLOCK, Q=>QKau(39 downto 32)); FSM_INIC6: FSM_in_3 Port Map(clock=>CLOCK,reset=>RESET, address=>AD(15 downto 0), can_read=>re); Mem_load6: Memory Port Map (clock=>CLOCK, enable=>en,read=>re,write=>w, Read_addr=>AD, Write_Addr=>WA,Data_in=>WD,Data_out=>D1); Reg_IN6: REG Port Map(D=>D1, Reset=>RESET,Clock=>CLOCK, Q=>QKau(47 downto 40)); FSM_INIC7: FSM_in_3 Port Map(clock=>CLOCK,reset=>RESET, address=>AD(15 downto 0), can_read=>re); Mem_load7: Memory Port Map (clock=>CLOCK, enable=>en,read=>re,write=>w, Read_addr=>AD, Write_Addr=>WA,Data_in=>WD,Data_out=>D1); Reg_IN7: REG Port Map(D=>D1, Reset=>RESET,Clock=>CLOCK, Q=>QKau(55 downto 48)); FSM_INIC8: FSM_in_3 Port Map(clock=>CLOCK,reset=>RESET, address=>AD(15 downto 0), can_read=>re); Mem_load8: Memory Port Map (clock=>CLOCK, enable=>en,read=>re,write=>w, Read_addr=>AD, Write_Addr=>WA,Data_in=>WD,Data_out=>D1); Reg_IN8: REG Port Map(D=>D1, Reset=>RESET,Clock=>CLOCK, Q=>QKau(63 downto 56)); FSM_INIC9: FSM_in_3 Port Map(clock=>CLOCK,reset=>RESET, address=>AD(15 downto 0), can_read=>re); Mem_load9: Memory Port Map (clock=>CLOCK, enable=>en,read=>re,write=>w, Read_addr=>AD, Write_Addr=>WA,Data_in=>WD,Data_out=>D1); Reg_IN9: REG Port Map(D=>D1, Reset=>RESET,Clock=>CLOCK, Q=>QKau(71 downto 64)); if (algo q sapiga q es el final de la fila) then end1<='1'; end if; end1<= '0'; else FSM_INICS1: FSM_in_3 Port Map(clock=>CLOCK,reset=>RESET, address=>AD(15 downto 0), can_read=>re); Mem_loadS1: Memory Port Map (clock=>CLOCK, enable=>en,read=>re,write=>w, Read_addr=>AD, Write_Addr=>WA,Data_in=>WD,Data_out=>D1); SHIF1: SHIFTREG Port Map(CLOCK=>CLK,RESET=>RES,ENABLE=>en_sh,Q=>D1(7 downto 0),QK=>QKau(71 downto 0)); FSM_INICS2: FSM_in_3 Port Map(clock=>CLOCK,reset=>RESET, address=>AD(15 downto 0), can_read=>re); Mem_loadS2: Memory Port Map (clock=>CLOCK, enable=>en,read=>re,write=>w, Read_addr=>AD, Write_Addr=>WA,Data_in=>WD,Data_out=>D1); SHIF2: SHIFTREG Port Map(CLOCK=>CLK,RESET=>RES,ENABLE=>en_sh,Q=>D1(7 downto 0),QK=>QKau(71 downto 0)); FSM_INICS3: FSM_in_3 Port Map(clock=>CLOCK,reset=>RESET, address=>AD(15 downto 0), can_read=>re); Mem_loadS3: Memory Port Map (clock=>CLOCK, enable=>en,read=>re,write=>w, Read_addr=>AD, Write_Addr=>WA,Data_in=>WD,Data_out=>D1); SHIF3: SHIFTREG Port Map(CLOCK=>CLK,RESET=>RES,ENABLE=>en_sh,Q=>D1(7 downto 0),QK=>QKau(71 downto 0)); end if; end SCHEMATIC; configuration CFG_chargue_SCHEMATIC of chargue is for SCHEMATIC for FSM_INIC1, FSM_INIC2,FSM_INIC3,FSM_INIC4,FSM_INIC5,FSM_INIC6,FSM_INIC7,FSM_INIC8,FSM_INIC9, FSM_INICS1,FSM_INICS2,FSM_INICS3 : FSM_in_3 use configuration WORK.CFG_FSM_in_3_BEHAVIORAL; end for; for Mem_load1, Mem_load2,Mem_load3,Mem_load4,Mem_load5,Mem_load6,Mem_load7,Mem_load8,Mem_load9, Mem_loadS1,Mem_loadS2,Mem_loadS3 : MEMORY use configuration WORK.CFG_MEMORY_BEHAVIORAL; end for; for Reg_IN1, Reg_IN2,Reg_IN3,Reg_IN4,Reg_IN5,Reg_IN6,Reg_IN7,Reg_IN8,Reg_IN9 : REG use configuration WORK.CFG_REG_BEHAVIORAL; end for; for SHIF1,SHIF2,SHIF3 : SHIFTREG use configuration WORK.CFG_SHIFTREG_BEHAVIORAL; end for; end for; end CFG_chargue_SCHEMATIC;
02207-work-groupdt07
trunk/Project/code/archive/charge.vhd
VHDL
lgpl
9,282
-- a simple 256*256 pixel (256*256*8 bits) Memory module -- arranged in a linear fashion. library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_arith.all; use ieee.std_logic_unsigned.all; entity MEMORY is port( Clock: in std_logic; Enable: in std_logic; Give_Zeros: in std_logic; Read: in std_logic; Write: in std_logic; Read_Addr: in std_logic_vector(15 downto 0); Write_Addr: in std_logic_vector(15 downto 0); Data_in: in std_logic_vector(7 downto 0); Data_out: out std_logic_vector(7 downto 0) ); end MEMORY; -------------------------------------------------------------- architecture BEH_MEMORY of MEMORY is type memory_type is array (0 to 65536) of std_logic_vector(7 downto 0); signal tmp_memory: memory_type; begin process(Clock) begin if (Clock'EVENT and Clock='1' and enable='1') then if (Give_Zeros='1') then Data_out <= (Data_out'range => '0'); elsif (Read='1') then Data_out <= tmp_memory(conv_integer(Read_Addr)); end if; if (Write='1') then tmp_memory(conv_integer(Write_Addr)) <= Data_in; end if; end if; end process; end BEH_MEMORY;
02207-work-groupdt07
trunk/Project/code/Memory.vhd
VHDL
lgpl
1,221
library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_unsigned.all; use ieee.std_logic_arith.all; entity TB_cra is -- entity declaration end TB_cra; architecture TB of TB_cra is component CRA_15 is port( A : In std_logic_vector (15 downto 0); B : In std_logic_vector (15 downto 0); Cin : In std_logic; Cout : Out std_logic; Y : Out std_logic_vector (15 downto 0) ); end component; signal t_A, t_B, t_Y: std_logic_vector(15 downto 0); signal t_cin,t_cout: std_logic; begin U_ADDER: CRA_15 port map (t_A, t_B, t_cin,t_cout, t_Y); process variable err_cnt: integer :=0; begin t_A <= "0000000000000000"; t_B <= "0000000000000000"; t_cin <= '1'; wait for 10 ns; t_A <= "1111110000000000"; t_B <= "0100000000000000"; t_cin <= '1'; wait for 10 ns; t_A <= "0000100000000000"; t_B <= "0000000000000000"; t_cin <= '1'; wait for 10 ns; t_A <= "1111111111111111"; t_B <= "0000111100000000"; t_cin <= '1'; wait for 10 ns; t_A <= "0000000000000000"; t_B <= "0000001011111111"; t_cin <= '1'; wait for 10 ns; if (err_cnt=0) then assert false report "Testbench of Adder completed successfully!" severity note; else assert true report "Something wrong, try again" severity error; end if; wait; end process; end TB;
02207-work-groupdt07
trunk/Project/code/tb_adder_.vhd
VHDL
lgpl
1,468
library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_arith.all; use ieee.std_logic_unsigned.all; entity parcial is port( M1: in std_logic_vector(7 downto 0); M2: in std_logic_vector(7 downto 0); O1: out std_logic_vector(15 downto 0); O2: out std_logic_vector(15 downto 0); O3: out std_logic_vector(15 downto 0); O4: out std_logic_vector(15 downto 0); O5: out std_logic_vector(15 downto 0); O6: out std_logic_vector(15 downto 0); O7: out std_logic_vector(15 downto 0); O8: out std_logic_vector(15 downto 0) ); end parcial; architecture BEHAVIORAL of parcial is signal aux: std_logic; begin process(M1,M2) variable i: integer; variable Pa1: std_logic_vector(15 downto 0):="0000000000000000"; variable Pa2: std_logic_vector(15 downto 0):="0000000000000000"; variable Pa3: std_logic_vector(15 downto 0):="0000000000000000"; variable Pa4: std_logic_vector(15 downto 0):="0000000000000000"; variable Pa5: std_logic_vector(15 downto 0):="0000000000000000"; variable Pa6: std_logic_vector(15 downto 0):="0000000000000000"; variable Pa7: std_logic_vector(15 downto 0):="0000000000000000"; variable Pa8: std_logic_vector(15 downto 0):="0000000000000000"; begin for i in 0 to 7 loop Pa1(i):= M1(0) AND M2(i); Pa2(i+1):=M1(1) AND M2(i); Pa3(i+2):=M1(2) AND M2(i); Pa4(i+3):=M1(3) AND M2(i); Pa5(i+4):=M1(4) AND M2(i); Pa6(i+5):=M1(5) AND M2(i); Pa7(i+6):=M1(6) AND M2(i); Pa8(i+7):=M1(7) AND M2(i); end loop; O1(15 downto 0)<= Pa1(15 downto 0); O2(15 downto 0)<= Pa2(15 downto 0); O3(15 downto 0)<= Pa3(15 downto 0); O4(15 downto 0)<= Pa4(15 downto 0); O5(15 downto 0)<= Pa5(15 downto 0); O6(15 downto 0)<= Pa6(15 downto 0); O7(15 downto 0)<= Pa7(15 downto 0); O8(15 downto 0)<= Pa8(15 downto 0); end process; end BEHAVIORAL; configuration CFG_parcial_BEHAVIORAL of parcial is for BEHAVIORAL end for; end CFG_parcial_BEHAVIORAL;
02207-work-groupdt07
trunk/Project/code/parcial.vhd
VHDL
lgpl
2,295
library IEEE; use IEEE.std_logic_1164.all; use STD.textio.all; use IEEE.std_logic_textio.all; use IEEE.std_logic_signed.all; entity E is end E; architecture A of E is signal CLOCK : std_logic; signal RESET : std_logic; signal disable : std_logic; signal QK : std_logic_vector (7 downto 0); signal Q : std_logic_vector (71 downto 0); component SHIFTREG Port ( CLOCK : In std_logic; RESET : In std_logic; disable : In std_logic; QK : In std_logic_vector (7 downto 0); Q : InOut std_logic_vector (71 downto 0) ); end component; begin UUT : SHIFTREG Port Map ( CLOCK, RESET, disable, QK, Q ); TB : block begin process CONSTANT NLOOPS : integer := 15; file cmdfile: TEXT; -- Define the file 'handle' variable line_in,line_out: Line; -- Line buffers variable good: boolean; -- Status of the read operations variable A,B: std_logic_vector(7 downto 0); variable S: std_logic_vector(55 downto 0); variable Z: std_logic_vector(71 downto 0); variable ERR: std_logic_vector(55 downto 0); variable d : integer; variable c : integer; -- constant TEST_PASSED: string := "Test passed:"; -- constant TEST_FAILED: string := "Test FAILED:"; begin c := 1; d := 1; FILE_OPEN(cmdfile,"testvecs.in",READ_MODE); reset <= '0'; clock <= '1'; wait for 5 ns; reset <= '1'; disable <= '0'; clock <= '0'; wait for 5 ns; -- ------------------------------------------------------------------------- loop if endfile(cmdfile) then -- Check EOF assert false report "End of file encountered; exiting." severity NOTE; exit; end if; readline(cmdfile,line_in); -- Read a line from the file next when line_in'length = 0; -- Skip empty lines hread(line_in,A,good); -- Read the D argument as hex value assert good report "Text I/O read error" severity ERROR; QK(7 downto 0) <= A(7 downto 0); clock <= '1'; wait for 5 ns; clock <= '0'; wait for 5 ns; Z(71 downto 0) := Q(71 downto 0); write(line_out, string'("byte ")); write(line_out,c-1); write(line_out, string'(" : ")); if (c = 4) then hwrite(line_out,A,RIGHT,2); write(line_out, string'(" -> ")); hwrite(line_out,Z,RIGHT,8); c := 0; else hwrite(line_out,A,RIGHT,2); end if; writeline(OUTPUT,line_out); -- write the message --assert (Z = S) report "Z does not match in pattern " severity error; c := c + 1; d := d + 1; if (d=25) then disable <= '1'; end if; if (d=45) then disable <= '0'; end if; end loop; -- ------------------------------------------------------------------------- write(line_out, string'("--------- END SHIFT REG ------------------")); writeline(OUTPUT,line_out); -- =============================================================== clock <= '1'; wait for 1000 ns; assert q = "11111111111111111111111111111111" report "--------- END SIMULATION ------------------ " severity error; -- =============================================================== end process; end block; end A;
02207-work-groupdt07
trunk/Project/code/tb_shiftreg.vhd
VHDL
lgpl
3,198
library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_unsigned.all; use ieee.std_logic_arith.all; entity ADDER_TB is -- entity declaration end ADDER_TB; architecture TB of ADDER_TB is component ADDER_2 is port( A : In std_logic_vector (7 downto 0); B : In std_logic_vector (7 downto 0); Z : Out std_logic_vector (7 downto 0) ); end component; signal t_A, t_B, t_C: std_logic_vector(7 downto 0); signal t_Z: std_logic_vector(7 downto 0); begin U_ADDER: ADDER_2 port map (t_A, t_B,t_Z); process variable err_cnt: integer :=0; begin t_A <= "00000000"; t_B <= "00000000"; wait for 10 ns; t_A <= "11111100"; t_B <= "01000000"; wait for 10 ns; t_A <= "00001000"; t_B <= "00000000"; wait for 10 ns; t_A <= "11111111"; t_B <= "00001111"; wait for 10 ns; t_A <= "00000100"; t_B <= "00000010"; wait for 10 ns; if (err_cnt=0) then assert false report "Testbench of Adder completed successfully!" severity note; else assert true report "Something wrong, try again" severity error; end if; wait; end process; end TB;
02207-work-groupdt07
trunk/Project/code/tb_adder.vhd
VHDL
lgpl
1,269
-------------------------------------------------------------------- -- Test Bench for memory module (ESD book Chapter 5) -- by Weijun Zhang, 04/2001 -- -- use loop statement to test module completely -------------------------------------------------------------------- library IEEE; use IEEE.std_logic_1164.all; use IEEE.std_logic_arith.all; use ieee.std_logic_unsigned.all; entity MEM_TB is -- entity declaration end MEM_TB; -------------------------------------------------------------------- architecture TB of MEM_TB is component SRAM is port( Clock: in std_logic; Enable: in std_logic; Give_Zeros: in std_logic; Read: in std_logic; Write: in std_logic; Read_Addr: in std_logic_vector(1 downto 0); Write_Addr: in std_logic_vector(1 downto 0); Data_in: in std_logic_vector(3 downto 0); Data_out: out std_logic_vector(3 downto 0) ); end component; signal T_Clock, T_Enable, T_Read, T_Write, T_Zeros: std_logic; signal T_Data_in, T_Data_out: std_logic_vector(3 downto 0); signal T_Read_Addr: std_logic_vector(1 downto 0); signal T_Write_Addr: std_logic_vector(1 downto 0); begin U_CKT: SRAM port map (T_Clock, T_Enable, T_Zeros, T_Read, T_Write, T_Read_Addr, T_Write_Addr, T_Data_in, T_Data_out); Clk_sig: process begin T_Clock<='1'; -- clock cycle 10 ns wait for 5 ns; T_Clock<='0'; wait for 5 ns; end process; process variable err_cnt: integer := 0; begin T_Enable <= '1'; T_Read <= '0'; T_Write <= '0'; T_Write_Addr <= (T_Write_Addr'range => '0'); T_Read_Addr <= (T_Read_Addr'range => '0'); T_Data_in <= (T_Data_in'range => '0'); T_Zeros <= '0'; wait for 20 ns; -- test write for i in 0 to 3 loop T_Write_Addr <= T_Write_Addr + '1'; T_Data_in <= T_Data_in + "10"; T_Write <= '1'; wait for 10 ns; end loop; T_Read_Addr <= (T_Read_Addr'range => '0'); T_Zeros <= '1'; -- test read -- test read for i in 0 to 2 loop T_Read_Addr <= T_Read_Addr + '1'; T_Read <= '1'; wait for 10 ns; end loop; T_Read_Addr <= (T_Read_Addr'range => '0'); T_Zeros <= '0'; for i in 0 to 2 loop T_Read_Addr <= T_Read_Addr + '1'; T_Read <= '1'; wait for 10 ns; end loop; wait; end process; end TB; -------------------------------------------------------------------------- configuration CFG_TB of MEM_TB is for TB end for; end CFG_TB; --------------------------------------------------------------------------
02207-work-groupdt07
trunk/Project/code/TB_memory.vhd
VHDL
lgpl
2,551
----------------------------------------------------- -- VHDL FSM (Finite State Machine) modeling -- (ESD book Figure 2.7) -- by Weijun Zhang, 04/2001 -- -- FSM model consists of two concurrent processes -- state_reg and comb_logic -- we use case statement to describe the state -- transistion. All the inputs and signals are -- put into the process sensitive list. ----------------------------------------------------- library ieee ; use ieee.std_logic_1164.all; ----------------------------------------------------- entity seq_design is port( a: in std_logic; clock: in std_logic; reset: in std_logic; x: out std_logic ); end seq_design; ----------------------------------------------------- architecture FSM of seq_design is -- define the states of FSM model type state_type is (S0, S1, S2, S3); signal next_state, current_state: state_type; begin -- cocurrent process#1: state registers state_reg: process(clock, reset) begin if (reset='1') then current_state <= S0; elsif (clock'event and clock='1') then current_state <= next_state; end if; end process; -- cocurrent process#2: combinational logic comb_logic: process(current_state, a) begin -- use case statement to show the -- state transistion case current_state is when S0 => x <= '0'; if a='0' then next_state <= S0; elsif a ='1' then next_state <= S1; end if; when S1 => x <= '0'; if a='0' then next_state <= S1; elsif a='1' then next_state <= S2; end if; when S2 => x <= '0'; if a='0' then next_state <= S2; elsif a='1' then next_state <= S3; end if; when S3 => x <= '1'; if a='0' then next_state <= S3; elsif a='1' then next_state <= S0; end if; when others => x <= '0'; next_state <= S0; end case; end process; end FSM; -----------------------------------------------------
02207-work-groupdt07
trunk/Project/code/Sample_FSM.vhd
VHDL
lgpl
1,981
library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_arith.all; use ieee.std_logic_unsigned.all; entity csa8bit is Port ( A : In std_logic_vector (7 downto 0); B : In std_logic_vector (7 downto 0); C : In std_logic_vector (7 downto 0); Cin : In std_logic; Cout : Out std_logic; Z : Out std_logic_vector (7 downto 0); Y : Out std_logic_vector (7 downto 0) ); end csa8bit; architecture BEHAVIORAL of csa8bit is signal aux : std_logic; begin process(A, B, C, Cin) variable p : std_logic_vector (7 downto 0) ; variable g : std_logic_vector (7 downto 0) ; variable Z_aux : std_logic_vector (7 downto 0) ; variable Y_aux : std_logic_vector (7 downto 0) ; variable i : integer; begin for i in 0 to 7 loop p(i) := A(i) XOR B(i) ; g(i) := A(i) AND B(i) ; end loop; -- CARRY ----------------------------------- Y_aux(0) := Cin; for i in 0 to 7-1 loop Y_aux(i+1) := g(i) OR (c(i) AND p(i)); end loop; Y(7 downto 0)<=Y_aux(7 downto 0); aux <= g(7) OR (c(7) AND p(7)); Cout<= aux; -- SUM ------------------------------------- for i in 0 to 7 loop Z_aux(i) := p(i) XOR c(i); end loop; Z(7 downto 0)<= Z_aux(7 downto 0); end process; end BEHAVIORAL; configuration CFG_csa8bit_BEHAVIORAL of csa8bit is for BEHAVIORAL end for; end CFG_csa8bit_BEHAVIORAL;
02207-work-groupdt07
trunk/Project/code/CSA_8bit.vhd
VHDL
lgpl
1,293
library IEEE; use ieee.std_logic_1164.all; use ieee.std_logic_arith.all; use IEEE.numeric_std.all; use ieee.std_logic_unsigned.all; entity fsm_in_tb is end fsm_in_tb; architecture FSM_TB of fsm_in_tb is signal T_clock: std_logic; signal T_reset: std_logic; signal T_can_read: std_logic; signal T_address: std_logic_vector(15 downto 0); signal t_addr: NATURAL; signal t_disable_cache: std_logic; component FSM_in_3 is port ( clock: in std_logic; reset: in std_logic; address: out std_logic_vector(15 downto 0); can_read: out std_logic; disable_cache: out std_logic ); end component FSM_in_3; begin U_fsm: fsm_in_3 port map(T_clock, T_reset, T_address, T_can_read, T_disable_cache); process begin T_clock <= '1'; wait for 1 ns; T_clock <= '0'; wait for 1 ns; end process; process variable counter: integer; begin T_reset <= '0'; wait for 10 ns; -- can put assert statements to assure something holds T_reset <= '1'; loop T_addr <= conv_integer(T_address); wait for 2 ns; end loop; end process; end FSM_TB; ---------------------------------------------------------------------- configuration CFG_TB_FSM_IN_3 of FSM_in_TB is for FSM_TB end for; end CFG_TB_FSM_IN_3; -----------------------------------------------------------------------
02207-work-groupdt07
trunk/Project/code/TB_FSM_in.vhd
VHDL
lgpl
1,391
library IEEE; use IEEE.std_logic_1164.all; use STD.textio.all; use IEEE.std_logic_arith.all; use IEEE.std_logic_textio.all; use IEEE.std_logic_signed.all; entity TB_Filter is end TB_Filter; architecture A of TB_Filter is signal Clock: std_logic; signal mem_Enable: std_logic; signal mem_give_zeros: std_logic; signal mem1_Data_in: std_logic_vector(7 downto 0); signal proc_RESET: std_logic; signal proc_Read_In_Mem: std_logic; signal proc_Write_In_Mem: std_logic; signal proc_Read_Out_Mem: std_logic; signal proc_Write_Out_Mem: std_logic; signal proc_Read_Addr_In_Mem: std_logic_vector(15 downto 0); signal proc_Read_Addr_Out_Mem: std_logic_vector(15 downto 0); signal proc_Write_Addr_Out_Mem: std_logic_vector(15 downto 0); signal proc_Data_in_1: std_logic_vector(7 downto 0); signal proc_Data_in_2: std_logic_vector(7 downto 0); signal proc_Data_out: std_logic_vector(7 downto 0); signal proc_filter_disable: std_logic; signal proc_filter: std_logic_vector(7 downto 0); component MEMORY is port( Clock: in std_logic; Enable: in std_logic; Give_Zeros: in std_logic; Read: in std_logic; Write: in std_logic; Read_Addr: in std_logic_vector(15 downto 0); Write_Addr: in std_logic_vector(15 downto 0); Data_in: in std_logic_vector(7 downto 0); Data_out: out std_logic_vector(7 downto 0) ); end component MEMORY; component Processor_3 is Port ( CLOCK : In std_logic; RESET : In std_logic; Read_In_Mem: Out std_logic; Write_In_Mem: Out std_logic; Read_Out_Mem: Out std_logic; Write_Out_Mem: Out std_logic; Read_Addr_In_Mem: Out std_logic_vector(15 downto 0); Read_Addr_Out_Mem: Out std_logic_vector(15 downto 0); Write_Addr_Out_Mem: Out std_logic_vector(15 downto 0); Data_in_1: In std_logic_vector(7 downto 0); Data_in_2: In std_logic_vector(7 downto 0); Data_out: Out std_logic_vector(7 downto 0); Filter: In std_logic_vector(7 downto 0); disable_filter: In std_logic ); end component Processor_3; begin -- UUTP : PROCESSOR_3 -- Port Map (CLOCK, proc_RESET, proc_Read_In_Mem, proc_Read_Out_Mem, proc_Write_Out_Mem, -- proc_Read_Addr_In_Mem, proc_Read_Addr_Out_Mem, proc_Write_Addr_Out_Mem, -- proc_Data_In_1, proc_Data_In_2, proc_Data_Out, proc_filter, proc_filter_disable); -- -- UUTM_in : MEMORY -- Port Map (CLOCK, mem_Enable, '0', mem1_Read, mem1_Write, -- mem1_Read_Addr, mem1_Write_Addr, mem1_Data_In, mem1_Data_Out); -- -- UUTM_out : MEMORY -- Port Map (CLOCK, mem_Enable, mem_give_zeros, mem2_Read, mem2_Write, -- mem2_Read_Addr, mem2_Write_Addr, mem2_Data_In, mem2_Data_Out); UUTP : PROCESSOR_3 Port Map (CLOCK, proc_RESET, proc_Read_In_Mem, proc_Write_In_Mem, proc_Read_Out_Mem, proc_Write_Out_Mem, proc_Read_Addr_In_Mem, proc_Read_Addr_Out_Mem, proc_Write_Addr_Out_Mem, proc_Data_In_1, proc_Data_In_2, proc_Data_Out, proc_filter, proc_filter_disable); UUTM_in : MEMORY Port Map (CLOCK, mem_Enable, '0', proc_Read_In_Mem, proc_Write_In_Mem, proc_Read_Addr_In_Mem, proc_Read_Addr_In_Mem, mem1_data_in, proc_Data_In_1); UUTM_out : MEMORY Port Map (CLOCK, mem_Enable, mem_give_zeros, proc_Read_Out_Mem, proc_Write_Out_Mem, proc_Read_Addr_Out_Mem, proc_Write_Addr_Out_Mem, proc_Data_Out, proc_Data_In_2); clock_signal: process begin Clock <= '1'; wait for 1 ns; Clock <= '0'; wait for 1 ns; end process; process CONSTANT NLOOPS : integer := 15; file cmdfile, outfile: TEXT; -- Define the file 'handle' variable line_in,line_out: Line; -- Line buffers variable good: boolean; -- Status of the read operations variable A,B: std_logic_vector(7 downto 0); variable S: std_logic_vector(55 downto 0); variable Z: std_logic_vector(31 downto 0); variable ERR: std_logic_vector(55 downto 0); variable c : integer; -- constant TEST_PASSED: string := "Test passed:"; -- constant TEST_FAILED: string := "Test FAILED:"; begin proc_RESET <= '0'; wait for 2 ns; mem_Enable <= '1'; mem_give_zeros <= '1'; -- initialize the filter with pixels proc_filter_disable <= '0'; c := 1; proc_RESET <= '1'; proc_filter_disable <= '0'; FILE_OPEN(cmdfile,"lena_256x256.mem",READ_MODE); -- start filling memory 1 with the image pixels from hex file. loop if endfile(cmdfile) then -- Check EOF assert false report "End of file encountered; exiting." severity NOTE; exit; end if; readline(cmdfile,line_in); -- Read a line from the file next when line_in'length = 0; -- Skip empty lines hread(line_in,A,good); -- Read the D argument as hex value assert good report "Text I/O read error" severity ERROR; mem1_Data_In <= A(7 downto 0); write(line_out,c); if(c = 10) then proc_filter_disable <= '1'; elsif ((c mod 2) = 0) then proc_filter <= "00000001"; else proc_filter <= "00000000"; end if; wait for 2 ns; c := c + 1; end loop; c := 1; mem_give_zeros <= '0'; loop wait for 2 ns; c := c + 1; if(c = 1560577) then -- ( 3 + 9 ) * 254 * 256 (780288) exit; end if; end loop; write(line_out, string'("--------- END-------------")); writeline(OUTPUT,line_out); end process; end A;
02207-work-groupdt07
trunk/Project/code/TB_filter.vhd
VHDL
lgpl
6,006
library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_arith.all; use ieee.std_logic_unsigned.all; entity csa15bit is Port ( A : In std_logic_vector (15 downto 0); B : In std_logic_vector (15 downto 0); C : In std_logic_vector (15 downto 0); Cin : In std_logic; Cout : Out std_logic; Z : Out std_logic_vector (15 downto 0); Y : Out std_logic_vector (15 downto 0) ); end csa15bit; architecture BEHAVIORAL of csa15bit is signal aux : std_logic; begin process(A, B, C, Cin) variable p : std_logic_vector (15 downto 0) ; variable g : std_logic_vector (15 downto 0) ; variable Z_aux : std_logic_vector (15 downto 0) ; variable Y_aux : std_logic_vector (15 downto 0) ; variable i : integer; begin for i in 0 to 15 loop p(i) := A(i) XOR B(i) ; g(i) := A(i) AND B(i) ; end loop; -- CARRY ----------------------------------- Y_aux(0) := Cin; for i in 0 to 15-1 loop Y_aux(i+1) := g(i) OR (c(i) AND p(i)); end loop; Y(15 downto 0)<=Y_aux(15 downto 0); aux <= g(15) OR (c(15) AND p(15)); Cout<= aux; -- SUM ------------------------------------- for i in 0 to 15 loop Z_aux(i) := p(i) XOR c(i); end loop; Z(15 downto 0)<= Z_aux(15 downto 0); end process; end BEHAVIORAL; configuration CFG_csa15bit_BEHAVIORAL of csa15bit is for BEHAVIORAL end for; end CFG_csa15bit_BEHAVIORAL;
02207-work-groupdt07
trunk/Project/code/CSA_15bit.vhd
VHDL
lgpl
1,318
library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_arith.all; use ieee.std_logic_unsigned.all; entity CRA_15 is port( A : In std_logic_vector (15 downto 0); B : In std_logic_vector (15 downto 0); Cin : In std_logic; Cout : Out std_logic; Y : Out std_logic_vector (15 downto 0) ); end CRA_15; architecture RTL of CRA_15 is begin process(A,B,Cin) variable tempC : std_logic_vector (16 downto 0); variable P : std_logic_vector (15 downto 0); variable G : std_logic_vector (15 downto 0); variable Yaux : std_logic_vector (15 downto 0); begin tempC(0):= Cin; for i in 0 to 15 loop P(i):= A(i) XOR B(i); G(i):= A(i) AND B(i); Yaux(i):= P(i) xor tempC(i); tempC(i+1):=G(i) OR (tempC(i) AND P(i)); end loop; if (tempC(16)='1') then Yaux(15 downto 0):= "1111111111111111"; end if; for i in 0 to 7 loop if (Yaux(i+8)='1') then Yaux(15 downto 0):="1111111111111111"; end if; end loop; Y(15 downto 0)<= Yaux(15 downto 0); Cout<=tempC(16); end process; end RTL; configuration CFG_CRA_15_BEHAVIORAL of CRA_15 is for RTL end for; end CFG_CRA_15_BEHAVIORAL;
02207-work-groupdt07
trunk/Project/code/CRA_15.vhd
VHDL
lgpl
1,625
library IEEE; use IEEE.std_logic_1164.all; use IEEE.std_logic_misc.all; use IEEE.std_logic_arith.all; entity Processor_3 is Port ( CLOCK : In std_logic; RESET : In std_logic; Read_In_Mem: Out std_logic; Write_In_Mem : Out std_logic; Read_Out_Mem: Out std_logic; Write_Out_Mem: Out std_logic; Read_Addr_In_Mem: Out std_logic_vector(15 downto 0); Read_Addr_Out_Mem: Out std_logic_vector(15 downto 0); Write_Addr_Out_Mem: Out std_logic_vector(15 downto 0); Data_in_1: In std_logic_vector(7 downto 0); Data_in_2: In std_logic_vector(7 downto 0); Data_out: Out std_logic_vector(7 downto 0); Filter: In std_logic_vector(7 downto 0); disable_filter: In std_logic ); end Processor_3; architecture SCHEMATIC_PROC_3 of Processor_3 is component ADDER_3 port( A : In std_logic_vector (7 downto 0); B : In std_logic_vector (7 downto 0); C : In std_logic_vector (7 downto 0); Z : Out std_logic_vector (7 downto 0)); end component ADDER_3; component ADDER_2 port( A : In std_logic_vector (7 downto 0); B : In std_logic_vector (7 downto 0); Z : Out std_logic_vector (7 downto 0)); end component ADDER_2; component SHIFTREG is Port ( CLOCK : In std_logic; RESET : In std_logic; disable : In std_logic; QK : In std_logic_vector (7 downto 0); Q : InOut std_logic_vector (71 downto 0) ); end component SHIFTREG; component Multiplier Port ( num1 : In std_logic_vector (7 downto 0); num2 : In std_logic_vector (7 downto 0); product : Out std_logic_vector (7 downto 0) ); end component Multiplier; component MUX_4 is port ( SEL: in STD_LOGIC_VECTOR (1 downto 0); A,B,C: in STD_LOGIC_VECTOR(7 downto 0); SIG: out STD_LOGIC_VECTOR(7 downto 0)); end component MUX_4; component MUX_2 is port ( SEL: in STD_LOGIC; A,B: in STD_LOGIC_VECTOR(15 downto 0); SIG: out STD_LOGIC_VECTOR(15 downto 0)); end component MUX_2; component MUX_2_1 is port ( SEL: in STD_LOGIC; A,B: in STD_LOGIC; SIG: out STD_LOGIC); end component MUX_2_1; component FSM_in_3 port ( clock: in std_logic; reset: in std_logic; address: out std_logic_vector(15 downto 0); can_read: out std_logic; can_write: out std_logic; disable_cache: out std_logic ); end component FSM_in_3; component FSM_out_3 port ( clock: in std_logic; reset: in std_logic; read_address: out std_logic_vector(15 downto 0); write_address: out std_logic_vector(15 downto 0); can_read: out std_logic; can_write: out std_logic; sel: out std_logic_vector(1 downto 0) ); end component FSM_out_3; component REG is port( D : in std_logic_vector(7 downto 0); Clock, Reset : in std_logic; Q : out std_logic_vector(7 downto 0)); end component REG; signal disable_to_cache: std_logic; signal cache_bits: std_logic_vector(71 downto 0); signal filter_bits: std_logic_vector(71 downto 0); signal mult1_out: std_logic_vector(7 downto 0); signal mult2_out: std_logic_vector(7 downto 0); signal mult3_out: std_logic_vector(7 downto 0); signal mult4_out: std_logic_vector(7 downto 0); signal mult5_out: std_logic_vector(7 downto 0); signal mult6_out: std_logic_vector(7 downto 0); signal mult7_out: std_logic_vector(7 downto 0); signal mult8_out: std_logic_vector(7 downto 0); signal mult9_out: std_logic_vector(7 downto 0); signal add1_out: std_logic_vector(7 downto 0); signal add2_out: std_logic_vector(7 downto 0); signal add3_out: std_logic_vector(7 downto 0); constant zeros: unsigned(7 downto 0) := (others => '0'); signal select_adder: std_logic_vector(1 downto 0); signal mux_out: std_logic_vector(7 downto 0); begin fsm_input: FSM_in_3 port map(CLOCK, RESET, Read_Addr_In_Mem, Read_In_Mem, Write_In_Mem, disable_to_cache); fsm_output: FSM_out_3 port map(CLOCK, RESET, Read_Addr_Out_Mem, Write_Addr_Out_Mem, Read_Out_Mem, Write_Out_Mem, select_adder); cache: SHIFTREG port map(CLOCK, RESET, disable_to_cache, Data_in_1, cache_bits); filtermask: SHIFTREG port map(CLOCK, RESET, disable_filter, Filter, filter_bits); Mult1: Multiplier port map(cache_bits(7 downto 0), filter_bits(7 downto 0),mult1_out); Mult2: Multiplier port map(cache_bits(15 downto 8), filter_bits(15 downto 8),mult2_out); Mult3: Multiplier port map(cache_bits(23 downto 16), filter_bits(23 downto 16),mult3_out); Mult4: Multiplier port map(cache_bits(31 downto 24), filter_bits(31 downto 24),mult4_out); Mult5: Multiplier port map(cache_bits(39 downto 32), filter_bits(39 downto 32),mult5_out); Mult6: Multiplier port map(cache_bits(47 downto 40), filter_bits(47 downto 40),mult6_out); Mult7: Multiplier port map(cache_bits(55 downto 48), filter_bits(55 downto 48),mult7_out); Mult8: Multiplier port map(cache_bits(63 downto 56), filter_bits(63 downto 56),mult8_out); Mult9: Multiplier port map(cache_bits(71 downto 64), filter_bits(71 downto 64),mult9_out); Add1: Adder_3 port map(mult1_out, mult2_out, mult3_out, add1_out); Add2: Adder_3 port map(mult4_out, mult5_out, mult6_out, add2_out); Add3: Adder_3 port map(mult7_out, mult8_out, mult9_out, add3_out); Multiplexer: Mux_4 port map(select_adder, add1_out, add2_out, add3_out, mux_out); Add_new_value: Adder_2 port map(Data_in_2, mux_out, Data_out); -- regster : Reg port map("11111111", Clock, Reset, data_out); end SCHEMATIC_PROC_3;
02207-work-groupdt07
trunk/Project/code/Processor_3.vhd
VHDL
lgpl
6,380
\documentclass[11pt,a4paper]{article} \usepackage{url,,} \usepackage{graphicx} \usepackage{hyperref} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsmath} \usepackage{multirow} \usepackage{listings} \usepackage{fullpage} \usepackage{fancyhdr,a4wide} \usepackage{makeidx} \usepackage{placeins} %\usepackage[procnames,noindent]{lgrind} \lstset{ % language=VHDL, % choose the language of the code basicstyle=\footnotesize, % the size of the fonts that are used for the code showstringspaces=false, % underline spaces within strings %numbers=left, % where to put the line-numbers %numberstyle=\footnotesize, % the size of the fonts that are used for the line-numbers %stepnumber=1, % the step between two line-numbers. If it's 1 each line will be numbered %numbersep=5pt, % how far the line-numbers are from the code %backgroundcolor=\color{white}, % choose the background color. You must add \usepackage{color} showspaces=false, % show spaces within strings adding particular underscores showtabs=false, % show tabs within strings adding particular underscores escapeinside={\%*}{*)} % if you want to add a comment within your code } \begin{document} \begin{titlepage} \thispagestyle{fancy} \lhead{} \chead{ \large{\textit{ Informatics and Mathematical Modelling\\ Technical University of Denmark}}} \rhead{} \rule{0pt}{50pt} \vspace{3cm} \begin{center} \huge{\textbf{02207 : Advanced Digital Design Techniques}}\\ \vspace{1cm} \huge{Low-pass Filter (2 x 1-D)}\\ \vspace{1cm} \huge{\textit{Examination Project}}\\ \vspace{1cm} \huge{Group \textit{dt07}}\\ \end{center} \vspace{4cm} \begin{flushright} \LARGE{Markku Eerola (s053739)}\\ \vspace{0.3cm} \LARGE{Rajesh Bachani (s061332)}\\ \vspace{0.3cm} \LARGE{Josep Renard (s071158)}\\ \end{flushright} \cfoot{\today} \end{titlepage} \newpage \tableofcontents \newpage \section{About the Report} In this project, we have designed and implemented the architecture for an image filtering processor which uses a 3x3 filter to perform a convolution on the image of size 256x256 pixels. Following is the work done by the authors. \paragraph{Authors by Section} \begin{itemize} \item \textit{Rajesh Bachani} \begin{itemize} \item VHDL: FSM\_In.vhd, FSM\_Out.vhd, Processor\_3.vhd, TB\_Filter.vhd \item Report: Sections \ref{sec:sequencing} and \ref{sec:controller} \end{itemize} \item \textit{Josep Renard} \begin{itemize} \item VHDL: Multiplier.vhd, parcial.vhd, CRA\_15.vhd, CSA\_15bit.vhd \item Report: Sections \ref{sec:results} and \ref{sec:limitations} \end{itemize} \item \textit{Markku Eerola} \begin{itemize} \item VHDL: Adder\_2.vhd, Adder\_3.vhd, Mux\_4.vhd, SHIFTREG.vhd, Memory.vhd, REG.vhd \item Report: Sections \ref{sec:design} and \ref{sec:synthesis} \end{itemize} \end{itemize} The rest of the report is organized as follows. In section \ref{sec:design}, we explain the internal architecture of the processor. Then in section \ref{sec:sequencing}, we give the sequencing of the operations involved in the computation. This section explains the operations performed for memory initialization and the order in which the input memory is read and the output memory is read and written. Also, we here explain the order in which the memory is accessed, which are different for the horizontal and vertical movements of the filter mask. Section \ref{sec:controller} explains the design of the controllers at the input and the output. In section \ref{sec:synthesis}, we provide the results from the synthesis of the design in Design Vision. The section \ref{sec:results} contains the images obtained after convolution, and also a summary of the results from the synthesis. Finally, we end the report with section \ref{sec:limitations} with a short explanation on what we think are the limitations of the work done here, and how it could be extended. \section{Design Architecture} \label{sec:design} The overall design of the filter unit can be seen in figure \ref{fig:proc}. More detailed architecture can be seen in figure \ref{fig:procdetail}. \begin{figure}[h] \centering \includegraphics[width=6in]{./images/processador.PNG} \caption{Filter Unit Design} \label{fig:proc} \end{figure} \begin{figure}[h] \centering \includegraphics[width=6in]{./images/insideproc.PNG} \caption{Processor Architecture} \label{fig:procdetail} \end{figure} \FloatBarrier The input and the output signals of the processor are explained below, with their bit-width's. \begin{itemize} \item \textit{Data\_in\_1}, 8 bits, transfers pixels of the image from the input memory to the processor's cache \item \textit{Clock}, 1 bit, the common clock signal \item \textit{Reset}, 1 bit, the common active low reset signal \item \textit{Filter}, 8 bits, used to get the $n$ pixels of the filter, 8 bits over $n$ clock cycles ($n$ = 3 here) \item \textit{Disable\_filter}, 1 bit, used to disable the filter, so the filter register is not written \item \textit{Data\_in\_2}, 8 bits, transfers pixels of the image from the output memory to the processor \item \textit{Read\_In\_Mem}, 1 bit, indicates the memory when to read pixels of the input image \item \textit{Write\_In\_Mem}, 1 bit, indicates the memory when to write pixels to the input image (this is used only when the input memory is initialized) \item \textit{Read\_Addr\_In\_Mem}, 16 bits, indicates the address from where the next pixel should be read from the input memory \item \textit{Data\_Out}, 8 bits, transfers processed pixels from the processor to the output memory \item \textit{Write\_Addr\_Out\_Mem}, 16 bits, indicates the address to which the next pixel should be written in the output memory \item \textit{Read\_Addr\_Out\_Mem}, 16 bits, indicates the address from where the next pixel must be read from the output memory \item \textit{Write\_Out\_Mem}, 1 bit, indicates the output memory when to allow writing of data \item \textit{Read\_Out\_Mem}, 1 bit, indicates the output memory when to allow reading of data \end{itemize} \section{Sequencing of Operations} \label{sec:sequencing} This section contains a description of the sequence in which the processor performs the operations needed for convolution of the image. \subsection{Memory Initialization} Before the processor starts its operations, we have the memory initialization step, in which both the input and the output memory's are set to initial values. The input memory is initialized with the image pixels, which is done through the testbench. The output memory has to be initialized to zero. \subsection{Memory Read and Write by Processor} \label{sec:memreadwrite} There are two controllers as part of the processor, the Input Controller and the Output Controller (indicated by FSM\_In and FSM\_Out in figure \ref{fig:procdetail}). The Input Controller is responsible for reading pixels from the input memory, which holds the original image. On the other hand, the output controller is responsible for reading as well as writing the computed pixels from and to the output memory. The output memory at the end of the computation, holds the pixels of the convoluted image. It is very important that these two controllers be well synchronized with each other, so the operations are performed smoothly, and there is no data loss. In particular, when the Input Controller is active, the Output Controller should not perform any operation. This is because until the Input Controller has read the next 3 pixels (for the 3x3 filter; it would be $n$ for nxn filter) from the input memory, the convolution is not stable, and so the Output Controller cannot write anything to the output memory. The vice-versa case is also true. So, when the Output Controller is active, the Input Controller should be inactive. This is because while the output memory is being written by the Output Controller, if the Input Controller reads new pixels, then the already computed values would be overwritten, and the synchronization is disturbed completely. \begin{figure}[h] \centering \includegraphics[width=6in]{./images/controllerreadwrite.PNG} \caption{Read Write Synchronization between Input and Output Controllers(1)} \label{fig:controllerreadwrite} \end{figure} \FloatBarrier Hence we have chosen the approach in which at no point of time, would both the Controllers be active, as shown in figure \ref{fig:controllerreadwrite}. As we can see, the signal \textit{read\_in\_mem} is \textit{1} for three clock cycles. The signal \textit{disable\_to\_cache} becomes \textit{1} after one clock cycle delay as compared to \textit{read\_in\_mem}. Also, once the \textit{read\_in\_mem} becomes \textit{0}, the \textit{read\_out\_mem} becomes \textit{1}. Also at this time, the \textit{disable\_to\_cache} becomes \textit{0}. Then there is no activity for one clock cycle, during which the convolution is done, after which \textit{write\_out\_mem} becomes \textit{1} to write the convoluted pixel to the output memory. The \textit{read\_in\_mem} then becomes \textit{1} again after nine clock cycles, i.e. when the Output Controller has finished reading and writing three convoluted pixels to the output memory. During the horizontal movement, when the horizontal end of the image is reached, the Output Controller becomes idle for a longer duration. This is because the Input Controller now has to load nine fresh pixels from the input memory, which happens in 27 clock cycles. So, once the end of the image is reached (this holds even for vertical movements), the Output Controller becomes idle for 27 cycles, and then starts reading and writing as usual, which goes on uptil the end of the image is again reached (which is 256 rounds of read and write). Figure \ref{fig:controllerreadwrite2} depicts this situation in the simulation. \begin{figure}[h] \centering \includegraphics[width=6in]{./images/controllerreadwrite2.PNG} \caption{Read Write Synchronization between Input and Output Controllers(2)} \label{fig:controllerreadwrite2} \end{figure} \subsection{Memory Access Sequence} \label{sec:memoryaccess} \begin{figure}[h] \centering \includegraphics[width=5in]{./images/memoryAccess.PNG} \caption{Sequence of Input Memory Address Access} \label{fig:memaccess} \end{figure} \FloatBarrier The figure \ref{fig:memaccess} shows the sequence in which the input memory pixels are accessed by the Input Controller. During the horizontal movement, the 3 pixels are accessed in every column, with the direction of movement of the access being the same as the direction of movement of the filter, i.e. from left to right. Once a horizontal end of the image is reached, the access is started from the next row, with again three pixels in every column and the direction of movement being horizontal. When the horizontal movement is completed, the vertical movement takes place. During this, three pixels are accessed in every row of the image, and the movement is vertical, from top to bottom. On reaching a vertical end of the image, the reading starts at the top of the next column, again with 3 pixels in each row and movement from top to bottom. \begin{figure}[h] \centering \includegraphics[width=5in]{./images/outmemoryaccess.jpg} \caption{Sequence of Output Memory Address Access} \label{fig:outmemaccess} \end{figure} \FloatBarrier The memory access for the Output Controller is simple as compared to the memory access by the Input Controller. The right part of the figure \ref{fig:outmemaccess} shows the access for the horizontal movement. The top most and the bottom most rows are not written. Once a row is completed the next row pixels are read and written. For the vertical movement, the first and the last columns are not written. The read and write sequence starts from the second column, and ends when the second last column is finished. \section{Finite State Machines} \label{sec:controller} The following subsections explain the finite state machines describing the Input and the Output Controllers. \subsection{Input Controller} The Input Controller has the following 16 states. \begin{enumerate} \item State \textit{init}. This is the initialization state of the controller. The next state is \textit{init\_in\_memory\_1}. \item State \textit{init\_in\_memory\_1}. This state performs the initialization of the input memory. The Controller puts the \textit{can\_write} signal to \textit{1}, so that the byte read from the $.hex$ file is written to the \textit{Data\_In} of the input memory. The address to which the byte should be written is also given by the Controller, through the signal \textit{address}. The next state is \textit{init\_in\_memory\_2}. \item State \textit{init\_in\_memory\_2}. This state does the same thing as the previous state, and it increments a counter. Once the value of the counter is greater than 65536, which means that the entire memory has been written, the state changes to \textit{h\_read\_1}. \item State \textit{h\_read\_1}. This state performs the read operation from the input memory for one pixel. The signal \textit{can\_write} is set to \textit{1}. The next state is \textit{h\_read\_2}. \item State \textit{h\_read\_2}. This state performs the read operation from the input memory for one pixel. The next state is \textit{h\_read\_3}. The signal \textit{disable\_cache} is set to \textit{0} here, since from now we want the cache to start loading the values from the input memory. \item State \textit{h\_read\_3}. This state performs the read operation from the input memory for one pixel. The next state is \textit{h\_cache}. \item State \textit{h\_cache}. This state is used as a delay. The signal \textit{disable\_cache} should be delayed by one clock cycle as compared to the signal \textit{can\_read} since the byte from the memory comes one clock cycle after the \textit{can\_read} is active. The signal \textit{can\_read} is set to \textit{0} here. The next state is \textit{h\_wait}. \item State \textit{h\_wait}. This state is used as a wait state, during which the Output FSM is active. Also, the \textit{disable\_cache} signal is set to \textit{1} here, so that no more values from the memory are read into the cache, until the Input Controller gets active again. The next state is \textit{h\_temp}. \item State \textit{h\_temp}. This state is also the wait state, and the finite state machine keeps shuttling between this state and the previous state, for 27 clock cycles. Once the Output Controller writes the new pixels to the output memory, the wait time is over, and the next state is set to \textit{v\_read\_1} and the vertical reading for the memory is started. The states for vertical movement are kept separate from the states for the horizontal movement. This is because the order in which the addresses are generated for the \textit{address} signal, are different in both the movements (as also shown in figure \ref{fig:memaccess}). The purpose of the following states is the same though, with only the address values being different, so we skip the explanation. \item State \textit{v\_read\_1}. \item State \textit{v\_read\_2}. \item State \textit{v\_read\_3}. \item State \textit{v\_cache}. \item State \textit{v\_wait}. \item State \textit{v\_temp}. \item State \textit{exit\_in}. This is the exit state of the finite state machine. \end{enumerate} \subsection{Output Controller} The Output Controller has the following 18 states. \begin{enumerate} \item State \textit{init}. This is the initialization state of the controller. The next state is \textit{init\_out\_memory\_1}. \item State \textit{init\_out\_memory\_1}. This state initializes the output memory to \textit{0}. The controller puts the \textit{can\_write} signal to \textit{1} and the \textit{write\_address} is incremented every time in the state. The next state is \textit{init\_out\_memory\_2}. Important to note here, that the output memory is initialized by zeros, since the \textit{Data\_In\_2} signal coming from the output memory is set to zero, using the \textit{give\_zeros} signal of the output memory. Also the multiplexer in this state gives zero since the select is forced to `11' by the controller. Hence the \textit{Data\_Out} of the processor is always zero in this state. \item State \textit{init\_out\_memory\_2}. This state performs the same function as the previous state. A counter is maintained which if greater than 65536 indicates that the memory is initialized. Then the next state is \textit{h\_init\_1} \item State \textit{h\_init\_1}. This state is created in order to wait for the cache shift register to get the pixels from the input memory. Actually, when the Input Controller finishes reading a line in the memory, during any of the horizontal or vertical movements, the Output Controller must wait for the time till the cache is filled with the new 9 pixels. The next state is \textit{h\_init\_2}. \item State \textit{h\_init\_2}. This state performs the same function, and waits till the 9 pixels are filled in the cache shift register. This takes 27 clock cycles, since the Input Controller also remains idle in between. Once this is done, the next state is set to \textit{h\_read\_1}. \item State \textit{h\_read\_1}. This state puts the \textit{can\_read} signal to \textit{1}. Also, the corresponding \textit{read\_address} is set. The next state is \textit{h\_read\_write}. \item State \textit{h\_read\_write}. In this state, the Controller remains idle, so that data is recieved from the output memory in the next clock cycle. The next state is \textit{h\_write\_1}. \item State \textit{h\_write\_1}. This state forces the adder to be selected, by changing the \textit{sel} signal. The old pixel from the output memory and the new pixel from the adder are added. The signal \textit{can\_write} is set to \textit{1} and the \textit{write\_address} is set to the same value as the \textit{read\_address} in the previous state. If the end of the row or column is reached in the memory, the next state is \textit{h\_init\_1}. Else the next state is \textit{h\_wait\_1}. Also, if the end of the image is identified, then the vertical movement begins, and in that case the next state is set to \textit{v\_init\_1} \item State \textit{h\_wait\_1}. In this state, the Controller waits for the Input Controller to read 3 new pixels from the input memory. The next state is \textit{h\_wait\_2}. \item State \textit{h\_wait\_2}. This state performs the same function as the previous state. If 3 clock cycles are over, i.e. if the Input Controller has read 3 new pixels, then the Controller gets active again, and the next state is set to \textit{h\_read\_1}. Again, we avoid giving explanation for the states during the vertical movement, since they all perform the same function as the states occuring during the horizontal movement. \item State \textit{v\_init\_1}. \item State \textit{v\_init\_2}. \item State \textit{v\_read\_1}. \item State \textit{v\_read\_write}. \item State \textit{v\_write\_1}. \item State \textit{v\_wait\_1}. \item State \textit{v\_wait\_2}. \item State \textit{exit\_in}. This is the exit state of the finite state machine. \end{enumerate} \section{Synthesis} \label{sec:synthesis} We synthesized the design using four different clock periods, namely 7ns, 5ns, 3ns and 2ns, and let Design Vision try to optimize the design for speed to get the fastest possible design. Turns out 2ns is the minimum clock period for our design, Design Vision was not able to synthesize a faster design even when we tried. To get meaningful power reports we simulated switching activity with the VSS Simulator and the activity was passed on to Design Vision. On top of power reports we also obtained area and timing reports from the design on all four clock periods. The actual reports can be seen in the appendix, but a summary of the results can be seen in table \ref{tab:synth}. The power breakdown for the designs on all four clock periods can be seen in table \ref{tab:broken}. In the breakdown \textit{MULT}$_{conv}$ and \textit{ADD}$_{conv}$ refer to the power dissipation in all multipliers and adders involved in the convolution combined. For more detailed breakdown please refer to the appendix. \begin{table}[h] \caption{Summary of Design Vision reports} \begin{center} \begin{tabular}{|l|l|l|l|l|l|l|} \hline \textbf{T}$_{C}$ [ns] & \textbf{P}$_{stat}$ [mW] & \textbf{P}$_{dyn}$ [mW] & \textbf{P}$_{tot}$ [mW] & \textbf{A}$_{comb}$ [$\mu$$m^2$]& \textbf{A}$_{tot}$ [$\mu$$m^2$] & \textbf{T}$_{cp}$ [ns] \\ \hline 7 & 0.16 & 1.77 & 1.93 & 44067 & 53079 & 4.7 \\ \hline 5 & 0.16 & 1.88 & 2.04 & 44067 & 53079 & 4.7 \\ \hline 3 & 0.11 & 2.17 & 2.28 & 49595 & 58611 & 2.9 \\ \hline 2 & 0.19 & 2.59 & 2.78 & 58668 & 67700 & 1.9 \\ \hline \end{tabular} \end{center} \label{tab:synth} \end{table} \begin{table}[h] \caption{Power breakdown, total power in mW} \begin{center} \begin{tabular}{|p{0.4cm}|p{1.15cm}|p{1.25cm}|p{1.5cm}|p{1.55cm}|p{1.75cm}|p{1.45cm}|p{1cm}|p{1.3cm}|p{1.25cm}|} \hline \textbf{T}$_{C}$ & \textbf{FSM}$_{in}$ & \textbf{FSM}$_{out}$ & \textbf{REG}$_{filter}$ & \textbf{REG}$_{cache}$ & \textbf{MULT}$_{conv}$ & \textbf{ADD}$_{conv}$ & \textbf{MUX} & \textbf{ADD}$_{out}$ & \textbf{REG}$_{out}$ \\ \hline 7 & 0.207 & 0.242 & 0.396 & 0.547 & 0.363 & 0.036 & 0.035 & 0.050 & 0.053 \\ \hline 5 & 0.256 & 0.300 & 0.396 & 0.549 & 0.365 & 0.036 & 0.036 & 0.056 & 0.052 \\ \hline 3 & 0.370 & 0.436 & 0.401 & 0.548 & 0.224 & 0.110 & 0.040 & 0.126 & 0.052 \\ \hline 2 & 0.512 & 0.606 & 0.395 & 0.557 & 0.371 & 0.103 & 0.044 & 0.143 & 0.052 \\ \hline \end{tabular} \end{center} \label{tab:broken} \end{table} The critical path of the design (see figure \ref{fig:procdetail}) is the same for all four clock periods and goes through the cache register, the convolution multipliers, the convolution adders, the multiplexer, the adder and the output register (added for the synthesizer's sake, to constrain the path - doesn't contribute to the delay in any of the timing reports). The path is illustrated in figure \ref{fig:critical} along with the delay information. \begin{figure}[h] \centering \includegraphics[width=6in]{./images/criticalpath.PNG} \caption{Critical path of the design} \label{fig:critical} \end{figure} \FloatBarrier \section{Results} \label{sec:results} The original image which is convoluted in the simulation is shown in figure \ref{fig:lena}. The convolution of this image takes a total time of 3252224 ns, which is broken down as (with a clock cycle of 2 ns): \begin{enumerate} \item Memory Initialization: 131072 ns (256 * 256 * 2 ns). \item Horizontal Movement: 1560576 ns (256 * 254 * 12 * 2 ns), where 12 is the number of cycles taken for one horizontal movement of the filter. \item Vertical Movement: 1560576 ns (256 * 254 * 12 * 2 ns), where 12 is the number of cycles taken for one vertical movement of the filter. \end{enumerate} The left image in the figure \ref{fig:lenanew} is computed using the filter mask of `000010000' and the right image in figure \ref{fig:lenanew} is computed using the filter mask of `010101010'. \begin{figure}[h] \centering \includegraphics[width=2in]{./images/lena.PNG} \caption{Original Image} \label{fig:lena} \end{figure} \FloatBarrier \begin{figure}[htp] \begin{center} \subfigure{\label{fig:lena1}\includegraphics[height=2in]{./images/lena1.PNG}} \hspace{1in} \subfigure{\label{fig:lena2}\includegraphics[height=2in]{./images/lena2.PNG}} \end{center} \caption{Convolution Results} \label{fig:lenanew} \end{figure} \FloatBarrier Provided below is a summary of the results obtained from the Synthesis of the design. \begin{table}[h] \caption{Summary} \begin{center} \begin{tabular}{|p{1cm}|p{2cm}|p{2cm}|l|l|} \hline \textbf{T}$_C$ [ns] & \textbf{Critical Path} [ns] & \textbf{N. cycles} (256 x 256) & \textbf{E}$_{pc}$ [mW/MHz] & \textbf{AREA} [$\mu$$m^2$] \\ \hline 7 & 4.7 & 3121152 & 0.01351 & 53079 \\ \hline 5 & 4.7 & 3121152 & 0.01020 & 53079 \\ \hline 3 & 2.9 & 3121152 & 0.00684 & 58611 \\ \hline 2 & 1.9 & 3121152 & 0.00556 & 67700 \\ \hline \end{tabular} \end{center} \label{tab:conclusion} \end{table} \FloatBarrier \section{Limitations and Extensions} \label{sec:limitations} We have designed and implemented the architecture for an image filtering processor which uses a 3x3 filter to perform a convolution on the image of size 256x256 pixels. Though the results of the convoluted image look promising, as shown in section \ref{sec:results}, we are aware of some of the limitations of the work. Given more time, we would have liked to add the following missing aspects into the project. \begin{enumerate} \item We have just been able to implement the 3x3 filter for the convolution. Though, it was proposed that we would implement the higher dimension filters as well, including 5x5, 7x7 and 9x9, we were not able to do so, due to the initial problems we faced in the implementation of the 3x3 filter itself. We believe the results obtained in the section \ref{sec:results}, in the form of the convoluted image could be better if the dimension of the filter is higher. In those cases, the blur effect on the image would be clearly evident, as compared to the case of the 3x3 filter. We would like to briefly mention how the design of the processor would be modified if we wish to convolute the image using higher dimension filters. If we consider the dimension of the filter as nxn, then we have the following: \begin{itemize} \item Number of Adders = $n^2$ \item Number of Multipliers = $n$ \item Size of the Cache Shift Register = $n^2$ \item Multiplexer would have $n$ inputs and $1$ output. \item Select signal from the Output Controller would be 3 bits for 5x5 and 7x7, and 4 bits for 9x9 filter. \end{itemize} In addition the synchronization of the Input and the Output Controllers would change due to the number of clock cycles required to get $n$ new pixels from the memory and compute the output for $n$ pixels at a time. This means the cases described in section \ref{sec:memreadwrite} would now be the following for the $n*n$ filter: \begin{itemize} \item Number of cycles taken for the Input Controller to read pixels due to the filter movement (horizontal or vertical): $n$. \item Number of cycles taken for the Output Controller to read and write $n$ new pixels to the output memory: $3*n$, since there are three states for every pixel, namely, read, idle and write. \item Number of cycles for which the Output Controller waits in the case when the horizontal movement shifts to the next row or the vertical movement shifts to the next column: [($n$ + $3*n$) + ($n$ + $3*n$) + .. $(n-1) times$ .. + ($n$ + $3*n$)] + $n$, which is $4*n^2 - 3*n$. \end{itemize} \item It is assumed that the filter is symmetric along the two dimensional x and y axes. We need this since the indices of the filter which need to be multiplied with the image pixels would change in horizontal and vertical movements. For simplicity therefore, we have made this assumption. The solution to this problem is quite simple though. We just need to have separate caches in the processor which hold the filter values in a different order. For horizontal movement we would use one cache, while the other one would be used for the vertical movement. \item The mechanism which we have designed for the accessing the memory is ofcourse not the best way. Since we began the implementation with the sequence explained in the section \ref{sec:memoryaccess}, we did not change it later. Though, we realized that this is not an efficient way, since it consumes a high number of clock cycles in order to run through the entire image of 256x256 pixels. \end{enumerate} \newpage \section{VHDL Implementation Files} \label{section:impl} Following are the VHDL files which are core to the project. In addition we have a lot of test benches, which we have created to test the individual components. These extra files (along with the core files) are provided in the ZIP archive. \lstinputlisting[frame=trbl,caption={Memory.vhd}]{../code/Memory.vhd} \newpage \lstinputlisting[frame=trbl, caption={FSM\_in.vhd}]{../code/FSM_in.vhd} \newpage \lstinputlisting[frame=trbl, caption={FSM\_out.vhd}]{../code/FSM_out.vhd} \lstinputlisting[frame=trbl,caption={REG.vhd}]{../code/REG.vhd} \newpage \lstinputlisting[frame=trbl,caption={SHIFTREG.vhd}]{../code/SHIFTREG.vhd} \newpage \lstinputlisting[frame=trbl, caption={CRA\_15.vhd}]{../code/CRA_15.vhd} \newpage \lstinputlisting[frame=trbl, caption={CSA\_15bit.vhd}]{../code/CSA_15bit.vhd} \newpage \lstinputlisting[frame=trbl,caption={parcial.vhd}]{../code/parcial.vhd} \newpage \lstinputlisting[frame=trbl,caption={Multiplier.vhd}]{../code/Multiplier.vhd} \newpage \lstinputlisting[frame=trbl, caption={Adder\_2.vhd}]{../code/Adder_2.vhd} \newpage \lstinputlisting[frame=trbl, caption={Adder\_3.vhd}]{../code/Adder_3.vhd} \newpage \lstinputlisting[frame=trbl, caption={MUX\_4.vhd}]{../code/MUX_4.vhd} \newpage \lstinputlisting[frame=trbl,caption={Processor\_3.vhd}]{../code/Processor_3.vhd} \newpage \lstinputlisting[frame=trbl,caption={TB\_filter.vhd}]{../code/TB_filter.vhd} \newpage Following are the Reports from Synopsys. \lstinputlisting[frame=trbl, caption={Area 2 ns}]{../Reports/area2ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Area 3 ns}]{../Reports/area3ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Area 5 ns}]{../Reports/area5ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Area 7 ns}]{../Reports/area7ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Total Power 2 ns}]{../Reports/power2ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Total Power 3 ns}]{../Reports/power3ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Total Power 5 ns}]{../Reports/power5ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Total Power 7 ns}]{../Reports/power7ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Power Breakdown 2 ns}]{../Reports/power_breakdown2ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Power Breakdown 3 ns}]{../Reports/power_breakdown3ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Power Breakdown 5 ns}]{../Reports/power_breakdown5ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Power Breakdown 7 ns}]{../Reports/power_breakdown7ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Timing 2 ns}]{../Reports/timing2ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Timing 3 ns}]{../Reports/timing3ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Timing 5 ns}]{../Reports/timing5ns.txt} \newpage \lstinputlisting[frame=trbl, caption={Timing 7 ns}]{../Reports/timing7ns.txt} \end{document}
02207-work-groupdt07
trunk/Project/Final report/dt07_report.tex
TeX
lgpl
31,406
package fracPackage; import java.awt.*; public class ColorScheme { public Color[] colorArr; public ColorScheme() { } public Color color(int nIter) { int red = (int)Math.round(-120*Math.cos(nIter/6.) + 120); int green = (int)Math.round(-120*Math.cos(nIter/6. + 1.04) + 120); int blue = (int)Math.round(-120*Math.cos(nIter/6. + 2.08) + 120); return new Color(red, green, blue); } }
121-fractal-builder
ColorScheme.java
Java
gpl3
438
package fracPackage; import java.awt.*; public class FractalPoint extends pObject { private double x, y; private int nIter; private Iteration pIter; public FractalPoint(int i0, int j0, double x0, double y0, Iteration iter) { super(x0, y0); x = x0; y = y0; nIter = 0; pIter = iter; } public int nIter() { return nIter; } public boolean isOut() { return super.isOut(pIter, x, y); } public void iterate(int n) { int i = 0; while (i < n && !isOut()) { i++; super.iterate(pIter, x, y); } nIter += i; } public Color color(ColorScheme cSchm) { if (isOut()) return cSchm.color(nIter); return Color.black; } }
121-fractal-builder
FractalPoint.java
Java
gpl3
710
package fracPackage; public class pObject{ private double re, im; public pObject(double x, double y) { re = 0; im = 0; } public void iterate (Iteration iter, double x, double y) { double oldRe = re; re = re*re - im*im + x; im = 2*im*oldRe + y; } public boolean isOut (Iteration iter, double x, double y) { return re*re + im*im > 4; } }
121-fractal-builder
trunk/PolishNotation/src/fracPackage/pObject.java
Java
gpl3
382
<HTML> <BODY> <table align='center' width = "390" border = "0"> <tr> <td> Пусть F(z)— многочлен, z—комплексное число. Рассмотрим следующую последовательность: <br /> z<sub>0</sub>, z<sub>1</sub> = F(z<sub>0</sub>), z<sub>2</sub> = F(F(z<sub>0</sub>)) = F(z<sub>1</sub>), <br/> z<sub>3</sub>=F(F(F(z<sub>0</sub>))) = F(z<sub>2</sub>) ... <br /> <b>Множество Мандельброта </b>— это множество всех c ϵ ₵, при которых {z<sub>n</sub>} для F(z)=z<sub>2</sub> +c и z<sub>0</sub> не стремится к бесконечности. <br /> <b> Множество Жюлиа </b> — это множество тех значений z<sub>0</sub>, для которых поведение последовательности {z<sub>n</sub>} может резко меняться при сколь угодно малых изменениях z<sub>0</sub>. <br /> Данная программа строит множество Мандельброта по заданной функции и для любой выбранной Вами точки рисует множество Жюлиа. </td> </tr> </table> </BODY> </HTML>
121-fractal-builder
trunk/Mandelbrot/programm.html
HTML
gpl3
1,268
package fracPackage; import java.awt.*; public class ColorScheme { public Color[] colorArr; public double alpha = 0; public double betta = 0; public double gamma = 0; public ColorScheme() { } public ColorScheme(double phi) { if(phi<10){ this.alpha = phi*0.628; } else if(phi<20){ this.betta = phi*0.628; } else { this.gamma = phi*0.628; } } public Color color(int nIter) { int red = (int)Math.round(-125*(Math.cos(nIter/6.+ alpha + 2* betta)) + 125); int green = (int)Math.round(-125*(Math.cos(nIter/6. + 1.04 + 2* alpha + gamma)) + 125); int blue = (int)Math.round(-125*(Math.cos(nIter/6. + 2.08 + betta +2*gamma)) + 125); return new Color(red, green, blue); } }
121-fractal-builder
trunk/Mandelbrot/src/fracPackage/ColorScheme.java
Java
gpl3
765
/*package fracPackage; import javax.swing.*; import java.awt.*; import java.awt.image.*; import java.awt.event.*; public class rawDraw extends JFrame implements KeyListener { UserMenu usrMenu; public rawDraw() { super("RawMandelbrot"); addKeyListener(this); usrMenu = new UserMenu(this); SwingComponent swComp = new SwingComponent(usrMenu); setDefaultCloseOperation(EXIT_ON_CLOSE); getContentPane().add(swComp); setSize(600, 600); setVisible(true); } class SwingComponent extends JComponent { UserMenu scFrac; public SwingComponent(UserMenu frac) { scFrac = frac; } public void paintComponent(Graphics g) { FractalObserver frObs = new FractalObserver(); super.paintComponent(g); g.drawImage(scFrac.getImage(),0,0, 600, 600, frObs); } } public static void main(String[] args) { new rawDraw(); } class FractalObserver implements ImageObserver { public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int heigth) { return true; } } public void keyPressed(KeyEvent ke) { int key = ke.getKeyCode(); switch(key) { case KeyEvent.VK_LEFT: usrMenu.moveLeft(); break; case KeyEvent.VK_RIGHT: usrMenu.moveRight(); break; case KeyEvent.VK_UP: usrMenu.moveUp(); break; case KeyEvent.VK_DOWN: usrMenu.moveDown(); break; case KeyEvent.VK_Z: usrMenu.enlarge(); break; case KeyEvent.VK_X: usrMenu.ensmall(); break; } } public void keyReleased(KeyEvent kEv) { } public void keyTyped(KeyEvent kEv) { } }*/
121-fractal-builder
trunk/Mandelbrot/src/fracPackage/rawDraw.java
Java
gpl3
1,676
package fracPackage; import polishNotation.Iteration; public class Message { public int type; public int dx; public int dy; public double chSize; public FractalPoint fPoint; public int i; public int j; public double xLeft; public double xRight; public double yLow; public double yHigh; public int nX; public int nY; public int nIter; public Iteration iter; public ColorScheme cschm; public double a, b; public double ceiling; }
121-fractal-builder
trunk/Mandelbrot/src/fracPackage/Message.java
Java
gpl3
487
package fracPackage; import polishNotation.Iteration; import java.awt.*; public class FractalPoint extends pObject { private double x, y; private int nIter; public FractalPoint(double x0, double y0, Iteration iter, double ceiling) { super(x0, y0, iter, ceiling); x = x0; y = y0; nIter = 0; } public FractalPoint(double x0, double y0, double a, double b, Iteration iter, double ceiling) { super(x0, y0, a, b, iter, ceiling); x = x0; y = y0; nIter = 0; } public FractalPoint(FractalPoint fp) { super(0, 0, null, 5); if(fp!= null) { x = fp.x; y = fp.y; nIter = fp.nIter; } } public double x() { return x; } public double y() { return y; } public int nIter() { return nIter; } public boolean isOut() { return super.isOut(x, y); } public void iterate(int n) { int i = 0; while (i < n && !isOut()) { i++; super.iterate(); } nIter += i; } public Color color(ColorScheme cSchm) { if (isOut()) return cSchm.color(nIter); return Color.black; } public String toString() { return "x: " + x + " y: " + y + " nIter: " + nIter; } }
121-fractal-builder
trunk/Mandelbrot/src/fracPackage/FractalPoint.java
Java
gpl3
1,220
package fracPackage; import java.awt.*; import polishNotation.Iteration; import polishNotation.PolishNotation; import java.awt.image.*; //--- public class Fractal implements Runnable { Thread computation; static double xLeftDefault = -2; static double xRightDefault = 2; static double yLowDefault = -2; static double yHighDefault = 2; static double aDefault = 0.35; static double bDefault = 0.1; static double ceilingDefault = 2; static int nXDefault = 600; static int nYDefault = 600; static int nIterDefault = 100; static String iterDefault = "z^2 + c"; private SynchrMenu synchr; private double xLeft; private double xRight; private double yLow; private double yHigh; private int nX; private int nY; private int nIter; private ColorScheme cSchm; private Iteration iter; protected double ceiling; protected double a; protected double b; private FractalPoint[][] field; private int nIterCurrent; private BufferedImage img; private Component comp; private AbleToDraw mainWindow; /*---------------------------------------------------------------------------------------------------------------------------------------*/ public Fractal(SynchrMenu Synchr, Component Graph, AbleToDraw mWindow) { computation = new Thread(this, "computation"); xLeft = xLeftDefault; xRight = xRightDefault; yLow = yLowDefault; yHigh = yHighDefault; nX = nXDefault; nY = nYDefault; nIterCurrent = 0; cSchm = new ColorScheme(); PolishNotation pnot = new PolishNotation(iterDefault); pnot.polish(); iter = new Iteration(pnot.outline); nIter = nIterDefault; ceiling = ceilingDefault; synchr = Synchr; mainWindow = mWindow; comp = Graph; newFracField(); img = new BufferedImage(nX, nY, BufferedImage.TYPE_INT_RGB); computation.start(); } /*--------------------------------------------------------------------------------------------------------------*/ public void newFracField() { field = new FractalPoint[nX][nY]; for(int i = 0; i < nX; i++) { double xi = ItoX(i, nX, xLeft, xRight); for(int j = 0; j < nY; j++) { double yj = JtoY(j, nY, yLow, yHigh); field[i][j] = makeField(xi, yj, iter); } } } public FractalPoint makeField(double xi, double yj, Iteration iter) { return new FractalPoint(xi, yj, iter, ceiling); } public void makeNewFractal() { newFracField(); iterateAndDraw(); } public void changeScale (double chSizeParam ) { double xl = xLeft; double xr = xRight; double yl = yLow; double yh = yHigh; xLeft = (xl + xr)/2 - (xr - xl)/2 * chSizeParam; xRight = (xl + xr)/2 + (xr - xl)/2 * chSizeParam; yLow = (yl + yh)/2 - (yh - yl)/2 * chSizeParam; yHigh = (yl + yh)/2 + (yh - yl)/2 * chSizeParam; makeNewFractal(); } /*--------------------------------------------------------------------------------------------------------------*/ public void iterate(int n) { for(int i = 0; i < nX; i++) for(int j = 0; j < nY; j++) field[i][j].iterate(n); nIterCurrent += n; } public void iterateAndDraw() { for(int j = 0; j < nY; j++) { if(synchr.watchMessage()) return; for(int i = 0; i < nX; i++) { field[i][j].iterate(nIter); } if(j % (nY/6 + 1) == 0 || j == nY - 1) draw(j + 1); } nIterCurrent = nIter; } /*--------------------------------------------------------------------------------------------------------------*/ public FractalPoint pointXY(double x, double y) { int i, j; i = XtoI(x, nX, xLeft, xRight); j = YtoJ(y, nY, yLow , yHigh ); return field[i][j]; } /*--------------------------------------------------------------------------------------------------------------*/ public void draw() { draw(nY); } public void draw(int height) { img = new BufferedImage(nX, nY, BufferedImage.TYPE_INT_RGB); Graphics2D graph = img.createGraphics(); for(int i = 0; i < nX; i ++) for(int j = 0; j < height; j++) { graph.setColor(field[i][j].color(cSchm)); graph.drawLine(i,j,i,j); } graph.setColor(Color.LIGHT_GRAY); graph.fillRect(0, height, nX, nY - height); comp.repaint(); } public void moveX(int dnX) { int i, j; if(dnX == 0) return; else if(dnX < 0) { for(i = nX - 1; i >= -dnX; i--) for(j = 0; j < nY; j++) field[i][j] = field[i + dnX][j]; for(i = 0; i < -dnX; i++) for(j = 0; j < nY; j++) { double x,y; x = ItoX(i + dnX, nX, xLeft, xRight); y = JtoY(j, nY, yLow, yHigh); field[i][j] = makeField(x,y, iter); field[i][j].iterate(nIter); } } else { for(i = 0; i < nX - dnX; i++) for(j = 0; j < nY; j++) field[i][j] = field[i + dnX][j]; for(i = nX - dnX; i < nX; i++) for(j = 0; j < nY; j++) { double x,y; x = ItoX(i + dnX, nX, xLeft, xRight); y = JtoY(j, nY, yLow, yHigh); field[i][j] = makeField(x,y, iter); field[i][j].iterate(nIter); } } double xLeftOld = xLeft; xLeft = ItoX(0 + dnX, nX, xLeftOld, xRight); xRight = ItoX(nX + dnX, nX, xLeftOld, xRight); draw(nY); } public void moveY(int dnY) { int i, j; if(dnY == 0) return; else if(dnY > 0) { for(i = 0; i < nX; i++) for(j = nY - 1; j >= dnY; j--) field[i][j] = field[i][j - dnY]; for(i = 0; i < nX; i++) for(j = 0; j < dnY; j++) { double x,y; x = ItoX(i , nX, xLeft, xRight); y = JtoY(j - dnY, nY, yLow, yHigh); field[i][j] = makeField(x,y, iter); field[i][j].iterate(nIter); } } else { for(i = 0; i < nX; i++) for(j = 0; j < nY + dnY; j++) field[i][j] = field[i][j - dnY]; for(i = 0; i < nX; i++) for(j = nY + dnY; j < nY; j++) { double x,y; x = ItoX(i , nX, xLeft, xRight); y = JtoY(j - dnY, nY, yLow, yHigh); field[i][j] = makeField(x,y, iter); field[i][j].iterate(nIter); } } double yLowOld = yLow; yLow = JtoY(nY - dnY, nY, yLowOld, yHigh); yHigh = JtoY(0 - dnY, nY, yLowOld, yHigh); draw(nY); } public BufferedImage getImage() { return img; } /*----------------------------------------------------------------------------------------------------------------------------------*/ public double getxLeft() { return xLeft; } public double getxRight() { return xRight; } public double getyLow() { return yLow; } public double getyHigh() { return yHigh; } /*------------------------------------------------------------------------------------------------------------------------- *------------------------------------------------------------------------------------------------------------------------- */ public static double ItoX(int i, int NX, double xleft, double xright) { return (xleft*(NX - i) + xright*i)/NX; } public static double JtoY(int j, int NY, double ylow, double yhigh) { return (yhigh*(NY - j) + ylow*j)/NY; } public static int XtoI(double x, int NX, double xleft, double xright) { return (int)Math.round( (x - xleft)/(xright - xleft)*NX ); } public static int YtoJ(double y, int NY, double ylow, double yhigh) { return (int)Math.round( (yhigh - y)/(yhigh - ylow )*NY ); } /*--------------------------------------------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------------------------------------------*/ public void run() { Message message; while( true ) { message = synchr.getMessage(); switch(message.type) { case SynchrMenu.MAKENEWFRACTAL: xLeft = message.xLeft; xRight = message.xRight; yLow = message.yLow; yHigh = message.yHigh; nX = message.nX; nY = message.nY; cSchm = message.cschm; iter = message.iter; nIter = message.nIter; ceiling= message.ceiling; a = message.a; b = message.b; makeNewFractal(); break; case SynchrMenu.MOVEX: moveX(message.dx); break; case SynchrMenu.MOVEY: moveY(message.dy); break; case SynchrMenu.CHANGESCALE: changeScale(message.chSize); break; case SynchrMenu.CHANGECOLOR: cSchm = message.cschm; draw(); break; case SynchrMenu.DRAW: draw(); break; case SynchrMenu.GETPOINT: FractalPoint fp = new FractalPoint( field[message.i][message.j] ); mainWindow.putIterXYdata(fp.x(), fp.y(), fp.nIter()); break; } } } }
121-fractal-builder
trunk/Mandelbrot/src/fracPackage/Fractal.java
Java
gpl3
9,076
package fracPackage; import polishNotation.Iteration; import polishNotation.PolishNotation; import java.util.*; public class SynchrMenu { public static final int NOTHING = -1; public static final int MAKENEWFRACTAL = 0; public static final int CHANGESCALE = 1; public static final int MOVEX = 2; public static final int MOVEY = 3; public static final int CHANGEDATA = 4; public static final int CHANGEITER = 5; public static final int CHANGECOLOR = 6; public static final int DRAW = 7; public static final int GETPOINT = 8; public static final int RENEWDATA = 9; public static final int CHANGEAB = 10; private LinkedList<Message> MessageQueue; private int dx; private int dy; private double chSize; private FractalPoint fPoint; private int i; private int j; private double xLeft; private double xRight; private double yLow; private double yHigh; private int nX; private int nY; private int nIter; private Iteration iter; private ColorScheme cschm; private double a, b; private double ceiling; private int gorizontal; private int vertical; boolean isMessage; boolean isBusy; public SynchrMenu() { xLeft = Fractal.xLeftDefault; xRight = Fractal.xRightDefault; yLow = Fractal.yLowDefault; yHigh = Fractal.yHighDefault; nX = Fractal.nXDefault; nY = Fractal.nYDefault; gorizontal = 600; vertical = 600; a = Fractal.aDefault; b = Fractal.bDefault; ceiling = Fractal.ceilingDefault; nIter = Fractal.nIterDefault; PolishNotation pont = new PolishNotation(Fractal.iterDefault); pont.polish(); iter = new Iteration(pont.outline); cschm = new ColorScheme(0); MessageQueue = new LinkedList<Message>(); isMessage = false; } public void makeNewFractal() { putMessage(MAKENEWFRACTAL); } synchronized private void putMessage(int MessageType) { Message mess = new Message(); mess.type = MessageType; mess.a = a; mess.b = b; mess.i = i; mess.j = j; mess.xLeft = xLeft; mess.xRight = xRight; mess.yLow = yLow; mess.yHigh = yHigh; mess.nX = nX; mess.nY = nY; mess.iter = iter; mess.nIter = nIter; mess.cschm = cschm; mess.dx = dx; mess.dy = dy; mess.chSize = chSize; mess.ceiling = ceiling; MessageQueue.offer(mess); notify(); } synchronized public Message getMessage() { if(MessageQueue.isEmpty()) try { wait(); } catch(InterruptedException e) { } return MessageQueue.poll(); } synchronized public boolean watchMessage() { for( Message msg : MessageQueue ) { if(msg.type == MAKENEWFRACTAL || msg.type == CHANGESCALE) return true; } return false; } //===============================BEFORE, IT WAS USERMENU================================================================= public int setIter(String input) { PolishNotation pnot = new PolishNotation(input); pnot.polish(); iter = new Iteration(pnot.outline); return 0; } public void setColor(double param) { cschm = new ColorScheme(param); putMessage(CHANGECOLOR); } public void setAB(double A, double B) { a = A; b = B; } public void changeScale (double chSizeParam ) { chSize = chSizeParam; double xl = xLeft; double xr = xRight; double yl = yLow; double yh = yHigh; xLeft = (xl + xr)/2 - (xr - xl)/2 * chSizeParam; xRight = (xl + xr)/2 + (xr - xl)/2 * chSizeParam; yLow = (yl + yh)/2 - (yh - yl)/2 * chSizeParam; yHigh = (yl + yh)/2 + (yh - yl)/2 * chSizeParam; putMessage(CHANGESCALE); } public void enlarge () { changeScale(0.6); } public void ensmall () { changeScale(1/0.6); } public void moveX(int dX) { dx = dX; double xLeftOld = xLeft; xLeft = Fractal.ItoX(0 + dx, nX, xLeftOld, xRight); xRight = Fractal.ItoX(nX + dx, nX, xLeftOld, xRight); putMessage(MOVEX); } public void moveY(int dY) { dy = dY; double yLowOld = yLow; yLow = Fractal.JtoY(nY - dy, nY, yLowOld, yHigh); yHigh = Fractal.JtoY(0 - dy, nY, yLowOld, yHigh); putMessage(MOVEY); } public FractalPoint getFPoint(int p, int q) { if(p < 0 || p > gorizontal || q < 0 || q > gorizontal) return null; i = nX*p/gorizontal; j = nY*q/vertical; putMessage(GETPOINT); return fPoint; } public void setDimension(int Size) { gorizontal = vertical = Size; } public int setProperties(String X, String Y, String Size, String nXY, String NIter, String Ceiling) { double x, y, size, ceil; int nxy, niter; try { x = Double .parseDouble(X); y = Double .parseDouble(Y); size = Double .parseDouble(Size); nxy = Integer.parseInt(nXY); niter = Integer.parseInt(NIter); ceil = Double .parseDouble(Ceiling); } catch (NumberFormatException e) { return -1; } if(size <= 2.0E-14 || nxy <= 0 || ceil < 2 || ceil > 1000) return -1; xLeft = x; xRight = x + size; yLow = y - size; yHigh = y; nX = nxy; nY = nxy; nIter = niter; ceiling = ceil; return 0; } public void setDefaultProperties() { xLeft = Fractal.xLeftDefault; xRight = Fractal.xRightDefault; yLow = Fractal.yLowDefault; yHigh = Fractal.yHighDefault; nX = Fractal.nXDefault; nY = Fractal.nYDefault; ceiling = Fractal.ceilingDefault; nIter = Fractal.nIterDefault; } public void moveLeft() { moveX(-nX/15 - 1); } public void moveRight() { moveX( nX/15 + 1); } public void moveUp() { moveY( nY/15 + 1); } public void moveDown() { moveY(-nY/15 - 1); } public double xLeft() { return xLeft; } public double xRight() { return xRight; } public double yLow() { return yLow; } public double yHigh() { return yHigh; } public int nX() { return nX; } public int nY() { return nY; } public int nIter() { return nIter; } public Iteration iter() { return iter; } public ColorScheme cschm() { return cschm; } public int dx() { return dx; } public int dy() { return dy; } public double chSize() { return chSize; } public double a() { return a; } public double b() { return b; } public double ceiling() { return ceiling; } }
121-fractal-builder
trunk/Mandelbrot/src/fracPackage/SynchrMenu.java
Java
gpl3
6,736
package fracPackage; import polishNotation.Complex; import polishNotation.Iteration; public class pObject { Iteration iter; private Complex z; private Complex c; private double ceiling; public pObject(double x, double y, Iteration Iter, double Ceiling) // MANDELBROT { z = new Complex(0,0); c = new Complex(x,y); iter = Iter; ceiling = Ceiling; } public pObject(double x, double y, double a, double b, Iteration Iter, double Ceiling) { z = new Complex(x,y); c = new Complex(a,b); // JULIA iter = Iter; ceiling = Ceiling; } public void iterate () { iter.setZ(z); iter.setC(c); z = new Complex(iter.iterate()); } public boolean isOut (double x, double y) { return z.mod() > ceiling; } }
121-fractal-builder
trunk/Mandelbrot/src/fracPackage/pObject.java
Java
gpl3
767
package fracPackage; public interface AbleToDraw { public void putIterXYdata(double x, double y, int nIter); }
121-fractal-builder
trunk/Mandelbrot/src/fracPackage/AbleToDraw.java
Java
gpl3
120
package fracPackage; import java.awt.Component; import polishNotation.Iteration; public class JuliaFractal extends Fractal { public JuliaFractal(SynchrMenu synchr, Component Graph, AbleToDraw Window) { super(synchr, Graph, Window); a = synchr.a(); b = synchr.b(); } public FractalPoint makeField(double xi, double yj, Iteration iter) { return new FractalPoint(xi, yj, a, b, iter, ceiling); } }
121-fractal-builder
trunk/Mandelbrot/src/fracPackage/JuliaFractal.java
Java
gpl3
433
package polishNotation; public class OperObject extends Operand{ private boolean isOperand; private boolean isOperator; private Operand operand; private char operator; OperObject(boolean nd, boolean tor, Operand o, char c){ //constructors this.isOperand = nd; this.isOperator = tor; this.operand = new Operand(o); this.operator = c; } OperObject(Operand o){ //constructors this.isOperand = true; this.isOperator = false; this.operand = new Operand(o); } OperObject(char c){ //constructors this.isOperand = false; this.isOperator = true; this.operator = c; } public boolean isOperand(){ return isOperand; } public boolean isOperator(){ return isOperator; } public void setOperand(Operand o){ operand.setOperand(o); } public void setOperator(char c){ this.operator = c; } public Operand getOperand(){ return operand; } public char getOperator(){ return operator; } public String toString(){ if(isOperand) return operand.toString(); else if(isOperator) return "operator " + operator; else return "0"; } }
121-fractal-builder
trunk/Mandelbrot/src/polishNotation/OperObject.java
Java
gpl3
1,143
package polishNotation; import java.util.LinkedList; public class PolishNotation{ public LinkedList<OperObject> outline; //fields public LinkedList<OperObject> stack; public String s; public PolishNotation(){ //constructor s = ""; outline = new LinkedList<OperObject>() ; stack = new LinkedList<OperObject>() ; } public PolishNotation(String arg){ //constructor 2 s = arg; outline = new LinkedList<OperObject>() ; stack = new LinkedList<OperObject>() ; } static boolean isDelim(char c) { return c == ' '; } static boolean isZ(char c) { return (c == 'z')||(c == 'Z'); } static boolean isC(char c) { return (c == 'c')||(c == 'C'); } static boolean isBiOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/' || c == '^'; } static boolean isUniOperator(char c) { return c == 's' || c == 'o' || c == 't' || c == 'g' || c == 'e'; } static int priority(char op) { switch (op) { case '(': return 1; case '+': case '-': return 2; case '*': case '/': return 3; case '^': return 4; case 's': case 'o': case 'g': case 't': case 'e': return 5; default: return -1; } } public int analyse(){ int count = 0; int i = 0; boolean biOperatorExpected = false; boolean operandExpected = true; boolean thereIsZ = false; boolean thereIsC = false; s = s.replace(" ", ""); s = s.replace("(-", "(0-"); s = s.replace("sin", "s"); s = s.replace("cos", "o"); s = s.replace("ctg", "g"); s = s.replace("tg", "t"); s = s.replace("exp", "e"); while(i < s.length()) { char b = s.charAt(i); if (! Character.isDigit(b) && !(b == '.')&& !(b == 'i') &&!isBiOperator(b) && !isUniOperator(b) && !(b == '(') && !( b== ')') && !(isZ(b)) && !(isC(b))){ return -1; } ++i; } i = 0; while(i < s.length()) { char b = s.charAt(i); if (Character.isDigit(b)){ if(operandExpected == false){ return -1; } while(i < s.length()-1 && (Character.isDigit(s.charAt(i+1)) || (s.charAt(i+1) == '.') )){ ++i; b = s.charAt(i); } biOperatorExpected = true; operandExpected = false; } if (b == 'i'){ if(i<=1 || ! Character.isDigit(s.charAt(i-1))){ return -1; } } if (isBiOperator(b)){ if(biOperatorExpected == false){ return -1; } biOperatorExpected = false; operandExpected = true; if (b == '^'){ int j = i+1; char h = s.charAt(j); if(h == '('){ int hCount = 1; while( hCount >0 && !isZ(h) && !isC(h) &&!(h == '/')&& !(h == '.') && j < s.length() ) { j++; h = s.charAt(j); if(h == '(') hCount++; if(h == ')') hCount--; System.out.println(h); } if (h == '.' || h == '/' || isZ(h) || isC(h)){ return -1; } } else { while( !isZ(h) && !isC(h) && !(h == '.')&& !(h == '/') && !isBiOperator(h) && !isUniOperator(h) && j < s.length() ) { j++; h = s.charAt(j); } if (h == '.' ||h == '/' || isZ(h) || isC(h)){ return -1; } } } } if (isUniOperator(b)){ if(operandExpected == false){ return -1; } } if(b == '('){ ++count; if(biOperatorExpected == true){ return -1; } } if( b== ')'){ --count; if(operandExpected == true){ return -1; } } if (isZ(b)) { if(operandExpected == false){ return -1; } biOperatorExpected = true; operandExpected = false; thereIsZ = true; } if (isC(b)) { if(biOperatorExpected == true){ return -1; } biOperatorExpected = true; operandExpected = false; thereIsC = true; } if(count<0){ return -1; } ++i; } if (!thereIsZ || !thereIsC){ return -1; } if(count != 0){ return -1; } else { return 1; } } public int polish() { for (int i = 0; i < s.length(); i++) { char b = s.charAt(i); if(b== '('){ stack.add(new OperObject(b)); } else if( b== ')'){ while(!stack.isEmpty() && !(stack.getLast().getOperator() == '(')){ OperObject op = stack.removeLast(); if(!(op.getOperator() == '(')){ outline.add(op); } } stack.removeLast(); } else if (isBiOperator(b)){ while(!stack.isEmpty() && (priority(stack.getLast().getOperator()) >= priority(b))){ OperObject op = stack.removeLast(); outline.add(op); } stack.add(new OperObject(b)); } else if (isUniOperator(b)){ while(!stack.isEmpty() && (priority(stack.getLast().getOperator()) >= priority(b))){ OperObject op = stack.removeLast(); outline.add(op); } stack.add(new OperObject(b)); } else if (isZ(b)) { outline.add(new OperObject(new Operand('z'))); } else if (isC(b)) { outline.add(new OperObject(new Operand('c'))); } else if(Character.isDigit(s.charAt(i))){ String number = ""; while (i < s.length() && (Character.isDigit(s.charAt(i)) || (s.charAt(i)== '.') || (s.charAt(i)== 'i'))) number += s.charAt(i++); --i; Complex a; if(s.charAt(i)== 'i'){ number = number.replace("i", ""); a = new Complex(0,Double.parseDouble(number)); }else { a = new Complex(Double.parseDouble(number)); } Operand oper = new Operand(a); OperObject toadd = new OperObject(oper); outline.add(toadd); } } while(!stack.isEmpty()){ OperObject sign = stack.removeLast(); if(! (sign.getOperator() == '(') && !(sign.getOperator() == ')')){ outline.add(sign); } } return 1; } }
121-fractal-builder
trunk/Mandelbrot/src/polishNotation/PolishNotation.java
Java
gpl3
6,495
package polishNotation; public class Complex { private static final double EPS = 1e-12; // accuracy private double re, im; public Complex(double re, double im) { // constructors this.re = re; this.im = im; } public Complex(double re){ this(re, 0.0); } public Complex(){ this(0.0, 0.0); } public Complex(Complex z){ this(z.getRe(), z.getIm()) ; } // access public double getRe(){ return re; } public double getIm(){ return im; } public Complex getZ(){ return this; } public void setRe(double re){this.re = re;} public void setIm(double im){this.im = im;} public void setZ(Complex z){re = z.getRe(); im = z.getIm();} // mod and arg public double mod(){ return Math.sqrt(re * re + im * im); } public double arg(){ return Math.atan2(im, re); } public boolean isReal(){ return Math.abs(im) < EPS; } // methods of class Object public boolean equals(Complex z){ return Math.abs(re -z.re) < EPS && Math.abs(im - z.im) < EPS; } public String toString(){ return "Complex: " + re + " " + im; } public void mul(Complex z){ //*= double t = re * z.re - im * z.im; im = re * z.im + im * z.re; re = t; } public Complex plus(Complex z){ // + return new Complex(re + z.re, im + z.im); } public Complex minus(Complex z){ //- return new Complex(re - z.re, im - z.im); } public Complex asterisk(Complex z){ // * return new Complex( re * z.re - im * z.im, re * z.im + im * z.re); } public Complex slash(Complex z){ // / double m = z.mod(); return new Complex( (re * z.re + im * z.im) / m /m, (im * z.re - re * z.im) / m /m); } public Complex pow(double n){ // ^ in real power if( ((int)n == n ) && n > 0){ Complex result = new Complex(this); int i=1; while(i < n){ result.mul(this); ++i; } return result; }else{ return new Complex(); } } public Complex exp(){ // exponenta return new Complex(Math.exp(re)* Math.cos(im) , Math.exp(re)* Math.sin(im)); } public Complex cos(){ // cos Complex a = new Complex(0.5); Complex b = new Complex(-im, re); Complex c = new Complex(im, -re); if(((b.exp()).plus(c.exp())).asterisk(a).mod() <EPS ){ return new Complex(); } else return new Complex( ((b.exp()).plus(c.exp())).asterisk(a)); } public Complex sin(){ // sin Complex a = new Complex(0, -0.5); Complex b = new Complex(-im, re); Complex c = new Complex(im, -re); if(((b.exp()).minus(c.exp())).asterisk(a).mod() <EPS ){ return new Complex(); } else return new Complex( ((b.exp()).minus(c.exp())).asterisk(a)); } public Complex tan(){ // tan return new Complex( this.sin().slash(this.cos())); } public Complex cotan(){ // cotan return new Complex( this.cos().slash(this.sin())); } }
121-fractal-builder
trunk/Mandelbrot/src/polishNotation/Complex.java
Java
gpl3
3,217
package polishNotation; public class Operand extends Complex{ private boolean isNumber; private boolean isZ; private boolean isC; private Complex value; Operand(){ //constructors this.isNumber = true; this.isZ = false; this.isC = false; this.value = new Complex(); } public Operand(boolean n, boolean z, boolean c, Complex val){ //constructors this.isNumber = n; this.isZ = z; this.isC = c; this.value = new Complex(val); } public Operand(Operand op){ //constructors this.isNumber = op.isNumber; this.isZ = op.isZ; this.isC = op.isC; this.value = new Complex(op.value); } public Operand(double re, double im){ //constructors this.isNumber = true; this.isZ = false; this.isC = false; this.value.setRe(re); this.value.setIm(im); } public Operand(Complex z){ //constructors this.isNumber = true; this.isZ = false; this.isC = false; this.value = new Complex(z); } public Operand(Complex z, Character c){ isNumber = false; if(c == 'c' || c == 'C') { isC = true; isZ = false; } if(c == 'z' || c == 'Z') { isZ = true; isC = false; } value = new Complex(z); } public Operand(Character c){ this(new Complex(),c); } public boolean isZ(){ return isZ; } public boolean isC(){ return isC; } public boolean isNumber(){ return isNumber; } public void setValue(Complex a){ value.setZ(a); } public Complex getValue(){ return value; } public void setOperand(boolean n, boolean z, boolean c, Complex val){ //constructors this.isNumber = n; this.isZ = z; this.isC = c; this.value = new Complex(val); } public void setOperand(Operand o){ //constructors this.setOperand(o.isNumber, o.isZ, o.isC, o.value); } // +, -, *, /, ^ public Operand plus(Operand z){ // + return new Operand(this.value.plus(z.value)); } public Operand minus(Operand z){ //- return new Operand(this.value.minus(z.value)); } public Operand asterisk(Operand z){ //* return new Operand(this.value.asterisk(z.value)); } public Operand slash(Operand z){ // * return new Operand(this.value.slash(z.value)); } public Operand pow(Operand z){ //- return new Operand(this.value.pow(z.value.getRe())); } public Operand exp(){ // exponenta return new Operand(this.value.exp()); } public Operand cos(){ // cos return new Operand(this.value.cos()); } public Operand sin(){ // sin return new Operand(this.value.sin()); } public Operand tan(){ // tan return new Operand(this.value.tan()); } public Operand cotan(){ // cotan return new Operand(this.value.cotan()); } public String toString(){ if(isNumber) return value.toString(); else if(isZ) return "z"; else if(isC) return "c"; else return "" + isNumber + isZ + isC + value; } }
121-fractal-builder
trunk/Mandelbrot/src/polishNotation/Operand.java
Java
gpl3
2,954
package polishNotation; import java.util.LinkedList; //import java.util.LinkedList; public class Iteration{ public LinkedList<OperObject> outline; public Complex z; public Complex c; public Iteration(){ z = new Complex(); c = new Complex(); this.outline = new LinkedList<OperObject>(); } public Iteration(Complex z, Complex c){ this.z = new Complex(z); this.c = new Complex(c); this.outline = new LinkedList<OperObject>(); } public Iteration(LinkedList<OperObject> iter, Complex z, Complex c){ this.z = new Complex(z); this.c = new Complex(c); this.outline = new LinkedList<OperObject>(iter); } public Iteration(Iteration a){ this.z = new Complex(a.z); this.c = new Complex(a.c); this.outline = new LinkedList<OperObject>(a.outline); } public Iteration(LinkedList<OperObject> iter){ this.z = new Complex(); this.c = new Complex(); this.outline = new LinkedList<OperObject>(iter); } public void setZ(Complex z){ this.z = new Complex(z); } public void setC(Complex c){ this.c = new Complex(c); } public Complex iterate(){ LinkedList<OperObject> line = new LinkedList<OperObject>(outline); LinkedList<Operand> st = new LinkedList<Operand>(); while(!line.isEmpty()){ OperObject op = line.removeFirst(); if (op.isOperand()){ if (op.getOperand().isZ()){ op.getOperand().setOperand(false, true, false, z); st.add(new Operand(op.getOperand().getValue())); } else if (op.getOperand().isC()){ op.getOperand().setOperand(false, false, true, c); st.add(new Operand(op.getOperand().getValue())); } else st.add(op.getOperand()); } if (op.isOperator()){ if (PolishNotation.isBiOperator(op.getOperator())){ Operand r = st.removeLast(); Operand l = st.removeLast(); switch (op.getOperator()) { case '+': st.add(l.plus(r)); break; case '-': st.add(l.minus(r)); break; case '*': st.add(l.asterisk(r)); break; case '/': st.add(l.slash(r)); break; case '^': st.add(l.pow(r)); break; } } if (PolishNotation.isUniOperator(op.getOperator())){ Operand r = st.removeLast(); switch (op.getOperator()) { case 's': st.add(r.sin()); break; case 'o': st.add(r.cos()); break; case 't': st.add(r.tan()); break; case 'g': st.add(r.cotan()); break; case 'e': st.add(r.exp()); break; } } } } Complex result = new Complex(st.removeLast().getValue()); return result; } }
121-fractal-builder
trunk/Mandelbrot/src/polishNotation/Iteration.java
Java
gpl3
2,813
package main_interface; import java.awt.Image; import java.awt.image.ImageObserver; public class FractalObserver implements ImageObserver { public boolean imageUpdate(Image img,int infoflags,int x,int y, int width, int heith){ return true; } }
121-fractal-builder
trunk/Mandelbrot/src/main_interface/FractalObserver.java
Java
gpl3
250
package main_interface; import java.awt.BorderLayout; import java.awt.Dimension; import java.io.File; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextPane; import javax.swing.ScrollPaneConstants; public class helpWindow extends JFrame{ public JEditorPane editor; public JEditorPane editor0; public void MakeAll(JEditorPane e1, JEditorPane e2) { JFrame frame = new JFrame(); frame.setName("Help"); frame.pack(); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); JPanel icon = new JPanel(); icon.setLayout(new BorderLayout()); JLabel us = new JLabel(new ImageIcon("fill-color.png")); us.setOpaque(false); icon.setPreferredSize(new Dimension(400,50)); icon.add(us,BorderLayout.WEST); JPanel other = new JPanel(); other.setLayout(new BorderLayout()); JTabbedPane tabPanel = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT); JPanel tab1 = new JPanel(new BorderLayout(0,0)); try{ File homePage0 = new File("programm.html"); String path0 = homePage0.getAbsolutePath(); e1 = new JEditorPane("file://"+path0); } catch (Exception ex) { } e1.setContentType("text/html"); e1.setEditable(false); tab1.add(e1); tab1.setPreferredSize(new Dimension(400,650)); tabPanel.addTab("О программе",tab1); JPanel tab2 = new JPanel(new BorderLayout(0,0)); try{ File homePage = new File("instuction.html"); String path = homePage.getAbsolutePath(); e2 = new JEditorPane("file://"+path); } catch (Exception ex) { } e2.setContentType("text/html"); e2.setEditable(false); JScrollPane scroll = new JScrollPane(e2); tab2.add(scroll); tabPanel.addTab("Инструкция",tab2); other.add(tabPanel,BorderLayout.CENTER); frame.add(icon, BorderLayout.NORTH); frame.add(other,BorderLayout.CENTER); frame.setSize(420,470); frame.setTitle("Help"); //frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setAlwaysOnTop(true); frame.setVisible(true); } }
121-fractal-builder
trunk/Mandelbrot/src/main_interface/helpWindow.java
Java
gpl3
2,210
package main_interface; import javax.swing.filechooser.FileFilter; public class JpgFilesFilter extends FileFilter { public boolean accept(java.io.File file) { if ( file.isDirectory() ) return true; return ( file.getName().endsWith("jpg")) ; } public String getDescription() { return "Изображения (*.jpg)"; } }
121-fractal-builder
trunk/Mandelbrot/src/main_interface/JpgFilesFilter.java
Java
gpl3
336
package main_interface; import javax.swing.filechooser.FileFilter; public class PngFilesFilter extends FileFilter { public boolean accept(java.io.File file) { if ( file.isDirectory() ) return true; return ( file.getName().endsWith("png")) ; } public String getDescription() { return "Изображения (*.png)"; } }
121-fractal-builder
trunk/Mandelbrot/src/main_interface/PngFilesFilter.java
Java
gpl3
335
package main_interface; import javax.swing.filechooser.FileFilter; public class TextFilesFilter extends FileFilter { public boolean accept(java.io.File file) { if ( file.isDirectory() ) return true; return ( file.getName().endsWith(".frac") ); } public String getDescription() { return "Фрактал (*.frac)"; } }
121-fractal-builder
trunk/Mandelbrot/src/main_interface/TextFilesFilter.java
Java
gpl3
341
package main_interface; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import fracPackage.SynchrMenu; public class ParametersWin { public JFrame frame; public JPanel pane[]; public JTextField text[]; public void MakeParamWin(final SynchrMenu sm){ frame = new JFrame(); frame.setResizable(false); frame.setSize(new Dimension(320,300)); frame.setAlwaysOnTop(true); JPanel panel = new JPanel(); JPanel pane0 = new JPanel(); pane0.add(new JLabel("Задайте параметры:")); panel.add(pane0); final String label[] = {" Координата X "," Координата Y "," Размер "," Разрешение ","Число итераций", " Бесконечность "}; JLabel[] label0 = new JLabel[label.length]; pane = new JPanel[label.length]; text = new JTextField[label.length]; for (int i=0;i < label.length;++i ){ label0[i] = new JLabel(); label0[i].setText(label[i]); pane[i] = new JPanel(); pane[i].add(label0[i]); text[i] = new JTextField(); text[i].setColumns(6); pane[i].add(text[i]); panel.add(pane[i]); } text[0].setText(""+sm.xLeft()); text[1].setText(""+sm.yHigh()); text[2].setText(""+(sm.xRight() - sm.xLeft())); text[3].setText(""+sm.nX()); text[4].setText(""+sm.nIter()); text[5].setText(""+sm.ceiling()); JButton confirm = new JButton("Применить"); confirm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ if (sm.setProperties(text[0].getText(),text[1].getText(),text[2].getText(),text[3].getText(),text[4].getText(),text[5].getText()) < 0 ){ JOptionPane.showMessageDialog(frame,"Некорректно заполнены поля!", "Ошибка",JOptionPane.WARNING_MESSAGE); return; } sm.makeNewFractal(); frame.dispose(); } }); JButton asItWas = new JButton("По умолчанию"); asItWas.addActionListener(new ActionListener(){ public void actionPerformed( ActionEvent e){ sm.setDefaultProperties(); sm.makeNewFractal(); frame.dispose(); } }); JPanel l = new JPanel(); JPanel l1 = new JPanel(); l.add(confirm); l1.add(asItWas); panel.add(l); panel.add(l1); frame.add(panel); frame.setTitle("Parameters"); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
121-fractal-builder
trunk/Mandelbrot/src/main_interface/ParametersWin.java
Java
gpl3
2,660
package main_interface; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JToolBar; import javax.swing.KeyStroke; import polishNotation.PolishNotation; import main_interface.MainFrame.swComponent; import fracPackage.AbleToDraw; import fracPackage.Fractal; import fracPackage.JuliaFractal; import fracPackage.SynchrMenu; public class JuliaWindow implements AbleToDraw { private JButton savePic; private SynchrMenu synchrMenuJ; JFrame frame= new JFrame(); private JFileChooser fcp; private JpgFilesFilter jpg; private PngFilesFilter png; public JuliaFractal fractalJulia; public JPanel graphJul; private swComponent c; public void MakeJuliaFrame(double a, double b,String s) { final JFrame frame= new JFrame(); frame.setName("Julia"); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); JMenuBar menuBar = new JMenuBar(); savePic = new JButton("Cохранить"); savePic.setFocusable(false); savePic.setOpaque(false); savePic.setContentAreaFilled(false); savePic.setBorderPainted(false); JButton param = new JButton("Параметры"); param.setFocusable(false); param.setOpaque(false); param.setContentAreaFilled(false); param.setBorderPainted(false); param.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ ParametersWin w = new ParametersWin(); w.MakeParamWin(synchrMenuJ); } }); jpg = new JpgFilesFilter(); png = new PngFilesFilter(); fcp = new JFileChooser(); fcp.addChoosableFileFilter(jpg); fcp.addChoosableFileFilter(png); savePic.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fcp.setDialogTitle("Сохранение файла"); fcp.setFileSelectionMode(JFileChooser.FILES_ONLY); int res = fcp.showSaveDialog(frame); if ( res == JFileChooser.APPROVE_OPTION ){ try{ if (fcp.getFileFilter() == jpg) { ImageIO.write(fractalJulia.getImage(), "JPG", new File(fcp.getSelectedFile().getAbsolutePath()+".jpg")); System.out.println(fcp.getSelectedFile().getAbsolutePath()); } else if (fcp.getFileFilter() == png) { ImageIO.write(fractalJulia.getImage(), "PNG", new File(fcp.getSelectedFile().getAbsolutePath()+".png")); System.out.println(fcp.getSelectedFile().getAbsolutePath()); } else { ImageIO.write(fractalJulia.getImage(), "JPG", new File(fcp.getSelectedFile().getAbsolutePath()+".jpg")); } } catch (IOException ie) { ie.printStackTrace(); } } } }); menuBar.add(savePic); menuBar.add(param); panel.add(menuBar,BorderLayout.NORTH); JPanel picture = new JPanel(); c = new swComponent(); synchrMenuJ = new SynchrMenu(); fractalJulia = new JuliaFractal (synchrMenuJ, c, this); synchrMenuJ.setAB(a,b); PolishNotation pol = new PolishNotation(s); synchrMenuJ.setIter(pol.s); synchrMenuJ.makeNewFractal(); c.setPreferredSize(new Dimension(600, 600)); picture.add(c, BorderLayout.CENTER); picture.add(new JLabel(" "), BorderLayout.NORTH); picture.add(new JLabel(" "), BorderLayout.SOUTH); picture.add(new JLabel(" "), BorderLayout.WEST); picture.setOpaque(false); picture.revalidate(); JToolBar toolbar = new JToolBar("Toolbar",JToolBar.VERTICAL); toolbar.setOpaque(false); toolbar.setFloatable(false); String[] iconFiles = { "zoom-in.png", "zoom-out.png","arrow-left1.png","arrow-right1.png","arrow-up1.png","arrow-down1.png", "fill-color1.png" }; String[] newiconFiles = { "zoom-in2.png", "zoom-out2.png","arrow-left.png","arrow-right.png","arrow-up.png","arrow-down.png", "fill-color.png" }; String[] buttonLabels = { "����������", "��������", "�����","������","�����","����","����"}; ImageIcon[] icons = new ImageIcon[iconFiles.length]; JButton[] buttons = new JButton[buttonLabels.length]; for (int i = 0; i < iconFiles.length; ++i) { icons[i] = new ImageIcon(iconFiles[i]); buttons[i] = new JButton(icons[i]); buttons[i].setFocusPainted(false); buttons[i].setContentAreaFilled(false); buttons[i].setToolTipText(buttonLabels[i]); buttons[i].setOpaque(false); buttons[i].setBorderPainted(false); buttons[i].setRolloverIcon(new ImageIcon(newiconFiles[i])); toolbar.add(buttons[i]); } buttons[1].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { synchrMenuJ.ensmall(); c.repaint(); } }); buttons[0].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { synchrMenuJ.enlarge(); c.repaint(); } }); buttons[2].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { synchrMenuJ.moveLeft(); } }); buttons[4].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { synchrMenuJ.moveUp(); } }); buttons[3].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { synchrMenuJ.moveRight(); } }); buttons[5].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { synchrMenuJ.moveDown();; } }); buttons[6].addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ ColorWindow cw = new ColorWindow(); int position = cw.getPosition(1); cw.MakeWindow(synchrMenuJ,position,1); } }); panel.add(toolbar,BorderLayout.EAST); panel.add(picture, BorderLayout.CENTER); frame.add(panel); frame.setSize(650,658); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.setVisible(true); } public class swComponent extends JComponent { public void paintComponent(Graphics g) { FractalObserver fObs = new FractalObserver(); super.paintComponent(g); g.drawImage(fractalJulia.getImage(),0,0, c.getHeight(), c.getHeight(),fObs); } } public void putIterXYdata(double x, double y, int nIter) { } }
121-fractal-builder
trunk/Mandelbrot/src/main_interface/JuliaWindow.java
Java
gpl3
6,526
package main_interface; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import fracPackage.SynchrMenu; public class ColorWindow extends JFrame{ private static JSlider slider; private static JFrame frame; public static int result; public static int result0; public void MakeWindow(final SynchrMenu frac, int res,final int a) { frame = new JFrame(); frame.setName("Color"); frame.pack(); JPanel panel = new JPanel(); JLabel shrift = new JLabel("Выберите цветовую гамму"); panel.add(new JLabel(" ")); panel.add(shrift); JLabel bar = new JLabel(new ImageIcon("ColorBar.png")); panel.add(bar); slider = new JSlider(0, 30, 0); slider.setMajorTickSpacing(500); slider.setPaintTicks(true); slider.setValue(res); slider.setValue(res); Dimension d = slider.getPreferredSize(); slider.setPreferredSize(new Dimension(d.width+117,d.height)); panel.add(slider); JButton okey = new JButton("Применить"); okey.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (a == 0 ) { result0 = slider.getValue(); frac.setColor(result0); } else { result = slider.getValue(); frac.setColor(result); } frame.dispose(); } }); panel.add(okey); frame.add(panel); frame.setSize(400,145); frame.setLocationRelativeTo(null); frame.setVisible(true); } public int getPosition(int a){ if (a == 0) return result0; else return result; } }
121-fractal-builder
trunk/Mandelbrot/src/main_interface/ColorWindow.java
Java
gpl3
1,700
package main_interface; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.swing.filechooser.*; import java.awt.AWTKeyStroke; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Image; import java.awt.KeyboardFocusManager; import java.awt.LayoutManager; import java.io.FileReader; import java.util.HashSet; import java.util.Locale; import java.util.Scanner; import javax.swing.border.*; import polishNotation.PolishNotation; import fracPackage.AbleToDraw; import fracPackage.ColorScheme; import fracPackage.Fractal; import fracPackage.JuliaFractal; import fracPackage.FractalPoint; import fracPackage.SynchrMenu; public class MainFrame extends JFrame implements AbleToDraw { private DefaultListModel<String> list_model; private DefaultListModel<String> list_model_favorite; private JList<String> list2; private JList<String> list1; private JpgFilesFilter jpg; private PngFilesFilter png; private TextFilesFilter txt; private JMenuItem delete; private JMenuItem removeAll; private JPopupMenu pm; private JButton[] buttons; public JPanel graph; public JPanel picture; private JFileChooser fc1; private JFileChooser fcp; private JMenuItem savePic; public final JTextField t1,t2,t3; private int i; private JButton param; private int ScreenWidth; private int ScreenHeight; public Fractal fractal; public SynchrMenu synchrMenu; public MainFrame() { super("main_frame"); setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); // setContentPane(new JLabel(new ImageIcon("3.jpg"))); getScreenSize(); setSize((ScreenWidth*25/40),(ScreenHeight*35/40)); setTitle("Mandelbrot ABC"); setLocationRelativeTo(null); JMenuBar menuBar = new JMenuBar(); JMenu file = new JMenu("Файл"); JMenuItem open = new JMenuItem("Открыть избранные"); //make hot key open.setAccelerator(KeyStroke.getKeyStroke("ctrl O")); JMenuItem saveObj = new JMenuItem("Cохранить избранные"); saveObj.setAccelerator(KeyStroke.getKeyStroke("ctrl S")); savePic = new JMenuItem("Cохранить изображение"); savePic.setAccelerator(KeyStroke.getKeyStroke("ctrl P")); file.add(open); file.addSeparator(); file.add(saveObj); file.add(savePic); //the rigth order is important! menuBar.add(file); JButton help = new JButton("Справка"); help.setContentAreaFilled(false); help.setOpaque(false); help.setBorderPainted(false); help.setFocusable(false); help.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { helpWindow u = new helpWindow(); u.editor0 = new JEditorPane(); u.editor = new JEditorPane(); u.MakeAll(u.editor0, u.editor); } }); param = new JButton("Параметры"); param.setOpaque(false); param.setContentAreaFilled(false); param.setBorderPainted(false); param.setEnabled(false); param.setFocusable(false); param.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ParametersWin paramWin = new ParametersWin(); paramWin.MakeParamWin(synchrMenu); } }); menuBar.add(param); menuBar.add(help); setJMenuBar(menuBar); final JTextField smallField; smallField = new JTextField(13); t1 = new JTextField(10); t1.setToolTipText("Re(c)"); t2 = new JTextField(10); t2.setToolTipText("Im(c)"); t3 = new JTextField(3); t3.setToolTipText("n - количество итераций до бесконечности"); //табличное колво строк, столбцов, расстояния JPanel grid = new JPanel(new GridLayout(1,1,0,0)); grid.setOpaque(false); // добавляем компоненты JPanel text_button = new JPanel(new FlowLayout(FlowLayout.LEFT)); text_button.setOpaque(false); smallField.setToolTipText("Введите функцию"); text_button.add(new JLabel("f(z) = ")); text_button.add( smallField); JButton draw = new JButton("ОК"); draw.setToolTipText("Нарисовать множество Мандельброта"); text_button.add(draw); ImageIcon favImage = new ImageIcon("bookmarks2.png"); JButton fav = new JButton(favImage); fav.setToolTipText("Добавить в избранное"); fav.setPreferredSize(new Dimension(22,22)); fav.setOpaque(false); fav.setFocusPainted(false); fav.setContentAreaFilled(false); fav.setRolloverIcon(new ImageIcon("bookmarks.png")); fav.setBorderPainted(false); text_button.add(fav); fav.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { check(smallField.getText(),list_model_favorite); } }); grid.add(text_button); // JPanel har_button = new JPanel(new FlowLayout(FlowLayout.LEFT)); // har_button.setOpaque(false); JPanel har = new JPanel(new FlowLayout(FlowLayout.CENTER )); har.setToolTipText("Характеристики выбранной точки"); har.setOpaque(false); har.add(t1); har.add(t2); har.add(t3); text_button.add(har); JButton Julia = new JButton("Жюлиа"); /////Julia Julia.setToolTipText("Нарисовать для точки мн-во Жюлиа"); Julia.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if ((t1.getText().length() > 0) & (t2.getText().length() > 0)) { JuliaWindow julfr = new JuliaWindow(); julfr.MakeJuliaFrame(Double.parseDouble(t1.getText()), Double.parseDouble(t2.getText()),smallField.getText()); } } }); text_button.add(Julia); // grid.add(har_button); picture = new JPanel(); picture.setOpaque(false); picture.setLayout(new BorderLayout()); graph = new JPanel();//// here we add picture of Mandelbrot made my Jenya graph.setOpaque(false); picture.add(graph); /*-----------From Jenya--------------------------------------------------------------------------------------*/ synchrMenu = new SynchrMenu(); fractal = new Fractal(synchrMenu, graph, this); /*-----------------------------------------------------------------------------------------------------------*/ graph.setLayout(new BorderLayout()); graph.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ if(e.getClickCount()==2) { synchrMenu.getFPoint(e.getX(), e.getY()); } } }); graph.setFocusable(true); graph.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseClicked(MouseEvent arg0) { graph.grabFocus(); } }); addKeyBindingLeft(graph); addKeyBindingRight(graph); addKeyBindingUp(graph); addKeyBindingDown(graph); draw.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if ((smallField.getText()).length() > 0 ) { PolishNotation input = new PolishNotation(smallField.getText()); if (input.analyse() < 0){ JOptionPane.showMessageDialog(MainFrame.this, "Проверьте коректность функционального выражения", "Ошибка", JOptionPane.WARNING_MESSAGE); } else { for (int i = 0; i < buttons.length; i++) { buttons[i].setEnabled(true); } param.setEnabled(true); synchrMenu.setDimension(graph.getHeight()); synchrMenu.setIter(input.s); synchrMenu.makeNewFractal(); swComponent sw1 = new swComponent(); graph.add(sw1, BorderLayout.CENTER); picture.revalidate(); } } else JOptionPane.showMessageDialog(MainFrame.this, "Задайте функцию!", "Ошибка", JOptionPane.WARNING_MESSAGE); }}); fc1 = new JFileChooser(); fcp = new JFileChooser(); jpg = new JpgFilesFilter(); png = new PngFilesFilter(); txt = new TextFilesFilter(); fcp.addChoosableFileFilter(jpg); fcp.addChoosableFileFilter(png); savePic.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fcp.setDialogTitle("Сохранение файла"); fcp.setFileSelectionMode(JFileChooser.FILES_ONLY); int res = fcp.showSaveDialog(getContentPane()); if ( res == JFileChooser.APPROVE_OPTION ){ try{ if (fcp.getFileFilter() == jpg) { ImageIO.write(fractal.getImage(), "JPG", new File(fcp.getSelectedFile().getAbsolutePath()+".jpg")); System.out.println(fcp.getSelectedFile().getAbsolutePath()); } else if (fcp.getFileFilter() == png) { ImageIO.write(fractal.getImage(), "PNG", new File(fcp.getSelectedFile().getAbsolutePath()+".png")); System.out.println(fcp.getSelectedFile().getAbsolutePath()); } else{ ImageIO.write(fractal.getImage(), "PNG", new File(fcp.getSelectedFile().getAbsolutePath()+".png")); System.out.println(fcp.getSelectedFile().getAbsolutePath()); } } catch (IOException ie) { ie.printStackTrace(); } } } }); fc1.addChoosableFileFilter(txt); saveObj.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fc1.setDialogTitle("Сохранение избранных"); fc1.setFileSelectionMode(JFileChooser.FILES_ONLY); int res = fc1.showSaveDialog(getContentPane()); if ( res == JFileChooser.APPROVE_OPTION ){ if (list2.getModel().getSize() != 0 ) { try { if (fc1.getFileFilter() == txt ) { FileWriter ryt = new FileWriter(fc1.getSelectedFile().getAbsolutePath()+ ".frac"); BufferedWriter out = new BufferedWriter(ryt); for (int i=0; i < list2.getModel().getSize();i++) { out.write((String)list_model_favorite.get(i)); out.newLine(); } out.close(); } else { FileWriter ryt = new FileWriter(fc1.getSelectedFile().getAbsolutePath()); BufferedWriter out = new BufferedWriter(ryt); for (int i=0; i < list2.getModel().getSize();i++) { out.write((String)list_model_favorite.get(i)); out.newLine(); } out.close(); } } catch (IOException ie) { ie.printStackTrace(); } } } }}); open.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { fc1.setDialogTitle("Открыть"); fc1.setFileSelectionMode(JFileChooser.FILES_ONLY); int res = fc1.showOpenDialog(getContentPane()); if (res == JFileChooser.APPROVE_OPTION) { File set_file = fc1.getSelectedFile(); try{ String selected_func; FileReader selected_file = new FileReader(set_file); BufferedReader reader = new BufferedReader(selected_file); while ((selected_func = reader.readLine()) != null) { check(selected_func,list_model_favorite); } } catch (FileNotFoundException o) { o.printStackTrace(); } catch (IOException o) { o.printStackTrace(); } } }}); smallField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if ((smallField.getText()).length() > 0 ) { PolishNotation input = new PolishNotation(smallField.getText()); if (input.analyse() < 0){ JOptionPane.showMessageDialog(MainFrame.this, "Проверьте коректность функционального выражения", "Ошибка", JOptionPane.WARNING_MESSAGE); } else { synchrMenu.setDimension(graph.getHeight()); synchrMenu.setIter(input.s); synchrMenu.makeNewFractal(); graph.add(new swComponent(), BorderLayout.CENTER); picture.add(graph); picture.revalidate(); } } }}); picture.add(new JLabel(" "), BorderLayout.WEST); picture.add(new JLabel(" "), BorderLayout.SOUTH); picture.add(new JLabel(" "), BorderLayout.NORTH); //////////////////////////////////////////////TOOLBAR JToolBar toolbar = new JToolBar("Toolbar",JToolBar.VERTICAL); toolbar.setOpaque(false); toolbar.setFloatable(false); String[] iconFiles = { "zoom-in.png", "zoom-out.png","arrow-left1.png","arrow-right1.png","arrow-up1.png","arrow-down1.png", "fill-color1.png" }; String[] newiconFiles = { "zoom-in2.png", "zoom-out2.png","arrow-left.png","arrow-right.png","arrow-up.png","arrow-down.png", "fill-color.png" }; String[] buttonLabels = { "Приблизить", "Отдалить", "Влево","Вправо","Вверх","Вниз","Цвет"}; ImageIcon[] icons = new ImageIcon[iconFiles.length]; buttons = new JButton[buttonLabels.length]; for (i = 0; i < iconFiles.length; ++i) { icons[i] = new ImageIcon(iconFiles[i]); buttons[i] = new JButton(icons[i]); buttons[i].setEnabled(false); buttons[i].setFocusPainted(false); buttons[i].setContentAreaFilled(false); buttons[i].setToolTipText(buttonLabels[i]); buttons[i].setOpaque(false); buttons[i].setBorderPainted(false); buttons[i].setRolloverIcon(new ImageIcon(newiconFiles[i])); toolbar.add(buttons[i]); } buttons[0].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { synchrMenu.enlarge(); graph.repaint(); } }); buttons[1].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { synchrMenu.ensmall(); graph.repaint(); } }); buttons[2].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { synchrMenu.moveLeft(); } }); buttons[4].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { synchrMenu.moveUp(); } }); buttons[3].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { synchrMenu.moveRight(); } }); buttons[5].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { synchrMenu.moveDown();; } }); buttons[6].addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ ColorWindow cw = new ColorWindow(); int position = cw.getPosition(0); cw.MakeWindow(synchrMenu, position,0); } }); picture.add(toolbar, BorderLayout.EAST); ////////////////////////////////////////////////// JPanel right = new JPanel(new BorderLayout()); right.setOpaque(false); JPanel left = new JPanel(new GridLayout(2,1)); left.setOpaque(false); list_model = new DefaultListModel<String>(); list_model.add(0,"z*(sin(z))^2 + c"); list_model.add(0,"z*tg(z) + c"); list_model.add(0,"z*(sin(z)-cos(z)) + c"); list_model.add(0,"z*(cos(z))^3 + c"); list_model.add(0,"exp(-z) + c"); list_model.add(0,"z*tg(z) + c"); list_model.add(0,"z*sin(z) + c"); list_model.add(0,"z^8 + z^3 + c"); list_model.add(0,"z^4 + c"); list_model.add(0,"z^3 + c"); list_model.add(0,"z^2 + c"); list_model.add(0,"z + c"); list1 = new JList<String>(list_model); JScrollPane scroll_list1 = new JScrollPane(list1); list1.setBorder(new CompoundBorder(new TitledBorder("Примеры"), new EmptyBorder(1, 1, 1, 1))); scroll_list1.setOpaque(false); scroll_list1.getViewport().setOpaque(false); left.add(scroll_list1); list_model_favorite = new DefaultListModel<String>(); list2 = new JList<String>(list_model_favorite); pm = new JPopupMenu(); delete = new JMenuItem("Удалить"); removeAll = new JMenuItem("Очистить список"); pm.add(delete); pm.add(removeAll); list2.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { if (SwingUtilities.isRightMouseButton(me) && !list2.isSelectionEmpty() && list2.locationToIndex(me.getPoint()) == list2.getSelectedIndex()) { pm.show(list2, me.getX(), me.getY()); } if(me.getClickCount()==2){ if (!list2.isSelectionEmpty() && list2.locationToIndex(me.getPoint()) == list1.getSelectedIndex()) { smallField.setText((String) list_model_favorite.get(list2.getSelectedIndex())); } } } }); list1.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ if(e.getClickCount()==2){ if (!list1.isSelectionEmpty() && list1.locationToIndex(e.getPoint()) == list1.getSelectedIndex()) { smallField.setText((String) list_model.get(list1.getSelectedIndex())); } } } }); list2.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ if(e.getClickCount()==2){ if (!list2.isSelectionEmpty() && list2.locationToIndex(e.getPoint()) == list2.getSelectedIndex()) { smallField.setText((String) list_model_favorite.get(list2.getSelectedIndex())); } } } }); delete.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { System.out.println(list2.getSelectedIndex()); list_model_favorite.remove(list2.getSelectedIndex()); } }); removeAll.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ list_model_favorite.removeAllElements(); } }); JScrollPane scroll_list2 = new JScrollPane(list2); list2.setBorder(new CompoundBorder(new TitledBorder("Избранные"), new EmptyBorder(1, 1, 1, 1))); scroll_list2.setOpaque(false); scroll_list2.getViewport().setOpaque(false); left.add(scroll_list2); JSplitPane splitVertic = new JSplitPane(JSplitPane.VERTICAL_SPLIT); splitVertic.setOpaque(false); splitVertic.setDividerSize(6); splitVertic.setResizeWeight(0.99); splitVertic.setEnabled(false); splitVertic.isContinuousLayout(); splitVertic.setTopComponent(picture); splitVertic.setBottomComponent(grid); JSplitPane splitHorizont = new JSplitPane(); splitHorizont.setOpaque(false); splitHorizont.setEnabled(false); //splitHorizont.setOneTouchExpandable(true); splitHorizont.setDividerSize(8); splitHorizont.isContinuousLayout(); splitHorizont.setDividerLocation(0.2); splitHorizont.setResizeWeight(0.2); splitHorizont.setLeftComponent(left); splitHorizont.setRightComponent(right); right.add(splitVertic); getContentPane().setLayout(new BorderLayout()); getContentPane().add(splitHorizont, BorderLayout.CENTER); /////////////////////////// setVisible(true); } void addKeyBindingLeft(JComponent jc) { jc.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "left pressed"); jc.getActionMap().put("left pressed", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { synchrMenu.moveLeft(); } }); } void addKeyBindingRight(JComponent jc) { jc.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "right pressed"); jc.getActionMap().put("right pressed", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { synchrMenu.moveRight(); } }); } void addKeyBindingUp(JComponent jc) { jc.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "up pressed"); jc.getActionMap().put("up pressed", new AbstractAction() { public void actionPerformed(ActionEvent ae) { synchrMenu.moveUp(); } }); } void addKeyBindingDown(JComponent jc) { jc.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "down pressed"); jc.getActionMap().put("down pressed", new AbstractAction() { @Override public void actionPerformed(ActionEvent ae) { synchrMenu.moveDown(); } }); } public SynchrMenu getFrac(){ return synchrMenu; } //====================================A FUNCTION GETTING THE SCREEN RESOLUTION=========================================== public void getScreenSize() { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); ScreenWidth = screenSize.width; ScreenHeight = screenSize.height; } //====================================================================================================================== public void putIterXYdata(double x, double y, int nIter) { t1.setText("" + x); t2.setText("" + y); t3.setText("" + nIter); t1.setCaretPosition(0); t2.setCaretPosition(0); t3.setCaretPosition(0); } public void check(String a,DefaultListModel<String> list ) { int i; if ( a.length() > 0 ) { int p = list2.getModel().getSize(); if (p == 0 ) list.add(0,a); System.out.println(p); for (i=0;i<p;++i){ if (a.equals((String) list.get(i))){ break; } } if ((i == p) & (p!= 0)) list_model_favorite.add((p),a); } } //======================================================================================================================= public class swComponent extends JComponent { public void paintComponent(Graphics g) { FractalObserver fObs = new FractalObserver(); super.paintComponent(g); g.drawImage(fractal.getImage(),0,0,graph.getSize().height,graph.getSize().height,fObs); } } /////////////////////// public static void main(String[] args) { Locale[] l = Locale.getAvailableLocales(); for (int i = 0; i < l.length; i++) { if(l[i].toString().equals("ru")){ Locale.setDefault(l[i]); break; } } MainFrame win = new MainFrame(); win.setResizable(false); } }
121-fractal-builder
trunk/Mandelbrot/src/main_interface/MainFrame.java
Java
gpl3
22,032
<HTML> <BODY> <table align='center' width = "390" border = "0"> <tr> <td> Главное окошко программы делится на 4 логические части: <br /> 1) главное окошко с рисунком посередине 2) окошко внизу <b> f(z) = </b> предназначено для ввода функции. Функция может содержать арифметические операции +, -, *, /, ^, скобки, тригонометрические функции sin(z), cos(z), tg(z), ctg(z), экспоненту exp(), действительные числа и комплексные числа в формате a+bi. <br /> Если вы видите сообщение об ошибке, проверьте, что <br /> - выражение содержит переменные z и c. <br /> - нет возведения в нецелую степень <br/> - нет посторонних символов <br /> - верно расставлены разделители и скобки. <br /> 3) 2 поля слева. В верхнем поле Вы можете выбрать функцию, из уже заготовленных нами. Нажав кнопку <b>'Добавить в избранное'</b>, Вы можете добавить понравившуюся Вам функцию в свой собстенный список, который может быть скорректирован Вами правой кнопкой мыши. <br /> 4)Справа есть панель инструментов, с помощью которой Вы можете управлять картинкой, а также выбирать цветовую гамму. <br /> Вы можете сохранить картинку и список избранных, а также открыть сохраненный ранее список избранных. Для этого выберете в панеле управления <b>"Файл" </b > -> <b>"Сохранить" </b>,<b> "Открыть"</b>. </td> </tr> </table> <br> <br/> </BODY> </HTML>
121-fractal-builder
trunk/Mandelbrot/instuction.html
HTML
gpl3
2,169
package fracPackage; import java.awt.*; public class FractalPoint extends pObject { private double x, y; private int nIter; private Iteration pIter; public FractalPoint(int i0, int j0, double x0, double y0, Iteration iter) { super(x0, y0); x = x0; y = y0; nIter = 0; pIter = iter; } public int nIter() { return nIter; } public boolean isOut() { return super.isOut(pIter, x, y); } public void iterate(int n) { int i = 0; while (i < n && !isOut()) { i++; super.iterate(pIter, x, y); } nIter += i; } public Color color(ColorScheme cSchm) { if (isOut()) return cSchm.color(nIter); return Color.black; } }
121-fractal-builder
svn/trunk/FractalPoint.java
Java
gpl3
710
#include <QCoreApplication> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); return a.exec(); }
123-3-orlov-maltsev
trunk/orlov1233/untitled11/main.cpp
C++
mit
132
#include <QCoreApplication> #include <iostream> #include <climits> #include <cfloat> #include <cmath> using namespace std; int kvadrat(int a); int main() { cout<<kvadrat(5); return 0; }
123-3-orlov-maltsev
trunk/orlov1233/main.cpp
C++
mit
206
//package com.serial; // //import java.lang.reflect.Array; //import java.util.Arrays; //import java.util.HashMap; // //import android.os.Handler; //import android.util.Log; // //import com.friendlyarm.AndroidSDK.HardwareControler; //import com.mini6410.DataPackage; //import com.mini6410.MainActivity; // //public class SerialServer { // private static final String TAG = "SerialServer"; // // public static final String SERIAL_COM_DEFAULT = "/dev/s3c2410_serial2"; // public static final String SERIAL_COM_0 = "/dev/s3c2410_serial0"; // public static final String SERIAL_COM_1 = "/dev/s3c2410_serial1"; // public static final String SERIAL_COM_2 = "/dev/s3c2410_serial2"; // public static final String SERIAL_COM_3 = "/dev/s3c2410_serial3"; // public static final String SERIAL_COM_4 = "/dev/s3c2410_serial4"; // public static final String SERIAL_COM_5 = "/dev/s3c2410_serial5"; // // public static final long SERIAL_BAUD_RATE_DEFAULT = 115200; // public static final long SERIAL_BAUD_RATE_110 = 110; // public static final long SERIAL_BAUD_RATE_300 = 300; // public static final long SERIAL_BAUD_RATE_600 = 600; // public static final long SERIAL_BAUD_RATE_1200 = 1200; // public static final long SERIAL_BAUD_RATE_2400 = 2400; // public static final long SERIAL_BAUD_RATE_4800 = 4800; //COŨ�� // public static final long SERIAL_BAUD_RATE_9600 = 9600; //�¶Ⱥ�PHֵ // public static final long SERIAL_BAUD_RATE_14400 = 14400; // public static final long SERIAL_BAUD_RATE_19200 = 19200; // public static final long SERIAL_BAUD_RATE_38400 = 38400; // public static final long SERIAL_BAUD_RATE_56000 = 56000; // public static final long SERIAL_BAUD_RATE_57600 = 57600; // public static final long SERIAL_BAUD_RATE_115200 = 115200; // public static final long SERIAL_BAUD_RATE_128000 = 128000; // public static final long SERIAL_BAUD_RATE_256000 = 256000; // // public static final int SERIAL_DATA_BITS_DEFAULT = 8; // public static final int SERIAL_DATA_BITS_5 = 5; // public static final int SERIAL_DATA_BITS_6 = 6; // public static final int SERIAL_DATA_BITS_7 = 7; // public static final int SERIAL_DATA_BITS_8 = 8; // // public static final int SERIAL_STOP_BITS_DEFAULT = 1; // public static final int SERIAL_STOP_BITS_1 = 1; // public static final int SERIAL_STOP_BITS_2 = 2; // // public static final int SERIAL_DATA_SEND_PERIOD_DEFAULT = 500; // public static final int SERIAL_DATA_SEND_PERIOD_500 = 500; // public static final int SERIAL_DATA_SEND_PERIOD_1000 = 1000; // public static final int SERIAL_DATA_SEND_PERIOD_1500 = 1500; // public static final int SERIAL_DATA_SEND_PERIOD_2000 = 2000; // // public static final byte[] SERIAL_COMMAND_GET_VALUE_CO = {(byte) 0x3A, (byte) 0x30, (byte) 0x31, (byte) 0x30, (byte) 0x33, (byte) 0x30,(byte) 0x32,(byte) 0x30, (byte) 0x30, (byte) 0x30, (byte) 0x41,(byte) 0x30,(byte) 0x39, (byte) 0x0D, (byte) 0x0A}; // public static final byte[] SERIAL_COMMAND_GET_VALUE_PH_TEMPERATURE = {(byte) 0x02, (byte) 0x30, (byte) 0x31}; // // // public static final int SERIAL_TYPE_CO = 0; // public static final int SERIAL_TYPE_PH_TEMPERATURE = 1; // // // /* �������BUF�ij��� */ // public static final int SERIAL_BUF_LENGTH_DEFAULT = 20; // // /* CO����Ũ�ȷ������BUF�ij��� */ // public static final int SERIAL_BUF_LENGTH_CO = 16; // // /* PH���¶�ֵ �������BUF�ij��� */ // public static final int SERIAL_BUF_LENGTH_PH_TEMPERATURE = 11; // // private String mdevName; // private long mbaud; // private int mdataBits; // private int mstopBits; // private int mtype; // private int mbuflength; // private byte[] mcommand; // // private HashMap<Byte, Integer> mHashMap = null; // // private DataPackage mDataPackage = null; // private serialServerThread mserialServerThread = null; // // Handler mHandler = null; // // public SerialServer(Handler mHandler){ // this.mHandler = mHandler; // // mdevName = SERIAL_COM_2; // mbaud = SERIAL_BAUD_RATE_115200; // mdataBits = SERIAL_DATA_BITS_8; // mstopBits = SERIAL_STOP_BITS_1; // // mDataPackage = new DataPackage(); // // buildHashMap(); // } // // public SerialServer(Handler mHandler,String devName, long baud, int dataBits, int stopBits){ // this.mHandler = mHandler; // // mdevName = devName; // mbaud = baud; // mdataBits = dataBits; // mstopBits = stopBits; // // mDataPackage = new DataPackage(); // // buildHashMap(); // } // // public void setSerialServerType(int type){ // mtype = type; // // switch (mtype) { // case SERIAL_TYPE_CO: // mbuflength = SERIAL_BUF_LENGTH_CO; // mcommand = SERIAL_COMMAND_GET_VALUE_CO; // break; // case SERIAL_TYPE_PH_TEMPERATURE: // mbuflength = SERIAL_BUF_LENGTH_PH_TEMPERATURE; // mcommand = SERIAL_COMMAND_GET_VALUE_PH_TEMPERATURE; // break; // default: // break; // } // } // // public int getSerialServerType(){ // return mtype; // } // // public void buildHashMap(){ // mHashMap = new HashMap<Byte, Integer>(); // // byte[] mkeys = {(byte)0x30,(byte)0x31,(byte)0x32,(byte)0x33, // (byte)0x34,(byte)0x35,(byte)0x36,(byte)0x37, // (byte)0x38,(byte)0x39,(byte)0x41,(byte)0x42, // (byte)0x43,(byte)0x44,(byte)0x45,(byte)0x46}; // int[] mvalues = {(int)0x0,(int)0x1,(int)0x2,(int)0x3, // (int)0x4,(int)0x5,(int)0x6,(int)0x7, // (int)0x8,(int)0x9,(int)0xA,(int)0xB, // (int)0xC,(int)0xD,(int)0xE,(int)0xF}; // // for(int i = 0; i < mkeys.length;i++){ // mHashMap.put(mkeys[i], mvalues[i]); // // } //} // //public int getValue(byte key){ // int value = 0; // Log.i("~~~~~~~~~~~~~~~~", String.valueOf(value)+"~~~~~~~0000000000~~~~~~~~~"+String.valueOf(key)); // // if (mHashMap != null) { // value = (Integer) mHashMap.get(key); // } // // Log.i("~~~~~~~~~~~~~~~~", String.valueOf(value)+"~~~~~~~~~111111111111~~~~~~~"+String.valueOf(key)); // return value; //} // //public void start(){ // safeStop(); // // mserialServerThread = new serialServerThread(); // mserialServerThread.start(); //} // //public void safeStop(){ // if(mserialServerThread != null && mserialServerThread.isAlive()){ // mserialServerThread.interrupt(); // mserialServerThread.stop = true; // try { // mserialServerThread.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } // mserialServerThread = null; //} // // //public void analyzeData(byte[] buf){ // byte[] mbuf = buf; // //byte[] mbuf ={(byte)0x3A,(byte)0x30,(byte)0x31 ,(byte)0x30 ,(byte)0x33 ,(byte)0x30 ,(byte)0x32 ,(byte)0x30 ,(byte)0x30 ,(byte)0x37 ,(byte)0x32 ,(byte)0x31 ,(byte)0x41 ,(byte)0x0D ,(byte)0x0A ,(byte)0xFF}; // // Log.i("!!!!!!!!!!!!!!", String.valueOf(mbuf[7])+ " "+String.valueOf(mbuf[8])+ " "+String.valueOf(mbuf[9])+ " "+String.valueOf(mbuf[10])); // // switch (mtype) { // case SERIAL_TYPE_CO: // if(mbuf[0] == 0x3A && mbuf[1] == 0x30 && mbuf[2] == 0x31 && // mbuf[3] == 0x30 && mbuf[4] == 0x33 && mbuf[5] == 0x30 && mbuf[6] == 0x32){ // mDataPackage.mgas_concentration = (float) (getValue(mbuf[7])*Math.pow(16, 3)+ getValue(mbuf[8])*Math.pow(16, 2)+ getValue(mbuf[9])*Math.pow(16, 1)+ getValue(mbuf[10])*Math.pow(16, 0)); // } // // break; // case SERIAL_TYPE_PH_TEMPERATURE: // if(mbuf[0] == 0x32 && mbuf[1] == 0x30 && mbuf[2] == 0x31){ // mDataPackage.mph_value = (float) (getValue(mbuf[3])*10 + getValue(mbuf[4])+ getValue(mbuf[5])*0.1 + getValue(mbuf[6])*0.01); // mDataPackage.mwater_temperature = (float) (getValue(mbuf[7])*10 + getValue(mbuf[8])+ getValue(mbuf[9])*0.1); // } // // break; // default: // break; // } //} // // // //public void generateData(){ // float random = (float) Math.random(); // mDataPackage.mgas_concentration = random*10+0; // mDataPackage.mwater_temperature = random*50+0; // mDataPackage.mph_value = (int)(random*14+0); //} // //public void sendData(){ // sendMessage(MainActivity.MSG_GET_DATA_SUCCESS,mtype,0, mDataPackage); //} // //public void sendMessage(int what ){ // if(mHandler != null){ // mHandler.sendMessage(mHandler.obtainMessage(what)); // } //} // //public void sendMessage(int what, Object obj ){ // if(mHandler != null){ // mHandler.sendMessage(mHandler.obtainMessage(what, obj)); // } //} // //public void sendMessage(int what, int arg1,int arg2,Object obj ){ // if(mHandler != null){ // mHandler.sendMessage(mHandler.obtainMessage(what,arg1,arg2,obj)); // } //} // //private class serialServerThread extends Thread{ // volatile boolean stop = false; // private byte[] buf = new byte[mbuflength]; // private byte[] buf1 = new byte[8]; // private byte[] buf2 = new byte[8]; // // private int fd = 0; //�ļ������� // int size = 0; // int ret = 0; // // // @Override // public void run() { // // fd = HardwareControler.openSerialPort(mdevName, mbaud, mdataBits, mstopBits); // // if(fd == -1) // { // Log.e(TAG, "Failed to open the serial port :" + mdevName); // // stop = true; // } // // // while(!stop){ // // //Send Command To Get Data // if(mcommand != null){ // HardwareControler.write(fd, mcommand); // } // // //Check Whether The Serial Port Has Data // ret = HardwareControler.select(fd, 2, 1000*1000); // switch(ret){ // case -1: // Log.e(TAG, "Error occurred when getting data!"); // break; // case 0: // Log.i(TAG, "There is No Data!"); // break; // case 1: // { Arrays.fill(buf,(byte)0); // size = HardwareControler.read(fd, buf, buf.length); // // /*size = HardwareControler.read(fd, buf, buf.length); // for(int i = 0; i < buf.length; i++) // { // size += HardwareControler.read(fd, p, 1); // buf++; // }*/ // // // Log.i("@@@@@@@@@@@", String.valueOf(size)); // if(size == buf.length) // { // //generateData(); // analyzeData(buf); // sendData(); // }else if(size == 0){ // Log.i(TAG, "There is No Data!"); // }else if(size == -1){ // Log.e(TAG, "Error occurred when getting data!"); // }else{ // Log.e(TAG, "Error occurred when getting data!"); // } // } // break; // default: // break; // } // // try { // Thread.sleep( SERIAL_DATA_SEND_PERIOD_500 ); // } catch ( InterruptedException e ) { // e.printStackTrace(); // } // // } // // if(fd != -1) // { // HardwareControler.close(fd); // } // // } //} //}
122569111-test
src/com/serial/SerialServer.java
Java
gpl3
10,572
package com.mini6410.PWM; import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ToggleButton; import com.friendlyarm.AndroidSDK.HardwareControler; import com.mini6410.R; /** * * ClassName:PWMActivity * Reason: PWM Demo * * @author snowdream * @version * @since Ver 1.1 * @Date 2011 2012-03-11 17:21 * * @see */ public class PWMActivity extends Activity implements Button.OnClickListener,ToggleButton.OnCheckedChangeListener{ public static final String TAG = "PWMActivity"; /*PWM频率*/ public static final int PWM_FREQUENCY_1 = 1; public static final int PWM_FREQUENCY_100 = 100; public static final int PWM_FREQUENCY_200 = 200; public static final int PWM_FREQUENCY_500 = 500; public static final int PWM_FREQUENCY_1000 = 1000; public static final int PWM_FREQUENCY_2000 = 2000; public static final int PWM_FREQUENCY_5000 = 5000; public static final int PWM_FREQUENCY_10000 = 10000; /*PWM播放时长*/ public static final int PWM_PLAY_PERIOD_FOR_EVER = -1; public static final int PWM_PLAY_PERIOD_100 = 100; public static final int PWM_PLAY_PERIOD_200 = 200; public static final int PWM_PLAY_PERIOD_300 = 300; public static final int PWM_PLAY_PERIOD_500 = 500; public static final int PWM_PLAY_PERIOD_1000 = 1000; /*PWM播放间隔*/ public static final int PWM_WAIT_PERIOD_100 = 100; public static final int PWM_WAIT_PERIOD_200 = 200; public static final int PWM_WAIT_PERIOD_300 = 300; public static final int PWM_WAIT_PERIOD_500 = 500; public static final int PWM_WAIT_PERIOD_1000 = 1000; /*播放频率*/ public int mfrequency = PWM_FREQUENCY_1000; /*频率改变步长Step*/ public int mfrequencystep = 100; /*播放时长*/ public int mplayperiod = PWM_PLAY_PERIOD_1000; /*播放间隔*/ public int mwaitperiod = PWM_WAIT_PERIOD_1000; /*播放次数*/ public int mplaynum = 20; private boolean mStop = false; private Button mButtonSub = null; private Button mButtonAdd = null; private ToggleButton mToggleButtonStartForEver= null; private ToggleButton mToggleButtonStartForTimes = null; private EditText mEditTextFrequency = null; private EditText mEditTextPlayPeriod = null; private EditText mTextViewWaitPeriod = null; private EditText mEditTextPlayNum = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pwmdemo); initUI(); initData(); } @Override protected void onDestroy() { mStop = true; super.onDestroy(); } /** * * initUI: 初始化UI * * @param * @return * @throws */ public void initUI(){ mButtonSub = (Button)findViewById(R.id.ButtonSUB); mButtonAdd = (Button)findViewById(R.id.ButtonADD); /*按钮监听器,具体实现参考下面的函数:onClick*/ mButtonSub.setOnClickListener(this); mButtonAdd.setOnClickListener(this); mToggleButtonStartForEver= (ToggleButton)findViewById(R.id.ToggleButtonStartForEver); mToggleButtonStartForTimes = (ToggleButton)findViewById(R.id.ToggleButtonStartForTimes); /*开关按钮监听器,具体实现参考下面的函数:onCheckedChanged*/ mToggleButtonStartForEver.setOnCheckedChangeListener(this); mToggleButtonStartForTimes.setOnCheckedChangeListener(this); mEditTextFrequency = (EditText)findViewById(R.id.EditTextFrequency); mEditTextPlayPeriod = (EditText)findViewById(R.id.EditTextPlayPeriod); mTextViewWaitPeriod = (EditText)findViewById(R.id.EditTextWaitPeriod); mEditTextPlayNum = (EditText)findViewById(R.id.EditTextPlayNum); /*EditText监听器,具体实现参考下面的函数:onTextChanged * 主要用于获取更改后最新的数值,下同。 * */ mEditTextFrequency.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub try { mfrequency = Integer.parseInt(mEditTextFrequency.getText().toString()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); mEditTextPlayPeriod.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub try { mplayperiod = Integer.parseInt(mEditTextPlayPeriod.getText().toString()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); mTextViewWaitPeriod.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub try { mwaitperiod = Integer.parseInt(mTextViewWaitPeriod.getText().toString()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); mEditTextPlayNum.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub try { mplaynum = Integer.parseInt(mEditTextPlayNum.getText().toString()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); } /** * * initData: 初始化各个控件的数值 * * @param * @return * @throws */ public void initData(){ mEditTextFrequency.setText(String.valueOf(mfrequency)); mEditTextPlayPeriod.setText(String.valueOf(mplayperiod)); mTextViewWaitPeriod.setText(String.valueOf(mwaitperiod)); mEditTextPlayNum.setText(String.valueOf(mplaynum)); } /** * * onCheckedChanged: 开关按钮监听器。当有开关按钮的状态改变时,响应点击。 * * @param buttonView 改变状态的开关按钮对象; * @param isChecked 该开关按钮是否被选中; * @return * @throws */ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ToggleButton mToggleButton = (ToggleButton)buttonView; switch (mToggleButton.getId()) { case R.id.ToggleButtonStartForEver: if(isChecked){ PWMPlay(mfrequency); }else{ mStop = true; PWMStop(); } break; case R.id.ToggleButtonStartForTimes: if(isChecked){ mStop = false; PWMThread mPWMThread = new PWMThread(); mPWMThread.start(); }else{ mStop = true; } break; default: break; } } /** * * onClick: 按钮监听器。当有按钮被点击时,响应点击。 * * @param v 被点击的按钮对象; * @return * @throws */ public void onClick(View v) { Button mButton = (Button)v; switch (mButton.getId()) { case R.id.ButtonSUB: if(mfrequency <= 1) mfrequency = PWM_FREQUENCY_1; else if(mfrequency == PWM_FREQUENCY_100) mfrequency = PWM_FREQUENCY_1; else mfrequency -= mfrequencystep; mEditTextFrequency.setText(String.valueOf(mfrequency)); break; case R.id.ButtonADD: if(mfrequency <= 1) mfrequency = PWM_FREQUENCY_100; else mfrequency += mfrequencystep; mEditTextFrequency.setText(String.valueOf(mfrequency)); break; default: break; } } /** * * PWMPlay: 启动蜂鸣器 ,并播放。 * * @param frequency 播放频率 * @return true 表示播放成功;否则,表示播放失败。 * @throws */ public boolean PWMPlay(int frequency) { boolean ret = false; int result = -1; result = HardwareControler.PWMPlay(frequency); if(result == 0) ret = true; else ret = false; return ret; } /** * * PWMStop: 停止并关闭蜂鸣器。 * * @param * @return true 表示停止成功;否则,表示停止失败。 * @throws */ public boolean PWMStop(){ boolean ret = false; int result = -1; result = HardwareControler.PWMStop(); if(result == 0) ret = true; else ret = false; return ret; } /** * * PWMThread: PWM播放线程 * * @param * @return * @throws */ public class PWMThread extends Thread{ @Override public void run() { Log.i(TAG, "PWMThread Start"); for(int i = 0 ; i < mplaynum; i++ ) { Log.i(TAG, String.valueOf(i)); if(mStop) { PWMStop(); break; } /*启动蜂鸣器,并使用频率 mfrequency 进行播放*/ PWMPlay(mfrequency); /*等待播放时长 mplayperiod 结束*/ try { sleep(mplayperiod); } catch (InterruptedException e) { e.printStackTrace(); } /*停止蜂鸣器*/ PWMStop(); if(mStop) break; /*等待播放间隔 mwaitperiod 结束*/ try { sleep(mwaitperiod); } catch (InterruptedException e) { e.printStackTrace(); } } Log.i(TAG, "PWMThread Stop"); } } }
122569111-test
src/com/mini6410/PWM/PWMActivity.java
Java
gpl3
9,947
package com.mini6410.EEPROM; import android.os.Handler; import android.util.Log; import com.friendlyarm.AndroidSDK.HardwareControler; public class ReadEEPROM{ private static final String TAG = "WriteEEPROM"; private static final int MAX_LENGTH = 256; //EEPROM最多可存储256个字节数据 Handler mHandler = null; private ReadEEPROMThread mReadEEPROMThread = null; public ReadEEPROM(Handler mHandler){ this.mHandler = mHandler; } public void ReadData(){ safeStop(); mReadEEPROMThread = new ReadEEPROMThread(); mReadEEPROMThread.start(); } public void safeStop(){ if(mReadEEPROMThread != null && mReadEEPROMThread.isAlive()){ mReadEEPROMThread.interrupt(); mReadEEPROMThread.stop = true; try { mReadEEPROMThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } mReadEEPROMThread = null; } public void sendMessage(int what ){ if(mHandler != null){ mHandler.sendMessage(mHandler.obtainMessage(what)); } } public void sendMessage(int what, Object obj ){ if(mHandler != null){ mHandler.sendMessage(mHandler.obtainMessage(what, obj)); } } public void sendMessage(int what, int arg1,int arg2,Object obj ){ if(mHandler != null){ mHandler.sendMessage(mHandler.obtainMessage(what,arg1,arg2,obj)); } } public void sendMessage(int what, int arg1,int arg2 ){ if(mHandler != null){ mHandler.sendMessage(mHandler.obtainMessage(what,arg1,arg2)); } } private class ReadEEPROMThread extends Thread{ volatile boolean stop = false; int fd = 0; int length = 0; int pos = 0; byte data = 0; @Override public void run() { fd = HardwareControler.openI2CDevice(); if(fd == -1) { Log.e(TAG, "Failed to open the I2CDevice !"); stop = true; } length = MAX_LENGTH; while(!stop){ if (pos >= length) { break; } data = (byte)HardwareControler.readByteDataFromI2C(fd, pos); sendMessage(EEPROMActivity.MSG_GET_DATA, data); sendMessage(EEPROMActivity.MSG_UPDATE_UI, pos,length); Log.i(TAG, "readByteDataFromI2C pos: "+ pos); pos++; // try { // Thread.sleep(10); // } catch ( InterruptedException e ) { // e.printStackTrace(); // } } if(fd != -1) { HardwareControler.close(fd); } } } }
122569111-test
src/com/mini6410/EEPROM/ReadEEPROM.java
Java
gpl3
2,434
package com.mini6410.EEPROM; import android.os.Handler; import android.util.Log; import com.friendlyarm.AndroidSDK.HardwareControler; public class WriteEEPROM{ private static final String TAG = "WriteEEPROM"; private static final int MAX_LENGTH = 256; //EEPROM最多可存储256个字节数据 Handler mHandler = null; byte[] mData = null; private WriteEEPROMThread mWriteEEPROMThread = null; public WriteEEPROM(Handler mHandler){ this.mHandler = mHandler; } public void WriteData(byte[] data){ mData = data; safeStop(); mWriteEEPROMThread = new WriteEEPROMThread(); mWriteEEPROMThread.start(); } public void safeStop(){ if(mWriteEEPROMThread != null && mWriteEEPROMThread.isAlive()){ mWriteEEPROMThread.interrupt(); mWriteEEPROMThread.stop = true; try { mWriteEEPROMThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } mWriteEEPROMThread = null; } public void sendMessage(int what ){ if(mHandler != null){ mHandler.sendMessage(mHandler.obtainMessage(what)); } } public void sendMessage(int what, Object obj ){ if(mHandler != null){ mHandler.sendMessage(mHandler.obtainMessage(what, obj)); } } public void sendMessage(int what, int arg1,int arg2,Object obj ){ if(mHandler != null){ mHandler.sendMessage(mHandler.obtainMessage(what,arg1,arg2,obj)); } } public void sendMessage(int what, int arg1,int arg2 ){ if(mHandler != null){ mHandler.sendMessage(mHandler.obtainMessage(what,arg1,arg2)); } } private class WriteEEPROMThread extends Thread{ volatile boolean stop = false; int fd = 0; int length = 0; int pos = 0; @Override public void run() { if(mData == null){ Log.e(TAG, "There is No Data!"); stop = true; } fd = HardwareControler.openI2CDevice(); if(fd == -1) { Log.e(TAG, "Failed to open the I2CDevice !"); stop = true; } length = mData.length; if (length > MAX_LENGTH) { length = MAX_LENGTH; } for(int i = 0 ; i < MAX_LENGTH; i++){ HardwareControler.writeByteDataToI2C(fd, i, (byte)'\0'); } while(!stop){ if (pos >= length) { break; } HardwareControler.writeByteDataToI2C(fd, pos, mData[pos]); sendMessage(EEPROMActivity.MSG_UPDATE_UI, pos,length); Log.i(TAG, "writeByteDataToI2C pos: "+ pos); pos++; // try { // Thread.sleep(10); // } catch ( InterruptedException e ) { // e.printStackTrace(); // } } if(fd != -1) { HardwareControler.close(fd); } } } }
122569111-test
src/com/mini6410/EEPROM/WriteEEPROM.java
Java
gpl3
2,687
package com.mini6410.EEPROM; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Editable; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import com.mini6410.R; public class EEPROMActivity extends Activity { public static final int MSG_UPDATE_UI = 0; public static final int MSG_GET_DATA = 1; private Button mButtonWrite = null; private Button mButtonRead = null; private EditText mEditTextWrite = null; private EditText mEditTextRead = null; private Editable mEditable = null; private WriteEEPROM mWriteEEPROM = null; private ReadEEPROM mReadEEPROM = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.eepromdemo); setProgressBarVisibility(true); initUI(); initData(); } public void initUI(){ mButtonWrite = (Button)findViewById(R.id.Button_write); mButtonRead = (Button)findViewById(R.id.Button_read); mButtonWrite.setOnClickListener(mClickListener); mButtonRead.setOnClickListener(mClickListener); mEditTextWrite = (EditText)findViewById(R.id.EditText_write); mEditTextRead = (EditText)findViewById(R.id.EditText_read); mEditable = mEditTextRead.getText(); } public void initData(){ mWriteEEPROM = new WriteEEPROM(mHandler); mReadEEPROM = new ReadEEPROM(mHandler); } private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_UPDATE_UI: int pos = (int)msg.arg1; int length = (int)msg.arg2; setProgress(pos*10000/(length -1)); break; case MSG_GET_DATA: Byte dataByte = (Byte)msg.obj; mEditable.append((char)dataByte.byteValue()); mEditTextRead.setText(mEditable); break; default: break; } } }; private Button.OnClickListener mClickListener = new Button.OnClickListener(){ public void onClick(View v) { Button mButton = (Button)v; switch (mButton.getId()) { case R.id.Button_read: ReadDataIntoEEPROM(); break; case R.id.Button_write: WriteDataIntoEEPROM(); break; default: break; } } }; public void WriteDataIntoEEPROM(){ byte[] data = mEditTextWrite.getText().toString().getBytes(); if(mWriteEEPROM != null) mWriteEEPROM.WriteData(data); } public void ReadDataIntoEEPROM(){ mEditable.clear(); if(mReadEEPROM != null) mReadEEPROM.ReadData(); } @Override protected void onDestroy() { super.onDestroy(); } }
122569111-test
src/com/mini6410/EEPROM/EEPROMActivity.java
Java
gpl3
2,646
package com.mini6410.ADC; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.TextView; import com.friendlyarm.AndroidSDK.HardwareControler; import com.mini6410.R; /** * * ClassName:ADCActivity * Reason: ADC Demo * * @author snowdream * @version * @since Ver 1.1 * @Date 2011 2012-03-16 12:04 * * @see */ public class ADCActivity extends Activity { private static final String TAG = "ADCActivity"; /*刷新UI标记*/ public static final int Update_UI = 0; /*计时器*/ private Timer mTimer = null; private TimerTask mTimerTask = null; /*用来显示ADC返回值的控件*/ private TextView mTextView_ADC = null; /*读取ADC的返回值*/ private int result = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.adcdemo); initUI(); initData(); } /** * * initUI: 初始化UI * * @param * @return * @throws */ private void initUI() { mTextView_ADC = (TextView)findViewById(R.id.TextView_adcresult); } /** * * initData: 新建定时器,每隔500ms发出消息,通知Activity刷新UI一次。 * * @param * @return * @throws */ private void initData() { mTimer = new Timer(); mTimerTask = new TimerTask() { @Override public void run() { /*调用底层库API读取ADC的值,正常情况下,返回ADC值,否则,出错,返回-1*/ result = HardwareControler.readADC(); if(-1 == result){ Log.e(TAG,"Read ADC Error!"); }else{ Log.i(TAG,"readADC result: "+ result); mHandler.sendMessage(mHandler.obtainMessage(Update_UI)); } } }; mTimer.schedule(mTimerTask, 0, 500); } private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { int type = msg.what; switch (type) { case Update_UI: mTextView_ADC.setText(String.valueOf(result)); break; default: break; } } }; @Override protected void onDestroy() { if(mTimer != null){ mTimer.cancel(); mTimer = null; } super.onDestroy(); } }
122569111-test
src/com/mini6410/ADC/ADCActivity.java
Java
gpl3
2,274
package com.mini6410.HelloMini6410; import com.mini6410.R; import android.app.Activity; import android.os.Bundle; /** * * ClassName:HelloMini6410Activity * Reason: Hello Mini6410 Demo * * @author snowdream * @version * @since Ver 1.1 * @Date 2011 2012-03-10 20:11 * * @see */ public class HelloMini6410Activity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.hellomini6410); } }
122569111-test
src/com/mini6410/HelloMini6410/HelloMini6410Activity.java
Java
gpl3
510
package com.mini6410.LED; import com.friendlyarm.AndroidSDK.HardwareControler; import com.mini6410.R; import android.app.Activity; import android.os.Bundle; import android.widget.CompoundButton; import android.widget.ToggleButton; /** * * ClassName:LEDActivity * Reason: LED Demo * * @author snowdream * @version * @since Ver 1.1 * @Date 2011 2012-03-11 16:07 * * @see */ public class LEDActivity extends Activity implements ToggleButton.OnCheckedChangeListener { /*四个LED灯,编号ID依次为:LED 0,LED_1,LED_2,LED_3*/ public static final int LED_0 = 0; public static final int LED_1 = 1; public static final int LED_2 = 2; public static final int LED_3 = 3; /*LED灯的状态: ON 表示点亮, OFF表示熄灭*/ public static final int OFF = 0; public static final int ON = 1; private int mledID = LED_0; private int mledState = OFF; private boolean mStop = false; /*LED编号数组*/ private int[] mleds = new int[]{LED_0,LED_1,LED_2,LED_3}; /*5个开关按钮*/ private ToggleButton mToggleButton_led0 = null; private ToggleButton mToggleButton_led1 = null; private ToggleButton mToggleButton_led2 = null; private ToggleButton mToggleButton_led3 = null; private ToggleButton mToggleButton_ledrandom = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.leddemo); initUI(); } @Override protected void onDestroy() { mStop = true; super.onDestroy(); } /** * * initUI: 初始化UI * * @param * @return * @throws */ public void initUI(){ mToggleButton_led0 = (ToggleButton)findViewById(R.id.button_led0); mToggleButton_led1 = (ToggleButton)findViewById(R.id.button_led1); mToggleButton_led2 = (ToggleButton)findViewById(R.id.button_led2); mToggleButton_led3 = (ToggleButton)findViewById(R.id.button_led3); mToggleButton_ledrandom = (ToggleButton)findViewById(R.id.button_ledrandom); mToggleButton_led0.setOnCheckedChangeListener(this); mToggleButton_led1.setOnCheckedChangeListener(this); mToggleButton_led2.setOnCheckedChangeListener(this); mToggleButton_led3.setOnCheckedChangeListener(this); mToggleButton_ledrandom.setOnCheckedChangeListener(this); } /** * * onCheckedChanged: 开关按钮监听器 * * @param buttonView 当前被按下的按钮对象;isChecked表示该按钮的开关状态 * @return * @throws */ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ToggleButton mToggleButton = (ToggleButton)buttonView; if(isChecked) mledState = ON; else mledState = OFF; switch (mToggleButton.getId()) { case R.id.button_led0: mledID = LED_0; setLedState(mledID, mledState); break; case R.id.button_led1: mledID = LED_1; setLedState(mledID, mledState); break; case R.id.button_led2: mledID = LED_2; setLedState(mledID, mledState); break; case R.id.button_led3: mledID = LED_3; setLedState(mledID, mledState); break; case R.id.button_ledrandom: if(isChecked){ mStop = false; RandomLight(); }else{ mStop = true; setALlLightsOff(); } break; default: break; } } /** * * setLedState: 设置LED灯的开关 * * @param ledID LED灯编号;ledState LED灯的开关状态 * @return true,表示操作成功;否则返回 false。 * @throws */ public boolean setLedState(int ledID, int ledState){ boolean ret = false; int result = -1; result = HardwareControler.setLedState(ledID, ledState); if(result == 0) ret = true; else ret = false; return ret; } /** * * RandomLight: 随机点亮LED灯 * * @param * @return * @throws */ public void RandomLight(){ new Thread(){ int mledNum = mleds.length; int mrandom = 0; @Override public void run() { while(!mStop){ /*从0 1 2 3范围内产生一个整数随机数*/ mrandom = (int)(Math.random()*(mledNum)); /*随机点亮一盏LED灯,然后关闭其他的LED灯*/ for(int i = 0; i <mleds.length; i++){ if(i == mrandom){ setLedState(mleds[i], ON); }else{ setLedState(mleds[i], OFF); } } try { sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } }}.start(); } /** * * setALlLightsOff: 熄灭全部的LED灯 * * @param * @return * @throws */ public void setALlLightsOff(){ for(int i = 0; i <mleds.length; i++){ setLedState(mleds[i], OFF); } } /** * * setALlLightsOn: 点亮全部的LED灯 * * @param * @return * @throws */ public void setALlLightsOn(){ for(int i = 0; i <mleds.length; i++){ setLedState(mleds[i], ON); } } }
122569111-test
src/com/mini6410/LED/LEDActivity.java
Java
gpl3
4,833
package com.mini6410; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.mini6410.ADC.ADCActivity; import com.mini6410.EEPROM.EEPROMActivity; import com.mini6410.HelloMini6410.HelloMini6410Activity; import com.mini6410.LED.LEDActivity; import com.mini6410.PWM.PWMActivity; public class MainActivity extends Activity implements OnItemClickListener { private static final String TAG = "MainActivity"; //ListView ListView mListView = null; //TextView TextView mEmptyView = null; public void onCreate(Bundle savedInstanceState) { Log.i(TAG,"onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.main); initUI(); initData(); } /** * * initUI: 初始化UI * * @param * @return * @throws */ public void initUI(){ mEmptyView=(TextView)findViewById(R.id.empty); mListView=(ListView)findViewById(R.id.listview); mListView.setOnItemClickListener(this); mListView.setEmptyView(mEmptyView); } /** * * initData: 初始化ListView的数据适配器 * * @param * @return * @throws */ public void initData(){ ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.demos, android.R.layout.simple_list_item_1); mListView.setAdapter(adapter); } /** * * onItemClick: 响应ListView的Item点击动作 * * @param * @return * @throws */ public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Intent intent = new Intent(); switch (position) { case 0: intent.setClass(this, HelloMini6410Activity.class); break; case 1: intent.setClass(this, LEDActivity.class); break; case 2: intent.setClass(this, PWMActivity.class); break; case 3: intent.setClass(this, ADCActivity.class); break; case 4: intent.setClass(this, EEPROMActivity.class); break; } startActivity(intent); } }
122569111-test
src/com/mini6410/MainActivity.java
Java
gpl3
2,193
package com.friendlyarm.AndroidSDK; import android.util.Log; public class HardwareControler { /* Serial Port */ static public native int openSerialPort( String devName, long baud, int dataBits, int stopBits ); /* LED */ static public native int setLedState( int ledID, int ledState ); /* PWM */ static public native int PWMPlay(int frequency); static public native int PWMStop(); /* ADC */ static public native int readADC(); /* I2C */ static public native int openI2CDevice(); static public native int writeByteDataToI2C(int fd, int pos, byte byteData); static public native int readByteDataFromI2C(int fd, int pos); /*通用接口*/ static public native int write(int fd, byte[] data); static public native int read(int fd, byte[] buf, int len); static public native int select(int fd, int sec, int usec); static public native void close(int fd); static { try { System.loadLibrary("friendlyarm-hardware"); } catch (UnsatisfiedLinkError e) { Log.d("HardwareControler", "libfriendlyarm-hardware library not found!"); } } }
122569111-test
src/com/friendlyarm/AndroidSDK/HardwareControler.java
Java
gpl3
1,098
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Wiring project - http://wiring.uniandes.edu.co Copyright (c) 2004-05 Hernando Barragan This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Modified 24 November 2006 by David A. Mellis */ #include <inttypes.h> #include <avr/io.h> #include <avr/interrupt.h> #include <avr/pgmspace.h> #include <stdio.h> #include "WConstants.h" #include "wiring_private.h" //##RG.Labs.20100919 begin //volatile static voidFuncPtr intFunc[EXTERNAL_NUM_INTERRUPTS]; static volatile voidFuncPtr intFunc[EXTERNAL_NUM_INTERRUPTS]; //##RG.Labs.20100919 end // volatile static voidFuncPtr twiIntFunc; #if defined(__AVR_ATmega8__) #define EICRA MCUCR #define EIMSK GICR #endif void attachInterrupt(uint8_t interruptNum, void (*userFunc)(void), int mode) { if(interruptNum < EXTERNAL_NUM_INTERRUPTS) { intFunc[interruptNum] = userFunc; // Configure the interrupt mode (trigger on low input, any change, rising // edge, or falling edge). The mode constants were chosen to correspond // to the configuration bits in the hardware register, so we simply shift // the mode into place. // Enable the interrupt. switch (interruptNum) { #if defined(__AVR_ATmega1280__) case 2: EICRA = (EICRA & ~((1 << ISC00) | (1 << ISC01))) | (mode << ISC00); EIMSK |= (1 << INT0); break; case 3: EICRA = (EICRA & ~((1 << ISC10) | (1 << ISC11))) | (mode << ISC10); EIMSK |= (1 << INT1); break; case 4: EICRA = (EICRA & ~((1 << ISC20) | (1 << ISC21))) | (mode << ISC20); EIMSK |= (1 << INT2); break; case 5: EICRA = (EICRA & ~((1 << ISC30) | (1 << ISC31))) | (mode << ISC30); EIMSK |= (1 << INT3); break; case 0: EICRB = (EICRB & ~((1 << ISC40) | (1 << ISC41))) | (mode << ISC40); EIMSK |= (1 << INT4); break; case 1: EICRB = (EICRB & ~((1 << ISC50) | (1 << ISC51))) | (mode << ISC50); EIMSK |= (1 << INT5); break; case 6: EICRB = (EICRB & ~((1 << ISC60) | (1 << ISC61))) | (mode << ISC60); EIMSK |= (1 << INT6); break; case 7: EICRB = (EICRB & ~((1 << ISC70) | (1 << ISC71))) | (mode << ISC70); EIMSK |= (1 << INT7); break; #else case 0: EICRA = (EICRA & ~((1 << ISC00) | (1 << ISC01))) | (mode << ISC00); EIMSK |= (1 << INT0); break; case 1: EICRA = (EICRA & ~((1 << ISC10) | (1 << ISC11))) | (mode << ISC10); EIMSK |= (1 << INT1); break; #endif } } } void detachInterrupt(uint8_t interruptNum) { if(interruptNum < EXTERNAL_NUM_INTERRUPTS) { // Disable the interrupt. (We can't assume that interruptNum is equal // to the number of the EIMSK bit to clear, as this isn't true on the // ATmega8. There, INT0 is 6 and INT1 is 7.) switch (interruptNum) { #if defined(__AVR_ATmega1280__) case 2: EIMSK &= ~(1 << INT0); break; case 3: EIMSK &= ~(1 << INT1); break; case 4: EIMSK &= ~(1 << INT2); break; case 5: EIMSK &= ~(1 << INT3); break; case 0: EIMSK &= ~(1 << INT4); break; case 1: EIMSK &= ~(1 << INT5); break; case 6: EIMSK &= ~(1 << INT6); break; case 7: EIMSK &= ~(1 << INT7); break; #else case 0: EIMSK &= ~(1 << INT0); break; case 1: EIMSK &= ~(1 << INT1); break; #endif } intFunc[interruptNum] = 0; } } /* void attachInterruptTwi(void (*userFunc)(void) ) { twiIntFunc = userFunc; } */ #if defined(__AVR_ATmega1280__) SIGNAL(INT0_vect) { if(intFunc[EXTERNAL_INT_2]) intFunc[EXTERNAL_INT_2](); } SIGNAL(INT1_vect) { if(intFunc[EXTERNAL_INT_3]) intFunc[EXTERNAL_INT_3](); } SIGNAL(INT2_vect) { if(intFunc[EXTERNAL_INT_4]) intFunc[EXTERNAL_INT_4](); } SIGNAL(INT3_vect) { if(intFunc[EXTERNAL_INT_5]) intFunc[EXTERNAL_INT_5](); } SIGNAL(INT4_vect) { if(intFunc[EXTERNAL_INT_0]) intFunc[EXTERNAL_INT_0](); } SIGNAL(INT5_vect) { if(intFunc[EXTERNAL_INT_1]) intFunc[EXTERNAL_INT_1](); } SIGNAL(INT6_vect) { if(intFunc[EXTERNAL_INT_6]) intFunc[EXTERNAL_INT_6](); } SIGNAL(INT7_vect) { if(intFunc[EXTERNAL_INT_7]) intFunc[EXTERNAL_INT_7](); } #else SIGNAL(INT0_vect) { if(intFunc[EXTERNAL_INT_0]) intFunc[EXTERNAL_INT_0](); } SIGNAL(INT1_vect) { if(intFunc[EXTERNAL_INT_1]) intFunc[EXTERNAL_INT_1](); } #endif /* SIGNAL(SIG_2WIRE_SERIAL) { if(twiIntFunc) twiIntFunc(); } */
0w-experimental-arduino-core
trunk/cores/arduino-0019/WInterrupts.c
C
lgpl
5,440
/* wiring_pulse.c - pulseIn() function Part of Arduino - http://www.arduino.cc/ Copyright (c) 2005-2006 David A. Mellis This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $ */ #include "wiring_private.h" #include "pins_arduino.h" /* Measures the length (in microseconds) of a pulse on the pin; state is HIGH * or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds * to 3 minutes in length, but must be called at least a few dozen microseconds * before the start of the pulse. */ unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout) { // cache the port and bit of the pin in order to speed up the // pulse width measuring loop and achieve finer resolution. calling // digitalRead() instead yields much coarser resolution. uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); uint8_t stateMask = (state ? bit : 0); unsigned long width = 0; // keep initialization out of time critical area // convert the timeout from microseconds to a number of times through // the initial loop; it takes 16 clock cycles per iteration. unsigned long numloops = 0; unsigned long maxloops = microsecondsToClockCycles(timeout) / 16; // wait for any previous pulse to end while ((*portInputRegister(port) & bit) == stateMask) if (numloops++ == maxloops) return 0; // wait for the pulse to start while ((*portInputRegister(port) & bit) != stateMask) if (numloops++ == maxloops) return 0; // wait for the pulse to stop while ((*portInputRegister(port) & bit) == stateMask) width++; // convert the reading to microseconds. The loop has been determined // to be 10 clock cycles long and have about 16 clocks between the edge // and the start of the loop. There will be some error introduced by // the interrupt handlers. return clockCyclesToMicroseconds(width * 10 + 16); }
0w-experimental-arduino-core
trunk/cores/arduino-0019/wiring_pulse.c
C
lgpl
2,595
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Wiring project - http://wiring.org.co Copyright (c) 2004-06 Hernando Barragan Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id$ */ extern "C" { #include "stdlib.h" } void randomSeed(unsigned int seed) { if (seed != 0) { srandom(seed); } } long random(long howbig) { if (howbig == 0) { return 0; } return random() % howbig; } long random(long howsmall, long howbig) { if (howsmall >= howbig) { return howsmall; } long diff = howbig - howsmall; return random(diff) + howsmall; } long map(long x, long in_min, long in_max, long out_min, long out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } unsigned int makeWord(unsigned int w) { return w; } unsigned int makeWord(unsigned char h, unsigned char l) { return (h << 8) | l; }
0w-experimental-arduino-core
trunk/cores/arduino-0019/WMath.cpp
C++
lgpl
1,649
#ifndef WProgram_h #define WProgram_h #include <stdlib.h> #include <string.h> #include <math.h> #include <avr/interrupt.h> #include "wiring.h" #ifdef __cplusplus #include "WString.h" #include "HardwareSerial.h" uint16_t makeWord(uint16_t w); uint16_t makeWord(byte h, byte l); #define word(...) makeWord(__VA_ARGS__) unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L); void tone(uint8_t _pin, unsigned int frequency, unsigned long duration = 0); void noTone(uint8_t _pin); // WMath prototypes long random(long); long random(long, long); void randomSeed(unsigned int); long map(long, long, long, long, long); #if defined(__AVR_ATmega1280__) const static uint8_t A0 = 54; const static uint8_t A1 = 55; const static uint8_t A2 = 56; const static uint8_t A3 = 57; const static uint8_t A4 = 58; const static uint8_t A5 = 59; const static uint8_t A6 = 60; const static uint8_t A7 = 61; const static uint8_t A8 = 62; const static uint8_t A9 = 63; const static uint8_t A10 = 64; const static uint8_t A11 = 65; const static uint8_t A12 = 66; const static uint8_t A13 = 67; const static uint8_t A14 = 68; const static uint8_t A15 = 69; #else const static uint8_t A0 = 14; const static uint8_t A1 = 15; const static uint8_t A2 = 16; const static uint8_t A3 = 17; const static uint8_t A4 = 18; const static uint8_t A5 = 19; const static uint8_t A6 = 20; const static uint8_t A7 = 21; #endif #endif #endif
0w-experimental-arduino-core
trunk/cores/arduino-0019/WProgram.h
C
lgpl
1,437
#ifndef Binary_h #define Binary_h #define B0 0 #define B00 0 #define B000 0 #define B0000 0 #define B00000 0 #define B000000 0 #define B0000000 0 #define B00000000 0 #define B1 1 #define B01 1 #define B001 1 #define B0001 1 #define B00001 1 #define B000001 1 #define B0000001 1 #define B00000001 1 #define B10 2 #define B010 2 #define B0010 2 #define B00010 2 #define B000010 2 #define B0000010 2 #define B00000010 2 #define B11 3 #define B011 3 #define B0011 3 #define B00011 3 #define B000011 3 #define B0000011 3 #define B00000011 3 #define B100 4 #define B0100 4 #define B00100 4 #define B000100 4 #define B0000100 4 #define B00000100 4 #define B101 5 #define B0101 5 #define B00101 5 #define B000101 5 #define B0000101 5 #define B00000101 5 #define B110 6 #define B0110 6 #define B00110 6 #define B000110 6 #define B0000110 6 #define B00000110 6 #define B111 7 #define B0111 7 #define B00111 7 #define B000111 7 #define B0000111 7 #define B00000111 7 #define B1000 8 #define B01000 8 #define B001000 8 #define B0001000 8 #define B00001000 8 #define B1001 9 #define B01001 9 #define B001001 9 #define B0001001 9 #define B00001001 9 #define B1010 10 #define B01010 10 #define B001010 10 #define B0001010 10 #define B00001010 10 #define B1011 11 #define B01011 11 #define B001011 11 #define B0001011 11 #define B00001011 11 #define B1100 12 #define B01100 12 #define B001100 12 #define B0001100 12 #define B00001100 12 #define B1101 13 #define B01101 13 #define B001101 13 #define B0001101 13 #define B00001101 13 #define B1110 14 #define B01110 14 #define B001110 14 #define B0001110 14 #define B00001110 14 #define B1111 15 #define B01111 15 #define B001111 15 #define B0001111 15 #define B00001111 15 #define B10000 16 #define B010000 16 #define B0010000 16 #define B00010000 16 #define B10001 17 #define B010001 17 #define B0010001 17 #define B00010001 17 #define B10010 18 #define B010010 18 #define B0010010 18 #define B00010010 18 #define B10011 19 #define B010011 19 #define B0010011 19 #define B00010011 19 #define B10100 20 #define B010100 20 #define B0010100 20 #define B00010100 20 #define B10101 21 #define B010101 21 #define B0010101 21 #define B00010101 21 #define B10110 22 #define B010110 22 #define B0010110 22 #define B00010110 22 #define B10111 23 #define B010111 23 #define B0010111 23 #define B00010111 23 #define B11000 24 #define B011000 24 #define B0011000 24 #define B00011000 24 #define B11001 25 #define B011001 25 #define B0011001 25 #define B00011001 25 #define B11010 26 #define B011010 26 #define B0011010 26 #define B00011010 26 #define B11011 27 #define B011011 27 #define B0011011 27 #define B00011011 27 #define B11100 28 #define B011100 28 #define B0011100 28 #define B00011100 28 #define B11101 29 #define B011101 29 #define B0011101 29 #define B00011101 29 #define B11110 30 #define B011110 30 #define B0011110 30 #define B00011110 30 #define B11111 31 #define B011111 31 #define B0011111 31 #define B00011111 31 #define B100000 32 #define B0100000 32 #define B00100000 32 #define B100001 33 #define B0100001 33 #define B00100001 33 #define B100010 34 #define B0100010 34 #define B00100010 34 #define B100011 35 #define B0100011 35 #define B00100011 35 #define B100100 36 #define B0100100 36 #define B00100100 36 #define B100101 37 #define B0100101 37 #define B00100101 37 #define B100110 38 #define B0100110 38 #define B00100110 38 #define B100111 39 #define B0100111 39 #define B00100111 39 #define B101000 40 #define B0101000 40 #define B00101000 40 #define B101001 41 #define B0101001 41 #define B00101001 41 #define B101010 42 #define B0101010 42 #define B00101010 42 #define B101011 43 #define B0101011 43 #define B00101011 43 #define B101100 44 #define B0101100 44 #define B00101100 44 #define B101101 45 #define B0101101 45 #define B00101101 45 #define B101110 46 #define B0101110 46 #define B00101110 46 #define B101111 47 #define B0101111 47 #define B00101111 47 #define B110000 48 #define B0110000 48 #define B00110000 48 #define B110001 49 #define B0110001 49 #define B00110001 49 #define B110010 50 #define B0110010 50 #define B00110010 50 #define B110011 51 #define B0110011 51 #define B00110011 51 #define B110100 52 #define B0110100 52 #define B00110100 52 #define B110101 53 #define B0110101 53 #define B00110101 53 #define B110110 54 #define B0110110 54 #define B00110110 54 #define B110111 55 #define B0110111 55 #define B00110111 55 #define B111000 56 #define B0111000 56 #define B00111000 56 #define B111001 57 #define B0111001 57 #define B00111001 57 #define B111010 58 #define B0111010 58 #define B00111010 58 #define B111011 59 #define B0111011 59 #define B00111011 59 #define B111100 60 #define B0111100 60 #define B00111100 60 #define B111101 61 #define B0111101 61 #define B00111101 61 #define B111110 62 #define B0111110 62 #define B00111110 62 #define B111111 63 #define B0111111 63 #define B00111111 63 #define B1000000 64 #define B01000000 64 #define B1000001 65 #define B01000001 65 #define B1000010 66 #define B01000010 66 #define B1000011 67 #define B01000011 67 #define B1000100 68 #define B01000100 68 #define B1000101 69 #define B01000101 69 #define B1000110 70 #define B01000110 70 #define B1000111 71 #define B01000111 71 #define B1001000 72 #define B01001000 72 #define B1001001 73 #define B01001001 73 #define B1001010 74 #define B01001010 74 #define B1001011 75 #define B01001011 75 #define B1001100 76 #define B01001100 76 #define B1001101 77 #define B01001101 77 #define B1001110 78 #define B01001110 78 #define B1001111 79 #define B01001111 79 #define B1010000 80 #define B01010000 80 #define B1010001 81 #define B01010001 81 #define B1010010 82 #define B01010010 82 #define B1010011 83 #define B01010011 83 #define B1010100 84 #define B01010100 84 #define B1010101 85 #define B01010101 85 #define B1010110 86 #define B01010110 86 #define B1010111 87 #define B01010111 87 #define B1011000 88 #define B01011000 88 #define B1011001 89 #define B01011001 89 #define B1011010 90 #define B01011010 90 #define B1011011 91 #define B01011011 91 #define B1011100 92 #define B01011100 92 #define B1011101 93 #define B01011101 93 #define B1011110 94 #define B01011110 94 #define B1011111 95 #define B01011111 95 #define B1100000 96 #define B01100000 96 #define B1100001 97 #define B01100001 97 #define B1100010 98 #define B01100010 98 #define B1100011 99 #define B01100011 99 #define B1100100 100 #define B01100100 100 #define B1100101 101 #define B01100101 101 #define B1100110 102 #define B01100110 102 #define B1100111 103 #define B01100111 103 #define B1101000 104 #define B01101000 104 #define B1101001 105 #define B01101001 105 #define B1101010 106 #define B01101010 106 #define B1101011 107 #define B01101011 107 #define B1101100 108 #define B01101100 108 #define B1101101 109 #define B01101101 109 #define B1101110 110 #define B01101110 110 #define B1101111 111 #define B01101111 111 #define B1110000 112 #define B01110000 112 #define B1110001 113 #define B01110001 113 #define B1110010 114 #define B01110010 114 #define B1110011 115 #define B01110011 115 #define B1110100 116 #define B01110100 116 #define B1110101 117 #define B01110101 117 #define B1110110 118 #define B01110110 118 #define B1110111 119 #define B01110111 119 #define B1111000 120 #define B01111000 120 #define B1111001 121 #define B01111001 121 #define B1111010 122 #define B01111010 122 #define B1111011 123 #define B01111011 123 #define B1111100 124 #define B01111100 124 #define B1111101 125 #define B01111101 125 #define B1111110 126 #define B01111110 126 #define B1111111 127 #define B01111111 127 #define B10000000 128 #define B10000001 129 #define B10000010 130 #define B10000011 131 #define B10000100 132 #define B10000101 133 #define B10000110 134 #define B10000111 135 #define B10001000 136 #define B10001001 137 #define B10001010 138 #define B10001011 139 #define B10001100 140 #define B10001101 141 #define B10001110 142 #define B10001111 143 #define B10010000 144 #define B10010001 145 #define B10010010 146 #define B10010011 147 #define B10010100 148 #define B10010101 149 #define B10010110 150 #define B10010111 151 #define B10011000 152 #define B10011001 153 #define B10011010 154 #define B10011011 155 #define B10011100 156 #define B10011101 157 #define B10011110 158 #define B10011111 159 #define B10100000 160 #define B10100001 161 #define B10100010 162 #define B10100011 163 #define B10100100 164 #define B10100101 165 #define B10100110 166 #define B10100111 167 #define B10101000 168 #define B10101001 169 #define B10101010 170 #define B10101011 171 #define B10101100 172 #define B10101101 173 #define B10101110 174 #define B10101111 175 #define B10110000 176 #define B10110001 177 #define B10110010 178 #define B10110011 179 #define B10110100 180 #define B10110101 181 #define B10110110 182 #define B10110111 183 #define B10111000 184 #define B10111001 185 #define B10111010 186 #define B10111011 187 #define B10111100 188 #define B10111101 189 #define B10111110 190 #define B10111111 191 #define B11000000 192 #define B11000001 193 #define B11000010 194 #define B11000011 195 #define B11000100 196 #define B11000101 197 #define B11000110 198 #define B11000111 199 #define B11001000 200 #define B11001001 201 #define B11001010 202 #define B11001011 203 #define B11001100 204 #define B11001101 205 #define B11001110 206 #define B11001111 207 #define B11010000 208 #define B11010001 209 #define B11010010 210 #define B11010011 211 #define B11010100 212 #define B11010101 213 #define B11010110 214 #define B11010111 215 #define B11011000 216 #define B11011001 217 #define B11011010 218 #define B11011011 219 #define B11011100 220 #define B11011101 221 #define B11011110 222 #define B11011111 223 #define B11100000 224 #define B11100001 225 #define B11100010 226 #define B11100011 227 #define B11100100 228 #define B11100101 229 #define B11100110 230 #define B11100111 231 #define B11101000 232 #define B11101001 233 #define B11101010 234 #define B11101011 235 #define B11101100 236 #define B11101101 237 #define B11101110 238 #define B11101111 239 #define B11110000 240 #define B11110001 241 #define B11110010 242 #define B11110011 243 #define B11110100 244 #define B11110101 245 #define B11110110 246 #define B11110111 247 #define B11111000 248 #define B11111001 249 #define B11111010 250 #define B11111011 251 #define B11111100 252 #define B11111101 253 #define B11111110 254 #define B11111111 255 #endif
0w-experimental-arduino-core
trunk/cores/arduino-0019/binary.h
C
lgpl
10,379
/* pins_arduino.c - pin definitions for the Arduino board Part of Arduino / Wiring Lite Copyright (c) 2005 David A. Mellis This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: pins_arduino.c 963 2010-05-16 04:05:40Z dmellis $ */ #include <avr/io.h> #include "wiring_private.h" #include "pins_arduino.h" // On the Arduino board, digital pins are also used // for the analog output (software PWM). Analog input // pins are a separate set. // ATMEL ATMEGA8 & 168 / ARDUINO // // +-\/-+ // PC6 1| |28 PC5 (AI 5) // (D 0) PD0 2| |27 PC4 (AI 4) // (D 1) PD1 3| |26 PC3 (AI 3) // (D 2) PD2 4| |25 PC2 (AI 2) // PWM+ (D 3) PD3 5| |24 PC1 (AI 1) // (D 4) PD4 6| |23 PC0 (AI 0) // VCC 7| |22 GND // GND 8| |21 AREF // PB6 9| |20 AVCC // PB7 10| |19 PB5 (D 13) // PWM+ (D 5) PD5 11| |18 PB4 (D 12) // PWM+ (D 6) PD6 12| |17 PB3 (D 11) PWM // (D 7) PD7 13| |16 PB2 (D 10) PWM // (D 8) PB0 14| |15 PB1 (D 9) PWM // +----+ // // (PWM+ indicates the additional PWM pins on the ATmega168.) // ATMEL ATMEGA1280 / ARDUINO // // 0-7 PE0-PE7 works // 8-13 PB0-PB5 works // 14-21 PA0-PA7 works // 22-29 PH0-PH7 works // 30-35 PG5-PG0 works // 36-43 PC7-PC0 works // 44-51 PJ7-PJ0 works // 52-59 PL7-PL0 works // 60-67 PD7-PD0 works // A0-A7 PF0-PF7 // A8-A15 PK0-PK7 #define PA 1 #define PB 2 #define PC 3 #define PD 4 #define PE 5 #define PF 6 #define PG 7 #define PH 8 #define PJ 10 #define PK 11 #define PL 12 #if defined(__AVR_ATmega1280__) const uint16_t PROGMEM port_to_mode_PGM[] = { NOT_A_PORT, &DDRA, &DDRB, &DDRC, &DDRD, &DDRE, &DDRF, &DDRG, &DDRH, NOT_A_PORT, &DDRJ, &DDRK, &DDRL, }; const uint16_t PROGMEM port_to_output_PGM[] = { NOT_A_PORT, &PORTA, &PORTB, &PORTC, &PORTD, &PORTE, &PORTF, &PORTG, &PORTH, NOT_A_PORT, &PORTJ, &PORTK, &PORTL, }; const uint16_t PROGMEM port_to_input_PGM[] = { NOT_A_PIN, &PINA, &PINB, &PINC, &PIND, &PINE, &PINF, &PING, &PINH, NOT_A_PIN, &PINJ, &PINK, &PINL, }; const uint8_t PROGMEM digital_pin_to_port_PGM[] = { // PORTLIST // ------------------------------------------- PE , // PE 0 ** 0 ** USART0_RX PE , // PE 1 ** 1 ** USART0_TX PE , // PE 4 ** 2 ** PWM2 PE , // PE 5 ** 3 ** PWM3 PG , // PG 5 ** 4 ** PWM4 PE , // PE 3 ** 5 ** PWM5 PH , // PH 3 ** 6 ** PWM6 PH , // PH 4 ** 7 ** PWM7 PH , // PH 5 ** 8 ** PWM8 PH , // PH 6 ** 9 ** PWM9 PB , // PB 4 ** 10 ** PWM10 PB , // PB 5 ** 11 ** PWM11 PB , // PB 6 ** 12 ** PWM12 PB , // PB 7 ** 13 ** PWM13 PJ , // PJ 1 ** 14 ** USART3_TX PJ , // PJ 0 ** 15 ** USART3_RX PH , // PH 1 ** 16 ** USART2_TX PH , // PH 0 ** 17 ** USART2_RX PD , // PD 3 ** 18 ** USART1_TX PD , // PD 2 ** 19 ** USART1_RX PD , // PD 1 ** 20 ** I2C_SDA PD , // PD 0 ** 21 ** I2C_SCL PA , // PA 0 ** 22 ** D22 PA , // PA 1 ** 23 ** D23 PA , // PA 2 ** 24 ** D24 PA , // PA 3 ** 25 ** D25 PA , // PA 4 ** 26 ** D26 PA , // PA 5 ** 27 ** D27 PA , // PA 6 ** 28 ** D28 PA , // PA 7 ** 29 ** D29 PC , // PC 7 ** 30 ** D30 PC , // PC 6 ** 31 ** D31 PC , // PC 5 ** 32 ** D32 PC , // PC 4 ** 33 ** D33 PC , // PC 3 ** 34 ** D34 PC , // PC 2 ** 35 ** D35 PC , // PC 1 ** 36 ** D36 PC , // PC 0 ** 37 ** D37 PD , // PD 7 ** 38 ** D38 PG , // PG 2 ** 39 ** D39 PG , // PG 1 ** 40 ** D40 PG , // PG 0 ** 41 ** D41 PL , // PL 7 ** 42 ** D42 PL , // PL 6 ** 43 ** D43 PL , // PL 5 ** 44 ** D44 PL , // PL 4 ** 45 ** D45 PL , // PL 3 ** 46 ** D46 PL , // PL 2 ** 47 ** D47 PL , // PL 1 ** 48 ** D48 PL , // PL 0 ** 49 ** D49 PB , // PB 3 ** 50 ** SPI_MISO PB , // PB 2 ** 51 ** SPI_MOSI PB , // PB 1 ** 52 ** SPI_SCK PB , // PB 0 ** 53 ** SPI_SS PF , // PF 0 ** 54 ** A0 PF , // PF 1 ** 55 ** A1 PF , // PF 2 ** 56 ** A2 PF , // PF 3 ** 57 ** A3 PF , // PF 4 ** 58 ** A4 PF , // PF 5 ** 59 ** A5 PF , // PF 6 ** 60 ** A6 PF , // PF 7 ** 61 ** A7 PK , // PK 0 ** 62 ** A8 PK , // PK 1 ** 63 ** A9 PK , // PK 2 ** 64 ** A10 PK , // PK 3 ** 65 ** A11 PK , // PK 4 ** 66 ** A12 PK , // PK 5 ** 67 ** A13 PK , // PK 6 ** 68 ** A14 PK , // PK 7 ** 69 ** A15 }; const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] = { // PIN IN PORT // ------------------------------------------- _BV( 0 ) , // PE 0 ** 0 ** USART0_RX _BV( 1 ) , // PE 1 ** 1 ** USART0_TX _BV( 4 ) , // PE 4 ** 2 ** PWM2 _BV( 5 ) , // PE 5 ** 3 ** PWM3 _BV( 5 ) , // PG 5 ** 4 ** PWM4 _BV( 3 ) , // PE 3 ** 5 ** PWM5 _BV( 3 ) , // PH 3 ** 6 ** PWM6 _BV( 4 ) , // PH 4 ** 7 ** PWM7 _BV( 5 ) , // PH 5 ** 8 ** PWM8 _BV( 6 ) , // PH 6 ** 9 ** PWM9 _BV( 4 ) , // PB 4 ** 10 ** PWM10 _BV( 5 ) , // PB 5 ** 11 ** PWM11 _BV( 6 ) , // PB 6 ** 12 ** PWM12 _BV( 7 ) , // PB 7 ** 13 ** PWM13 _BV( 1 ) , // PJ 1 ** 14 ** USART3_TX _BV( 0 ) , // PJ 0 ** 15 ** USART3_RX _BV( 1 ) , // PH 1 ** 16 ** USART2_TX _BV( 0 ) , // PH 0 ** 17 ** USART2_RX _BV( 3 ) , // PD 3 ** 18 ** USART1_TX _BV( 2 ) , // PD 2 ** 19 ** USART1_RX _BV( 1 ) , // PD 1 ** 20 ** I2C_SDA _BV( 0 ) , // PD 0 ** 21 ** I2C_SCL _BV( 0 ) , // PA 0 ** 22 ** D22 _BV( 1 ) , // PA 1 ** 23 ** D23 _BV( 2 ) , // PA 2 ** 24 ** D24 _BV( 3 ) , // PA 3 ** 25 ** D25 _BV( 4 ) , // PA 4 ** 26 ** D26 _BV( 5 ) , // PA 5 ** 27 ** D27 _BV( 6 ) , // PA 6 ** 28 ** D28 _BV( 7 ) , // PA 7 ** 29 ** D29 _BV( 7 ) , // PC 7 ** 30 ** D30 _BV( 6 ) , // PC 6 ** 31 ** D31 _BV( 5 ) , // PC 5 ** 32 ** D32 _BV( 4 ) , // PC 4 ** 33 ** D33 _BV( 3 ) , // PC 3 ** 34 ** D34 _BV( 2 ) , // PC 2 ** 35 ** D35 _BV( 1 ) , // PC 1 ** 36 ** D36 _BV( 0 ) , // PC 0 ** 37 ** D37 _BV( 7 ) , // PD 7 ** 38 ** D38 _BV( 2 ) , // PG 2 ** 39 ** D39 _BV( 1 ) , // PG 1 ** 40 ** D40 _BV( 0 ) , // PG 0 ** 41 ** D41 _BV( 7 ) , // PL 7 ** 42 ** D42 _BV( 6 ) , // PL 6 ** 43 ** D43 _BV( 5 ) , // PL 5 ** 44 ** D44 _BV( 4 ) , // PL 4 ** 45 ** D45 _BV( 3 ) , // PL 3 ** 46 ** D46 _BV( 2 ) , // PL 2 ** 47 ** D47 _BV( 1 ) , // PL 1 ** 48 ** D48 _BV( 0 ) , // PL 0 ** 49 ** D49 _BV( 3 ) , // PB 3 ** 50 ** SPI_MISO _BV( 2 ) , // PB 2 ** 51 ** SPI_MOSI _BV( 1 ) , // PB 1 ** 52 ** SPI_SCK _BV( 0 ) , // PB 0 ** 53 ** SPI_SS _BV( 0 ) , // PF 0 ** 54 ** A0 _BV( 1 ) , // PF 1 ** 55 ** A1 _BV( 2 ) , // PF 2 ** 56 ** A2 _BV( 3 ) , // PF 3 ** 57 ** A3 _BV( 4 ) , // PF 4 ** 58 ** A4 _BV( 5 ) , // PF 5 ** 59 ** A5 _BV( 6 ) , // PF 6 ** 60 ** A6 _BV( 7 ) , // PF 7 ** 61 ** A7 _BV( 0 ) , // PK 0 ** 62 ** A8 _BV( 1 ) , // PK 1 ** 63 ** A9 _BV( 2 ) , // PK 2 ** 64 ** A10 _BV( 3 ) , // PK 3 ** 65 ** A11 _BV( 4 ) , // PK 4 ** 66 ** A12 _BV( 5 ) , // PK 5 ** 67 ** A13 _BV( 6 ) , // PK 6 ** 68 ** A14 _BV( 7 ) , // PK 7 ** 69 ** A15 }; const uint8_t PROGMEM digital_pin_to_timer_PGM[] = { // TIMERS // ------------------------------------------- NOT_ON_TIMER , // PE 0 ** 0 ** USART0_RX NOT_ON_TIMER , // PE 1 ** 1 ** USART0_TX TIMER3B , // PE 4 ** 2 ** PWM2 TIMER3C , // PE 5 ** 3 ** PWM3 TIMER0B , // PG 5 ** 4 ** PWM4 TIMER3A , // PE 3 ** 5 ** PWM5 TIMER4A , // PH 3 ** 6 ** PWM6 TIMER4B , // PH 4 ** 7 ** PWM7 TIMER4C , // PH 5 ** 8 ** PWM8 TIMER2B , // PH 6 ** 9 ** PWM9 TIMER2A , // PB 4 ** 10 ** PWM10 TIMER1A , // PB 5 ** 11 ** PWM11 TIMER1B , // PB 6 ** 12 ** PWM12 TIMER0A , // PB 7 ** 13 ** PWM13 NOT_ON_TIMER , // PJ 1 ** 14 ** USART3_TX NOT_ON_TIMER , // PJ 0 ** 15 ** USART3_RX NOT_ON_TIMER , // PH 1 ** 16 ** USART2_TX NOT_ON_TIMER , // PH 0 ** 17 ** USART2_RX NOT_ON_TIMER , // PD 3 ** 18 ** USART1_TX NOT_ON_TIMER , // PD 2 ** 19 ** USART1_RX NOT_ON_TIMER , // PD 1 ** 20 ** I2C_SDA NOT_ON_TIMER , // PD 0 ** 21 ** I2C_SCL NOT_ON_TIMER , // PA 0 ** 22 ** D22 NOT_ON_TIMER , // PA 1 ** 23 ** D23 NOT_ON_TIMER , // PA 2 ** 24 ** D24 NOT_ON_TIMER , // PA 3 ** 25 ** D25 NOT_ON_TIMER , // PA 4 ** 26 ** D26 NOT_ON_TIMER , // PA 5 ** 27 ** D27 NOT_ON_TIMER , // PA 6 ** 28 ** D28 NOT_ON_TIMER , // PA 7 ** 29 ** D29 NOT_ON_TIMER , // PC 7 ** 30 ** D30 NOT_ON_TIMER , // PC 6 ** 31 ** D31 NOT_ON_TIMER , // PC 5 ** 32 ** D32 NOT_ON_TIMER , // PC 4 ** 33 ** D33 NOT_ON_TIMER , // PC 3 ** 34 ** D34 NOT_ON_TIMER , // PC 2 ** 35 ** D35 NOT_ON_TIMER , // PC 1 ** 36 ** D36 NOT_ON_TIMER , // PC 0 ** 37 ** D37 NOT_ON_TIMER , // PD 7 ** 38 ** D38 NOT_ON_TIMER , // PG 2 ** 39 ** D39 NOT_ON_TIMER , // PG 1 ** 40 ** D40 NOT_ON_TIMER , // PG 0 ** 41 ** D41 NOT_ON_TIMER , // PL 7 ** 42 ** D42 NOT_ON_TIMER , // PL 6 ** 43 ** D43 TIMER5C , // PL 5 ** 44 ** D44 TIMER5B , // PL 4 ** 45 ** D45 TIMER5A , // PL 3 ** 46 ** D46 NOT_ON_TIMER , // PL 2 ** 47 ** D47 NOT_ON_TIMER , // PL 1 ** 48 ** D48 NOT_ON_TIMER , // PL 0 ** 49 ** D49 NOT_ON_TIMER , // PB 3 ** 50 ** SPI_MISO NOT_ON_TIMER , // PB 2 ** 51 ** SPI_MOSI NOT_ON_TIMER , // PB 1 ** 52 ** SPI_SCK NOT_ON_TIMER , // PB 0 ** 53 ** SPI_SS NOT_ON_TIMER , // PF 0 ** 54 ** A0 NOT_ON_TIMER , // PF 1 ** 55 ** A1 NOT_ON_TIMER , // PF 2 ** 56 ** A2 NOT_ON_TIMER , // PF 3 ** 57 ** A3 NOT_ON_TIMER , // PF 4 ** 58 ** A4 NOT_ON_TIMER , // PF 5 ** 59 ** A5 NOT_ON_TIMER , // PF 6 ** 60 ** A6 NOT_ON_TIMER , // PF 7 ** 61 ** A7 NOT_ON_TIMER , // PK 0 ** 62 ** A8 NOT_ON_TIMER , // PK 1 ** 63 ** A9 NOT_ON_TIMER , // PK 2 ** 64 ** A10 NOT_ON_TIMER , // PK 3 ** 65 ** A11 NOT_ON_TIMER , // PK 4 ** 66 ** A12 NOT_ON_TIMER , // PK 5 ** 67 ** A13 NOT_ON_TIMER , // PK 6 ** 68 ** A14 NOT_ON_TIMER , // PK 7 ** 69 ** A15 }; #else // these arrays map port names (e.g. port B) to the // appropriate addresses for various functions (e.g. reading // and writing) //##RG.Labs.20100919 begin //const uint16_t PROGMEM port_to_mode_PGM[] = { // NOT_A_PORT, // NOT_A_PORT, // &DDRB, // &DDRC, // &DDRD, //}; const uint16_t PROGMEM port_to_mode_PGM[] = { NOT_A_PORT, NOT_A_PORT, (uint16_t) &DDRB, (uint16_t) &DDRC, (uint16_t) &DDRD, }; //##RG.Labs.20100919 end //##RG.Labs.20100919 begin //const uint16_t PROGMEM port_to_output_PGM[] = { // NOT_A_PORT, // NOT_A_PORT, // &PORTB, // &PORTC, // &PORTD, //}; //Why the orig core uses uint16_t, while port pointers are uint8_t according to the //avr-libc documentation? //See http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_port_pass const uint16_t PROGMEM port_to_output_PGM[] = { NOT_A_PORT, NOT_A_PORT, (uint16_t) &PORTB, (uint16_t)&PORTC, (uint16_t)&PORTD, }; //##RG.Labs.20100919 end //##RG.Labs.20100919 begin //const uint16_t PROGMEM port_to_input_PGM[] = { // NOT_A_PORT, // NOT_A_PORT, // &PINB, // &PINC, // &PIND, const uint16_t PROGMEM port_to_input_PGM[] = { NOT_A_PORT, NOT_A_PORT, (uint16_t)&PINB, (uint16_t)&PINC, (uint16_t)&PIND, }; //##RG.Labs.20100919 end const uint8_t PROGMEM digital_pin_to_port_PGM[] = { PD, /* 0 */ PD, PD, PD, PD, PD, PD, PD, PB, /* 8 */ PB, PB, PB, PB, PB, PC, /* 14 */ PC, PC, PC, PC, PC, }; const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] = { _BV(0), /* 0, port D */ _BV(1), _BV(2), _BV(3), _BV(4), _BV(5), _BV(6), _BV(7), _BV(0), /* 8, port B */ _BV(1), _BV(2), _BV(3), _BV(4), _BV(5), _BV(0), /* 14, port C */ _BV(1), _BV(2), _BV(3), _BV(4), _BV(5), }; const uint8_t PROGMEM digital_pin_to_timer_PGM[] = { NOT_ON_TIMER, /* 0 - port D */ NOT_ON_TIMER, NOT_ON_TIMER, // on the ATmega168, digital pin 3 has hardware pwm #if defined(__AVR_ATmega8__) NOT_ON_TIMER, #else TIMER2B, #endif NOT_ON_TIMER, // on the ATmega168, digital pins 5 and 6 have hardware pwm #if defined(__AVR_ATmega8__) NOT_ON_TIMER, NOT_ON_TIMER, #else TIMER0B, TIMER0A, #endif NOT_ON_TIMER, NOT_ON_TIMER, /* 8 - port B */ TIMER1A, TIMER1B, #if defined(__AVR_ATmega8__) TIMER2, #else TIMER2A, #endif NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, /* 14 - port C */ NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, }; #endif
0w-experimental-arduino-core
trunk/cores/arduino-0019/pins_arduino.c
C
lgpl
12,945
/* wiring.c - Partial implementation of the Wiring API for the ATmega8. Part of Arduino - http://www.arduino.cc/ Copyright (c) 2005-2006 David A. Mellis This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: wiring.c 970 2010-05-25 20:16:15Z dmellis $ */ #include "wiring_private.h" // the prescaler is set so that timer0 ticks every 64 clock cycles, and the // the overflow handler is called every 256 ticks. #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256)) // the whole number of milliseconds per timer0 overflow #define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000) // the fractional number of milliseconds per timer0 overflow. we shift right // by three to fit these numbers into a byte. (for the clock speeds we care // about - 8 and 16 MHz - this doesn't lose precision.) #define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3) #define FRACT_MAX (1000 >> 3) volatile unsigned long timer0_overflow_count = 0; volatile unsigned long timer0_millis = 0; static unsigned char timer0_fract = 0; SIGNAL(TIMER0_OVF_vect) { // copy these to local variables so they can be stored in registers // (volatile variables must be read from memory on every access) unsigned long m = timer0_millis; unsigned char f = timer0_fract; m += MILLIS_INC; f += FRACT_INC; if (f >= FRACT_MAX) { f -= FRACT_MAX; m += 1; } timer0_fract = f; timer0_millis = m; timer0_overflow_count++; } unsigned long millis() { unsigned long m; uint8_t oldSREG = SREG; // disable interrupts while we read timer0_millis or we might get an // inconsistent value (e.g. in the middle of a write to timer0_millis) cli(); m = timer0_millis; SREG = oldSREG; return m; } unsigned long micros() { unsigned long m; uint8_t oldSREG = SREG, t; cli(); m = timer0_overflow_count; t = TCNT0; #ifdef TIFR0 if ((TIFR0 & _BV(TOV0)) && (t < 255)) m++; #else if ((TIFR & _BV(TOV0)) && (t < 255)) m++; #endif SREG = oldSREG; return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond()); } void delay(unsigned long ms) { uint16_t start = (uint16_t)micros(); while (ms > 0) { if (((uint16_t)micros() - start) >= 1000) { ms--; start += 1000; } } } /* Delay for the given number of microseconds. Assumes a 8 or 16 MHz clock. */ void delayMicroseconds(unsigned int us) { // calling avrlib's delay_us() function with low values (e.g. 1 or // 2 microseconds) gives delays longer than desired. //delay_us(us); #if F_CPU >= 16000000L // for the 16 MHz clock on most Arduino boards // for a one-microsecond delay, simply return. the overhead // of the function call yields a delay of approximately 1 1/8 us. if (--us == 0) return; // the following loop takes a quarter of a microsecond (4 cycles) // per iteration, so execute it four times for each microsecond of // delay requested. us <<= 2; // account for the time taken in the preceeding commands. us -= 2; #else // for the 8 MHz internal clock on the ATmega168 // for a one- or two-microsecond delay, simply return. the overhead of // the function calls takes more than two microseconds. can't just // subtract two, since us is unsigned; we'd overflow. if (--us == 0) return; if (--us == 0) return; // the following loop takes half of a microsecond (4 cycles) // per iteration, so execute it twice for each microsecond of // delay requested. us <<= 1; // partially compensate for the time taken by the preceeding commands. // we can't subtract any more than this or we'd overflow w/ small delays. us--; #endif // busy wait __asm__ __volatile__ ( "1: sbiw %0,1" "\n\t" // 2 cycles "brne 1b" : "=w" (us) : "0" (us) // 2 cycles ); } void init() { // this needs to be called before setup() or some functions won't // work there sei(); // on the ATmega168, timer 0 is also used for fast hardware pwm // (using phase-correct PWM would mean that timer 0 overflowed half as often // resulting in different millis() behavior on the ATmega8 and ATmega168) #if !defined(__AVR_ATmega8__) sbi(TCCR0A, WGM01); sbi(TCCR0A, WGM00); #endif // set timer 0 prescale factor to 64 #if defined(__AVR_ATmega8__) sbi(TCCR0, CS01); sbi(TCCR0, CS00); #else sbi(TCCR0B, CS01); sbi(TCCR0B, CS00); #endif // enable timer 0 overflow interrupt #if defined(__AVR_ATmega8__) sbi(TIMSK, TOIE0); #else sbi(TIMSK0, TOIE0); #endif // timers 1 and 2 are used for phase-correct hardware pwm // this is better for motors as it ensures an even waveform // note, however, that fast pwm mode can achieve a frequency of up // 8 MHz (with a 16 MHz clock) at 50% duty cycle // set timer 1 prescale factor to 64 sbi(TCCR1B, CS11); sbi(TCCR1B, CS10); // put timer 1 in 8-bit phase correct pwm mode sbi(TCCR1A, WGM10); // set timer 2 prescale factor to 64 #if defined(__AVR_ATmega8__) sbi(TCCR2, CS22); #else sbi(TCCR2B, CS22); #endif // configure timer 2 for phase correct pwm (8-bit) #if defined(__AVR_ATmega8__) sbi(TCCR2, WGM20); #else sbi(TCCR2A, WGM20); #endif #if defined(__AVR_ATmega1280__) // set timer 3, 4, 5 prescale factor to 64 sbi(TCCR3B, CS31); sbi(TCCR3B, CS30); sbi(TCCR4B, CS41); sbi(TCCR4B, CS40); sbi(TCCR5B, CS51); sbi(TCCR5B, CS50); // put timer 3, 4, 5 in 8-bit phase correct pwm mode sbi(TCCR3A, WGM30); sbi(TCCR4A, WGM40); sbi(TCCR5A, WGM50); #endif // set a2d prescale factor to 128 // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range. // XXX: this will not work properly for other clock speeds, and // this code should use F_CPU to determine the prescale factor. sbi(ADCSRA, ADPS2); sbi(ADCSRA, ADPS1); sbi(ADCSRA, ADPS0); // enable a2d conversions sbi(ADCSRA, ADEN); // the bootloader connects pins 0 and 1 to the USART; disconnect them // here so they can be used as normal digital i/o; they will be // reconnected in Serial.begin() #if defined(__AVR_ATmega8__) UCSRB = 0; #else UCSR0B = 0; #endif }
0w-experimental-arduino-core
trunk/cores/arduino-0019/wiring.c
C
lgpl
6,598
/* wiring_private.h - Internal header file. Part of Arduino - http://www.arduino.cc/ Copyright (c) 2005-2006 David A. Mellis This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: wiring.h 239 2007-01-12 17:58:39Z mellis $ */ #ifndef WiringPrivate_h #define WiringPrivate_h #include <avr/io.h> #include <avr/interrupt.h> //##RG.Labs.20100919 begin //#include <avr/delay.h> #include <util/delay.h> //##RG.Labs.20100919 end #include <stdio.h> #include <stdarg.h> #include "wiring.h" #ifdef __cplusplus extern "C"{ #endif #ifndef cbi #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) #endif #ifndef sbi #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) #endif #define EXTERNAL_INT_0 0 #define EXTERNAL_INT_1 1 #define EXTERNAL_INT_2 2 #define EXTERNAL_INT_3 3 #define EXTERNAL_INT_4 4 #define EXTERNAL_INT_5 5 #define EXTERNAL_INT_6 6 #define EXTERNAL_INT_7 7 #if defined(__AVR_ATmega1280__) #define EXTERNAL_NUM_INTERRUPTS 8 #else #define EXTERNAL_NUM_INTERRUPTS 2 #endif typedef void (*voidFuncPtr)(void); #ifdef __cplusplus } // extern "C" #endif #endif
0w-experimental-arduino-core
trunk/cores/arduino-0019/wiring_private.h
C
lgpl
1,826
/* wiring_digital.c - digital input and output functions Part of Arduino - http://www.arduino.cc/ Copyright (c) 2005-2006 David A. Mellis This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $ */ #include "wiring_private.h" #include "pins_arduino.h" void pinMode(uint8_t pin, uint8_t mode) { uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); volatile uint8_t *reg; if (port == NOT_A_PIN) return; // JWS: can I let the optimizer do this? reg = portModeRegister(port); if (mode == INPUT) { uint8_t oldSREG = SREG; cli(); *reg &= ~bit; SREG = oldSREG; } else { uint8_t oldSREG = SREG; cli(); *reg |= bit; SREG = oldSREG; } } // Forcing this inline keeps the callers from having to push their own stuff // on the stack. It is a good performance win and only takes 1 more byte per // user than calling. (It will take more bytes on the 168.) // // But shouldn't this be moved into pinMode? Seems silly to check and do on // each digitalread or write. // static inline void turnOffPWM(uint8_t timer) __attribute__ ((always_inline)); static inline void turnOffPWM(uint8_t timer) { if (timer == TIMER1A) cbi(TCCR1A, COM1A1); if (timer == TIMER1B) cbi(TCCR1A, COM1B1); #if defined(__AVR_ATmega8__) if (timer == TIMER2) cbi(TCCR2, COM21); #else if (timer == TIMER0A) cbi(TCCR0A, COM0A1); if (timer == TIMER0B) cbi(TCCR0A, COM0B1); if (timer == TIMER2A) cbi(TCCR2A, COM2A1); if (timer == TIMER2B) cbi(TCCR2A, COM2B1); #endif #if defined(__AVR_ATmega1280__) if (timer == TIMER3A) cbi(TCCR3A, COM3A1); if (timer == TIMER3B) cbi(TCCR3A, COM3B1); if (timer == TIMER3C) cbi(TCCR3A, COM3C1); if (timer == TIMER4A) cbi(TCCR4A, COM4A1); if (timer == TIMER4B) cbi(TCCR4A, COM4B1); if (timer == TIMER4C) cbi(TCCR4A, COM4C1); if (timer == TIMER5A) cbi(TCCR5A, COM5A1); if (timer == TIMER5B) cbi(TCCR5A, COM5B1); if (timer == TIMER5C) cbi(TCCR5A, COM5C1); #endif } void digitalWrite(uint8_t pin, uint8_t val) { uint8_t timer = digitalPinToTimer(pin); uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); volatile uint8_t *out; if (port == NOT_A_PIN) return; // If the pin that support PWM output, we need to turn it off // before doing a digital write. if (timer != NOT_ON_TIMER) turnOffPWM(timer); out = portOutputRegister(port); if (val == LOW) { uint8_t oldSREG = SREG; cli(); *out &= ~bit; SREG = oldSREG; } else { uint8_t oldSREG = SREG; cli(); *out |= bit; SREG = oldSREG; } } int digitalRead(uint8_t pin) { uint8_t timer = digitalPinToTimer(pin); uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); if (port == NOT_A_PIN) return LOW; // If the pin that support PWM output, we need to turn it off // before getting a digital reading. if (timer != NOT_ON_TIMER) turnOffPWM(timer); if (*portInputRegister(port) & bit) return HIGH; return LOW; }
0w-experimental-arduino-core
trunk/cores/arduino-0019/wiring_digital.c
C
lgpl
3,683
/* pins_arduino.h - Pin definition functions for Arduino Part of Arduino - http://www.arduino.cc/ Copyright (c) 2007 David A. Mellis This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: wiring.h 249 2007-02-03 16:52:51Z mellis $ */ #ifndef Pins_Arduino_h #define Pins_Arduino_h #include <avr/pgmspace.h> #define NOT_A_PIN 0 #define NOT_A_PORT 0 #define NOT_ON_TIMER 0 #define TIMER0A 1 #define TIMER0B 2 #define TIMER1A 3 #define TIMER1B 4 #define TIMER2 5 #define TIMER2A 6 #define TIMER2B 7 #define TIMER3A 8 #define TIMER3B 9 #define TIMER3C 10 #define TIMER4A 11 #define TIMER4B 12 #define TIMER4C 13 #define TIMER5A 14 #define TIMER5B 15 #define TIMER5C 16 #if defined(__AVR_ATmega1280__) const static uint8_t SS = 53; const static uint8_t MOSI = 51; const static uint8_t MISO = 50; const static uint8_t SCK = 52; #else //##RG.Labs.20100919 begin //const static uint8_t SS = 10; //const static uint8_t MOSI = 11; //const static uint8_t MISO = 12; //const static uint8_t SCK = 13; static const uint8_t SS = 10; static const uint8_t MOSI = 11; static const uint8_t MISO = 12; static const uint8_t SCK = 13; //##RG.Labs.20100919 end #endif // On the ATmega1280, the addresses of some of the port registers are // greater than 255, so we can't store them in uint8_t's. extern const uint16_t PROGMEM port_to_mode_PGM[]; extern const uint16_t PROGMEM port_to_input_PGM[]; extern const uint16_t PROGMEM port_to_output_PGM[]; extern const uint8_t PROGMEM digital_pin_to_port_PGM[]; // extern const uint8_t PROGMEM digital_pin_to_bit_PGM[]; extern const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[]; extern const uint8_t PROGMEM digital_pin_to_timer_PGM[]; // Get the bit location within the hardware port of the given virtual pin. // This comes from the pins_*.c file for the active board configuration. // // These perform slightly better as macros compared to inline functions // #define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) ) #define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) ) #define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) ) #define analogInPinToBit(P) (P) #define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) ) #define portInputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_input_PGM + (P))) ) #define portModeRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_mode_PGM + (P))) ) #endif
0w-experimental-arduino-core
trunk/cores/arduino-0019/pins_arduino.h
C
lgpl
3,253
/* wiring.h - Partial implementation of the Wiring API for the ATmega8. Part of Arduino - http://www.arduino.cc/ Copyright (c) 2005-2006 David A. Mellis This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: wiring.h 1073 2010-08-17 21:50:41Z dmellis $ */ #ifndef Wiring_h #define Wiring_h #include <avr/io.h> #include <stdlib.h> #include "binary.h" #ifdef __cplusplus extern "C"{ #endif #define HIGH 0x1 #define LOW 0x0 #define INPUT 0x0 #define OUTPUT 0x1 #define true 0x1 #define false 0x0 #define PI 3.1415926535897932384626433832795 #define HALF_PI 1.5707963267948966192313216916398 #define TWO_PI 6.283185307179586476925286766559 #define DEG_TO_RAD 0.017453292519943295769236907684886 #define RAD_TO_DEG 57.295779513082320876798154814105 #define SERIAL 0x0 #define DISPLAY 0x1 #define LSBFIRST 0 #define MSBFIRST 1 #define CHANGE 1 #define FALLING 2 #define RISING 3 #if defined(__AVR_ATmega1280__) #define INTERNAL1V1 2 #define INTERNAL2V56 3 #else #define INTERNAL 3 #endif #define DEFAULT 1 #define EXTERNAL 0 // undefine stdlib's abs if encountered #ifdef abs #undef abs #endif #define min(a,b) ((a)<(b)?(a):(b)) #define max(a,b) ((a)>(b)?(a):(b)) #define abs(x) ((x)>0?(x):-(x)) #define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt))) #define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5)) #define radians(deg) ((deg)*DEG_TO_RAD) #define degrees(rad) ((rad)*RAD_TO_DEG) #define sq(x) ((x)*(x)) #define interrupts() sei() #define noInterrupts() cli() #define clockCyclesPerMicrosecond() ( F_CPU / 1000000L ) #define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() ) #define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() ) #define lowByte(w) ((uint8_t) ((w) & 0xff)) #define highByte(w) ((uint8_t) ((w) >> 8)) #define bitRead(value, bit) (((value) >> (bit)) & 0x01) #define bitSet(value, bit) ((value) |= (1UL << (bit))) #define bitClear(value, bit) ((value) &= ~(1UL << (bit))) #define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit)) typedef unsigned int word; #define bit(b) (1UL << (b)) typedef uint8_t boolean; typedef uint8_t byte; void init(void); void pinMode(uint8_t, uint8_t); void digitalWrite(uint8_t, uint8_t); int digitalRead(uint8_t); int analogRead(uint8_t); void analogReference(uint8_t mode); void analogWrite(uint8_t, int); unsigned long millis(void); unsigned long micros(void); void delay(unsigned long); void delayMicroseconds(unsigned int us); unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout); void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val); uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder); void attachInterrupt(uint8_t, void (*)(void), int mode); void detachInterrupt(uint8_t); void setup(void); void loop(void); #ifdef __cplusplus } // extern "C" #endif #endif
0w-experimental-arduino-core
trunk/cores/arduino-0019/wiring.h
C
lgpl
3,591
/* Print.h - Base class that provides print() and println() Copyright (c) 2008 David A. Mellis. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef Print_h #define Print_h #include <inttypes.h> #include <stdio.h> // for size_t #include "WString.h" #define DEC 10 #define HEX 16 #define OCT 8 #define BIN 2 #define BYTE 0 class Print { private: void printNumber(unsigned long, uint8_t); void printFloat(double, uint8_t); public: virtual void write(uint8_t) = 0; virtual void write(const char *str); virtual void write(const uint8_t *buffer, size_t size); void print(const String &); void print(const char[]); void print(char, int = BYTE); void print(unsigned char, int = BYTE); void print(int, int = DEC); void print(unsigned int, int = DEC); void print(long, int = DEC); void print(unsigned long, int = DEC); void print(double, int = 2); void println(const String &s); void println(const char[]); void println(char, int = BYTE); void println(unsigned char, int = BYTE); void println(int, int = DEC); void println(unsigned int, int = DEC); void println(long, int = DEC); void println(unsigned long, int = DEC); void println(double, int = 2); void println(void); }; #endif
0w-experimental-arduino-core
trunk/cores/arduino-0019/Print.h
C++
lgpl
1,990
/* HardwareSerial.h - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef HardwareSerial_h #define HardwareSerial_h #include <inttypes.h> #include "Stream.h" struct ring_buffer; class HardwareSerial : public Stream { private: ring_buffer *_rx_buffer; volatile uint8_t *_ubrrh; volatile uint8_t *_ubrrl; volatile uint8_t *_ucsra; volatile uint8_t *_ucsrb; volatile uint8_t *_udr; uint8_t _rxen; uint8_t _txen; uint8_t _rxcie; uint8_t _udre; uint8_t _u2x; public: HardwareSerial(ring_buffer *rx_buffer, volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre, uint8_t u2x); void begin(long); void end(); virtual int available(void); virtual int peek(void); virtual int read(void); virtual void flush(void); virtual void write(uint8_t); using Print::write; // pull in write(str) and write(buf, size) from Print }; extern HardwareSerial Serial; #if defined(__AVR_ATmega1280__) extern HardwareSerial Serial1; extern HardwareSerial Serial2; extern HardwareSerial Serial3; #endif #endif
0w-experimental-arduino-core
trunk/cores/arduino-0019/HardwareSerial.h
C++
lgpl
1,999
/* WString.h - String library for Wiring & Arduino Copyright (c) 2009-10 Hernando Barragan. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef String_h #define String_h //#include "WProgram.h" #include <stdlib.h> #include <string.h> #include <ctype.h> class String { public: // constructors String( const char *value = "" ); String( const String &value ); String( const char ); String( const unsigned char ); String( const int, const int base=10); String( const unsigned int, const int base=10 ); String( const long, const int base=10 ); //##RG.Labs.20100919 begin //String( const unsigned long, const int base=10 ); String( const unsigned long); //##RG.Labs.20100919 end ~String() { free(_buffer); _length = _capacity = 0;} //added _length = _capacity = 0; // operators const String & operator = ( const String &rhs ); const String & operator +=( const String &rhs ); //const String & operator +=( const char ); int operator ==( const String &rhs ) const; int operator !=( const String &rhs ) const; int operator < ( const String &rhs ) const; int operator > ( const String &rhs ) const; int operator <=( const String &rhs ) const; int operator >=( const String &rhs ) const; char operator []( unsigned int index ) const; char& operator []( unsigned int index ); //operator const char *() const { return _buffer; } // general methods char charAt( unsigned int index ) const; int compareTo( const String &anotherString ) const; unsigned char endsWith( const String &suffix ) const; unsigned char equals( const String &anObject ) const; unsigned char equalsIgnoreCase( const String &anotherString ) const; int indexOf( char ch ) const; int indexOf( char ch, unsigned int fromIndex ) const; int indexOf( const String &str ) const; int indexOf( const String &str, unsigned int fromIndex ) const; int lastIndexOf( char ch ) const; int lastIndexOf( char ch, unsigned int fromIndex ) const; int lastIndexOf( const String &str ) const; int lastIndexOf( const String &str, unsigned int fromIndex ) const; //##RG.Labs.20100919 begin //const unsigned int length( ) const { return _length; } unsigned int length( ) const { return _length; } //##RG.Labs.20100919 end void setCharAt(unsigned int index, const char ch); unsigned char startsWith( const String &prefix ) const; unsigned char startsWith( const String &prefix, unsigned int toffset ) const; String substring( unsigned int beginIndex ) const; String substring( unsigned int beginIndex, unsigned int endIndex ) const; String toLowerCase( ) const; String toUpperCase( ) const; String trim( ) const; void getBytes(unsigned char *buf, unsigned int bufsize); void toCharArray(char *buf, unsigned int bufsize); const String& concat( const String &str ); String replace( char oldChar, char newChar ); String replace( const String& match, const String& replace ); friend String operator + ( String lhs, const String &rhs ); protected: char *_buffer; // the actual char array unsigned int _capacity; // the array length minus one (for the '\0') unsigned int _length; // the String length (not counting the '\0') void getBuffer(unsigned int maxStrLen); private: }; // allocate buffer space inline void String::getBuffer(unsigned int maxStrLen) { _capacity = maxStrLen; _buffer = (char *) malloc(_capacity + 1); if (_buffer == NULL) _length = _capacity = 0; } inline String operator+( String lhs, const String &rhs ) { return lhs += rhs; } #endif
0w-experimental-arduino-core
trunk/cores/arduino-0019/WString.h
C++
lgpl
4,481
/* HardwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include "wiring.h" #include "wiring_private.h" #include "HardwareSerial.h" // Define constants and variables for buffering incoming serial data. We're // using a ring buffer (I think), in which rx_buffer_head is the index of the // location to which to write the next incoming character and rx_buffer_tail // is the index of the location from which to read. #define RX_BUFFER_SIZE 128 struct ring_buffer { unsigned char buffer[RX_BUFFER_SIZE]; int head; int tail; }; ring_buffer rx_buffer = { { 0 }, 0, 0 }; #if defined(__AVR_ATmega1280__) ring_buffer rx_buffer1 = { { 0 }, 0, 0 }; ring_buffer rx_buffer2 = { { 0 }, 0, 0 }; ring_buffer rx_buffer3 = { { 0 }, 0, 0 }; #endif inline void store_char(unsigned char c, ring_buffer *rx_buffer) { int i = (rx_buffer->head + 1) % RX_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != rx_buffer->tail) { rx_buffer->buffer[rx_buffer->head] = c; rx_buffer->head = i; } } #if defined(__AVR_ATmega1280__) SIGNAL(SIG_USART0_RECV) { unsigned char c = UDR0; store_char(c, &rx_buffer); } SIGNAL(SIG_USART1_RECV) { unsigned char c = UDR1; store_char(c, &rx_buffer1); } SIGNAL(SIG_USART2_RECV) { unsigned char c = UDR2; store_char(c, &rx_buffer2); } SIGNAL(SIG_USART3_RECV) { unsigned char c = UDR3; store_char(c, &rx_buffer3); } #else #if defined(__AVR_ATmega8__) SIGNAL(SIG_UART_RECV) #else SIGNAL(USART_RX_vect) #endif { #if defined(__AVR_ATmega8__) unsigned char c = UDR; #else unsigned char c = UDR0; #endif store_char(c, &rx_buffer); } #endif // Constructors //////////////////////////////////////////////////////////////// HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre, uint8_t u2x) { _rx_buffer = rx_buffer; _ubrrh = ubrrh; _ubrrl = ubrrl; _ucsra = ucsra; _ucsrb = ucsrb; _udr = udr; _rxen = rxen; _txen = txen; _rxcie = rxcie; _udre = udre; _u2x = u2x; } // Public Methods ////////////////////////////////////////////////////////////// void HardwareSerial::begin(long baud) { uint16_t baud_setting; bool use_u2x; // U2X mode is needed for baud rates higher than (CPU Hz / 16) //##RG.Labs.20100919 begin //if (baud > F_CPU / 16) { if (baud > (long)(F_CPU / 16)) { //##RG.Labs.20100919 end use_u2x = true; } else { // figure out if U2X mode would allow for a better connection // calculate the percent difference between the baud-rate specified and // the real baud rate for both U2X and non-U2X mode (0-255 error percent) uint8_t nonu2x_baud_error = abs((int)(255-((F_CPU/(16*(((F_CPU/8/baud-1)/2)+1))*255)/baud))); uint8_t u2x_baud_error = abs((int)(255-((F_CPU/(8*(((F_CPU/4/baud-1)/2)+1))*255)/baud))); // prefer non-U2X mode because it handles clock skew better use_u2x = (nonu2x_baud_error > u2x_baud_error); } if (use_u2x) { *_ucsra = 1 << _u2x; baud_setting = (F_CPU / 4 / baud - 1) / 2; } else { *_ucsra = 0; baud_setting = (F_CPU / 8 / baud - 1) / 2; } // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) *_ubrrh = baud_setting >> 8; *_ubrrl = baud_setting; sbi(*_ucsrb, _rxen); sbi(*_ucsrb, _txen); sbi(*_ucsrb, _rxcie); } void HardwareSerial::end() { cbi(*_ucsrb, _rxen); cbi(*_ucsrb, _txen); cbi(*_ucsrb, _rxcie); } int HardwareSerial::available(void) { return (RX_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % RX_BUFFER_SIZE; } int HardwareSerial::peek(void) { if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { return _rx_buffer->buffer[_rx_buffer->tail]; } } int HardwareSerial::read(void) { // if the head isn't ahead of the tail, we don't have any characters if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { unsigned char c = _rx_buffer->buffer[_rx_buffer->tail]; _rx_buffer->tail = (_rx_buffer->tail + 1) % RX_BUFFER_SIZE; return c; } } void HardwareSerial::flush() { // don't reverse this or there may be problems if the RX interrupt // occurs after reading the value of rx_buffer_head but before writing // the value to rx_buffer_tail; the previous value of rx_buffer_head // may be written to rx_buffer_tail, making it appear as if the buffer // don't reverse this or there may be problems if the RX interrupt // occurs after reading the value of rx_buffer_head but before writing // the value to rx_buffer_tail; the previous value of rx_buffer_head // may be written to rx_buffer_tail, making it appear as if the buffer // were full, not empty. _rx_buffer->head = _rx_buffer->tail; } void HardwareSerial::write(uint8_t c) { while (!((*_ucsra) & (1 << _udre))) ; *_udr = c; } // Preinstantiate Objects ////////////////////////////////////////////////////// #if defined(__AVR_ATmega8__) HardwareSerial Serial(&rx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRE, U2X); #else HardwareSerial Serial(&rx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRE0, U2X0); #endif #if defined(__AVR_ATmega1280__) HardwareSerial Serial1(&rx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRE1, U2X1); HardwareSerial Serial2(&rx_buffer2, &UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UDR2, RXEN2, TXEN2, RXCIE2, UDRE2, U2X2); HardwareSerial Serial3(&rx_buffer3, &UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UDR3, RXEN3, TXEN3, RXCIE3, UDRE3, U2X3); #endif
0w-experimental-arduino-core
trunk/cores/arduino-0019/HardwareSerial.cpp
C++
lgpl
7,022
/* Stream.h - base class for character-based streams. Copyright (c) 2010 David A. Mellis. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef Stream_h #define Stream_h #include <inttypes.h> #include "Print.h" class Stream : public Print { public: virtual int available() = 0; virtual int read() = 0; virtual void flush() = 0; }; #endif
0w-experimental-arduino-core
trunk/cores/arduino-0019/Stream.h
C++
lgpl
1,061
#ifndef CPPLib__h #define CPPLib__h //"Alternate linkage specification": extern "C" { //#include <avr/io.h> //#include <stdlib.h> //#include <avr/sfr_defs.h> #include <stdint.h> } //Global overloaded new and delete operators can't be declared within a namespace: // 'void* SNAPI::operator new(SNAPI::size_t)' may not be declared within a namespace" typedef unsigned int size_t; typedef void (*new_handler)(); extern "C" void __cxa_pure_virtual(); void * operator new (size_t sz) throw(); void * operator new[] (size_t sz) throw(); void operator delete (void *ptr) throw (); void operator delete[] (void *ptr) throw (); #endif
0w-experimental-arduino-core
trunk/cores/arduino-0019/CPPLib.h
C
lgpl
662
/* wiring_analog.c - analog input and output Part of Arduino - http://www.arduino.cc/ Copyright (c) 2005-2006 David A. Mellis This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $ */ #include "wiring_private.h" #include "pins_arduino.h" uint8_t analog_reference = DEFAULT; void analogReference(uint8_t mode) { // can't actually set the register here because the default setting // will connect AVCC and the AREF pin, which would cause a short if // there's something connected to AREF. analog_reference = mode; } int analogRead(uint8_t pin) { uint8_t low, high; #if defined(__AVR_ATmega1280__) if (pin >= 54) pin -= 54; // allow for channel or pin numbers // the MUX5 bit of ADCSRB selects whether we're reading from channels // 0 to 7 (MUX5 low) or 8 to 15 (MUX5 high). ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5); #else if (pin >= 14) pin -= 14; // allow for channel or pin numbers #endif // set the analog reference (high two bits of ADMUX) and select the // channel (low 4 bits). this also sets ADLAR (left-adjust result) // to 0 (the default). ADMUX = (analog_reference << 6) | (pin & 0x07); // without a delay, we seem to read from the wrong channel //delay(1); // start the conversion sbi(ADCSRA, ADSC); // ADSC is cleared when the conversion finishes while (bit_is_set(ADCSRA, ADSC)); // we have to read ADCL first; doing so locks both ADCL // and ADCH until ADCH is read. reading ADCL second would // cause the results of each conversion to be discarded, // as ADCL and ADCH would be locked when it completed. low = ADCL; high = ADCH; // combine the two bytes return (high << 8) | low; } // Right now, PWM output only works on the pins with // hardware support. These are defined in the appropriate // pins_*.c file. For the rest of the pins, we default // to digital output. void analogWrite(uint8_t pin, int val) { // We need to make sure the PWM output is enabled for those pins // that support it, as we turn it off when digitally reading or // writing with them. Also, make sure the pin is in output mode // for consistenty with Wiring, which doesn't require a pinMode // call for the analog output pins. pinMode(pin, OUTPUT); if (digitalPinToTimer(pin) == TIMER1A) { // connect pwm to pin on timer 1, channel A sbi(TCCR1A, COM1A1); // set pwm duty OCR1A = val; } else if (digitalPinToTimer(pin) == TIMER1B) { // connect pwm to pin on timer 1, channel B sbi(TCCR1A, COM1B1); // set pwm duty OCR1B = val; #if defined(__AVR_ATmega8__) } else if (digitalPinToTimer(pin) == TIMER2) { // connect pwm to pin on timer 2, channel B sbi(TCCR2, COM21); // set pwm duty OCR2 = val; #else } else if (digitalPinToTimer(pin) == TIMER0A) { if (val == 0) { digitalWrite(pin, LOW); } else { // connect pwm to pin on timer 0, channel A sbi(TCCR0A, COM0A1); // set pwm duty OCR0A = val; } } else if (digitalPinToTimer(pin) == TIMER0B) { if (val == 0) { digitalWrite(pin, LOW); } else { // connect pwm to pin on timer 0, channel B sbi(TCCR0A, COM0B1); // set pwm duty OCR0B = val; } } else if (digitalPinToTimer(pin) == TIMER2A) { // connect pwm to pin on timer 2, channel A sbi(TCCR2A, COM2A1); // set pwm duty OCR2A = val; } else if (digitalPinToTimer(pin) == TIMER2B) { // connect pwm to pin on timer 2, channel B sbi(TCCR2A, COM2B1); // set pwm duty OCR2B = val; #endif #if defined(__AVR_ATmega1280__) // XXX: need to handle other timers here } else if (digitalPinToTimer(pin) == TIMER3A) { // connect pwm to pin on timer 3, channel A sbi(TCCR3A, COM3A1); // set pwm duty OCR3A = val; } else if (digitalPinToTimer(pin) == TIMER3B) { // connect pwm to pin on timer 3, channel B sbi(TCCR3A, COM3B1); // set pwm duty OCR3B = val; } else if (digitalPinToTimer(pin) == TIMER3C) { // connect pwm to pin on timer 3, channel C sbi(TCCR3A, COM3C1); // set pwm duty OCR3C = val; } else if (digitalPinToTimer(pin) == TIMER4A) { // connect pwm to pin on timer 4, channel A sbi(TCCR4A, COM4A1); // set pwm duty OCR4A = val; } else if (digitalPinToTimer(pin) == TIMER4B) { // connect pwm to pin on timer 4, channel B sbi(TCCR4A, COM4B1); // set pwm duty OCR4B = val; } else if (digitalPinToTimer(pin) == TIMER4C) { // connect pwm to pin on timer 4, channel C sbi(TCCR4A, COM4C1); // set pwm duty OCR4C = val; } else if (digitalPinToTimer(pin) == TIMER5A) { // connect pwm to pin on timer 5, channel A sbi(TCCR5A, COM5A1); // set pwm duty OCR5A = val; } else if (digitalPinToTimer(pin) == TIMER5B) { // connect pwm to pin on timer 5, channel B sbi(TCCR5A, COM5B1); // set pwm duty OCR5B = val; #endif } else if (val < 128) digitalWrite(pin, LOW); else digitalWrite(pin, HIGH); }
0w-experimental-arduino-core
trunk/cores/arduino-0019/wiring_analog.c
C
lgpl
5,542
/* WString.cpp - String library for Wiring & Arduino Copyright (c) 2009-10 Hernando Barragan. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdlib.h> #include "WProgram.h" #include "WString.h" String::String( const char *value ) { if ( value == NULL ) value = ""; getBuffer( _length = strlen( value ) ); if ( _buffer != NULL ) strcpy( _buffer, value ); } String::String( const String &value ) { getBuffer( _length = value._length ); if ( _buffer != NULL ) strcpy( _buffer, value._buffer ); } String::String( const char value ) { _length = 1; getBuffer(1); if ( _buffer != NULL ) { _buffer[0] = value; _buffer[1] = 0; } } String::String( const unsigned char value ) { _length = 1; getBuffer(1); if ( _buffer != NULL) { _buffer[0] = value; _buffer[1] = 0; } } String::String( const int value, const int base ) { char buf[33]; itoa((signed long)value, buf, base); getBuffer( _length = strlen(buf) ); if ( _buffer != NULL ) strcpy( _buffer, buf ); } String::String( const unsigned int value, const int base ) { char buf[33]; ultoa((unsigned long)value, buf, base); getBuffer( _length = strlen(buf) ); if ( _buffer != NULL ) strcpy( _buffer, buf ); } String::String( const long value, const int base ) { char buf[33]; ltoa(value, buf, base); getBuffer( _length = strlen(buf) ); if ( _buffer != NULL ) strcpy( _buffer, buf ); } //##RG.Labs.20100919 begin //String::String( const unsigned long value, const int base ) //{ // char buf[33]; // ultoa(value, buf, 10); // getBuffer( _length = strlen(buf) ); // if ( _buffer != NULL ) // strcpy( _buffer, buf ); //} String::String( const unsigned long value) { char buf[33]; ultoa(value, buf, 10); getBuffer( _length = strlen(buf) ); if ( _buffer != NULL ) strcpy( _buffer, buf ); } //##RG.Labs.20100919 end char String::charAt( unsigned int loc ) const { return operator[]( loc ); } void String::setCharAt( unsigned int loc, const char aChar ) { if(_buffer == NULL) return; if(_length > loc) { _buffer[loc] = aChar; } } int String::compareTo( const String &s2 ) const { return strcmp( _buffer, s2._buffer ); } const String & String::concat( const String &s2 ) { return (*this) += s2; } const String & String::operator=( const String &rhs ) { if ( this == &rhs ) return *this; if ( rhs._length > _length ) { free(_buffer); getBuffer( rhs._length ); } if ( _buffer != NULL ) { _length = rhs._length; strcpy( _buffer, rhs._buffer ); } return *this; } //const String & String::operator+=( const char aChar ) //{ // if ( _length == _capacity ) // doubleBuffer(); // // _buffer[ _length++ ] = aChar; // _buffer[ _length ] = '\0'; // return *this; //} const String & String::operator+=( const String &other ) { _length += other._length; if ( _length > _capacity ) { char *temp = _buffer; getBuffer( _length ); if ( _buffer != NULL ) strcpy( _buffer, temp ); free(temp); } if ( _buffer != NULL ) strcat( _buffer, other._buffer ); return *this; } int String::operator==( const String &rhs ) const { return ( _length == rhs._length && strcmp( _buffer, rhs._buffer ) == 0 ); } int String::operator!=( const String &rhs ) const { return ( _length != rhs.length() || strcmp( _buffer, rhs._buffer ) != 0 ); } int String::operator<( const String &rhs ) const { return strcmp( _buffer, rhs._buffer ) < 0; } int String::operator>( const String &rhs ) const { return strcmp( _buffer, rhs._buffer ) > 0; } int String::operator<=( const String &rhs ) const { return strcmp( _buffer, rhs._buffer ) <= 0; } int String::operator>=( const String & rhs ) const { return strcmp( _buffer, rhs._buffer ) >= 0; } char & String::operator[]( unsigned int index ) { static char dummy_writable_char; if (index >= _length || !_buffer) { dummy_writable_char = 0; return dummy_writable_char; } return _buffer[ index ]; } char String::operator[]( unsigned int index ) const { // need to check for valid index, to do later return _buffer[ index ]; } boolean String::endsWith( const String &s2 ) const { if ( _length < s2._length ) return 0; return strcmp( &_buffer[ _length - s2._length], s2._buffer ) == 0; } boolean String::equals( const String &s2 ) const { return ( _length == s2._length && strcmp( _buffer,s2._buffer ) == 0 ); } boolean String::equalsIgnoreCase( const String &s2 ) const { if ( this == &s2 ) return true; //1; else if ( _length != s2._length ) return false; //0; return strcmp(toLowerCase()._buffer, s2.toLowerCase()._buffer) == 0; } String String::replace( char findChar, char replaceChar ) { if ( _buffer == NULL ) return *this; String theReturn = _buffer; char* temp = theReturn._buffer; while( (temp = strchr( temp, findChar )) != 0 ) *temp = replaceChar; return theReturn; } String String::replace( const String& match, const String& replace ) { if ( _buffer == NULL ) return *this; String temp = _buffer, newString; int loc; while ( (loc = temp.indexOf( match )) != -1 ) { newString += temp.substring( 0, loc ); newString += replace; temp = temp.substring( loc + match._length ); } newString += temp; return newString; } int String::indexOf( char temp ) const { return indexOf( temp, 0 ); } int String::indexOf( char ch, unsigned int fromIndex ) const { if ( fromIndex >= _length ) return -1; const char* temp = strchr( &_buffer[fromIndex], ch ); if ( temp == NULL ) return -1; return temp - _buffer; } int String::indexOf( const String &s2 ) const { return indexOf( s2, 0 ); } int String::indexOf( const String &s2, unsigned int fromIndex ) const { if ( fromIndex >= _length ) return -1; const char *theFind = strstr( &_buffer[ fromIndex ], s2._buffer ); if ( theFind == NULL ) return -1; return theFind - _buffer; // pointer subtraction } int String::lastIndexOf( char theChar ) const { return lastIndexOf( theChar, _length - 1 ); } int String::lastIndexOf( char ch, unsigned int fromIndex ) const { if ( fromIndex >= _length ) return -1; char tempchar = _buffer[fromIndex + 1]; _buffer[fromIndex + 1] = '\0'; char* temp = strrchr( _buffer, ch ); _buffer[fromIndex + 1] = tempchar; if ( temp == NULL ) return -1; return temp - _buffer; } int String::lastIndexOf( const String &s2 ) const { return lastIndexOf( s2, _length - s2._length ); } int String::lastIndexOf( const String &s2, unsigned int fromIndex ) const { // check for empty strings if ( s2._length == 0 || s2._length - 1 > fromIndex || fromIndex >= _length ) return -1; // matching first character char temp = s2[ 0 ]; for ( int i = fromIndex; i >= 0; i-- ) { if ( _buffer[ i ] == temp && (*this).substring( i, i + s2._length ).equals( s2 ) ) return i; } return -1; } boolean String::startsWith( const String &s2 ) const { if ( _length < s2._length ) return 0; return startsWith( s2, 0 ); } boolean String::startsWith( const String &s2, unsigned int offset ) const { if ( offset > _length - s2._length ) return 0; return strncmp( &_buffer[offset], s2._buffer, s2._length ) == 0; } String String::substring( unsigned int left ) const { return substring( left, _length ); } String String::substring( unsigned int left, unsigned int right ) const { if ( left > right ) { int temp = right; right = left; left = temp; } if ( right > _length ) { right = _length; } char temp = _buffer[ right ]; // save the replaced character _buffer[ right ] = '\0'; String outPut = ( _buffer + left ); // pointer arithmetic _buffer[ right ] = temp; //restore character return outPut; } String String::toLowerCase() const { String temp = _buffer; for ( unsigned int i = 0; i < _length; i++ ) temp._buffer[ i ] = (char)tolower( temp._buffer[ i ] ); return temp; } String String::toUpperCase() const { String temp = _buffer; for ( unsigned int i = 0; i < _length; i++ ) temp._buffer[ i ] = (char)toupper( temp._buffer[ i ] ); return temp; } String String::trim() const { if ( _buffer == NULL ) return *this; String temp = _buffer; unsigned int i,j; for ( i = 0; i < _length; i++ ) { if ( !isspace(_buffer[i]) ) break; } for ( j = temp._length - 1; j > i; j-- ) { if ( !isspace(_buffer[j]) ) break; } return temp.substring( i, j + 1); } void String::getBytes(unsigned char *buf, unsigned int bufsize) { if (!bufsize || !buf) return; unsigned int len = bufsize - 1; if (len > _length) len = _length; strncpy((char *)buf, _buffer, len); buf[len] = 0; } void String::toCharArray(char *buf, unsigned int bufsize) { if (!bufsize || !buf) return; unsigned int len = bufsize - 1; if (len > _length) len = _length; strncpy(buf, _buffer, len); buf[len] = 0; }
0w-experimental-arduino-core
trunk/cores/arduino-0019/WString.cpp
C++
lgpl
10,084
/* Tone.cpp A Tone Generator Library Written by Brett Hagman This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Version Modified By Date Comments ------- ----------- -------- -------- 0001 B Hagman 09/08/02 Initial coding 0002 B Hagman 09/08/18 Multiple pins 0003 B Hagman 09/08/18 Moved initialization from constructor to begin() 0004 B Hagman 09/09/26 Fixed problems with ATmega8 0005 B Hagman 09/11/23 Scanned prescalars for best fit on 8 bit timers 09/11/25 Changed pin toggle method to XOR 09/11/25 Fixed timer0 from being excluded 0006 D Mellis 09/12/29 Replaced objects with functions *************************************************/ #include <avr/interrupt.h> #include <avr/pgmspace.h> #include <wiring.h> #include <pins_arduino.h> #if defined(__AVR_ATmega8__) #define TCCR2A TCCR2 #define TCCR2B TCCR2 #define COM2A1 COM21 #define COM2A0 COM20 #define OCR2A OCR2 #define TIMSK2 TIMSK #define OCIE2A OCIE2 #define TIMER2_COMPA_vect TIMER2_COMP_vect #define TIMSK1 TIMSK #endif // timerx_toggle_count: // > 0 - duration specified // = 0 - stopped // < 0 - infinitely (until stop() method called, or new play() called) #if !defined(__AVR_ATmega8__) volatile long timer0_toggle_count; volatile uint8_t *timer0_pin_port; volatile uint8_t timer0_pin_mask; #endif volatile long timer1_toggle_count; volatile uint8_t *timer1_pin_port; volatile uint8_t timer1_pin_mask; volatile long timer2_toggle_count; volatile uint8_t *timer2_pin_port; volatile uint8_t timer2_pin_mask; #if defined(__AVR_ATmega1280__) volatile long timer3_toggle_count; volatile uint8_t *timer3_pin_port; volatile uint8_t timer3_pin_mask; volatile long timer4_toggle_count; volatile uint8_t *timer4_pin_port; volatile uint8_t timer4_pin_mask; volatile long timer5_toggle_count; volatile uint8_t *timer5_pin_port; volatile uint8_t timer5_pin_mask; #endif #if defined(__AVR_ATmega1280__) #define AVAILABLE_TONE_PINS 1 const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 3, 4, 5, 1, 0 */ }; static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255, 255, 255, 255, 255 */ }; #elif defined(__AVR_ATmega8__) #define AVAILABLE_TONE_PINS 1 const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 1 */ }; static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255 */ }; #else #define AVAILABLE_TONE_PINS 1 //##RG.Labs.20100919 begin // The warning in the next code line seems to be a gcc reported bug. // See: // http://gcc.gnu.org/ml/gcc-bugs/2008-01/msg00969.html // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734 // http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html // Leave timer 0 to last. //const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 1, 0 */ }; const uint8_t __attribute__((section(".progmem.tone"))) tone_pin_to_timer_PGM[] = { 2 /*, 1, 0 */ }; //##RG.Labs.20100919 end static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255, 255 */ }; #endif static int8_t toneBegin(uint8_t _pin) { int8_t _timer = -1; // if we're already using the pin, the timer should be configured. for (int i = 0; i < AVAILABLE_TONE_PINS; i++) { if (tone_pins[i] == _pin) { return pgm_read_byte(tone_pin_to_timer_PGM + i); } } // search for an unused timer. for (int i = 0; i < AVAILABLE_TONE_PINS; i++) { if (tone_pins[i] == 255) { tone_pins[i] = _pin; _timer = pgm_read_byte(tone_pin_to_timer_PGM + i); break; } } if (_timer != -1) { // Set timer specific stuff // All timers in CTC mode // 8 bit timers will require changing prescalar values, // whereas 16 bit timers are set to either ck/1 or ck/64 prescalar switch (_timer) { #if !defined(__AVR_ATmega8__) case 0: // 8 bit timer TCCR0A = 0; TCCR0B = 0; bitWrite(TCCR0A, WGM01, 1); bitWrite(TCCR0B, CS00, 1); timer0_pin_port = portOutputRegister(digitalPinToPort(_pin)); timer0_pin_mask = digitalPinToBitMask(_pin); break; #endif case 1: // 16 bit timer TCCR1A = 0; TCCR1B = 0; bitWrite(TCCR1B, WGM12, 1); bitWrite(TCCR1B, CS10, 1); timer1_pin_port = portOutputRegister(digitalPinToPort(_pin)); timer1_pin_mask = digitalPinToBitMask(_pin); break; case 2: // 8 bit timer TCCR2A = 0; TCCR2B = 0; bitWrite(TCCR2A, WGM21, 1); bitWrite(TCCR2B, CS20, 1); timer2_pin_port = portOutputRegister(digitalPinToPort(_pin)); timer2_pin_mask = digitalPinToBitMask(_pin); break; #if defined(__AVR_ATmega1280__) case 3: // 16 bit timer TCCR3A = 0; TCCR3B = 0; bitWrite(TCCR3B, WGM32, 1); bitWrite(TCCR3B, CS30, 1); timer3_pin_port = portOutputRegister(digitalPinToPort(_pin)); timer3_pin_mask = digitalPinToBitMask(_pin); break; case 4: // 16 bit timer TCCR4A = 0; TCCR4B = 0; bitWrite(TCCR4B, WGM42, 1); bitWrite(TCCR4B, CS40, 1); timer4_pin_port = portOutputRegister(digitalPinToPort(_pin)); timer4_pin_mask = digitalPinToBitMask(_pin); break; case 5: // 16 bit timer TCCR5A = 0; TCCR5B = 0; bitWrite(TCCR5B, WGM52, 1); bitWrite(TCCR5B, CS50, 1); timer5_pin_port = portOutputRegister(digitalPinToPort(_pin)); timer5_pin_mask = digitalPinToBitMask(_pin); break; #endif } } return _timer; } // frequency (in hertz) and duration (in milliseconds). void tone(uint8_t _pin, unsigned int frequency, unsigned long duration) { uint8_t prescalarbits = 0b001; long toggle_count = 0; uint32_t ocr = 0; int8_t _timer; _timer = toneBegin(_pin); if (_timer >= 0) { // Set the pinMode as OUTPUT pinMode(_pin, OUTPUT); // if we are using an 8 bit timer, scan through prescalars to find the best fit if (_timer == 0 || _timer == 2) { ocr = F_CPU / frequency / 2 - 1; prescalarbits = 0b001; // ck/1: same for both timers if (ocr > 255) { ocr = F_CPU / frequency / 2 / 8 - 1; prescalarbits = 0b010; // ck/8: same for both timers if (_timer == 2 && ocr > 255) { ocr = F_CPU / frequency / 2 / 32 - 1; prescalarbits = 0b011; } if (ocr > 255) { ocr = F_CPU / frequency / 2 / 64 - 1; prescalarbits = _timer == 0 ? 0b011 : 0b100; if (_timer == 2 && ocr > 255) { ocr = F_CPU / frequency / 2 / 128 - 1; prescalarbits = 0b101; } if (ocr > 255) { ocr = F_CPU / frequency / 2 / 256 - 1; prescalarbits = _timer == 0 ? 0b100 : 0b110; if (ocr > 255) { // can't do any better than /1024 ocr = F_CPU / frequency / 2 / 1024 - 1; prescalarbits = _timer == 0 ? 0b101 : 0b111; } } } } #if !defined(__AVR_ATmega8__) if (_timer == 0) TCCR0B = prescalarbits; else #endif TCCR2B = prescalarbits; } else { // two choices for the 16 bit timers: ck/1 or ck/64 ocr = F_CPU / frequency / 2 - 1; prescalarbits = 0b001; if (ocr > 0xffff) { ocr = F_CPU / frequency / 2 / 64 - 1; prescalarbits = 0b011; } if (_timer == 1) TCCR1B = (TCCR1B & 0b11111000) | prescalarbits; #if defined(__AVR_ATmega1280__) else if (_timer == 3) TCCR3B = (TCCR3B & 0b11111000) | prescalarbits; else if (_timer == 4) TCCR4B = (TCCR4B & 0b11111000) | prescalarbits; else if (_timer == 5) TCCR5B = (TCCR5B & 0b11111000) | prescalarbits; #endif } // Calculate the toggle count if (duration > 0) { toggle_count = 2 * frequency * duration / 1000; } else { toggle_count = -1; } // Set the OCR for the given timer, // set the toggle count, // then turn on the interrupts switch (_timer) { #if !defined(__AVR_ATmega8__) case 0: OCR0A = ocr; timer0_toggle_count = toggle_count; bitWrite(TIMSK0, OCIE0A, 1); break; #endif case 1: OCR1A = ocr; timer1_toggle_count = toggle_count; bitWrite(TIMSK1, OCIE1A, 1); break; case 2: OCR2A = ocr; timer2_toggle_count = toggle_count; bitWrite(TIMSK2, OCIE2A, 1); break; #if defined(__AVR_ATmega1280__) case 3: OCR3A = ocr; timer3_toggle_count = toggle_count; bitWrite(TIMSK3, OCIE3A, 1); break; case 4: OCR4A = ocr; timer4_toggle_count = toggle_count; bitWrite(TIMSK4, OCIE4A, 1); break; case 5: OCR5A = ocr; timer5_toggle_count = toggle_count; bitWrite(TIMSK5, OCIE5A, 1); break; #endif } } } // XXX: this function only works properly for timer 2 (the only one we use // currently). for the others, it should end the tone, but won't restore // proper PWM functionality for the timer. void disableTimer(uint8_t _timer) { switch (_timer) { #if !defined(__AVR_ATmega8__) case 0: TIMSK0 = 0; break; #endif case 1: bitWrite(TIMSK1, OCIE1A, 0); break; case 2: bitWrite(TIMSK2, OCIE2A, 0); // disable interrupt TCCR2A = (1 << WGM20); TCCR2B = (TCCR2B & 0b11111000) | (1 << CS22); OCR2A = 0; break; #if defined(__AVR_ATmega1280__) case 3: TIMSK3 = 0; break; case 4: TIMSK4 = 0; break; case 5: TIMSK5 = 0; break; #endif } } void noTone(uint8_t _pin) { int8_t _timer = -1; for (int i = 0; i < AVAILABLE_TONE_PINS; i++) { if (tone_pins[i] == _pin) { _timer = pgm_read_byte(tone_pin_to_timer_PGM + i); tone_pins[i] = 255; } } disableTimer(_timer); digitalWrite(_pin, 0); } #if 0 #if !defined(__AVR_ATmega8__) ISR(TIMER0_COMPA_vect) { if (timer0_toggle_count != 0) { // toggle the pin *timer0_pin_port ^= timer0_pin_mask; if (timer0_toggle_count > 0) timer0_toggle_count--; } else { disableTimer(0); *timer0_pin_port &= ~(timer0_pin_mask); // keep pin low after stop } } #endif ISR(TIMER1_COMPA_vect) { if (timer1_toggle_count != 0) { // toggle the pin *timer1_pin_port ^= timer1_pin_mask; if (timer1_toggle_count > 0) timer1_toggle_count--; } else { disableTimer(1); *timer1_pin_port &= ~(timer1_pin_mask); // keep pin low after stop } } #endif ISR(TIMER2_COMPA_vect) { if (timer2_toggle_count != 0) { // toggle the pin *timer2_pin_port ^= timer2_pin_mask; if (timer2_toggle_count > 0) timer2_toggle_count--; } else { disableTimer(2); *timer2_pin_port &= ~(timer2_pin_mask); // keep pin low after stop } } //#if defined(__AVR_ATmega1280__) #if 0 ISR(TIMER3_COMPA_vect) { if (timer3_toggle_count != 0) { // toggle the pin *timer3_pin_port ^= timer3_pin_mask; if (timer3_toggle_count > 0) timer3_toggle_count--; } else { disableTimer(3); *timer3_pin_port &= ~(timer3_pin_mask); // keep pin low after stop } } ISR(TIMER4_COMPA_vect) { if (timer4_toggle_count != 0) { // toggle the pin *timer4_pin_port ^= timer4_pin_mask; if (timer4_toggle_count > 0) timer4_toggle_count--; } else { disableTimer(4); *timer4_pin_port &= ~(timer4_pin_mask); // keep pin low after stop } } ISR(TIMER5_COMPA_vect) { if (timer5_toggle_count != 0) { // toggle the pin *timer5_pin_port ^= timer5_pin_mask; if (timer5_toggle_count > 0) timer5_toggle_count--; } else { disableTimer(5); *timer5_pin_port &= ~(timer5_pin_mask); // keep pin low after stop } } #endif
0w-experimental-arduino-core
trunk/cores/arduino-0019/Tone.cpp
C++
lgpl
13,198
/* wiring_shift.c - shiftOut() function Part of Arduino - http://www.arduino.cc/ Copyright (c) 2005-2006 David A. Mellis This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $ */ #include "wiring_private.h" uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) { uint8_t value = 0; uint8_t i; for (i = 0; i < 8; ++i) { digitalWrite(clockPin, HIGH); if (bitOrder == LSBFIRST) value |= digitalRead(dataPin) << i; else value |= digitalRead(dataPin) << (7 - i); digitalWrite(clockPin, LOW); } return value; } void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val) { uint8_t i; for (i = 0; i < 8; i++) { if (bitOrder == LSBFIRST) digitalWrite(dataPin, !!(val & (1 << i))); else digitalWrite(dataPin, !!(val & (1 << (7 - i)))); digitalWrite(clockPin, HIGH); digitalWrite(clockPin, LOW); } }
0w-experimental-arduino-core
trunk/cores/arduino-0019/wiring_shift.c
C
lgpl
1,601
#include <WProgram.h> int main(void) { init(); setup(); for (;;) loop(); return 0; }
0w-experimental-arduino-core
trunk/cores/arduino-0019/main.cpp
C++
lgpl
108
extern "C" { //#include "avr/io.h" #include "stdlib.h" } #include "CPPLib.h" void __cxa_pure_virtual() { //abort(); //See http://www.arduino.cc/playground/Code/Eclipse cli(); for (;;); } void operator delete (void *ptr) throw () { //I know: The "if" is not necessary, according to the standard. //But it's just one more line of code, and I sleep better with it: if (ptr) free (ptr); } void operator delete[] (void *ptr) throw () { ::operator delete (ptr); } void *operator new (size_t size) throw() { return malloc(size); } void *operator new[] (size_t size) throw() { return ::operator new(size); } /* void * operator new[](size_t size) { return malloc(size); } void operator delete[](void * ptr) { free(ptr); } */
0w-experimental-arduino-core
trunk/cores/arduino-0019/CPPLib.cpp
C++
lgpl
844
/* Print.cpp - Base class that provides print() and println() Copyright (c) 2008 David A. Mellis. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "wiring.h" #include "Print.h" // Public Methods ////////////////////////////////////////////////////////////// /* default implementation: may be overridden */ void Print::write(const char *str) { while (*str) write(*str++); } /* default implementation: may be overridden */ void Print::write(const uint8_t *buffer, size_t size) { while (size--) write(*buffer++); } void Print::print(const String &s) { //##RG.Labs.20100919 begin //for (int i = 0; i < s.length(); i++) { for (unsigned int i = 0; i < s.length(); i++) { //##RG.Labs.20100919 end write(s[i]); } } void Print::print(const char str[]) { write(str); } void Print::print(char c, int base) { print((long) c, base); } void Print::print(unsigned char b, int base) { print((unsigned long) b, base); } void Print::print(int n, int base) { print((long) n, base); } void Print::print(unsigned int n, int base) { print((unsigned long) n, base); } void Print::print(long n, int base) { if (base == 0) { write(n); } else if (base == 10) { if (n < 0) { print('-'); n = -n; } printNumber(n, 10); } else { printNumber(n, base); } } void Print::print(unsigned long n, int base) { if (base == 0) write(n); else printNumber(n, base); } void Print::print(double n, int digits) { printFloat(n, digits); } void Print::println(void) { print('\r'); print('\n'); } void Print::println(const String &s) { print(s); println(); } void Print::println(const char c[]) { print(c); println(); } void Print::println(char c, int base) { print(c, base); println(); } void Print::println(unsigned char b, int base) { print(b, base); println(); } void Print::println(int n, int base) { print(n, base); println(); } void Print::println(unsigned int n, int base) { print(n, base); println(); } void Print::println(long n, int base) { print(n, base); println(); } void Print::println(unsigned long n, int base) { print(n, base); println(); } void Print::println(double n, int digits) { print(n, digits); println(); } // Private Methods ///////////////////////////////////////////////////////////// void Print::printNumber(unsigned long n, uint8_t base) { unsigned char buf[8 * sizeof(long)]; // Assumes 8-bit chars. unsigned long i = 0; if (n == 0) { print('0'); return; } while (n > 0) { buf[i++] = n % base; n /= base; } for (; i > 0; i--) print((char) (buf[i - 1] < 10 ? '0' + buf[i - 1] : 'A' + buf[i - 1] - 10)); } void Print::printFloat(double number, uint8_t digits) { // Handle negative numbers if (number < 0.0) { print('-'); number = -number; } // Round correctly so that print(1.999, 2) prints as "2.00" double rounding = 0.5; for (uint8_t i=0; i<digits; ++i) rounding /= 10.0; number += rounding; // Extract the integer part of the number and print it unsigned long int_part = (unsigned long)number; double remainder = number - (double)int_part; print(int_part); // Print the decimal point, but only if there are digits beyond if (digits > 0) print("."); // Extract digits from the remainder one at a time while (digits-- > 0) { remainder *= 10.0; int toPrint = int(remainder); print(toPrint); remainder -= toPrint; } }
0w-experimental-arduino-core
trunk/cores/arduino-0019/Print.cpp
C++
lgpl
4,516
#include "wiring.h"
0w-experimental-arduino-core
trunk/cores/arduino-0019/WConstants.h
C
lgpl
20
#ifndef RGLib__h #define RGLib__h //By now, this is the only thing here. //See: //http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1284655356 const int nonAssigned_pin = -1; //Negative pins don't exist, and int is signed. #endif
0w-experimental-arduino-core
trunk/cores/arduino-0019/RGLib.h
C
lgpl
241
void setup() { } void loop() { }
0w-experimental-arduino-core
trunk/main.pde
Processing
lgpl
41
//#include "CPPLib.h" #include "WProgram.h" #include "main.pde" //Arduino-like main: int main(void) { init(); setup(); for (;;) loop(); return 0; } /* //WinAVR C++ conventional main: int main() { while(true) { } return 0; } */
0w-experimental-arduino-core
trunk/main.cpp
C++
lgpl
287
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.TAG; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.telephony.CellLocation; import android.telephony.NeighboringCellInfo; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import java.util.List; /** * A class to monitor the network signal strength. * * TODO: i18n * * @author Sandor Dornbush */ public class SignalStrengthListenerCupcake extends PhoneStateListener implements SignalStrengthListener { private static final Uri APN_URI = Uri.parse("content://telephony/carriers"); private final Context context; private final SignalStrengthCallback callback; private TelephonyManager manager; private int signalStrength = -1; public SignalStrengthListenerCupcake(Context context, SignalStrengthCallback callback) { this.context = context; this.callback = callback; } @Override public void register() { manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (manager == null) { Log.e(TAG, "Cannot get telephony manager."); } else { manager.listen(this, getListenEvents()); } } protected int getListenEvents() { return PhoneStateListener.LISTEN_SIGNAL_STRENGTH; } @SuppressWarnings("hiding") @Override public void onSignalStrengthChanged(int signalStrength) { Log.d(TAG, "Signal Strength: " + signalStrength); this.signalStrength = signalStrength; notifySignalSampled(); } protected void notifySignalSampled() { int networkType = manager.getNetworkType(); callback.onSignalStrengthSampled(getDescription(), getIcon(networkType)); } /** * Gets a human readable description for the network type. * * @param type The integer constant for the network type * @return A human readable description of the network type */ protected String getTypeAsString(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE"; case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS"; case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "UNKNOWN"; } } /** * Builds a description for the current signal strength. * * @return A human readable description of the network state */ private String getDescription() { StringBuilder sb = new StringBuilder(); sb.append(getStrengthAsString()); sb.append("Network Type: "); sb.append(getTypeAsString(manager.getNetworkType())); sb.append('\n'); sb.append("Operator: "); sb.append(manager.getNetworkOperatorName()); sb.append(" / "); sb.append(manager.getNetworkOperator()); sb.append('\n'); sb.append("Roaming: "); sb.append(manager.isNetworkRoaming()); sb.append('\n'); appendCurrentApns(sb); List<NeighboringCellInfo> infos = manager.getNeighboringCellInfo(); Log.i(TAG, "Found " + infos.size() + " cells."); if (infos.size() > 0) { sb.append("Neighbors: "); for (NeighboringCellInfo info : infos) { sb.append(info.toString()); sb.append(' '); } sb.append('\n'); } CellLocation cell = manager.getCellLocation(); if (cell != null) { sb.append("Cell: "); sb.append(cell.toString()); sb.append('\n'); } return sb.toString(); } private void appendCurrentApns(StringBuilder output) { ContentResolver contentResolver = context.getContentResolver(); Cursor cursor = contentResolver.query( APN_URI, new String[] { "name", "apn" }, "current=1", null, null); if (cursor == null) { return; } try { String name = null; String apn = null; while (cursor.moveToNext()) { int nameIdx = cursor.getColumnIndex("name"); int apnIdx = cursor.getColumnIndex("apn"); if (apnIdx < 0 || nameIdx < 0) { continue; } name = cursor.getString(nameIdx); apn = cursor.getString(apnIdx); output.append("APN: "); if (name != null) { output.append(name); } if (apn != null) { output.append(" ("); output.append(apn); output.append(")\n"); } } } finally { cursor.close(); } } /** * Gets the url for the waypoint icon for the current network type. * * @param type The network type * @return A url to a image to use as the waypoint icon */ protected String getIcon(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: return "http://maps.google.com/mapfiles/ms/micons/green.png"; case TelephonyManager.NETWORK_TYPE_UMTS: return "http://maps.google.com/mapfiles/ms/micons/blue.png"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "http://maps.google.com/mapfiles/ms/micons/red.png"; } } @Override public void unregister() { if (manager != null) { manager.listen(this, PhoneStateListener.LISTEN_NONE); manager = null; } } public String getStrengthAsString() { return "Strength: " + signalStrength + "\n"; } protected Context getContext() { return context; } public SignalStrengthCallback getSignalStrengthCallback() { return callback; } }
10812sreeja-cine
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthListenerCupcake.java
Java
asf20
6,236
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import com.google.android.apps.mytracks.signalstrength.SignalStrengthListener.SignalStrengthCallback; import android.content.Context; import android.util.Log; /** * Factory for producing a proper {@link SignalStrengthListenerCupcake} according to the * current API level. * * @author Rodrigo Damazio */ public class SignalStrengthListenerFactory { public SignalStrengthListener create(Context context, SignalStrengthCallback callback) { if (hasModernSignalStrength()) { Log.d(TAG, "TrackRecordingService using modern signal strength api."); return new SignalStrengthListenerEclair(context, callback); } else { Log.w(TAG, "TrackRecordingService using legacy signal strength api."); return new SignalStrengthListenerCupcake(context, callback); } } // @VisibleForTesting protected boolean hasModernSignalStrength() { return ANDROID_API_LEVEL >= 7; } }
10812sreeja-cine
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthListenerFactory.java
Java
asf20
1,650
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.START_SAMPLING; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.STOP_SAMPLING; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.TAG; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.signalstrength.SignalStrengthListener.SignalStrengthCallback; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.IBinder; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import java.util.List; /** * Serivce which actually reads signal strength and sends it to My Tracks. * * @author Rodrigo Damazio */ public class SignalStrengthService extends Service implements ServiceConnection, SignalStrengthCallback, OnSharedPreferenceChangeListener { private ComponentName mytracksServiceComponent; private SharedPreferences preferences; private SignalStrengthListenerFactory signalListenerFactory; private SignalStrengthListener signalListener; private ITrackRecordingService mytracksService; private long lastSamplingTime; private long samplingPeriod; @Override public void onCreate() { super.onCreate(); mytracksServiceComponent = new ComponentName( getString(R.string.mytracks_service_package), getString(R.string.mytracks_service_class)); preferences = PreferenceManager.getDefaultSharedPreferences(this); signalListenerFactory = new SignalStrengthListenerFactory(); } @Override public void onStart(Intent intent, int startId) { handleCommand(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleCommand(intent); return START_STICKY; } private void handleCommand(Intent intent) { String action = intent.getAction(); if (START_SAMPLING.equals(action)) { startSampling(); } else { stopSampling(); } } private void startSampling() { // TODO: Start foreground if (!isMytracksRunning()) { Log.w(TAG, "My Tracks not running!"); return; } Log.d(TAG, "Starting sampling"); Intent intent = new Intent(); intent.setComponent(mytracksServiceComponent); if (!bindService(intent, SignalStrengthService.this, 0)) { Log.e(TAG, "Couldn't bind to service."); return; } } private boolean isMytracksRunning() { ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo serviceInfo : services) { if (serviceInfo.pid != 0 && serviceInfo.service.equals(mytracksServiceComponent)) { return true; } } return false; } @Override public void onServiceConnected(ComponentName name, IBinder service) { synchronized (this) { mytracksService = ITrackRecordingService.Stub.asInterface(service); Log.d(TAG, "Bound to My Tracks"); boolean recording = false; try { recording = mytracksService.isRecording(); } catch (RemoteException e) { Log.e(TAG, "Failed to talk to my tracks", e); } if (!recording) { Log.w(TAG, "My Tracks is not recording, bailing"); stopSampling(); return; } // We're ready to send waypoints, so register for signal sampling signalListener = signalListenerFactory.create(this, this); signalListener.register(); // Register for preference changes samplingPeriod = Long.parseLong(preferences.getString( getString(R.string.settings_min_signal_sampling_period_key), "-1")); preferences.registerOnSharedPreferenceChangeListener(this); // Tell the user we've started. Toast.makeText(this, R.string.started_sampling, Toast.LENGTH_SHORT).show(); } } @Override public void onSignalStrengthSampled(String description, String icon) { long now = System.currentTimeMillis(); if (now - lastSamplingTime < samplingPeriod * 60 * 1000) { return; } try { long waypointId; synchronized (this) { if (mytracksService == null) { Log.d(TAG, "No my tracks service to send to"); return; } // Create a waypoint. WaypointCreationRequest request = new WaypointCreationRequest(WaypointCreationRequest.WaypointType.MARKER, "Signal Strength", description, icon); waypointId = mytracksService.insertWaypoint(request); } if (waypointId >= 0) { Log.d(TAG, "Added signal marker"); lastSamplingTime = now; } else { Log.e(TAG, "Cannot insert waypoint marker?"); } } catch (RemoteException e) { Log.e(TAG, "Cannot talk to my tracks service", e); } } private void stopSampling() { Log.d(TAG, "Stopping sampling"); synchronized (this) { // Unregister from preference change updates preferences.unregisterOnSharedPreferenceChangeListener(this); // Unregister from receiving signal updates if (signalListener != null) { signalListener.unregister(); signalListener = null; } // Unbind from My Tracks if (mytracksService != null) { unbindService(this); mytracksService = null; } // Reset the last sampling time lastSamplingTime = 0; // Tell the user we've stopped Toast.makeText(this, R.string.stopped_sampling, Toast.LENGTH_SHORT).show(); // Stop stopSelf(); } } @Override public void onServiceDisconnected(ComponentName name) { Log.i(TAG, "Disconnected from My Tracks"); synchronized (this) { mytracksService = null; } } @Override public void onDestroy() { stopSampling(); super.onDestroy(); } @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { if (getString(R.string.settings_min_signal_sampling_period_key).equals(key)) { samplingPeriod = Long.parseLong(sharedPreferences.getString(key, "-1")); } } @Override public IBinder onBind(Intent intent) { return null; } public static void startService(Context context) { Intent intent = new Intent(); intent.setClass(context, SignalStrengthService.class); intent.setAction(START_SAMPLING); context.startService(intent); } public static void stopService(Context context) { Intent intent = new Intent(); intent.setClass(context, SignalStrengthService.class); intent.setAction(STOP_SAMPLING); context.startService(intent); } }
10812sreeja-cine
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthService.java
Java
asf20
7,870
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import android.content.Context; import android.telephony.PhoneStateListener; import android.telephony.SignalStrength; import android.telephony.TelephonyManager; import android.util.Log; /** * A class to monitor the network signal strength. * * TODO: i18n * * @author Sandor Dornbush */ public class SignalStrengthListenerEclair extends SignalStrengthListenerCupcake { private SignalStrength signalStrength = null; public SignalStrengthListenerEclair(Context ctx, SignalStrengthCallback callback) { super(ctx, callback); } @Override protected int getListenEvents() { return PhoneStateListener.LISTEN_SIGNAL_STRENGTHS; } @SuppressWarnings("hiding") @Override public void onSignalStrengthsChanged(SignalStrength signalStrength) { Log.d(TAG, "Signal Strength Modern: " + signalStrength); this.signalStrength = signalStrength; notifySignalSampled(); } /** * Gets a human readable description for the network type. * * @param type The integer constant for the network type * @return A human readable description of the network type */ @Override protected String getTypeAsString(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_1xRTT: return "1xRTT"; case TelephonyManager.NETWORK_TYPE_CDMA: return "CDMA"; case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE"; case TelephonyManager.NETWORK_TYPE_EVDO_0: return "EVDO 0"; case TelephonyManager.NETWORK_TYPE_EVDO_A: return "EVDO A"; case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS"; case TelephonyManager.NETWORK_TYPE_HSDPA: return "HSDPA"; case TelephonyManager.NETWORK_TYPE_HSPA: return "HSPA"; case TelephonyManager.NETWORK_TYPE_HSUPA: return "HSUPA"; case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "UNKNOWN"; } } /** * Gets the url for the waypoint icon for the current network type. * * @param type The network type * @return A url to a image to use as the waypoint icon */ @Override protected String getIcon(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: return "http://maps.google.com/mapfiles/ms/micons/green.png"; case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_UMTS: return "http://maps.google.com/mapfiles/ms/micons/blue.png"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "http://maps.google.com/mapfiles/ms/micons/red.png"; } } @Override public String getStrengthAsString() { if (signalStrength == null) { return "Strength: " + getContext().getString(R.string.unknown) + "\n"; } StringBuffer sb = new StringBuffer(); if (signalStrength.isGsm()) { appendSignal(signalStrength.getGsmSignalStrength(), R.string.gsm_strength, sb); maybeAppendSignal(signalStrength.getGsmBitErrorRate(), R.string.error_rate, sb); } else { appendSignal(signalStrength.getCdmaDbm(), R.string.cdma_strength, sb); appendSignal(signalStrength.getCdmaEcio() / 10.0, R.string.ecio, sb); appendSignal(signalStrength.getEvdoDbm(), R.string.evdo_strength, sb); appendSignal(signalStrength.getEvdoEcio() / 10.0, R.string.ecio, sb); appendSignal(signalStrength.getEvdoSnr(), R.string.signal_to_noise_ratio, sb); } return sb.toString(); } private void maybeAppendSignal( int signal, int signalFormat, StringBuffer sb) { if (signal > 0) { sb.append(getContext().getString(signalFormat, signal)); } } private void appendSignal(int signal, int signalFormat, StringBuffer sb) { sb.append(getContext().getString(signalFormat, signal)); sb.append("\n"); } private void appendSignal(double signal, int signalFormat, StringBuffer sb) { sb.append(getContext().getString(signalFormat, signal)); sb.append("\n"); } }
10812sreeja-cine
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthListenerEclair.java
Java
asf20
5,243
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; /** * Main signal strength sampler activity, which displays preferences. * * @author Rodrigo Damazio */ public class SignalStrengthPreferences extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); // Attach service control funciontality findPreference(getString(R.string.settings_control_start_key)) .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { SignalStrengthService.startService(SignalStrengthPreferences.this); return true; } }); findPreference(getString(R.string.settings_control_stop_key)) .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { SignalStrengthService.stopService(SignalStrengthPreferences.this); return true; } }); // TODO: Check that my tracks is installed - if not, give a warning and // offer to go to the android market. } }
10812sreeja-cine
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthPreferences.java
Java
asf20
2,044
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import android.os.Build; /** * Constants for the signal sampler. * * @author Rodrigo Damazio */ public class SignalStrengthConstants { public static final String START_SAMPLING = "com.google.android.apps.mytracks.signalstrength.START"; public static final String STOP_SAMPLING = "com.google.android.apps.mytracks.signalstrength.STOP"; public static final int ANDROID_API_LEVEL = Integer.parseInt( Build.VERSION.SDK); public static final String TAG = "SignalStrengthSampler"; private SignalStrengthConstants() {} }
10812sreeja-cine
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthConstants.java
Java
asf20
1,200
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; /** * Interface for the service that reads signal strength. * * @author Rodrigo Damazio */ public interface SignalStrengthListener { /** * Interface for getting notified about a new sampled signal strength. */ public interface SignalStrengthCallback { void onSignalStrengthSampled( String description, String icon); } /** * Starts listening to signal strength. */ void register(); /** * Stops listening to signal strength. */ void unregister(); }
10812sreeja-cine
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/SignalStrengthListener.java
Java
asf20
1,157
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; /** * Broadcast listener which gets notified when we start or stop recording a track. * * @author Rodrigo Damazio */ public class RecordingStateReceiver extends BroadcastReceiver { @Override public void onReceive(Context ctx, Intent intent) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx); String action = intent.getAction(); if (ctx.getString(R.string.track_started_broadcast_action).equals(action)) { boolean autoStart = preferences.getBoolean( ctx.getString(R.string.settings_auto_start_key), false); if (!autoStart) { Log.d(TAG, "Not auto-starting signal sampling"); return; } startService(ctx); } else if (ctx.getString(R.string.track_stopped_broadcast_action).equals(action)) { boolean autoStop = preferences.getBoolean( ctx.getString(R.string.settings_auto_stop_key), true); if (!autoStop) { Log.d(TAG, "Not auto-stopping signal sampling"); return; } stopService(ctx); } else { Log.e(TAG, "Unknown action received: " + action); } } // @VisibleForTesting protected void stopService(Context ctx) { SignalStrengthService.stopService(ctx); } // @VisibleForTesting protected void startService(Context ctx) { SignalStrengthService.startService(ctx); } }
10812sreeja-cine
SignalStrengthSampler/src/com/google/android/apps/mytracks/signalstrength/RecordingStateReceiver.java
Java
asf20
2,316
/* * Copyright 2010 Dynastream Innovations Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.dsi.ant; /** * The Android Ant API is not finalized, and *will* be updated and expanded. * This is the base level ANT messaging API and gives any application full * control over the ANT radio HW. Caution should be exercised when using * this interface. * * Public API for controlling the Ant Service. * * {@hide} */ interface IAnt { // Since version 1 (1.0): boolean enable(); boolean disable(); boolean isEnabled(); boolean ANTTxMessage(in byte[] message); boolean ANTResetSystem(); boolean ANTUnassignChannel(byte channelNumber); boolean ANTAssignChannel(byte channelNumber, byte channelType, byte networkNumber); boolean ANTSetChannelId(byte channelNumber, int deviceNumber, byte deviceType, byte txType); boolean ANTSetChannelPeriod(byte channelNumber, int channelPeriod); boolean ANTSetChannelRFFreq(byte channelNumber, byte radioFrequency); boolean ANTSetChannelSearchTimeout(byte channelNumber, byte searchTimeout); boolean ANTSetLowPriorityChannelSearchTimeout(byte channelNumber, byte searchTimeout); boolean ANTSetProximitySearch(byte channelNumber, byte searchThreshold); boolean ANTSetChannelTxPower(byte channelNumber, byte txPower); boolean ANTAddChannelId(byte channelNumber, int deviceNumber, byte deviceType, byte txType, byte listIndex); boolean ANTConfigList(byte channelNumber, byte listSize, byte exclude); boolean ANTOpenChannel(byte channelNumber); boolean ANTCloseChannel(byte channelNumber); boolean ANTRequestMessage(byte channelNumber, byte messageID); boolean ANTSendBroadcastData(byte channelNumber, in byte[] txBuffer); boolean ANTSendAcknowledgedData(byte channelNumber, in byte[] txBuffer); boolean ANTSendBurstTransferPacket(byte control, in byte[] txBuffer); int ANTSendBurstTransfer(byte channelNumber, in byte[] txBuffer); int ANTTransmitBurst(byte channelNumber, in byte[] txBuffer, int initialPacket, boolean containsEndOfBurst); // Since version 4 (1.3): boolean ANTConfigEventBuffering(int screenOnFlushTimerInterval, int screenOnFlushBufferThreshold, int screenOffFlushTimerInterval, int screenOffFlushBufferThreshold); // Since version 2 (1.1): boolean ANTDisableEventBuffering(); // Since version 3 (1.2): int getServiceLibraryVersionCode(); String getServiceLibraryVersionName(); }
10812sreeja-cine
MyTracks/src/com/dsi/ant/IAnt.aidl
AIDL
asf20
3,017
/* * Copyright 2010 Dynastream Innovations Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.dsi.ant; /** * The Android Ant API is not finalized, and *will* change. Use at your * own risk. * * Public API for controlling the Ant Service. * AntDefines contains definitions commonly used in ANT messaging. * * @hide */ public class AntDefine { ////////////////////////////////////////////// // Valid Configuration Values ////////////////////////////////////////////// public static final byte MIN_BIN = 0; public static final byte MAX_BIN = 10; public static final short MIN_DEVICE_ID = 0; public static final short MAX_DEVICE_ID = (short)65535; public static final short MIN_BUFFER_THRESHOLD = 0; public static final short MAX_BUFFER_THRESHOLD = 996; ////////////////////////////////////////////// // ANT Message Payload Size ////////////////////////////////////////////// public static final byte ANT_STANDARD_DATA_PAYLOAD_SIZE =((byte)8); ////////////////////////////////////////////// // ANT LIBRARY Extended Data Message Fields // NOTE: You must check the extended message // bitfield first to find out which fields // are present before accessing them! ////////////////////////////////////////////// public static final byte ANT_EXT_MESG_DEVICE_ID_FIELD_SIZE =((byte)4); //public static final byte ANT_EXT_STRING_SIZE =((byte)19); // this is the additional buffer space required required for setting USB Descriptor strings public static final byte ANT_EXT_STRING_SIZE =((byte)0); // changed to 0 as we will not be dealing with ANT USB parts. ////////////////////////////////////////////// // ANT Extended Data Message Bifield Definitions ////////////////////////////////////////////// public static final byte ANT_EXT_MESG_BITFIELD_DEVICE_ID =((byte)0x80); // first field after bitfield public static final byte ANT_EXT_MESG_BITFIELD_RSSI =((byte)0x40); // next field after ID, if there is one public static final byte ANT_EXT_MESG_BITFIELD_TIME_STAMP =((byte)0x20); // next field after RSSI, if there is one // 4 bits free reserved set to 0 public static final byte ANT_EXT_MESG_BIFIELD_EXTENSION =((byte)0x01); // extended message input bitfield defines public static final byte ANT_EXT_MESG_BITFIELD_OVERWRITE_SHARED_ADR =((byte)0x10); public static final byte ANT_EXT_MESG_BITFIELD_TRANSMISSION_TYPE =((byte)0x08); ////////////////////////////////////////////// // ID Definitions ////////////////////////////////////////////// public static final byte ANT_ID_SIZE =((byte)4); public static final byte ANT_ID_TRANS_TYPE_OFFSET =((byte)3); public static final byte ANT_ID_DEVICE_TYPE_OFFSET =((byte)2); public static final byte ANT_ID_DEVICE_NUMBER_HIGH_OFFSET =((byte)1); public static final byte ANT_ID_DEVICE_NUMBER_LOW_OFFSET =((byte)0); public static final byte ANT_ID_DEVICE_TYPE_PAIRING_FLAG =((byte)0x80); public static final byte ANT_TRANS_TYPE_SHARED_ADDR_MASK =((byte)0x03); public static final byte ANT_TRANS_TYPE_1_BYTE_SHARED_ADDRESS =((byte)0x02); public static final byte ANT_TRANS_TYPE_2_BYTE_SHARED_ADDRESS =((byte)0x03); ////////////////////////////////////////////// // Assign Channel Parameters ////////////////////////////////////////////// public static final byte PARAMETER_RX_NOT_TX =((byte)0x00); public static final byte PARAMETER_TX_NOT_RX =((byte)0x10); public static final byte PARAMETER_SHARED_CHANNEL =((byte)0x20); public static final byte PARAMETER_NO_TX_GUARD_BAND =((byte)0x40); public static final byte PARAMETER_ALWAYS_RX_WILD_CARD_SEARCH_ID =((byte)0x40); //Pre-AP2 public static final byte PARAMETER_RX_ONLY =((byte)0x40); ////////////////////////////////////////////// // Ext. Assign Channel Parameters ////////////////////////////////////////////// public static final byte EXT_PARAM_ALWAYS_SEARCH =((byte)0x01); public static final byte EXT_PARAM_FREQUENCY_AGILITY =((byte)0x04); ////////////////////////////////////////////// // Radio TX Power Definitions ////////////////////////////////////////////// public static final byte RADIO_TX_POWER_LVL_MASK =((byte)0x03); public static final byte RADIO_TX_POWER_LVL_0 =((byte)0x00); //(formerly: RADIO_TX_POWER_MINUS20DB); lowest public static final byte RADIO_TX_POWER_LVL_1 =((byte)0x01); //(formerly: RADIO_TX_POWER_MINUS10DB); public static final byte RADIO_TX_POWER_LVL_2 =((byte)0x02); //(formerly: RADIO_TX_POWER_MINUS5DB); public static final byte RADIO_TX_POWER_LVL_3 =((byte)0x03); //(formerly: RADIO_TX_POWER_0DB); highest ////////////////////////////////////////////// // Channel Status ////////////////////////////////////////////// public static final byte STATUS_CHANNEL_STATE_MASK =((byte)0x03); public static final byte STATUS_UNASSIGNED_CHANNEL =((byte)0x00); public static final byte STATUS_ASSIGNED_CHANNEL =((byte)0x01); public static final byte STATUS_SEARCHING_CHANNEL =((byte)0x02); public static final byte STATUS_TRACKING_CHANNEL =((byte)0x03); ////////////////////////////////////////////// // Standard capabilities defines ////////////////////////////////////////////// public static final byte CAPABILITIES_NO_RX_CHANNELS =((byte)0x01); public static final byte CAPABILITIES_NO_TX_CHANNELS =((byte)0x02); public static final byte CAPABILITIES_NO_RX_MESSAGES =((byte)0x04); public static final byte CAPABILITIES_NO_TX_MESSAGES =((byte)0x08); public static final byte CAPABILITIES_NO_ACKD_MESSAGES =((byte)0x10); public static final byte CAPABILITIES_NO_BURST_TRANSFER =((byte)0x20); ////////////////////////////////////////////// // Advanced capabilities defines ////////////////////////////////////////////// public static final byte CAPABILITIES_OVERUN_UNDERRUN =((byte)0x01); // Support for this functionality has been dropped public static final byte CAPABILITIES_NETWORK_ENABLED =((byte)0x02); public static final byte CAPABILITIES_AP1_VERSION_2 =((byte)0x04); // This Version of the AP1 does not support transmit and only had a limited release public static final byte CAPABILITIES_SERIAL_NUMBER_ENABLED =((byte)0x08); public static final byte CAPABILITIES_PER_CHANNEL_TX_POWER_ENABLED =((byte)0x10); public static final byte CAPABILITIES_LOW_PRIORITY_SEARCH_ENABLED =((byte)0x20); public static final byte CAPABILITIES_SCRIPT_ENABLED =((byte)0x40); public static final byte CAPABILITIES_SEARCH_LIST_ENABLED =((byte)0x80); ////////////////////////////////////////////// // Advanced capabilities 2 defines ////////////////////////////////////////////// public static final byte CAPABILITIES_LED_ENABLED =((byte)0x01); public static final byte CAPABILITIES_EXT_MESSAGE_ENABLED =((byte)0x02); public static final byte CAPABILITIES_SCAN_MODE_ENABLED =((byte)0x04); public static final byte CAPABILITIES_RESERVED =((byte)0x08); public static final byte CAPABILITIES_PROX_SEARCH_ENABLED =((byte)0x10); public static final byte CAPABILITIES_EXT_ASSIGN_ENABLED =((byte)0x20); public static final byte CAPABILITIES_FREE_1 =((byte)0x40); public static final byte CAPABILITIES_FIT1_ENABLED =((byte)0x80); ////////////////////////////////////////////// // Advanced capabilities 3 defines ////////////////////////////////////////////// public static final byte CAPABILITIES_SENSRCORE_ENABLED =((byte)0x01); public static final byte CAPABILITIES_RESERVED_1 =((byte)0x02); public static final byte CAPABILITIES_RESERVED_2 =((byte)0x04); public static final byte CAPABILITIES_RESERVED_3 =((byte)0x08); ////////////////////////////////////////////// // Burst Message Sequence ////////////////////////////////////////////// public static final byte CHANNEL_NUMBER_MASK =((byte)0x1F); public static final byte SEQUENCE_NUMBER_MASK =((byte)0xE0); public static final byte SEQUENCE_NUMBER_ROLLOVER =((byte)0x60); public static final byte SEQUENCE_FIRST_MESSAGE =((byte)0x00); public static final byte SEQUENCE_LAST_MESSAGE =((byte)0x80); public static final byte SEQUENCE_NUMBER_INC =((byte)0x20); ////////////////////////////////////////////// // Control Message Flags ////////////////////////////////////////////// public static final byte BROADCAST_CONTROL_BYTE =((byte)0x00); public static final byte ACKNOWLEDGED_CONTROL_BYTE =((byte)0xA0); ////////////////////////////////////////////// // Response / Event Codes ////////////////////////////////////////////// public static final byte RESPONSE_NO_ERROR =((byte)0x00); public static final byte NO_EVENT =((byte)0x00); public static final byte EVENT_RX_SEARCH_TIMEOUT =((byte)0x01); public static final byte EVENT_RX_FAIL =((byte)0x02); public static final byte EVENT_TX =((byte)0x03); public static final byte EVENT_TRANSFER_RX_FAILED =((byte)0x04); public static final byte EVENT_TRANSFER_TX_COMPLETED =((byte)0x05); public static final byte EVENT_TRANSFER_TX_FAILED =((byte)0x06); public static final byte EVENT_CHANNEL_CLOSED =((byte)0x07); public static final byte EVENT_RX_FAIL_GO_TO_SEARCH =((byte)0x08); public static final byte EVENT_CHANNEL_COLLISION =((byte)0x09); public static final byte EVENT_TRANSFER_TX_START =((byte)0x0A); // a pending transmit transfer has begun public static final byte EVENT_CHANNEL_ACTIVE =((byte)0x0F); public static final byte EVENT_TRANSFER_TX_NEXT_MESSAGE =((byte)0x11); // only enabled in FIT1 public static final byte CHANNEL_IN_WRONG_STATE =((byte)0x15); // returned on attempt to perform an action from the wrong channel state public static final byte CHANNEL_NOT_OPENED =((byte)0x16); // returned on attempt to communicate on a channel that is not open public static final byte CHANNEL_ID_NOT_SET =((byte)0x18); // returned on attempt to open a channel without setting the channel ID public static final byte CLOSE_ALL_CHANNELS =((byte)0x19); // returned when attempting to start scanning mode, when channels are still open public static final byte TRANSFER_IN_PROGRESS =((byte)0x1F); // returned on attempt to communicate on a channel with a TX transfer in progress public static final byte TRANSFER_SEQUENCE_NUMBER_ERROR =((byte)0x20); // returned when sequence number is out of order on a Burst transfer public static final byte TRANSFER_IN_ERROR =((byte)0x21); public static final byte TRANSFER_BUSY =((byte)0x22); public static final byte INVALID_MESSAGE_CRC =((byte)0x26); // returned if there is a framing error on an incomming message public static final byte MESSAGE_SIZE_EXCEEDS_LIMIT =((byte)0x27); // returned if a data message is provided that is too large public static final byte INVALID_MESSAGE =((byte)0x28); // returned when the message has an invalid parameter public static final byte INVALID_NETWORK_NUMBER =((byte)0x29); // returned when an invalid network number is provided public static final byte INVALID_LIST_ID =((byte)0x30); // returned when the provided list ID or size exceeds the limit public static final byte INVALID_SCAN_TX_CHANNEL =((byte)0x31); // returned when attempting to transmit on channel 0 when in scan mode public static final byte INVALID_PARAMETER_PROVIDED =((byte)0x33); // returned when an invalid parameter is specified in a configuration message public static final byte EVENT_SERIAL_QUE_OVERFLOW =((byte)0x34); public static final byte EVENT_QUE_OVERFLOW =((byte)0x35); // ANT event que has overflowed and lost 1 or more events public static final byte EVENT_CLK_ERROR =((byte)0x36); // debug event for XOSC16M on LE1 public static final byte SCRIPT_FULL_ERROR =((byte)0x40); // error writing to script, memory is full public static final byte SCRIPT_WRITE_ERROR =((byte)0x41); // error writing to script, bytes not written correctly public static final byte SCRIPT_INVALID_PAGE_ERROR =((byte)0x42); // error accessing script page public static final byte SCRIPT_LOCKED_ERROR =((byte)0x43); // the scripts are locked and can't be dumped public static final byte NO_RESPONSE_MESSAGE =((byte)0x50); // returned to the Command_SerialMessageProcess function, so no reply message is generated public static final byte RETURN_TO_MFG =((byte)0x51); // default return to any mesg when the module determines that the mfg procedure has not been fully completed public static final byte FIT_ACTIVE_SEARCH_TIMEOUT =((byte)0x60); // Fit1 only event added for timeout of the pairing state after the Fit module becomes active public static final byte FIT_WATCH_PAIR =((byte)0x61); // Fit1 only public static final byte FIT_WATCH_UNPAIR =((byte)0x62); // Fit1 only public static final byte USB_STRING_WRITE_FAIL =((byte)0x70); // Internal only events below this point public static final byte INTERNAL_ONLY_EVENTS =((byte)0x80); public static final byte EVENT_RX =((byte)0x80); // INTERNAL: Event for a receive message public static final byte EVENT_NEW_CHANNEL =((byte)0x81); // INTERNAL: EVENT for a new active channel public static final byte EVENT_PASS_THRU =((byte)0x82); // INTERNAL: Event to allow an upper stack events to pass through lower stacks public static final byte EVENT_BLOCKED =((byte)0xFF); // INTERNAL: Event to replace any event we do not wish to go out, will also zero the size of the Tx message /////////////////////////////////////////////////////// // Script Command Codes /////////////////////////////////////////////////////// public static final byte SCRIPT_CMD_FORMAT =((byte)0x00); public static final byte SCRIPT_CMD_DUMP =((byte)0x01); public static final byte SCRIPT_CMD_SET_DEFAULT_SECTOR =((byte)0x02); public static final byte SCRIPT_CMD_END_SECTOR =((byte)0x03); public static final byte SCRIPT_CMD_END_DUMP =((byte)0x04); public static final byte SCRIPT_CMD_LOCK =((byte)0x05); /////////////////////////////////////////////////////// // Reset Mesg Codes /////////////////////////////////////////////////////// public static final byte RESET_FLAGS_MASK =((byte)0xE0); public static final byte RESET_SUSPEND =((byte)0x80); // this must follow bitfield def public static final byte RESET_SYNC =((byte)0x40); // this must follow bitfield def public static final byte RESET_CMD =((byte)0x20); // this must follow bitfield def public static final byte RESET_WDT =((byte)0x02); public static final byte RESET_RST =((byte)0x01); public static final byte RESET_POR =((byte)0x00); }
10812sreeja-cine
MyTracks/src/com/dsi/ant/AntDefine.java
Java
asf20
17,797
/* * Copyright 2011 Dynastream Innovations Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.dsi.ant; /** * Defines version numbers * * @hide */ public class Version { ////////////////////////////////////////////// // Library Version Information ////////////////////////////////////////////// public static final int ANT_LIBRARY_VERSION_CODE = 6; public static final int ANT_LIBRARY_VERSION_MAJOR = 2; public static final int ANT_LIBRARY_VERSION_MINOR = 0; public static final String ANT_LIBRARY_VERSION_NAME = String.valueOf(ANT_LIBRARY_VERSION_MAJOR) + "." + String.valueOf(ANT_LIBRARY_VERSION_MINOR); }
10812sreeja-cine
MyTracks/src/com/dsi/ant/Version.java
Java
asf20
1,193
/* * Copyright 2010 Dynastream Innovations Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.dsi.ant; /** * Public API for controlling the Ant Service. * AntMesg contains definitions for ANT message IDs * * @hide */ public class AntMesg { ///////////////////////////////////////////////////////////////////////////// // HCI VS Message Format // Messages are in the format: // // Outgoing ANT messages (host -> ANT chip) // 01 D1 FD XX YY YY II JJ ------ // ^ ^ ^ ^ // | HCI framing | | ANT Mesg | // // where: 01 is the 1 byte HCI packet Identifier (HCI Command packet) // D1 FD is the 2 byte HCI op code (0xFDD1 stored in little endian) // XX is the 1 byte Length of all parameters in bytes (number of bytes in the HCI packet after this byte) // YY YY is the 2 byte Parameter describing the length of the entire ANT message (II JJ ------) stored in little endian // II is the 1 byte size of the ANT message (0-249) // JJ is the 1 byte ID of the ANT message (1-255, 0 is invalid) // ------ is the data of the ANT message (0-249 bytes of data) // // Incoming HCI Command Complete for ANT message command (host <- ANT chip) // 04 0E 04 01 D1 FD ZZ // // where: 04 is the 1 byte HCI packet Identifier (HCI Event packet) // 0E is the 1 byte HCI event (Command Complete) // 04 is the 1 byte Length of all parameters in bytes (there are 4 bytes) // 01 is the 1 byte Number of parameters in the packet (there is 1 parameter) // D1 FD is the 2 byte HCI Op code of the command (0xFDD1 stored in little endian) // ZZ is the 1 byte response to the command (0x00 - Command Successful // 0x1F - Returned if the receive message queue of the ANT chip is full, the command should be retried // Other - Any other non-zero response code indicates an error) // // Incoming ANT messages (host <- ANT chip) // 04 FF XX 00 05 YY YY II JJ ------ // ^ ^ ^ ^ // | HCI framing | | ANT Mesg | // // where: 04 is the 1 byte HCI packet Identifier (HCI Event packet) // FF is the 1 byte HCI event code (0xFF Vendor Specific event) // XX is the 1 byte Length of all parameters in bytes (number of bytes in the HCI packet after this byte) // 00 05 is the 2 byte vendor specific event code for ANT messages (0x0500 stored in little endian) // YY YY is the 2 byte Parameter describing the length of the entire ANT message (II JJ ------) stored in little endian // II is the 1 byte size of the ANT message (0-249) // JJ is the 1 byte ID of the ANT message (1-255, 0 is invalid) // ------ is the data of the ANT message (0-249 bytes of data) // ///////////////////////////////////////////////////////////////////////////// public static final byte MESG_SYNC_SIZE =((byte)0); // Ant messages are embedded in HCI messages we do not include a sync byte public static final byte MESG_SIZE_SIZE =((byte)1); public static final byte MESG_ID_SIZE =((byte)1); public static final byte MESG_CHANNEL_NUM_SIZE =((byte)1); public static final byte MESG_EXT_MESG_BF_SIZE =((byte)1); // NOTE: this could increase in the future public static final byte MESG_CHECKSUM_SIZE =((byte)0); // Ant messages are embedded in HCI messages we do not include a checksum public static final byte MESG_DATA_SIZE =((byte)9); // The largest serial message is an ANT data message with all of the extended fields public static final byte MESG_ANT_MAX_PAYLOAD_SIZE =AntDefine.ANT_STANDARD_DATA_PAYLOAD_SIZE; public static final byte MESG_MAX_EXT_DATA_SIZE =(AntDefine.ANT_EXT_MESG_DEVICE_ID_FIELD_SIZE + AntDefine.ANT_EXT_STRING_SIZE); // ANT device ID (4 bytes) + Padding for ANT EXT string size(19 bytes) public static final byte MESG_MAX_DATA_SIZE =(MESG_ANT_MAX_PAYLOAD_SIZE + MESG_EXT_MESG_BF_SIZE + MESG_MAX_EXT_DATA_SIZE); // ANT data payload (8 bytes) + extended bitfield (1 byte) + extended data (10 bytes) public static final byte MESG_MAX_SIZE_VALUE =(MESG_MAX_DATA_SIZE + MESG_CHANNEL_NUM_SIZE); // this is the maximum value that the serial message size value is allowed to be public static final byte MESG_BUFFER_SIZE =(MESG_SIZE_SIZE + MESG_ID_SIZE + MESG_CHANNEL_NUM_SIZE + MESG_MAX_DATA_SIZE + MESG_CHECKSUM_SIZE); public static final byte MESG_FRAMED_SIZE =(MESG_ID_SIZE + MESG_CHANNEL_NUM_SIZE + MESG_MAX_DATA_SIZE); public static final byte MESG_HEADER_SIZE =(MESG_SYNC_SIZE + MESG_SIZE_SIZE + MESG_ID_SIZE); public static final byte MESG_FRAME_SIZE =(MESG_HEADER_SIZE + MESG_CHECKSUM_SIZE); public static final byte MESG_MAX_SIZE =(MESG_MAX_DATA_SIZE + MESG_FRAME_SIZE); public static final byte MESG_SIZE_OFFSET =(MESG_SYNC_SIZE); public static final byte MESG_ID_OFFSET =(MESG_SYNC_SIZE + MESG_SIZE_SIZE); public static final byte MESG_DATA_OFFSET =(MESG_HEADER_SIZE); public static final byte MESG_RECOMMENDED_BUFFER_SIZE =((byte) 64); // This is the recommended size for serial message buffers if there are no RAM restrictions on the system ////////////////////////////////////////////// // Message ID's ////////////////////////////////////////////// public static final byte MESG_INVALID_ID =((byte)0x00); public static final byte MESG_EVENT_ID =((byte)0x01); public static final byte MESG_VERSION_ID =((byte)0x3E); public static final byte MESG_RESPONSE_EVENT_ID =((byte)0x40); public static final byte MESG_UNASSIGN_CHANNEL_ID =((byte)0x41); public static final byte MESG_ASSIGN_CHANNEL_ID =((byte)0x42); public static final byte MESG_CHANNEL_MESG_PERIOD_ID =((byte)0x43); public static final byte MESG_CHANNEL_SEARCH_TIMEOUT_ID =((byte)0x44); public static final byte MESG_CHANNEL_RADIO_FREQ_ID =((byte)0x45); public static final byte MESG_NETWORK_KEY_ID =((byte)0x46); public static final byte MESG_RADIO_TX_POWER_ID =((byte)0x47); public static final byte MESG_RADIO_CW_MODE_ID =((byte)0x48); public static final byte MESG_SYSTEM_RESET_ID =((byte)0x4A); public static final byte MESG_OPEN_CHANNEL_ID =((byte)0x4B); public static final byte MESG_CLOSE_CHANNEL_ID =((byte)0x4C); public static final byte MESG_REQUEST_ID =((byte)0x4D); public static final byte MESG_BROADCAST_DATA_ID =((byte)0x4E); public static final byte MESG_ACKNOWLEDGED_DATA_ID =((byte)0x4F); public static final byte MESG_BURST_DATA_ID =((byte)0x50); public static final byte MESG_CHANNEL_ID_ID =((byte)0x51); public static final byte MESG_CHANNEL_STATUS_ID =((byte)0x52); public static final byte MESG_RADIO_CW_INIT_ID =((byte)0x53); public static final byte MESG_CAPABILITIES_ID =((byte)0x54); public static final byte MESG_STACKLIMIT_ID =((byte)0x55); public static final byte MESG_SCRIPT_DATA_ID =((byte)0x56); public static final byte MESG_SCRIPT_CMD_ID =((byte)0x57); public static final byte MESG_ID_LIST_ADD_ID =((byte)0x59); public static final byte MESG_ID_LIST_CONFIG_ID =((byte)0x5A); public static final byte MESG_OPEN_RX_SCAN_ID =((byte)0x5B); public static final byte MESG_EXT_CHANNEL_RADIO_FREQ_ID =((byte)0x5C); // OBSOLETE: (for 905 radio) public static final byte MESG_EXT_BROADCAST_DATA_ID =((byte)0x5D); public static final byte MESG_EXT_ACKNOWLEDGED_DATA_ID =((byte)0x5E); public static final byte MESG_EXT_BURST_DATA_ID =((byte)0x5F); public static final byte MESG_CHANNEL_RADIO_TX_POWER_ID =((byte)0x60); public static final byte MESG_GET_SERIAL_NUM_ID =((byte)0x61); public static final byte MESG_GET_TEMP_CAL_ID =((byte)0x62); public static final byte MESG_SET_LP_SEARCH_TIMEOUT_ID =((byte)0x63); public static final byte MESG_SET_TX_SEARCH_ON_NEXT_ID =((byte)0x64); public static final byte MESG_SERIAL_NUM_SET_CHANNEL_ID_ID =((byte)0x65); public static final byte MESG_RX_EXT_MESGS_ENABLE_ID =((byte)0x66); public static final byte MESG_RADIO_CONFIG_ALWAYS_ID =((byte)0x67); public static final byte MESG_ENABLE_LED_FLASH_ID =((byte)0x68); public static final byte MESG_XTAL_ENABLE_ID =((byte)0x6D); public static final byte MESG_STARTUP_MESG_ID =((byte)0x6F); public static final byte MESG_AUTO_FREQ_CONFIG_ID =((byte)0x70); public static final byte MESG_PROX_SEARCH_CONFIG_ID =((byte)0x71); public static final byte MESG_EVENT_BUFFERING_CONFIG_ID =((byte)0x74); public static final byte MESG_CUBE_CMD_ID =((byte)0x80); public static final byte MESG_GET_PIN_DIODE_CONTROL_ID =((byte)0x8D); public static final byte MESG_PIN_DIODE_CONTROL_ID =((byte)0x8E); public static final byte MESG_FIT1_SET_AGC_ID =((byte)0x8F); public static final byte MESG_FIT1_SET_EQUIP_STATE_ID =((byte)0x91); // *** CONFLICT: w/ Sensrcore, Fit1 will never have sensrcore enabled // Sensrcore Messages public static final byte MESG_SET_CHANNEL_INPUT_MASK_ID =((byte)0x90); public static final byte MESG_SET_CHANNEL_DATA_TYPE_ID =((byte)0x91); public static final byte MESG_READ_PINS_FOR_SECT_ID =((byte)0x92); public static final byte MESG_TIMER_SELECT_ID =((byte)0x93); public static final byte MESG_ATOD_SETTINGS_ID =((byte)0x94); public static final byte MESG_SET_SHARED_ADDRESS_ID =((byte)0x95); public static final byte MESG_ATOD_EXTERNAL_ENABLE_ID =((byte)0x96); public static final byte MESG_ATOD_PIN_SETUP_ID =((byte)0x97); public static final byte MESG_SETUP_ALARM_ID =((byte)0x98); public static final byte MESG_ALARM_VARIABLE_MODIFY_TEST_ID =((byte)0x99); public static final byte MESG_PARTIAL_RESET_ID =((byte)0x9A); public static final byte MESG_OVERWRITE_TEMP_CAL_ID =((byte)0x9B); public static final byte MESG_SERIAL_PASSTHRU_SETTINGS_ID =((byte)0x9C); public static final byte MESG_BIST_ID =((byte)0xAA); public static final byte MESG_UNLOCK_INTERFACE_ID =((byte)0xAD); public static final byte MESG_SERIAL_ERROR_ID =((byte)0xAE); public static final byte MESG_SET_ID_STRING_ID =((byte)0xAF); public static final byte MESG_PORT_GET_IO_STATE_ID =((byte)0xB4); public static final byte MESG_PORT_SET_IO_STATE_ID =((byte)0xB5); public static final byte MESG_SLEEP_ID =((byte)0xC5); public static final byte MESG_GET_GRMN_ESN_ID =((byte)0xC6); public static final byte MESG_SET_USB_INFO_ID =((byte)0xC7); public static final byte MESG_COMMAND_COMPLETE_RESPONSE_ID =((byte)0xC8); ////////////////////////////////////////////// // Command complete results ////////////////////////////////////////////// public static final byte MESG_COMMAND_COMPLETE_SUCCESS =((byte)0x00); public static final byte MESG_COMMAND_COMPLETE_RETRY =((byte)0x1F); ////////////////////////////////////////////// // Message Sizes ////////////////////////////////////////////// public static final byte MESG_INVALID_SIZE =((byte)0); public static final byte MESG_VERSION_SIZE =((byte)13); public static final byte MESG_RESPONSE_EVENT_SIZE =((byte)3); public static final byte MESG_CHANNEL_STATUS_SIZE =((byte)2); public static final byte MESG_UNASSIGN_CHANNEL_SIZE =((byte)1); public static final byte MESG_ASSIGN_CHANNEL_SIZE =((byte)3); public static final byte MESG_CHANNEL_ID_SIZE =((byte)5); public static final byte MESG_CHANNEL_MESG_PERIOD_SIZE =((byte)3); public static final byte MESG_CHANNEL_SEARCH_TIMEOUT_SIZE =((byte)2); public static final byte MESG_CHANNEL_RADIO_FREQ_SIZE =((byte)2); public static final byte MESG_CHANNEL_RADIO_TX_POWER_SIZE =((byte)2); public static final byte MESG_NETWORK_KEY_SIZE =((byte)9); public static final byte MESG_RADIO_TX_POWER_SIZE =((byte)2); public static final byte MESG_RADIO_CW_MODE_SIZE =((byte)3); public static final byte MESG_RADIO_CW_INIT_SIZE =((byte)1); public static final byte MESG_SYSTEM_RESET_SIZE =((byte)1); public static final byte MESG_OPEN_CHANNEL_SIZE =((byte)1); public static final byte MESG_CLOSE_CHANNEL_SIZE =((byte)1); public static final byte MESG_REQUEST_SIZE =((byte)2); public static final byte MESG_CAPABILITIES_SIZE =((byte)6); public static final byte MESG_STACKLIMIT_SIZE =((byte)2); public static final byte MESG_SCRIPT_DATA_SIZE =((byte)10); public static final byte MESG_SCRIPT_CMD_SIZE =((byte)3); public static final byte MESG_ID_LIST_ADD_SIZE =((byte)6); public static final byte MESG_ID_LIST_CONFIG_SIZE =((byte)3); public static final byte MESG_OPEN_RX_SCAN_SIZE =((byte)1); public static final byte MESG_EXT_CHANNEL_RADIO_FREQ_SIZE =((byte)3); public static final byte MESG_RADIO_CONFIG_ALWAYS_SIZE =((byte)2); public static final byte MESG_RX_EXT_MESGS_ENABLE_SIZE =((byte)2); public static final byte MESG_SET_TX_SEARCH_ON_NEXT_SIZE =((byte)2); public static final byte MESG_SET_LP_SEARCH_TIMEOUT_SIZE =((byte)2); public static final byte MESG_SERIAL_NUM_SET_CHANNEL_ID_SIZE =((byte)3); public static final byte MESG_ENABLE_LED_FLASH_SIZE =((byte)2); public static final byte MESG_GET_SERIAL_NUM_SIZE =((byte)4); public static final byte MESG_GET_TEMP_CAL_SIZE =((byte)4); public static final byte MESG_XTAL_ENABLE_SIZE =((byte)1); public static final byte MESG_STARTUP_MESG_SIZE =((byte)1); public static final byte MESG_AUTO_FREQ_CONFIG_SIZE =((byte)4); public static final byte MESG_PROX_SEARCH_CONFIG_SIZE =((byte)2); public static final byte MESG_GET_PIN_DIODE_CONTROL_SIZE =((byte)1); public static final byte MESG_PIN_DIODE_CONTROL_ID_SIZE =((byte)2); public static final byte MESG_FIT1_SET_EQUIP_STATE_SIZE =((byte)2); public static final byte MESG_FIT1_SET_AGC_SIZE =((byte)3); public static final byte MESG_BIST_SIZE =((byte)6); public static final byte MESG_UNLOCK_INTERFACE_SIZE =((byte)1); public static final byte MESG_SET_SHARED_ADDRESS_SIZE =((byte)3); public static final byte MESG_GET_GRMN_ESN_SIZE =((byte)5); public static final byte MESG_PORT_SET_IO_STATE_SIZE =((byte)5); public static final byte MESG_EVENT_BUFFERING_CONFIG_SIZE =((byte)6); public static final byte MESG_SLEEP_SIZE =((byte)1); public static final byte MESG_EXT_DATA_SIZE =((byte)13); protected AntMesg() { } }
10812sreeja-cine
MyTracks/src/com/dsi/ant/AntMesg.java
Java
asf20
16,889
/* * Copyright 2011 Dynastream Innovations Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.dsi.ant; /** * The Android Ant API is not finalized, and *will* be updated and expanded. * This is the base level ANT messaging API and gives any application full * control over the ANT radio HW. Caution should be exercised when using * this interface. * * Public API for controlling the Ant Service. * * {@hide} */ interface IAnt_6 { // Since version 1 (1.0): boolean enable(); boolean disable(); boolean isEnabled(); boolean ANTTxMessage(in byte[] message); boolean ANTResetSystem(); boolean ANTUnassignChannel(byte channelNumber); boolean ANTAssignChannel(byte channelNumber, byte channelType, byte networkNumber); boolean ANTSetChannelId(byte channelNumber, int deviceNumber, byte deviceType, byte txType); boolean ANTSetChannelPeriod(byte channelNumber, int channelPeriod); boolean ANTSetChannelRFFreq(byte channelNumber, byte radioFrequency); boolean ANTSetChannelSearchTimeout(byte channelNumber, byte searchTimeout); boolean ANTSetLowPriorityChannelSearchTimeout(byte channelNumber, byte searchTimeout); boolean ANTSetProximitySearch(byte channelNumber, byte searchThreshold); boolean ANTSetChannelTxPower(byte channelNumber, byte txPower); boolean ANTAddChannelId(byte channelNumber, int deviceNumber, byte deviceType, byte txType, byte listIndex); boolean ANTConfigList(byte channelNumber, byte listSize, byte exclude); boolean ANTOpenChannel(byte channelNumber); boolean ANTCloseChannel(byte channelNumber); boolean ANTRequestMessage(byte channelNumber, byte messageID); boolean ANTSendBroadcastData(byte channelNumber, in byte[] txBuffer); boolean ANTSendAcknowledgedData(byte channelNumber, in byte[] txBuffer); boolean ANTSendBurstTransferPacket(byte control, in byte[] txBuffer); int ANTSendBurstTransfer(byte channelNumber, in byte[] txBuffer); int ANTTransmitBurst(byte channelNumber, in byte[] txBuffer, int initialPacket, boolean containsEndOfBurst); // Since version 4 (1.3): boolean ANTConfigEventBuffering(int screenOnFlushTimerInterval, int screenOnFlushBufferThreshold, int screenOffFlushTimerInterval, int screenOffFlushBufferThreshold); // Since version 2 (1.1): boolean ANTDisableEventBuffering(); // Since version 3 (1.2): int getServiceLibraryVersionCode(); String getServiceLibraryVersionName(); // Since version 6 (1.5): boolean claimInterface(); boolean requestForceClaimInterface(String appName); boolean stopRequestForceClaimInterface(); boolean releaseInterface(); boolean hasClaimedInterface(); }
10812sreeja-cine
MyTracks/src/com/dsi/ant/IAnt_6.aidl
AIDL
asf20
3,249
/* * Copyright 2010 Dynastream Innovations Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.dsi.ant; /** * * API for configuring the non-ANT components of the ANT Service. * * {@hide} */ interface IServiceSettings { void debugLogging(boolean debug); boolean setNumCombinedBurstPackets(int numPackets); int getNumCombinedBurstPackets(); }
10812sreeja-cine
MyTracks/src/com/dsi/ant/IServiceSettings.aidl
AIDL
asf20
902