Pesquisar neste blog

02/11/2021

Fatorial #1 com MIPS Assembly

.data
promptMessage: .asciiz "Entre com o número do fatorial: "
resultMessage: .asciiz "\nFatorial = "
theNumber: .word 0
theAnswer: .word 0
.text
.globl main
main:
#leia o número do usuário
li $v0, 4
la $a0, promptMessage
syscall
li $v0, 5
syscall
sw $v0, theNumber
#Chama a função fatorial
lw $a0, theNumber
jal findFactorial
sw $v0, theAnswer
#Exibi os resultados
li $v0, 4
la $a0, resultMessage
syscall
li $v0, 1
lw $a0, theAnswer
syscall
#Informa ao sistema que este é o fim do programa
li $v0, 10
syscall
#--------------------
# função findFactorial
.globl findFactorial
findFactorial:
subu $sp, $sp, 8
sw $ra, ($sp)
sw $s0, 4($sp)
#Base caso
li $v0, 1
beq $a0, 0, factorialDone
#findFactorial (o número -1)
move $s0, $a0
sub $a0, $a0, 1
jal findFactorial
#A mágia acontece aqui
mul $v0, $s0, $v0
factorialDone:
lw $ra, ($sp)
lw $s0, 4($sp)
addu $sp, $sp, 8
jr $ra

Saída gerada no MARS 4.5
























Palavras chave:

Factorial with MIPS Assembly
Factorial con ensamblaje MIPS
Faktoriell med MIPS-montering
פקטוריאלי עם MIPS Assembly
Silnia z zespołem MIPS
MIPS সমাবেশের সাথে ফ্যাক্টরিয়াল
Faktorial dengan Majelis MIPS
Факториал с MIPS монтаж
Factorial cu Asamblare MIPS

17/10/2021

Soma, subtração, divisão e multiplicação com MIPS Assembly

.data
#soma
num1: .asciiz "Digite o primeiro numero: "
num2: .asciiz "Digite o segundo numero: "
Resultado: .asciiz "Soma = "

#subtração
n1: .asciiz "\n\nDigite o 1° num: "
n2: .asciiz "Digite o 2° num: "
result: .asciiz "Subração = "

#divisão
x1: .asciiz "\n\nDigite o 1° número: "
x2: .asciiz "Digite o 2° número: "
Rdiv: .asciiz "Divisão = "

#multiplicação
k1: .asciiz "\n\nDigite o 1° número: "
k2: .asciiz "Digite o 2° número: "
Mult: .asciiz "Multiplicação = "
.text
li $v0, 4
la $a0, num1
syscall

li $v0, 5
syscall
move $t0, $v0

li $v0, 4
la $a0, num2
syscall

li $v0, 5
syscall
move $t1, $v0

#tendo os dois valores 
add $t2, $t0, $t1
li $v0, 4
la $a0, Resultado
syscall

li $v0, 1
move $a0, $t2
syscall

#subtração
li $v0, 4
la $a0, n1
syscall

li $v0, 5
syscall

move $t0, $v0 #move para o registrador

li $v0, 4
la $a0, n2
syscall

li $v0, 5
syscall

move $t1, $v0

sub $t2, $t0, $t1

li $v0, 4
la $a0, result
syscall

li $v0, 1
move $a0, $t2
syscall

#bloco da divisão
li $v0, 4
la $a0, x1
syscall

li $v0, 5
syscall

move $t0, $v0

li $v0, 4
la $a0, x2
syscall

li $v0, 5
syscall

move $t1, $v0
div $t0, $t1

mflo $s3 #pega o valor menor
li $v0, 4
la $a0, Rdiv
syscall

li $v0, 1
move $a0, $s3
syscall

#multiplicação
li $v0, 4
la $a0, k1
syscall

li $v0, 5
syscall

move $t0, $v0

li $v0, 4
la $a0, k2
syscall

li $v0, 5
syscall

move $t1, $v0

mult $t0, $t1

mflo $s3

li $v0, 4
la $a0, Mult
syscall

li $v0, 1
move $a0, $s3
syscall

Saída gerada




Loop de repetição com Mips MARS - Assembly

CÓDIGO FEITO NO MARS4

.data
pergunta: .asciiz "Digite a sua idade: "
msg1: .asciiz "Você é menor de idade\n"
msg2: .asciiz "Você é maior de idade\n"
.text
.globl prog #aponta para o programa principal

prog: # função principal
li $v0, 4 # imprimir uma string
la $a0, pergunta # a0 = pergunta
syscall # Executar
li $v0, 5 # Faz a leitura de um número inteiro
syscall # Executa
move $t1, $v0 # t1 = v0
beq $t1, $0, sair # Desvia para o bloco sair
blt $t1, 18, menor # Desvia para o bloco menor
bge $t1, 18, maior # Devia para o bloco maior
j prog # DESVIA PARA O BLOCO PROG

menor: 
li $v0, 4 # Imprimi uma string
la $a0, msg1 # a0 = msg1
syscall
j prog #DESVIA PARA O jprog

maior:
li $v0, 4 # IMPRIMI UMA STRING
la $a0, msg2 # a0 = msg2
syscall
j prog # DESVIA PARA O BLOCO PROG

sair:
li $v0, 10 # FINALIZAR
syscall # EXECUTAR

Saída gerada



15/10/2021

Motor de passo no PicSimlab

CÓDIGO FEITO NO CCS C Compiler

#include <16F877A.h>
#device adc=8
#FUSES NOWDT //No Watch Dog Timer
#FUSES HS //High speed Osc (> 4mhz for PCM/PCH) (>10mhz for PCD)
#FUSES PUT //Power Up Timer
#FUSES NOPROTECT //Code not protected from reading
#FUSES NODEBUG //No Debug mode for ICD
#FUSES BROWNOUT //Reset when brownout detected
#FUSES NOLVP //No low voltage prgming, B3(PIC16) or B5(PIC18) used for I/O
#FUSES NOCPD //No EE protection
#FUSES NOWRT //Program memory not write protected
#use delay(clock=20000000)
unsigned int8 posicao[4] = {3, 6, 12, 9}; // {1, 2, 4, 8};
 //3=0011 6=0110 12=1100 9=1001
signed int8 passo=0;
int1 dar_passo=0;
signed int8 sentido=-1;
unsigned int8 ref_passo=10,contador=0;
unsigned int16 ref_mcc=127;
//================== MOTOR PASSO =================================//
#int_RTCC

void RTCC_isr(void)
{
 if(++contador > ref_passo){
 passo = passo + sentido;
 if(passo>3)passo=0;
 if(passo<0)passo=3;
 OUTPUT_D(posicao[passo]);
 contador = 0;
 }
}
#int_TIMER1
void TIMER1_isr(void)
{
 //== Motor CC ======//
 set_adc_channel(0);
 delay_us( 50 );
 ref_mcc = read_adc();
 if(ref_mcc<1) ref_mcc =1;
 if(ref_mcc>254) ref_mcc =254;
 set_pwm1_duty(4*ref_mcc);

 //== Motor Passo ======//
 set_adc_channel(1);
 delay_us( 50 );
 ref_passo = read_adc();
 if(ref_passo<1) ref_passo =1;
 
 if(ref_passo>254) ref_passo =254;
}
//================== Interrupção externa B0 =====================//
#int_EXT
void EXT_isr(void)
{
sentido *= (-1);
}
//================== SERVOMOTOR =================================//
void Rotation0() //0 Degree
 {
 unsigned int i;
 for(i=0;i<50;i++)
 {
 output_high(PIN_C7);
 delay_us(800); // pulse of 800us
 output_low(PIN_C7);
 delay_us(19200);
 }
 }
void Rotation45() //0 Degree
{
 unsigned int i;
 for(i=0;i<50;i++)
 {
 output_high(PIN_C7);
 delay_us(1150); // pulse of 800us // 1400 - 180o
 output_low(PIN_C7); // x 45o
 delay_us(18850);
 }
 }
void Rotation90() //90 Degree
 {
 unsigned int i;
 for(i=0;i<50;i++)
 { // 180o 0o
 output_high(PIN_C7); // 2200 - 800 = 1400 90o = 700
 delay_us(1500); // pulse of 1500us
 output_low(PIN_C7);
 delay_us(18500);
 }
 }
void Rotation180() //180 Degree
 {
unsigned int i;
 for(i=0;i<50;i++)
 {
 output_high(PIN_C7);
 delay_us(2200); // pulse of 2200us
 output_low(PIN_C7);
 delay_us(17800);
 }
 }
 
 void main()
{
 setup_adc_ports(AN0_AN1_AN2_AN3_AN4);
 setup_adc(ADC_CLOCK_DIV_16);

 setup_psp(PSP_DISABLED);
 setup_spi(SPI_SS_DISABLED);
 setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
 setup_timer_1(T1_INTERNAL|T1_DIV_BY_8);
 setup_timer_2(T2_DIV_BY_16,255,1);
 setup_ccp1(CCP_PWM);
 set_pwm1_duty(512);

 setup_comparator(NC_NC_NC_NC);
 setup_vref(FALSE);
 enable_interrupts(INT_EXT);
 ext_int_edge( L_TO_H );

 enable_interrupts(INT_RTCC);
 enable_interrupts(INT_TIMER1);
 enable_interrupts(GLOBAL);
 set_adc_channel(1);
 delay_us( 50 );


 while(true){
 Rotation0(); // 0 graus
 delay_ms(4000);
 Rotation90(); // 90 graus
 delay_ms(4000);
 Rotation180(); // 180 graus
 delay_ms(4000);
 Rotation45(); // 45 graus
 delay_ms(6000);
 }
}



















22/09/2021

PWM #02 com PIC 16F628A

 Código feito no CCS C Compiler

#include <16F628A.h>
#FUSES NOWDT
#FUSES NOBROWNOUT
#FUSES NOLVP

#use delay(crystal = 4MHz)
int16 ton, toff;
unsigned int cont = 0;

void main(){
   while(true){
      if(++ton >= 1000) ton = 0;
      toff = 1000 - ton;
      
      for(cont =1; cont <= 10; cont++){//vai repetir 10 vezes o valor
         output_high(PIN_A0);
         delay_us(ton);
         toff = 1000 - ton;
         output_low(pin_A0);
         delay_us(toff);
      }

   }
}


Emulador: PIC SimLab










20/09/2021

PWM #01 com PIC 16F628A no PIC SimLab

Código feito no CCS C Compiler

#include <16F628A.h>
#FUSES NOWDT
#FUSES NOBROWNOUT
#FUSES NOLVP

#use delay(crystal = 4MHz)

int16 ton, toff;
unsigned int cont = 0;
signed int cd = 1;

void main(){
   while(true){
   
      ton = ton + cd;
      
      if(ton >= 1000) cd = -1;
      if(ton <= 0) cd = 1;
      
      toff = 1000 - ton;
      
      for(cont =1; cont <= 10; cont++){//vai repetir 10 vezes o valor
         output_high(PIN_A0);
         delay_us(ton);
         toff = 1000 - ton;
         output_low(pin_A0);
         delay_us(toff);
      }
      
      
      
   }
}












08/07/2021

Plugin #02 com jQuery em HTML

TEMPORIZADOR EM HTML USANDO jQuery

Arquivo: estilo.css
@font-face {
    font-family'Oswald';
    srcurl('../fonts/Oswald-Regular.ttf'format('truetype');
}

*{
    font-family'Oswald'sans-serif;
}

html {
    height100%;
}

body {
    margin0;
    background-color#0D262D;
    color#fff;
    height100%;
}

table {
    border-collapsecollapse;
}

tr {
    border-bottomsolid 1px white;
}

td {
    font-size1.6em;
    padding10px;
}

li {
    font-size1.6em;
}

.conteudo {
    displayflex;
    flex-directioncolumn;
    align-itemscenter;
    min-height100%;
}

.exercicio div {
    font-size1.8em;
    bordersolid 5px #fff;
    padding0px 40px;
    margin10px;
}

.exercicio div:nth-of-type(1) {
    background-colordarkgoldenrod;
}

.exercicio div:nth-of-type(2) {
    background-colorcrimson;
}

.exercicio div:nth-of-type(3) {
    background-colordarkcyan;
}

.exercicio div:nth-of-type(4) {
    background-colordarkorchid;
}

.exercicio div:nth-of-type(5) {
    background-colordodgerblue;
}

.exercicio div:nth-of-type(6) {
    background-colorsalmon;
}

.exercicio .destaque {
    bordersolid 10px greenyellow;
    colorgreenyellow;
    font-weightbold;
}

Arquivo: temporizador.js
(function ($) {
    $.fn.temporizador = function (opcoes) {
        const opcoesFinais = $.extend({
            mensagem: 'Em breve!',
            horario: '23:59:59'
        }, opcoes)

        const horaDezena = $('<span class="digito">').html('0')
        const horaUnidade = $('<span class="digito">').html('0')
        const minutoDezena = $('<span class="digito">').html('0')
        const minutoUnidade = $('<span class="digito">').html('0')
        const segundoDezena = $('<span class="digito">').html('0')
        const segundoUnidade = $('<span class="digito">').html('0')

        const separadorHora = $('<span class="separador">').html(':')
        const separadorMinuto = $('<span class="separador">').html(':')
        const mensagem = $('<div class="mensagem">').html(opcoesFinais.mensagem)

        $(this).addClass('temporizador')
        $(this).append(horaDezenahoraUnidadeseparadorHora,
            minutoDezenaminutoUnidadeseparadorMinuto,
            segundoDezenasegundoUnidademensagem)

        const regex = new RegExp(/(\d\d):(\d\d):(\d\d)/)
        const horarioAlvo = regex.exec(opcoesFinais.horario)
        // console.log(horarioAlvo)

        let temporizador = setInterval(() => {
            const agora = new Date()
            const alvo = new Date()
            alvo.setHours(horarioAlvo[1])
            alvo.setMinutes(horarioAlvo[2])
            alvo.setSeconds(horarioAlvo[3])

            const diferencaEmMili = alvo.getTime() - agora.getTime()
            if (diferencaEmMili >= 0) {
                const diferenca = regex.exec(new Date(diferencaEmMili).toISOString())
                console.log(diferenca)

                horaDezena.html(diferenca[1][0])
                horaUnidade.html(diferenca[1][1])
                minutoDezena.html(diferenca[2][0])
                minutoUnidade.html(diferenca[2][1])
                segundoDezena.html(diferenca[3][0])
                segundoUnidade.html(diferenca[3][1])
            } else {
                clearInterval(temporizador)
            }
        }, 1000)
        
        return this
    }
})(jQuery)

Arquivo: plugin2.html
<!DOCTYPE html>
<html>

<head>
    <meta charset='UTF-8'>
    <title>Plugin #02</title>
    <link rel='stylesheet' href='css/temporizador.css'>
    <script src='js/jquery.js'></script>
</head>

<body>
    <h1>Plugin #02 - Temporizador</h1>
    <div></div>
    <script src="js/temporizador.js"></script>
    <script>
        // ...
        $('div').temporizador({
            mensagem: 'Em breve um novo site para você',
            horario: '20:00:00'
        }).hide().fadeIn(3000)
    </script>
</body>

Arquivo: jquery.js CLIQUE AQUI para fazer o download do arquivo




07/07/2021

Plugin #01 com jQuery em HTML

Arquivo: estilo.css
@font-face {
    font-family'Oswald';
    srcurl('../fonts/Oswald-Regular.ttf'format('truetype');
}

*{
    font-family'Oswald'sans-serif;
}

html {
    height100%;
}

body {
    margin0;
    background-color#0D262D;
    color#fff;
    height100%;
}

table {
    border-collapsecollapse;
}

tr {
    border-bottomsolid 1px white;
}

td {
    font-size1.6em;
    padding10px;
}

li {
    font-size1.6em;
}

.conteudo {
    displayflex;
    flex-directioncolumn;
    align-itemscenter;
    min-height100%;
}

.exercicio div {
    font-size1.8em;
    bordersolid 5px #fff;
    padding0px 40px;
    margin10px;
}

.exercicio div:nth-of-type(1) {
    background-colordarkgoldenrod;
}

.exercicio div:nth-of-type(2) {
    background-colorcrimson;
}

.exercicio div:nth-of-type(3) {
    background-colordarkcyan;
}

.exercicio div:nth-of-type(4) {
    background-colordarkorchid;
}

.exercicio div:nth-of-type(5) {
    background-colordodgerblue;
}

.exercicio div:nth-of-type(6) {
    background-colorsalmon;
}

.exercicio .destaque {
    bordersolid 10px greenyellow;
    colorgreenyellow;
    font-weightbold;
}

Arquivo: plugin1.html
<!DOCTYPE html>
<html>

<head>
    <meta charset='UTF-8'>
    <title>Plugin #01</title>
    <link rel='stylesheet' href='css/estilo.css'>
    <script src='js/jquery.js'></script>
</head>

<body class='conteudo exercicio'>
    <h1>Plugin #01</h1>
    <div>
        {{ 1 + 2 }}
        Texto 1
        {{ 3 ** 3 }}
        Texto 2
        {{ console.log('Funcionou!') }}
        Texto 3
        {{ (function() { return 'Legal!!!' })() }}
        Texto Final
    </div>

    <script>
        //Objetivo: converter o texto acima em algo concreto
        //const $ = {nome: 'Não é o jQuery'}
        (function ($) {
            $.fn.interpretar = function (){
                const retirarChaves = s => s.substring(2s.length -2)
                const conteudo = $(this).html()
                const expressoesComChaves = conteudo.match(/\{\{.+\}\}/g)
                const expressoes = expressoesComChaves.map(retirarChaves)
                const resultados = expressoes.map(e => eval(e))

                let conteudoFinal = conteudo
                for(let i = 0i < expressoesComChaves.lengthi++){
                    conteudoFinal = conteudoFinal.replace(
                        expressoesComChaves[i], resultados[i]
                    )
                }
                $(this).html(conteudoFinal)
            }
        })(jQuery)
        $('div').interpretar()//chamando o plugin
    </script>
</body>

Arquivo: jquery.js CLIQUE AQUI para fazer o download do arquivo







06/07/2021

Animação #02 com jQuery em HTML

Arquivo: estilo.css
@font-face {
    font-family'Oswald';
    srcurl('../fonts/Oswald-Regular.ttf'format('truetype');
}

*{
    font-family'Oswald'sans-serif;
}

html {
    height100%;
}

body {
    margin0;
    background-color#0D262D;
    color#fff;
    height100%;
}

table {
    border-collapsecollapse;
}

tr {
    border-bottomsolid 1px white;
}

td {
    font-size1.6em;
    padding10px;
}

li {
    font-size1.6em;
}

.conteudo {
    displayflex;
    flex-directioncolumn;
    align-itemscenter;
    min-height100%;
}

.exercicio div {
    font-size1.8em;
    bordersolid 5px #fff;
    padding0px 40px;
    margin10px;
}

.exercicio div:nth-of-type(1) {
    background-colordarkgoldenrod;
}

.exercicio div:nth-of-type(2) {
    background-colorcrimson;
}

.exercicio div:nth-of-type(3) {
    background-colordarkcyan;
}

.exercicio div:nth-of-type(4) {
    background-colordarkorchid;
}

.exercicio div:nth-of-type(5) {
    background-colordodgerblue;
}

.exercicio div:nth-of-type(6) {
    background-colorsalmon;
}

.exercicio .destaque {
    bordersolid 10px greenyellow;
    colorgreenyellow;
    font-weightbold;
}

Arquivo: animacao2.html
<!DOCTYPE html>
<html>

<head>
    <meta charset='UTF-8'>
    <title>Animação #02</title>
    <link rel='stylesheet' href='css/estilo.css'>
    <script src='js/jquery.js'></script>
    <style>
        body {
            positionrelative;
            background-color#999;
            color#000;
        }

        div {
            positionabsolute;
            displayinline;
            bordersolid 10px #000;
            padding50px;
            font-size3em;
            background-colorcrimson;
        }
    </style>
</head>

<body>
    <div>Animar!</div>

    <script>
        //Função para alterar largura
        function alterarLargura(valorduracaocallback) {
            $('div').animate({ width: `+=${valor}` }, duracao
                , callback)
        }

        //função para mover na diagonal
        function moverDiagonal(valorduracaocallback) {
            $('div').animate({ top: `+=${valor}`left: `+=${valor}` }
                , duracaocallback)
        }

        //função de girar
        function girar(valorduracaocallback) {
            $('div').animate({ transform: `+=${valor}` }, {
                step: function (valor) {
                    $(this).css('transform'`rotate(${valor}deg)`)
                },
                duration: duracao
            }, 'linear'callback)
        }

        //chamando as funções
        alterarLargura(300100, () => {
            alterarLargura(-300'slow', () => {
                moverDiagonal(300600, () => {
                    girar(33003000)
                })
            })
        })
    </script>
</body>


Arquivo: jquery.js clique aqui para fazer o download
































01/07/2021

Animação #01 com jQuery em HTML

Arquivo: estilo.css

@font-face {
    font-family'Oswald';
    srcurl('../fonts/Oswald-Regular.ttf'format('truetype');
}

*{
    font-family'Oswald'sans-serif;
}

html {
    height100%;
}

body {
    margin0;
    background-color#0D262D;
    color#fff;
    height100%;
}

table {
    border-collapsecollapse;
}

tr {
    border-bottomsolid 1px white;
}

td {
    font-size1.6em;
    padding10px;
}

li {
    font-size1.6em;
}

.conteudo {
    displayflex;
    flex-directioncolumn;
    align-itemscenter;
    min-height100%;
}

.exercicio div {
    font-size1.8em;
    bordersolid 5px #fff;
    padding0px 40px;
    margin10px;
}

.exercicio div:nth-of-type(1) {
    background-colordarkgoldenrod;
}

.exercicio div:nth-of-type(2) {
    background-colorcrimson;
}

.exercicio div:nth-of-type(3) {
    background-colordarkcyan;
}

.exercicio div:nth-of-type(4) {
    background-colordarkorchid;
}

.exercicio div:nth-of-type(5) {
    background-colordodgerblue;
}

.exercicio div:nth-of-type(6) {
    background-colorsalmon;
}

.exercicio .destaque {
    bordersolid 10px greenyellow;
    colorgreenyellow;
    font-weightbold;
}

Arquivo: animacao1.html

<!DOCTYPE html>
<html>

<head>
    <meta charset='UTF-8'>
    <title>Animação #01</title>
    <link rel='stylesheet' href='css/estilo.css'>
    <script src='js/jquery.js'></script>
    <style>
        div {
            text-aligncenter;
        }
        button {
            font-size1.8em;
            margin10px;
        }
    </style>
</head>

<body class='conteudo exercicio'>
    <h1>Animação #01</h1>
    <button>Iniciar</button>
    <div id='animar'>Animar!</div>

    <script>        
        // tempo da animação
        $('button').click(e =>{
            const t = 450
            $('#animar').hide(t).show(t)
            //$('#animar').fadeOut(t).fadeIn(t)//se estiver exibindo vai esconder e vice verso
            $('#animar').fadeToggle(t).fadeToggle(t)
            //$('#animar').slideUp(t).slideDown(t)
            $('#animar').slideToggle(t).slideToggle(t)
        })

    </script>
</body>

Arquivo: jquery.js clique aqui para fazer o download