How to make DE0-nano use ttl-232R-3V3 cable communication with PC by 1 bit(with clash-lang)? - intel-fpga

I am trying to use the Altera DE0-nano to communication with the PC. I am using the ttl-232R-3v3 cable, currently it transmit 8 bits data once, but with the cable, it can be 1 bit a time transmit. How do I do it?
I have finish the 8 bit code:
type ST = BitVector 28
example :: ( ST , ST ) -> BitVector 8 -> (( ST , ST ) , BitVector 8)
example ( cntr1 , cntr2 ) input = ((cntr1’,cntr2’) , out)
where
sec_5 = 250000000
ascii_Y = 0x59 --ASCII for "Y" yes
ascii_N = 0x4E --ASCII for "N" no
cntr1’ | cntr1 >= sec_5 = 0 --At 50 MHz : 5 seconds
| otherwise = cntr1 + 1
cntr2’ = cntr2
out | input == maxBound = ascii_Y
| otherwise = ascii_Y
Here is the output:

Related

Blit 8-bit colour to screen by converting binary values in file to 3-3-2 colour

I have recently been working on a small emulated 8-bit CPU that I wish to have graphics capabilities. At the moment, it dumps the upper 16K of ram as a binary file every cycle for it to be read as "video memory." I've made a simple pygame-based program that reads the file and then attempts to convert it to a 128x128 grayscale 3d array for it to be directly blit as a surface. It does not work. I thought I could directly cut to the chase and just ask, Is there a way to read a binary file and convert its bytes into 3-3-2 colour, regardless of the file's actual content?
Here's my current code:
import pygame
import numpy as np
from time import sleep
class Viewer:
def __init__(self, update_func, display_size):
self.display_size = display_size
self.update_func = update_func
pygame.init()
self.display = pygame.display.set_mode(display_size)
def set_title(self, title):
pygame.display.set_caption(title)
def start(self):
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
z = self.update_func()
surf = pygame.surfarray.make_surface(z)
new = pygame.transform.scale(surf, self.display_size)
self.display.blit(new, (0, 0))
pygame.display.update()
pygame.quit()
def update():
file = open("core.bin", "rb")
value = bytearray(file.read())
lst = list(value)
file.close()
image = [[ [lst for col in range(len(lst))] for col in range(len(lst))] for row in range(len(lst))]
print(image)
sleep(0.25)
return image
viewer = Viewer(update, (512, 512))
viewer.start()
update()
I've tried numpy.dstack in the past, and normal 3d arrays work fine with my code, just not binary files. And yes, my bin files are exactly 16k. No error messages either.
Not Working
My Intent
Made a 128 *128 8-bit image, for testing; assuming RRRGGGBB, as opposed to BBGGGRRR. Flip 'em around, if that's the case. Found that numpy's reshape() wrecked images. Injecting values directly into the expected numpy location gave better results. Should be faster, too.
#! /usr/bin/env python3
import pygame
import numpy as np
from time import sleep
from random import randint
class Viewer:
def __init__(self, update_func, display_size):
self.display_size = display_size
self.update_func = update_func
pygame.init()
self.display = pygame.display.set_mode(display_size)
def set_title(self, title):
pygame.display.set_caption(title)
def start(self):
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
z = self.update_func()
surf = pygame.surfarray.make_surface(z)
new = pygame.transform.scale(surf, self.display_size)
self.display.blit(new, (0, 0))
pygame.display.update()
pygame.quit()
'''
32 111 000 00 = randint( 0, 7 ) << 5 r
64 000 111 00 = randint( 0, 7 ) << 2 g
96 000 000 11 = randint( 0, 3 ) b
128 111 111 11 = randint( 0, 255 ) w
'''
screenshot = bytearray( 128 *128 ) ## 128 *128 8-bit image, just for testing
for red in range( 0, 128 *32 ): screenshot[ red ] = randint( 0, 7 ) << 5
for green in range( 128 *32, 128 *64 ): screenshot[ green ] = randint( 0, 7 ) << 2
for blue in range( 128 *64, 128 *96 ): screenshot[ blue ] = randint( 0, 3 )
for white in range( 128 *96, 128 *128 ): screenshot[ white ] = randint( 0, 255 )
row, col = 0, 0
arr = np .zeros( ( 128, 128, 3 ) ) ## generate empty numpy array
for byte in screenshot:
rrr = int( ( ( byte & 0b11100000 ) >> 5 ) *36.4285714286 ) ## red
ggg = int( ( ( byte & 0b00011100 ) >> 2 ) *36.4285714286 ) ## green
bb = int( ( byte & 0b00000011 ) *85 ) ## blue -- multiplied to max 255 range
arr[ col ][ row ][ 0 ] = rrr ## insert color values directly into numpy cells
arr[ col ][ row ][ 1 ] = ggg
arr[ col ][ row ][ 2 ] = bb
col += 1
if col == 128:
col = 0 ## \r carriage return
row += 1 ## \n newline
def update():
image = arr
sleep(0.25)
return image
viewer = Viewer(update, (512, 512))
viewer.start()
update()

How to make one second timer with atmega8?

I want make a one second timer with atmega8 and timer0. I used 8Mhz crystal and prescale = 1.
Every 125ns timer0 increases by one, so when timer0 overflows 31250 times, we should have one second, but it doesn't work properly and delays more then 5 seconds.
I used BascomAVR.
$regfile = "m8def.dat"
$crystal = 8000000
Config Lcd = 16 * 2
Config Lcdpin = Pin , Db4 = Portd.4 , Db5 = Portd.5 , Db6 = Portd.6
,Db7 = Portd.7 , E = Portd.3 , Rs = Portd.2
Config Timer0 = Timer , Prescale = 1
Dim Second As Word , Minute As Word , Hour As Word , Z As Integer
Second = 0
Minute = 0
Hour = 0
Z = 0
Enable Interrupts
Enable Timer0
Enable Ovf0
On Ovf0 Ovfroutin
Timer0 = 0
Start Timer0
Cursor Off
Cls : Home
Lcd "00:00:00"
Do
Loop
End 'end program
Ovfroutin:
Incr Z
If Z = 31250 Then
Stop Timer0
Z = 0
Incr Second
If Second = 60 Then
Second = 0
Incr Minute
If Minute = 60 Then
Minute = 0
Incr Hour
If Hour = 24 Then
Hour = 0
End If
If Hour < 10 Then
Locate 1 , 1
Lcd "0"
Locate 1 , 2
Else
Locate 1 , 1
End If
Lcd Hour
End If
If Minute < 10 Then
Locate 1 , 4
Lcd "0"
Locate 1 , 5
Else
Locate 1 , 4
End If
Lcd Minute
End If
If Second < 10 Then
Locate 1 , 7
Lcd "0"
Locate 1 , 8
Else
Locate 1 , 7
End If
Lcd Second
Start Timer0
End If
Timer0 = 0
Return

How to split an ordered array of durations in one-hour groups

I have an array with some durations (in seconds), I'd like to split that array into accumulated duration groups that not surpass 3600 seconds in MATLAB. The durations are in order.
Input:
Duration(s) | 2010 1000 500 1030 80 2030 1090
With an:
------------- ------------ ----
Accumulated duration (s) | 3510 3130 1090
------------- ------------ ----
1st group 2nd group 3rd
Output:
Groups index | 1 1 1 2 2 2 3
I've tried with some scripts, but these take so long, and I have to process a lot of data.
Here is a vectorized way using bsxfun and cumsum:
durations = [2010 1000 500 1030 80 2030 1090]
stepsize = 3600;
idx = sum(bsxfun(#ge, cumsum(durations), (0:stepsize:sum(durations)).'),1)
idx =
1 1 1 2 2 2 3
The accumulated durations you can then get with:
accDuratiation = accumarray(idx(:),durations(:),[],#sum).'
accDuratiation =
3510 3140 1090
Explanation:
%// cumulative sum of all durations
csum = cumsum(durations);
%// thresholds
threshs = 0:stepsize:sum(durations);
%// comparison
comp = bsxfun(#ge, csum(:).',threshs(:)) %'
comp =
1 1 1 1 1 1 1
0 0 0 1 1 1 1
0 0 0 0 0 0 1
%// get index
idx = sum(comp,1)
This will get you close . . .
durs = [2010 1000 500 1030 80 2030 1090];
cums = cumsum(durs);
t = 3600;
idx = zeros(size(durs));
while ~all(idx)
idx = idx + (cums <= t);
cums = cums - max(cums(cums <= t));
end
You can then get the output into your preferred format with a simple . .
idx = -(idx-max(idx)-1)
and just in case you don't have enough, yet another way to do it:
durations = [2010 1000 500 1030 80 2030 1090] ;
stepsize = 3600;
cs = cumsum(durations) ;
idxbeg = [1 find(sign([1 diff(mod(cs,stepsize))])==-1)] ; %// first index of each group
idxend = [idxbeg(2:end)-1 numel(d)] ; %// last index of each group
groupDuration = [cs(idxend(1)) diff(cs(idxend))]
groupIndex = cell2mat( arrayfun(#(x,y) repmat(x,1,y), 1:numel(idxbeg) , idxend-idxbeg+1 , 'uni',0) )
groupDuration =
3510 3140 1090
groupIndex =
1 1 1 2 2 2 3
although if you ask me I find the bsxfun solution more elegant

How to make cipher more efficient

I have written the code for a rail fence cipher decoder, the input provided is the number of rails and the already encoded text. The decoder works, however, it only works for small inputs or short words. If i try entering a paragraph with a rails of 10 no output shows up.
I am still trying to grasp the concept of Order of a function, so I'm unsure of the order of my program. How do I make it more efficient or improve its efficiency?
Decrypt Function:
void decrypt(int rail,char *cipher) {
int length = strlen(cipher);
int i, j;
int counter=0,num=0,in=1;
int railfence[rail][100],count[100];
for(i=0;i < length;i++)
count[i]=0;
for(i=0;i < length;i++){
if(num + in == rail) in =- 1;
else if(num + in == -1)in = 1;
railfence[num][count[num]] = i;
++count[num];
num += in;
}
char buffer[1000];
for(i=0;i < rail;i++)
for(j=0;j < count[i];j++){
buffer[railfence[i][j]] = cipher[counter];
++counter;
}
buffer[length]='\0';
printf("%s\n",buffer);
}
Any help would be appreciated.
When your rail is larger than the message length, your have uninitialised string lengths for each rail. You initialise count in a loop from 0 to the message length, but you should initalise a length for each rail:
for (i = 0; i < rail; i++)
count[i] = 0;
That change should fix your error.
You are using variable-length arrays, and you know the size of these arrays. So there's no need to guess the dimensions (and make them large enough just in case). You can determine the lengths:
int zigzag[rail][length / (rail - 1) + 1];
int count[rail];
char buffer[length + 1];
(The zigzag array's inner rails have twice the number of letters in the two outer rails. Considering top and bottom rail as one, each rail must cater for at most length / (rail - 1) + 1. The + 1 at the end catches division cutoffs.)
The algorithm can probably be made more efficient by walking the message without an additional two-dimensional array. Traverse rail i with an alternating stride of 2 * (rail - 1 - i) and 2 * i. You must take care not to treat the letters of the top and bottom rails twice (when the stride is zero).
This should be considered a teaser for an optimal implementation:
if (rail == 0 || rail == railCount - 1) {
plaintextOffset = rail + offInRail * (iterfreq * 2);
} else {
if (offInRail % 2 == 0) {
plaintextOffset = rail + offInRail * iterfreq;
} else {
plaintextOffset = railCount - rail - 1 + offInRail * iterfreq;
}
}
You'll need to iterate over the rails, keeping the starting offset of the rail in the ciphertext in mind. Then you can iterate over the possible characters in the rail, while testing if plaintextOffset is not too high.
Example output using the Wikipedia plaintext as test vector:
Rails: 3, size 25
CT rail 0 : 0 + 0 = 0 <-> 0 PT
CT rail 0 : 0 + 1 = 1 <-> 4 PT
CT rail 0 : 0 + 2 = 2 <-> 8 PT
CT rail 0 : 0 + 3 = 3 <-> 12 PT
CT rail 0 : 0 + 4 = 4 <-> 16 PT
CT rail 0 : 0 + 5 = 5 <-> 20 PT
CT rail 0 : 0 + 6 = 6 <-> 24 PT
CT rail 0 : 7 + 7 = 14 <-> 28 PT (too high)
CT rail 1 : 7 + 0 = 7 <-> 1 PT
CT rail 1 : 7 + 1 = 8 <-> 3 PT
CT rail 1 : 7 + 2 = 9 <-> 5 PT
CT rail 1 : 7 + 3 = 10 <-> 7 PT
CT rail 1 : 7 + 4 = 11 <-> 9 PT
CT rail 1 : 7 + 5 = 12 <-> 11 PT
CT rail 1 : 7 + 6 = 13 <-> 13 PT
CT rail 1 : 7 + 7 = 14 <-> 15 PT
CT rail 1 : 7 + 8 = 15 <-> 17 PT
CT rail 1 : 7 + 9 = 16 <-> 19 PT
CT rail 1 : 7 + 10 = 17 <-> 21 PT
CT rail 1 : 7 + 11 = 18 <-> 23 PT
CT rail 1 : 19 + 12 = 31 <-> 25 PT (too high)
CT rail 2 : 19 + 0 = 19 <-> 2 PT
CT rail 2 : 19 + 1 = 20 <-> 6 PT
CT rail 2 : 19 + 2 = 21 <-> 10 PT
CT rail 2 : 19 + 3 = 22 <-> 14 PT
CT rail 2 : 19 + 4 = 23 <-> 18 PT
CT rail 2 : 19 + 5 = 24 <-> 22 PT
CT rail 2 : 25 + 6 = 31 <-> 26 PT (too high)
WECRLTEERDSOEEFEAOCAIVDEN
Rails: 3, size 25
CT rail 0 : 0 + 0 = 0 <-> 0 PT
CT rail 0 : 0 + 1 = 1 <-> 4 PT
CT rail 0 : 0 + 2 = 2 <-> 8 PT
CT rail 0 : 0 + 3 = 3 <-> 12 PT
CT rail 0 : 0 + 4 = 4 <-> 16 PT
CT rail 0 : 0 + 5 = 5 <-> 20 PT
CT rail 0 : 0 + 6 = 6 <-> 24 PT
CT rail 0 : 7 + 7 = 14 <-> 28 PT (too high)
CT rail 1 : 7 + 0 = 7 <-> 1 PT
CT rail 1 : 7 + 1 = 8 <-> 3 PT
CT rail 1 : 7 + 2 = 9 <-> 5 PT
CT rail 1 : 7 + 3 = 10 <-> 7 PT
CT rail 1 : 7 + 4 = 11 <-> 9 PT
CT rail 1 : 7 + 5 = 12 <-> 11 PT
CT rail 1 : 7 + 6 = 13 <-> 13 PT
CT rail 1 : 7 + 7 = 14 <-> 15 PT
CT rail 1 : 7 + 8 = 15 <-> 17 PT
CT rail 1 : 7 + 9 = 16 <-> 19 PT
CT rail 1 : 7 + 10 = 17 <-> 21 PT
CT rail 1 : 7 + 11 = 18 <-> 23 PT
CT rail 1 : 19 + 12 = 31 <-> 25 PT (too high)
CT rail 2 : 19 + 0 = 19 <-> 2 PT
CT rail 2 : 19 + 1 = 20 <-> 6 PT
CT rail 2 : 19 + 2 = 21 <-> 10 PT
CT rail 2 : 19 + 3 = 22 <-> 14 PT
CT rail 2 : 19 + 4 = 23 <-> 18 PT
CT rail 2 : 19 + 5 = 24 <-> 22 PT
CT rail 2 : 25 + 6 = 31 <-> 26 PT (too high)
WEAREDISCOVEREDFLEEATONCE
I'm not super familiar with the algorithm, but it seems like you could save a bunch of time and memory if first you found the length of the string, then found the number of spaces (possibly using this), subtracted those two numbers, and then divided by rail (let's call the resulting number numCols). Then you'd just create one 2D char array, with rail rows and numCols columns. Go through with two for loops (columns nested inside of the rows) inserting the characters in order (making sure to avoid spaces).
Once you've done that, just read them back out, except this time, nest your rows loop inside your columns loop.

bitwise OR in iOS

enum {
UIViewAnimationOptionLayoutSubviews = 1 << 0,
UIViewAnimationOptionAllowUserInteraction = 1 << 1,
UIViewAnimationOptionBeginFromCurrentState = 1 << 2,
UIViewAnimationOptionRepeat = 1 << 3,
UIViewAnimationOptionAutoreverse = 1 << 4,
UIViewAnimationOptionOverrideInheritedDuration = 1 << 5,
UIViewAnimationOptionOverrideInheritedCurve = 1 << 6,
UIViewAnimationOptionAllowAnimatedContent = 1 << 7,
UIViewAnimationOptionShowHideTransitionViews = 1 << 8,
UIViewAnimationOptionCurveEaseInOut = 0 << 16,
UIViewAnimationOptionCurveEaseIn = 1 << 16,
UIViewAnimationOptionCurveEaseOut = 2 << 16,
UIViewAnimationOptionCurveLinear = 3 << 16,
UIViewAnimationOptionTransitionNone = 0 << 20,
UIViewAnimationOptionTransitionFlipFromLeft = 1 << 20,
UIViewAnimationOptionTransitionFlipFromRight = 2 << 20,
UIViewAnimationOptionTransitionCurlUp = 3 << 20,
UIViewAnimationOptionTransitionCurlDown = 4 << 20,
};
typedef NSUInteger UIViewAnimationOptions;
What exactly means this expression: UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse.
Value of UIViewAnimationOptionRepeat is equal to 8(in bin 1000), UIViewAnimationOptionAutoreverse is equal to 16(in bin 10000). So expression UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse should generate as I think 16(bin 10000) -> UIViewAnimationOptionReverse.
The operation | is defined by the truth table
| 0 | 1
---+---+---
0 | 0 | 1
1 | 1 | 1
that is, x | y == 0 only if both x == 0 and y == 0. The | operator works on all bits of a machine word at the same time. So
001000 (8)
| 010000 (16)
------------
011000 (24)
UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse is known as a "mask".
If you have a variable of type UIViewAnimationOptions, say:
UIViewAnimationOptions a;
you can apply the mask to it like this:
bool b = a && (UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse)
to determine if a "contains" either flags. If
a == 0x0000001;
then
b == false;
if
a == 0x0101001; //-- completely arbitrary mask
then
b == true;
So you are not actually interested in what UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse evaluates to, but only in the result of logically and-ing a value of that type to the flags you are interested in checking.
The bits are or'd:
UIViewAnimationOptionRepeat = 1 << 3 = 8 = 01000 in binary
UIViewAnimationOptionAutoreverse = 1 << 4 = 16 = 10000 in binary
01000
OR 10000
--------
11000
11000 in binary is 16 + 8 = 24 - an integer with third and fourth bits set (counting from 0).
UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse
is equivalent to
01000
10000 |
the result of which is
11000
which is not 10000 as you had assumed.

Resources