예제 #1
0
def test_avr():
    avr = Avr(mcu='atmega48', f_cpu=8000000)

    eq_(avr.f_cpu, 8000000)
    eq_(avr.mcu, 'atmega48')
    eq_(avr.pc, 0)
    avr.step(1)
    eq_(avr.pc, 2)
예제 #2
0
파일: test.py 프로젝트: blinthicum/pysimavr
def test_avr():
    avr = Avr(mcu='atmega48', f_cpu=8000000)

    eq_(avr.f_cpu, 8000000)
    eq_(avr.mcu, 'atmega48')
    eq_(avr.pc, 0)
    avr.step(1)
    eq_(avr.pc, 2)
예제 #3
0
def test_background_thread():
    cc = AvrGcc(mcu=mcu)
    cc.build('int main(){}')
    fw = Firmware(cc.output)
    avr = Avr(mcu=mcu, firmware=fw, f_cpu=8000000)    
    eq_(avr.state, cpu_Running, "mcu is not running")
    avr.goto_cycle(100)
    eq_(avr.state, cpu_Running, "mcu is not running")
    avr.terminate()
예제 #4
0
 def __init__(self, sock, mcu_name, freq=16000000, version=1):
     self.mcu_name = mcu_name
     self.mcu = Avr(mcu=mcu_name, f_cpu=freq)
     self.socket = sock
     self.fw_path = None
     self.version = version
     self.bind_callback_for_digit_pins(atmega_328_digit_pin_table)
     self.vcd = None
     self.connect_vcd()
예제 #5
0
def test_fw_3():
    cc = AvrGcc(mcu=mcu)
    cc.build('int main(){}')
    fw = Firmware(cc.output)

    avr = Avr(mcu=mcu, f_cpu=8000000)
    avr.load_firmware(fw)
    eq_(avr.f_cpu, 8000000)
    eq_(avr.mcu, 'atmega48')
예제 #6
0
def test_fw_1():
    cc = AvrGcc(mcu=mcu)
    cc.build('int main(){}')
    fw = Firmware(cc.output)

    avr = Avr(mcu=mcu, firmware=fw, f_cpu=8000000)
    eq_(avr.f_cpu, 8000000)
    eq_(avr.frequency, avr.f_cpu)
    eq_(avr.mcu, 'atmega48')
    avr.terminate()
예제 #7
0
def test_fw_1():
    cc = AvrGcc(mcu=mcu)
    cc.build('int main(){}')
    fw = Firmware(cc.output)

    avr = Avr(mcu=mcu, firmware=fw, f_cpu=8000000)
    eq_(avr.f_cpu, 8000000)
    eq_(avr.frequency, avr.f_cpu)
    eq_(avr.mcu, 'atmega48')
    avr.terminate()
예제 #8
0
파일: sim.py 프로젝트: blinthicum/pysimavr
    def simulate(self):
        elf = self.cc.output

        # run
        firmware = Firmware(elf)
        avr = Avr(mcu=self.cc.mcu, f_cpu=self.cc.f_cpu)
        avr.load_firmware(firmware)
#        udpReader = UdpReader()
#        udp = Udp(avr)
#        udp.connect()
#        udpReader.start()

        simvcd = None
        if self.vcd:
            simvcd = VcdFile(avr, period=1000, filename=self.vcd)
            connect_pins_by_rule('''
                                avr.D0 ==> vcd
                                avr.D1 ==> vcd
                                avr.D2 ==> vcd
                                avr.D3 ==> vcd
                                avr.D4 ==> vcd
                                avr.D5 ==> vcd
                                avr.D6 ==> vcd
                                avr.D7 ==> vcd

                                avr.B0 ==> vcd
                                avr.B1 ==> vcd
                                avr.B2 ==> vcd
                                avr.B3 ==> vcd
                                avr.B4 ==> vcd
                                avr.B5 ==> vcd
                                ''',
                                 dict(
                                 avr=avr,
                                 ),
                                 vcd=simvcd,
                                 )
            simvcd.start()

# not working
#        if self.serial_in:
#            avr.uart.send_string(self.serial_in)
        avr.move_time_marker(self.timespan)

        while avr.time_passed() < self.timespan * 0.99:
            time.sleep(0.05)

        if simvcd:
            simvcd.terminate()
#        udpReader.terminate()

        log.debug('cycles=%s' % avr.cycle)
        log.debug('mcu time=%s' % avr.time_passed())
#        time.sleep(1)
        self.serial_data = avr.uart.buffer
        self.serial = ''.join(self.serial_data)
        avr.terminate()
예제 #9
0
def test_timer_cancel():
    avr = Avr(mcu='atmega88', f_cpu=1000000)
    callbackMock = Mock(return_value=200)
    timer = avr.timer(callbackMock, cycle=50)
    avr.step(10)
    callbackMock.assert_not_called()

    timer.cancel()
    avr.step(1000)
    callbackMock.assert_not_called()

    avr.terminate()
예제 #10
0
def run_sim(vcdfile='lcd.vcd', speed=0.1, fps=20, timeout=0.0, visible=1, image_file=''):
    firmware = Firmware(path(__file__).dirname() / 'lcd.elf')
    avr = Avr(firmware, f_cpu=16000000)
    lcd = Lcd(avr)
    ledrow = LedRow(avr, size=7)
    # period=1000 -> vcd error
    vcd = VcdFile(avr, period=10, filename=vcdfile)

    def state_func(i):
        return (ledrow.pinstate(i), ledrow.reset_dirty(i))
    led_game = LedRowGame(state_func=state_func,
                          labels='D4 D5 D6 D7 RS E RW'.split()
                          )
    ac = Ac(avr)
    connect_pins_by_rule('''
    avr.B0 <=> lcd.D4 -> vcd
    avr.B1 <=> lcd.D5 -> vcd
    avr.B2 <=> lcd.D6 -> vcd
    avr.B3 <=> lcd.D7 -> vcd

    avr.B4 ==> lcd.RS -> vcd
    avr.B5 ==> lcd.E  -> vcd
    avr.B6 ==> lcd.RW -> vcd
    vcd <- ac.OUT -> avr.D2

    lcd.D4 -> led.0
    lcd.D5 -> led.1
    lcd.D6 -> led.2
    lcd.D7 -> led.3

    lcd.RS -> led.4
    lcd.E  -> led.5
    lcd.RW -> led.6
                        ''',
                         dict(
                             avr=avr,
                             led=ledrow,
                             lcd=lcd,
                             ac=ac
                         ),
                         vcd=vcd,
                         )

    dev = CompositeGame([
                        CompositeGame(
                        [LcdGame(
                         lambda x, y:lcd.get_char(x, y), (20, 2)),
                         led_game,
                         ],
                        align=1),
                        InfoGame(avr),
                        ])

    scrshot_by_exit = [(dev, image_file)] if image_file else None

    AvrSimMain(
        avr, dev, vcd, speed=speed, fps=fps, visible=visible, timeout=timeout,
        scrshot_by_exit=scrshot_by_exit).run_game()
예제 #11
0
파일: test_1log.py 프로젝트: ponty/pysimavr
def test_custom_logger():
    loggerMethod = Mock()
    #Register custom callback method for simav logs
    logger.init_simavr_logger(loggerMethod)
    avr = Avr(mcu='atmega48', f_cpu=8000000)
    #Let the simavr run in background until it sadly crashes on ramend
    avr.run() 
    while avr.cycle < 8000 and avr.state == cpu_Running :
        time.sleep(0.1)
        
    # Expected:
    #('Starting atmega48 - flashend 0fff ramend 02ff e2end 00ff\n', 3)
    #('atmega48 init\n', 3)
    #('atmega48 reset\n', 3)
    #('avr_sadly_crashed\n', 1)
    eq_(loggerMethod.call_count, 4, "number of callback invocations")
    loggerMethod.assert_called_with('avr_sadly_crashed\n', 1)    
    avr.terminate()
예제 #12
0
def test_timer_GC():
    avr = Avr(mcu='atmega88', f_cpu=1000000)
    callbackMock = Mock(return_value=0)
    #Don't let avr object to keep the callback referenced.
    t = weakref.ref(avr.timer(callbackMock, cycle=10, keep_alive=False))
    gc.collect()
    assert_that(t(), is_(none()), "Orphan Timer didn't get garbage collected.")
    avr.step(100)
    assert_that(callbackMock.call_count, equal_to(0), "Number of IRQ callback invocations.")

    #Now let avr object keep the callback alive.
    t = weakref.ref(avr.timer(callbackMock, cycle=110, keep_alive=True))
    gc.collect()
    assert_that(t(), is_ (not_none()), "Avr object didn't kept Timer callback alive.")
    avr.step(1000)
    assert_that(callbackMock.call_count, equal_to(1), "Number of IRQ callback invocations.")
    avr.terminate()
    gc.collect()
    assert_that(t(), is_(none()), "Orphan Timer didn't get garbage collected even after Avr is terminated.")
예제 #13
0
def test_timer_cancel():
    avr = Avr(mcu='atmega88', f_cpu=1000000)
    callbackMock = Mock(return_value=200)
    timer = avr.timer(callbackMock, cycle=50)    
    avr.step(10)
    callbackMock.assert_not_called()
    
    timer.cancel()
    avr.step(1000)
    callbackMock.assert_not_called()    
         
    avr.terminate()
예제 #14
0
def test():
    avr = Avr(mcu='atmega48', f_cpu=8000000)
    Ac(avr)
    Button(avr)
    Inverter(avr)
    LedRow(avr)
    Sgm7(avr)
    Lcd(avr)
    Spk(avr)

    Udp(avr)
예제 #15
0
def run_test(f_cpu, mcu, timeout, gdb, testfile):
    avr = Avr(mcu=mcu, f_cpu=f_cpu)
    fw = Firmware(testfile)
    avr.load_firmware(fw)

    if gdb:
        avr.gdb_port = 1234
        avr_gdb_init(avr.backend)
        avr.state = cpu_Stopped

    t_start = time.time()
    while not avr.peek(GPIOR0) & TEST_COMPLETE:
        if timeout and time.time() - t_start > timeout:
            raise click.ClickException('Timeout')
        avr.step(100)

    if avr.uart.buffer:
        print(''.join(avr.uart.buffer))

    sys.exit(0 if avr.peek(GPIOR0) & TEST_SUCCESS else 1)
예제 #16
0
    def startAvr(self):
        self.avr = Avr(mcu='atmega88',f_cpu=8000000)
        
        self.udp = Udp(self.avr)
        self.udp.connect()

        self.uartBridge = UartBridge()
        
        firmware = Firmware(ELFNAME)
        self.avr.load_firmware(firmware);

        self.uartBridge.start();
        self.avr.run()
예제 #17
0
def run_sim(vcdfile='ledramp.vcd',
            speed=0.1,
            fps=20,
            timeout=0.0,
            visible=1,
            image_file=''):
    firmware = Firmware(path(__file__).dirname() / 'ledramp.elf')
    avr = Avr(firmware, f_cpu=8000000, mcu='atmega48')

    vcd = VcdFile(avr, period=1000, filename=vcdfile)
    ledrow = LedRow(avr)
    connect_pins_by_rule(
        '''
                        avr.B0 ==> led.0 -> vcd
                        avr.B1 ==> led.1 -> vcd
                        avr.B2 ==> led.2 -> vcd
                        avr.B3 ==> led.3 -> vcd
                        avr.B4 ==> led.4 -> vcd
                        avr.B5 ==> led.5 -> vcd
                        avr.B6 ==> led.6 -> vcd
                        avr.B7 ==> led.7 -> vcd
                        ''',
        dict(
            avr=avr,
            led=ledrow,
        ),
        vcd=vcd,
    )

    def state_func(i):
        return (ledrow.pinstate(i), ledrow.reset_dirty(i))

    led_game = LedRowGame(state_func=state_func,
                          labels=['B' + str(x) for x in range(8)])

    dev = CompositeGame([
        led_game,
        InfoGame(avr),
    ])

    scrshot_by_exit = [(dev, image_file)] if image_file else None

    AvrSimMain(avr,
               dev,
               vcd,
               speed=speed,
               fps=fps,
               visible=visible,
               timeout=timeout,
               scrshot_by_exit=scrshot_by_exit).run_game()
예제 #18
0
def test_background_thread():
    cc = AvrGcc(mcu=mcu)
    cc.build('int main(){}')
    fw = Firmware(cc.output)
    avr = Avr(mcu=mcu, firmware=fw, f_cpu=8000000)
    eq_(avr.state, cpu_Running, "mcu is not running")
    avr.goto_cycle(100)
    eq_(avr.state, cpu_Running, "mcu is not running")
    avr.terminate()
예제 #19
0
def test_timer_GC():
    avr = Avr(mcu='atmega88', f_cpu=1000000)
    callbackMock = Mock(return_value=0)
    t = weakref.ref(avr.timer(callbackMock, cycle=10))
    gc.collect()
    assert_that(t(), is_(none()), "Orphan Timer didn't get garbage collected.")
    avr.step(100)
    assert_that(callbackMock.call_count, equal_to(0), "Number of IRQ callback invocations.")        
    avr.terminate()
예제 #20
0
def test_timer_reoccuring():
    avr = Avr(mcu='atmega48', f_cpu=8000000)
    # Callback method mocked out. It will register another callback 
    # at 200 cycles and then cancel by returning 0.
    callbackMock = Mock(side_effect = [200, 0])

    timer = avr.timer(callbackMock)
    avr.step(10)
    eq_(avr.state, cpu_Running, "mcu is not running")
    callbackMock.assert_not_called()

    # Request first timer callback at 100 cycles
    timer.set_timer_cycles(100)

    # Run long enought to ensure callback is canceled by returning 0 on the second invocation.
    avr.step(1000)
    eq_(avr.state, cpu_Running, "mcu is not running")
    eq_(callbackMock.call_count, 2, "number of calback invocations")

    lastCallFirstArg = callbackMock.call_args[0][0]
    assert_that(lastCallFirstArg, close_to(200, 10),
                "The last cycle number received in the callback doesn't match the requested one")
    avr.terminate()
예제 #21
0
def test_timer_simple():
    avr = Avr(mcu='atmega88', f_cpu=8000000)
    # Callback method mocked out. 
    callbackMock = Mock(return_value=0)

    #Schedule callback at 20uSec.
    # cycles = avr->frequency * (avr_cycle_count_t)usec / 1000000;
    timer = avr.timer(callbackMock, uSec=20)

    assert_that(timer.status(), close_to(8000000*20/1000000, 10),
                "uSec to cycles convertion")

    avr.step(1000)
    eq_(avr.state, cpu_Running, "mcu is not running")

    eq_(callbackMock.call_count, 1, "number of calback invocations")
    avr.terminate()
예제 #22
0
def test_timer_reoccuring():        
    avr = Avr(mcu='atmega48', f_cpu=8000000)
    # Callback method mocked out. It will register another callback 
    # at 200 cycles and then cancel by returning 0.
    callbackMock = Mock(side_effect = [200, 0])
    
    timer = avr.timer(callbackMock)
    avr.step(10)
    eq_(avr.state, cpu_Running, "mcu is not running")
    callbackMock.assert_not_called()
    
    # Request first timer callback at 100 cycles
    timer.set_timer_cycles(100)    
    
    # Run long enought to ensure callback is canceled by returning 0 on the second invocation.
    avr.step(1000)
    eq_(avr.state, cpu_Running, "mcu is not running")
    eq_(callbackMock.call_count, 2, "number of calback invocations")
        
    lastCallFirstArg = callbackMock.call_args[0][0]    
    assert_that(lastCallFirstArg, close_to(200, 10), 
                "The last cycle number received in the callback doesn't match the requested one") 
    avr.terminate()
예제 #23
0
def test_timer_simple():
    avr = Avr(mcu='atmega88', f_cpu=8000000)    
    # Callback method mocked out. 
    callbackMock = Mock(return_value=0)
    
    #Schedule callback at 20uSec.  
    # cycles = avr->frequency * (avr_cycle_count_t)usec / 1000000;
    timer = avr.timer(callbackMock, uSec=20)
         
    assert_that(timer.status(), close_to(8000000*20/1000000, 10), 
                "uSec to cycles convertion")    
    
    avr.step(1000)
    eq_(avr.state, cpu_Running, "mcu is not running")
            
    eq_(callbackMock.call_count, 1, "number of calback invocations")
    avr.terminate()
예제 #24
0
def test_custom_logger():
    loggerMethod = Mock()
    #Register custom callback method for simav logs
    logger.init_simavr_logger(loggerMethod)
    avr = Avr(mcu='atmega48', f_cpu=8000000)
    #Let the simavr run in background until it sadly crashes on ramend
    avr.run()
    while avr.cycle < 8000 and avr.state == cpu_Running:
        time.sleep(0.1)

    # Expected:
    #('Starting atmega48 - flashend 0fff ramend 02ff e2end 00ff\n', 3)
    #('atmega48 init\n', 3)
    #('atmega48 reset\n', 3)
    #('avr_sadly_crashed\n', 1)
    eq_(loggerMethod.call_count, 4, "number of callback invocations")
    loggerMethod.assert_called_with('avr_sadly_crashed\n', 1)
    avr.terminate()
예제 #25
0
from pysimavr.avr import Avr

if __name__ == "__main__":
    avr = Avr(mcu="atmega48", f_cpu=8000000)
    print(avr.pc)
    avr.step(1)
    print(avr.pc)
    avr.step(1)
    print(avr.pc)

    avr.terminate()
예제 #26
0
class TestBase(unittest.TestCase):

    def setUp(self):
        self.first = True
        self.startAvr();
        pass

    def tearDown(self):
        self.uartBridge.terminate()        
        self.avr.terminate()
        pass

    def messageSanityCheck(self, bytes, commandId, expectedSize, first):
        '''
        Check that the response has correct size, message Id, checksum 
        @param bytes: list of bytes
        @param commandId: message identifier
        @param expectedSize: expected size of the response
        @param first: is is a first response  
        @raise exception: unittest.TestCase.assertEqual 
        @return: None
        '''
        if (expectedSize != None):
            self.assertEqual(len(bytes), expectedSize, "Message length "+str(len(bytes))+", expected size "+str(expectedSize));
        self.assertEqual(bytes[0], 0x7f, "1st sync byte is "+str(bytes[0]));                             
        self.assertEqual(bytes[1], 0xef, "2nd sync byte is "+str(bytes[1]));                             
        if (first):                                                                                      
            self.assertEqual(bytes[2], commandId, "Message id "+str(bytes[2]));                               
        else:                                                                                            
            self.assertEqual(bytes[2], commandId | 0x80, "Message id "+str(bytes[2]));                               
        self.assertEqual(bytes[3], expectedSize-4, "Payload size is "+str(bytes[3]));                              
                                                                                                         
        bytesWithoutChecksum = bytes[:-1]                                                                
        csExpected = calculateChecksum(bytesWithoutChecksum)                                             
        csActual = bytes[len(bytes)-1]                                                                              
        self.assertEqual(csActual, csExpected, "Checksum is "+hex(csActual)+" instead "+hex(csExpected));

    def startAvr(self):
        self.avr = Avr(mcu='atmega88',f_cpu=8000000)
        
        self.udp = Udp(self.avr)
        self.udp.connect()

        self.uartBridge = UartBridge()
        
        firmware = Firmware(ELFNAME)
        self.avr.load_firmware(firmware);

        self.uartBridge.start();
        self.avr.run()
        #self.time_passed();
        
    def time_passed(self, timeout=0.99):
        while self.avr.time_passed() < 0.1 * timeout:
            time.sleep(0.05)
    

    def sendCommand(self, command, payload):
        syncBytes = [0x7f, 0xef];
        command = syncBytes + command + [len(payload)+1] + payload;
        cs = calculateChecksum(command)
        command = command + [cs];
        
        s = str(bytearray(command))
        self.uartBridge.send_str(s);
        self.time_passed(0.05*len(s))
예제 #27
0
import logging
from os import path

if __name__ == '__main__':
    print("Start")
    # logging.basicConfig(level=logging.DEBUG)
    logging.basicConfig(level=logging.INFO)

    # Load firmware from ./avr/Button/Debug/Button.elf
    modulePath = path.dirname(path.realpath(__file__))
    fw = Firmware(path.join(modulePath, "avr", "Button", "Debug",
                            "Button.elf"))
    # fw = Firmware(path.join(modulePath, "avr", "Button", "Release", "Button.elf")
    print("Loading {}".format(fw.filename))

    avr = Avr(firmware=fw)  # The Button.elf has mcu and freq info embedded
    # avr = Avr(firmware=fw, mcu='atmega2560', f_cpu=8000000)
    # avr = Avr(firmware=fw, mcu='attiny2313', f_cpu=8000000)

    print("Fw loaded")

    # Set the GDB port and start simavr GDB
    avr.gdb_port = 1234
    avr_gdb_init(avr.backend)
    # avr.state = cpu_Stopped #To let simavr wait on the first instruction for GDB to connect.

    # Get the AVR A3 input pin.
    A3IRQ = avr.getirq(('A', 3))

    # Create simavr inbuilt button part.
    b = Button(avr)
예제 #28
0
파일: simple.py 프로젝트: x2nie/pysimavr
from pysimavr.avr import Avr

if __name__ == "__main__":
    avr = Avr(mcu='atmega48', f_cpu=8000000)
    print(avr.pc)
    avr.step(1)
    print(avr.pc)
    avr.step(1)
    print(avr.pc)

    avr.terminate()
예제 #29
0
    def simulate(self):
        if not self.external_elf:
            elf = self.cc.output
        else:
            elf = self.external_elf

        # run
        firmware = Firmware(elf)
        avr = Avr(mcu=self.cc.mcu, f_cpu=self.cc.f_cpu)
        avr.uart.char_logger = self.serial_char_logger
        avr.uart.line_logger = self.serial_line_logger
        avr.load_firmware(firmware)
#        udpReader = UdpReader()
#        udp = Udp(avr)
#        udp.connect()
#        udpReader.start()

        simvcd = None
        if self.vcd:
            simvcd = VcdFile(avr, period=1000, filename=self.vcd)
            connect_pins_by_rule('''
                                avr.D0 ==> vcd
                                avr.D1 ==> vcd
                                avr.D2 ==> vcd
                                avr.D3 ==> vcd
                                avr.D4 ==> vcd
                                avr.D5 ==> vcd
                                avr.D6 ==> vcd
                                avr.D7 ==> vcd

                                avr.B0 ==> vcd
                                avr.B1 ==> vcd
                                avr.B2 ==> vcd
                                avr.B3 ==> vcd
                                avr.B4 ==> vcd
                                avr.B5 ==> vcd
                                ''',
                                 dict(
                                 avr=avr,
                                 ),
                                 vcd=simvcd,
                                 )
            simvcd.start()

# not working
#        if self.serial_in:
#            avr.uart.send_string(self.serial_in)

        if self.fps:
            dt_real = 1. / self.fps
            dt_mcu = dt_real * self.speed
            count = int(self.timespan * self.fps / self.speed)
            for _ in range(count):
                time.sleep(dt_real)

        avr.goto_time(self.timespan)
        while avr.time_passed() < self.timespan * 0.99:
            time.sleep(0.05)

        if simvcd:
            simvcd.terminate()
#        udpReader.terminate()

        log.debug('cycles=%s' % avr.cycle)
        log.debug('mcu time=%s' % avr.time_passed())
#        time.sleep(1)
        self.serial_data = avr.uart.buffer
        self.serial = ''.join(self.serial_data)
        avr.terminate()
예제 #30
0
#!/usr/bin/env python

DIR = '/tmp/build5444690825086055604.tmp'

from pysimavr.avr import Avr, Firmware
avr = Avr(mcu='atmega48', f_cpu=8000000)
firmware = Firmware(DIR + '/PaleoSolarCharger.cpp.elf')
avr.load_firmware(firmware)
예제 #31
0
def arduino_sim(
    elf='',
    mcu='atmega328',
    f_cpu=16000000,
    vcdfile='arduino.vcd',
    speed=0.5,
    fps=20,
    timeout=0.0,
    visible=1,
    image_file='',
    rate=11025,
    buttons_enable=1,
    vcd_enable=0,
    spk_enable=0,
    #            udp_enable=1,
    avcc=5000,
    vcc=5000,
    code=None,
):
    '''

    MCU:
     - atmega168 OK
     - atmega328p OK
     - atmega2560 NO
     - atmega1280 NO

    :param mcu:
    :param avcc: AVcc  in mV
    :param vcc: Vcc  in mV

    '''

    if code and pyavrutils:
        cc = pyavrutils.Arduino()
        cc.build(code)
        elf = cc.output

    if not elf:
        elf = find_elf()
    firmware = Firmware(elf)
    avr = Avr(mcu=mcu, f_cpu=f_cpu, vcc=vcc / 1000.0, avcc=avcc / 1000.0)
    avr.load_firmware(firmware)

    #    udpReader = UdpReader()

    #    if udp_enable:
    #        udp = Udp(avr)
    #        udp.connect()
    #        udpReader.start()

    lcd = Lcd(avr)

    vcd = VcdFile(avr, period=1000, filename=vcdfile) if vcd_enable else None
    ledrow = LedRow(avr, size=14)
    buttons = [Button(avr, pullup=0)
               for x in range(14)] if buttons_enable else 14 * [None]
    spk = Spk(avr, rate=rate, speed=speed) if spk_enable else None

    connect_pins_by_rule(
        '''
                        but0 .OUT ==> avr.D0 ==> dig.0  -> vcd
                        but1 .OUT ==> avr.D1 ==> dig.1  -> vcd
                        but2 .OUT ==> avr.D2 ==> dig.2  -> vcd
                        but3 .OUT ==> avr.D3 ==> dig.3  -> vcd
                        but4 .OUT ==> avr.D4 ==> dig.4  -> vcd
                        but5 .OUT ==> avr.D5 ==> dig.5  -> vcd
                        but6 .OUT ==> avr.D6 ==> dig.6  -> vcd
                        but7 .OUT ==> avr.D7 ==> dig.7  -> vcd

                        but8 .OUT ==> avr.B0 ==> dig.8  -> vcd
                        but9 .OUT ==> avr.B1 ==> dig.9  -> vcd
                        but10.OUT ==> avr.B2 ==> dig.10 -> vcd
                        but11.OUT ==> avr.B3 ==> dig.11 -> vcd
                        but12.OUT ==> avr.B4 ==> dig.12 -> vcd
                        but13.OUT ==> avr.B5 ==> dig.13 -> vcd

                        dig.13 --> spk.IN -> vcd

                        dig.5 <=> lcd.D4 -> vcd
                        dig.4 <=> lcd.D5 -> vcd
                        dig.3 <=> lcd.D6 -> vcd
                        dig.2 <=> lcd.D7 -> vcd

                        dig.12 ==> lcd.RS -> vcd
                        dig.11 ==> lcd.RW -> vcd
                        dig.10 ==> lcd.E  -> vcd
                        ''',
        dict(avr=avr,
             dig=ledrow,
             lcd=lcd,
             spk=spk,
             **dict([('but' + str(i), b) for i, b in enumerate(buttons)])),
        vcd=vcd,
    )
    #################
    # GUI
    #################
    if spk_enable:

        def spk_func(size):
            return spk.read()

        spk_game = SpkGame(spk_func, rate=rate)

    def state_func(i):
        return (ledrow.pinstate(i), ledrow.reset_dirty(i))

    led_game = LedRowGame(
        state_func=state_func,
        labels=[str(x) for x in range(14)],
        align=1,
    )

    but_guis = [
        ButtonGame(
            label=label,
            shortcut=shortcut,
            hook=dict(up=x.up, down=x.down) if x else {},
            size=(50, 30),
        ) for x, label, shortcut in zip(
            buttons,
            '0 1 2 3 4 5 6 7 8 9 10 11 12 13'.split(),
            '0 1 2 3 4 5 6 7 8 9 a b c d'.split(),
        )
    ]
    info = InfoGame(avr)

    def reload_firmware():
        firmware = Firmware(find_elf())
        avr.load_firmware(firmware)
        lcd.reset()
        info.reload()

    class MyFloat(object):
        def __init__(self, value=0.0):
            self.value = value

        def __float__(self):
            return float(self.value)

        def inc(self):
            self.value *= 10.0

        def dec(self):
            self.value /= 10.0

    speed = MyFloat(speed)

    #    def udp_read():
    #        if not hasattr(udp_read, 'display'):
    #            udp_read.display = ''
    #        if not hasattr(udp_read, 'lastline'):
    #            udp_read.lastline = ''
    #        s = udpReader.read()
    #        if s:
    #            sys.stdout.write(s)
    #            udp_read.lastline += s
    #            udp_read.lastline = lastline(udp_read.lastline)
    #            udp_read.display = udp_read.lastline.replace(
    #                '\n', '\\n').replace('\r', '\\r')
    #        return  udp_read.display
    def uart_read():
        return avr.uart.last_line.replace('\n', '\\n').replace('\r', '\\r')

    dev = CompositeGame([
        CompositeGame([
            led_game,
            CompositeGame(but_guis, align=1),
        ], align=0), info,
        CompositeGame([
            CompositeGame([
                ButtonGame(label='reload',
                           shortcut='r',
                           hook=dict(down=reload_firmware)),
                ButtonGame(
                    label='speed up', shortcut='+', hook=dict(down=speed.inc)),
                ButtonGame(label='speed down',
                           shortcut='-',
                           hook=dict(down=speed.dec)),
                TextGame((lambda: "speed set= %fx" % float(speed))),
            ],
                          align=1),
            LcdGame(lambda x, y: lcd.get_char(x, y), (16, 2)),
            TextGame((lambda: 'ser=' + uart_read())),
        ],
                      align=1)
    ])

    scrshot_by_exit = [(dev, image_file)] if image_file else None

    class ArduinoMain(AvrSimMain):
        bufpos = 0

        def cb_loop(self):
            AvrSimMain.cb_loop(self)
#            if len(udpReader.buffer) > self.bufpos:
#                sys.stdout.write(''.join(udpReader.buffer[self.bufpos:]))
#                self.bufpos = len(udpReader.buffer)

    sim = ArduinoMain(avr,
                      dev,
                      vcd,
                      speed=speed,
                      fps=fps,
                      visible=visible,
                      timeout=timeout,
                      scrshot_by_exit=scrshot_by_exit)
    sim.run_game()

    time.sleep(1)
    if spk_enable:
        spk_game.terminate()
예제 #32
0
파일: button.py 프로젝트: ponty/pysimavr
import time
import logging
from os import path

if __name__ == '__main__':   
    print("Start")
    # logging.basicConfig(level=logging.DEBUG)
    logging.basicConfig(level=logging.INFO)
        
    # Load firmware from ./avr/Button/Debug/Button.elf
    modulePath = path.dirname(path.realpath(__file__))
    fw = Firmware(path.join(modulePath, "avr", "Button", "Debug", "Button.elf"))    
    # fw = Firmware(path.join(modulePath, "avr", "Button", "Release", "Button.elf")
    print("Loading {}".format(fw.filename))
    
    avr = Avr(firmware=fw)  # The Button.elf has mcu and freq info embedded
    # avr = Avr(firmware=fw, mcu='atmega2560', f_cpu=8000000)
    # avr = Avr(firmware=fw, mcu='attiny2313', f_cpu=8000000)  
          
    print("Fw loaded")
    
    # Set the GDB port and start simavr GDB
    avr.gdb_port = 1234;
    avr_gdb_init(avr.backend)
    # avr.state = cpu_Stopped #To let simavr wait on the first instruction for GDB to connect. 
    
    # Get the AVR A3 input pin.
    A3IRQ = avr.getirq(('A', 3));
    
    # Create simavr inbuilt button part.
    b = Button(avr); 
예제 #33
0
def run_sim():
    avr = Avr(mcu='atmega48', f_cpu=8000000)
    avr.step(1)
    print avr.pc
예제 #34
0
파일: simple.py 프로젝트: vencax/pysimavr
from pysimavr.avr import Avr

avr=Avr(mcu='atmega48',f_cpu=8000000)
avr.step(1)
print avr.pc
예제 #35
0
def run_sim(vcdfile='spk.vcd',
            speed=0.5,
            fps=20,
            timeout=0.0,
            visible=1,
            image_file='',
            rate=11025):
    firmware = Firmware(path(__file__).dirname() / 'spk.elf')
    avr = Avr(
        firmware=firmware,
        mcu="atmega168",
        f_cpu=16000000,
    )
    ledrow = LedRow(avr, size=1)
    # period=1000 -> vcd error
    vcd = VcdFile(avr, period=10, filename=vcdfile)
    spk = Spk(avr, rate=rate, speed=speed)

    connect_pins_by_rule(
        '''
    led.0 <-- avr.B5 --> spk.IN -> vcd
                        ''',
        dict(
            avr=avr,
            spk=spk,
            led=ledrow,
        ),
        vcd=vcd,
    )

    ####################################                     )
    # GUI

    def spk_func(size):
        return spk.read()

    spk_game = SpkGame(spk_func, rate=rate)

    def state_func(i):
        return (ledrow.pinstate(i), ledrow.reset_dirty(i))

    led_game = LedRowGame(state_func=state_func, labels=['SPK'])
    dev = CompositeGame([
        CompositeGame([
            led_game,
        ], align=1),
        InfoGame(avr),
    ])

    scrshot_by_exit = [(dev, image_file)] if image_file else None

    AvrSimMain(avr,
               dev,
               vcd,
               speed=speed,
               fps=fps,
               visible=visible,
               timeout=timeout,
               scrshot_by_exit=scrshot_by_exit).run_game()

    spk_game.terminate()
예제 #36
0
#!/usr/bin/env python

DIR = '/tmp/build5444690825086055604.tmp'

from pysimavr.avr import Avr, Firmware
avr=Avr(mcu='atmega48',f_cpu=8000000)
firmware = Firmware(DIR + '/PaleoSolarCharger.cpp.elf')
avr.load_firmware(firmware)
예제 #37
0
    def simulate(self):
        if not self.external_elf:
            elf = self.cc.output
        else:
            elf = self.external_elf

        # run
        firmware = Firmware(elf)
        avr = Avr(mcu=self.cc.mcu, f_cpu=self.cc.f_cpu)
        avr.uart.char_logger = self.serial_char_logger
        avr.uart.line_logger = self.serial_line_logger
        avr.load_firmware(firmware)
        #        udpReader = UdpReader()
        #        udp = Udp(avr)
        #        udp.connect()
        #        udpReader.start()

        simvcd = None
        if self.vcd:
            simvcd = VcdFile(avr, period=1000, filename=self.vcd)
            connect_pins_by_rule(
                '''
                                avr.D0 ==> vcd
                                avr.D1 ==> vcd
                                avr.D2 ==> vcd
                                avr.D3 ==> vcd
                                avr.D4 ==> vcd
                                avr.D5 ==> vcd
                                avr.D6 ==> vcd
                                avr.D7 ==> vcd

                                avr.B0 ==> vcd
                                avr.B1 ==> vcd
                                avr.B2 ==> vcd
                                avr.B3 ==> vcd
                                avr.B4 ==> vcd
                                avr.B5 ==> vcd
                                ''',
                dict(avr=avr, ),
                vcd=simvcd,
            )
            simvcd.start()

# not working
#        if self.serial_in:
#            avr.uart.send_string(self.serial_in)

        if self.fps:
            dt_real = 1. / self.fps
            dt_mcu = dt_real * self.speed
            count = int(self.timespan * self.fps / self.speed)
            for _ in range(count):
                time.sleep(dt_real)

        avr.goto_time(self.timespan)
        while avr.time_passed() < self.timespan * 0.99:
            time.sleep(0.05)

        if simvcd:
            simvcd.terminate()
#        udpReader.terminate()

        log.debug('cycles=%s' % avr.cycle)
        log.debug('mcu time=%s' % avr.time_passed())
        #        time.sleep(1)
        self.serial_data = avr.uart.buffer
        self.serial = ''.join(self.serial_data)
        avr.terminate()
예제 #38
0
def run_sim(vcdfile='sgm7.vcd',
            speed=0.001,
            fps=20,
            timeout=0.0,
            visible=1,
            image_file=''):
    firmware = Firmware(path(__file__).dirname() / 'sgm7.elf')
    firmware.f_cpu = 8000000
    firmware.mcu = "atmega168"
    avr = Avr(firmware)
    vcd = VcdFile(avr, period=1000, filename=vcdfile)

    ####################################################
    # ledrow
    ledrow = LedRow(avr, size=12)

    ####################################################
    # ledrow game
    def state_func_seg(i):
        return (ledrow.pinstate(i), ledrow.reset_dirty(i))

    led_game_seg = LedRowGame(state_func=state_func_seg,
                              disp_size=8,
                              labels=['B' + str(x) for x in range(8)])

    def state_func_dig(i):
        return (ledrow.pinstate(i + 8), ledrow.reset_dirty(i + 8))

    led_game_dig = LedRowGame(state_func=state_func_dig,
                              disp_size=4,
                              labels=['C' + str(x) for x in range(4)])
    ####################################################
    # sgm7
    sgm7 = Sgm7(avr, size=4)

    inv = [Inverter(avr) for x in range(4)]

    connect_pins_by_rule(
        '''
                        ledrow.0 <== avr.B0 ==> sgm7.A -> vcd
                        ledrow.1 <== avr.B1 ==> sgm7.B -> vcd
                        ledrow.2 <== avr.B2 ==> sgm7.C -> vcd
                        ledrow.3 <== avr.B3 ==> sgm7.D -> vcd
                        ledrow.4 <== avr.B4 ==> sgm7.E -> vcd
                        ledrow.5 <== avr.B5 ==> sgm7.F -> vcd
                        ledrow.6 <== avr.B6 ==> sgm7.G -> vcd
                        ledrow.7 <== avr.B7 ==> sgm7.P -> vcd

                        ledrow.8 <== avr.C0 ==> inv0.IN | inv0.OUT -> sgm7.D0 -> vcd
                        ledrow.9 <== avr.C1 ==> inv1.IN | inv1.OUT -> sgm7.D1 -> vcd
                        ledrow.10<== avr.C2 ==> inv2.IN | inv2.OUT -> sgm7.D2 -> vcd
                        ledrow.11<== avr.C3 ==> inv3.IN | inv3.OUT -> sgm7.D3 -> vcd
                        ''',
        dict(
            avr=avr,
            sgm7=sgm7,
            ledrow=ledrow,
            inv0=inv[0],
            inv1=inv[1],
            inv2=inv[2],
            inv3=inv[3],
        ),
        vcd=vcd,
    )

    ####################################################
    # sgm7 game
    def segments_func(digit_index):
        return (sgm7.digit_segments(digit_index),
                sgm7.reset_dirty(digit_index))

    sgm7_game = Sgm7Game(segments_func=segments_func, disp_size=4)

    ####################################################
    # compose game
    dev = CompositeGame([
        CompositeGame([
            sgm7_game,
            led_game_seg,
            led_game_dig,
        ], align=1),
        InfoGame(avr),
    ])

    scrshot_by_exit = [(dev, image_file)] if image_file else None

    AvrSimMain(avr,
               dev,
               vcd,
               speed=speed,
               fps=fps,
               visible=visible,
               timeout=timeout,
               scrshot_by_exit=scrshot_by_exit).run_game()
예제 #39
0
def arduino_sim(
    elf='',
    mcu='atmega328',
    f_cpu=16000000,
    vcdfile='arduino.vcd',
            speed=0.5,
            fps=20,
            timeout=0.0,
            visible=1,
            image_file='',
            rate=11025,
            buttons_enable=1,
            vcd_enable=0,
            spk_enable=0,
#            udp_enable=1,
            avcc=5000,
            vcc=5000,
            code=None,
):
    '''

    MCU:
     - atmega168 OK
     - atmega328p OK
     - atmega2560 NO
     - atmega1280 NO

    :param mcu:
    :param avcc: AVcc  in mV
    :param vcc: Vcc  in mV

    '''

    if code and pyavrutils:
        cc = pyavrutils.Arduino()
        cc.build(code)
        elf = cc.output

    if not elf:
        elf = find_elf()
    firmware = Firmware(elf)
    avr = Avr(mcu=mcu, f_cpu=f_cpu, vcc=vcc / 1000.0, avcc=avcc / 1000.0)
    avr.load_firmware(firmware)

#    udpReader = UdpReader()

#    if udp_enable:
#        udp = Udp(avr)
#        udp.connect()
#        udpReader.start()

    lcd = Lcd(avr)

    vcd = VcdFile(avr, period=1000, filename=vcdfile) if vcd_enable else None
    ledrow = LedRow(avr, size=14)
    buttons = [Button(
        avr, pullup=0) for x in range(14)] if buttons_enable else 14 * [None]
    spk = Spk(avr, rate=rate, speed=speed) if spk_enable else None

    connect_pins_by_rule('''
                        but0 .OUT ==> avr.D0 ==> dig.0  -> vcd
                        but1 .OUT ==> avr.D1 ==> dig.1  -> vcd
                        but2 .OUT ==> avr.D2 ==> dig.2  -> vcd
                        but3 .OUT ==> avr.D3 ==> dig.3  -> vcd
                        but4 .OUT ==> avr.D4 ==> dig.4  -> vcd
                        but5 .OUT ==> avr.D5 ==> dig.5  -> vcd
                        but6 .OUT ==> avr.D6 ==> dig.6  -> vcd
                        but7 .OUT ==> avr.D7 ==> dig.7  -> vcd

                        but8 .OUT ==> avr.B0 ==> dig.8  -> vcd
                        but9 .OUT ==> avr.B1 ==> dig.9  -> vcd
                        but10.OUT ==> avr.B2 ==> dig.10 -> vcd
                        but11.OUT ==> avr.B3 ==> dig.11 -> vcd
                        but12.OUT ==> avr.B4 ==> dig.12 -> vcd
                        but13.OUT ==> avr.B5 ==> dig.13 -> vcd

                        dig.13 --> spk.IN -> vcd

                        dig.5 <=> lcd.D4 -> vcd
                        dig.4 <=> lcd.D5 -> vcd
                        dig.3 <=> lcd.D6 -> vcd
                        dig.2 <=> lcd.D7 -> vcd

                        dig.12 ==> lcd.RS -> vcd
                        dig.11 ==> lcd.RW -> vcd
                        dig.10 ==> lcd.E  -> vcd
                        ''',
                         dict(
                             avr=avr,
                             dig=ledrow,
                             lcd=lcd,
                             spk=spk,
                             **dict([('but' + str(i), b) for i, b in enumerate(buttons)])
                         ),
                         vcd=vcd,
                         )
    #################
    # GUI
    #################
    if spk_enable:
        def spk_func(size):
            return spk.read()
        spk_game = SpkGame(spk_func, rate=rate)

    def state_func(i):
        return (ledrow.pinstate(i), ledrow.reset_dirty(i))
    led_game = LedRowGame(state_func=state_func,
                          labels=[str(x) for x in range(14)],
                          align=1,)

    but_guis = [ButtonGame(
                label=label,
                shortcut=shortcut,
                hook=dict(up=x.up, down=x.down) if x else {},
                size=(50, 30),
                ) for x, label, shortcut in zip(
                buttons,
                '0 1 2 3 4 5 6 7 8 9 10 11 12 13'.split(),
                '0 1 2 3 4 5 6 7 8 9 a b c d'.split(),
                )
                ]
    info = InfoGame(avr)

    def reload_firmware():
        firmware = Firmware(find_elf())
        avr.load_firmware(firmware)
        lcd.reset()
        info.reload()

    class MyFloat(object):
        def __init__(self, value=0.0):
            self.value = value

        def __float__(self):
            return float(self.value)

        def inc(self):
            self.value *= 10.0

        def dec(self):
            self.value /= 10.0
    speed = MyFloat(speed)

#    def udp_read():
#        if not hasattr(udp_read, 'display'):
#            udp_read.display = ''
#        if not hasattr(udp_read, 'lastline'):
#            udp_read.lastline = ''
#        s = udpReader.read()
#        if s:
#            sys.stdout.write(s)
#            udp_read.lastline += s
#            udp_read.lastline = lastline(udp_read.lastline)
#            udp_read.display = udp_read.lastline.replace(
#                '\n', '\\n').replace('\r', '\\r')
#        return  udp_read.display
    def uart_read():
        return avr.uart.last_line.replace('\n', '\\n').replace('\r', '\\r')

    dev = CompositeGame([
                        CompositeGame([led_game,
                                       CompositeGame(but_guis, align=1),
                                       ], align=0),
                        info,
                        CompositeGame([
                            CompositeGame([
                                ButtonGame(label='reload',
                                           shortcut='r',
                                           hook=dict(down=reload_firmware)),
                                ButtonGame(label='speed up',
                                           shortcut='+',
                                           hook=dict(down=speed.inc)),
                                ButtonGame(label='speed down',
                                           shortcut='-',
                                           hook=dict(down=speed.dec)),
                                TextGame((lambda:
                                         "speed set= %fx" % float(speed))),
                            ], align=1),

        LcdGame(
        lambda x, y:lcd.get_char(x, y), (16, 2)),
                            TextGame((lambda: 'ser=' + uart_read())),
                        ], align=1)
    ])

    scrshot_by_exit = [(dev, image_file)] if image_file else None

    class ArduinoMain(AvrSimMain):
        bufpos = 0

        def cb_loop(self):
            AvrSimMain.cb_loop(self)
#            if len(udpReader.buffer) > self.bufpos:
#                sys.stdout.write(''.join(udpReader.buffer[self.bufpos:]))
#                self.bufpos = len(udpReader.buffer)

    sim = ArduinoMain(
        avr, dev, vcd, speed=speed, fps=fps, visible=visible, timeout=timeout,
        scrshot_by_exit=scrshot_by_exit)
    sim.run_game()

    time.sleep(1)
    if spk_enable:
        spk_game.terminate()
예제 #40
0
class Controller:
    def __init__(self, sock, mcu_name, freq=16000000, version=1):
        self.mcu_name = mcu_name
        self.mcu = Avr(mcu=mcu_name, f_cpu=freq)
        self.socket = sock
        self.fw_path = None
        self.version = version
        self.bind_callback_for_digit_pins(atmega_328_digit_pin_table)
        self.vcd = None
        self.connect_vcd()

    def upload_firmware(self, fw_path):
        self.fw_path = fw_path
        fw = Firmware(fw_path)
        self.mcu.load_firmware(fw)

    def connect_vcd(self):
        self.vcd = VcdFile(self.mcu, filename='out' + str(self.version))
        connect_pins_by_rule('''
                            avr.D0 ==> vcd
                            avr.D1 ==> vcd
                            avr.D2 ==> vcd
                            avr.D3 ==> vcd
                            avr.D4 ==> vcd
                            avr.D5 ==> vcd
                            avr.D6 ==> vcd
                            avr.D7 ==> vcd

                            avr.B0 ==> vcd
                            avr.B1 ==> vcd
                            avr.B2 ==> vcd
                            avr.B3 ==> vcd
                            avr.B4 ==> vcd
                            avr.B5 ==> vcd
                            ''',
                             dict(avr=self.mcu),
                             vcd=self.vcd)

    def bind_callback_for_digit_pins(self, ports):
        def port_callback(irq, new_val):
            msg = "change " + self.mcu_name + ' ' + irq.name[
                0] + " " + irq.name[1] + " " + str(new_val)
            self.socket.send_msg(msg)

        callback = Mock(side_effect=port_callback)

        for port in ports:
            p = self.mcu.irq.ioport_register_notify(callback,
                                                    (port[0], int(port[1:])))
            p.get_irq().name = port

    def new_pin_val(self, port_pin, new_val):
        # type: ((str, int), int) -> None

        irq = self.mcu.irq.getioport(port_pin)
        avr_raise_irq(irq, new_val)

    def run(self):
        self.vcd.start()
        self.mcu.run()

    def pause(self):
        self.vcd.stop()
        self.mcu.pause()

    def terminate(self):
        if self.vcd:
            self.vcd.terminate()
        self.mcu.terminate()
예제 #41
0
파일: test_irq.py 프로젝트: Premik/pysimavr
def _create_avr(mcu, f_cpu, code):
    cc = AvrGcc(mcu=mcu)
    cc.build(code)
    fw = Firmware(cc.output)
    return Avr(mcu=mcu, firmware=fw, f_cpu=f_cpu)