Skip to content

Instantly share code, notes, and snippets.

@ochaochaocha3
Created October 1, 2014 12:46
Show Gist options
  • Save ochaochaocha3/e71f0a88c8cebad23943 to your computer and use it in GitHub Desktop.
Save ochaochaocha3/e71f0a88c8cebad23943 to your computer and use it in GitHub Desktop.
T-FF シミュレータ:タイムチャート描画
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int time;
int length;
} pulse;
typedef struct {
unsigned char negative_edge : 1;
unsigned char t : 1;
unsigned char q : 1;
unsigned char not_q : 1;
} t_ff;
void
t_ff_init(t_ff *ff, int negative_edge)
{
ff->negative_edge = negative_edge ? 1 : 0;
ff->t = 0;
ff->q = 0;
ff->not_q = 1;
}
void
t_ff_update(t_ff *ff, t_ff *prev)
{
#define INVERT(x) ((x) ? 0 : 1);
ff->q = prev->q;
if (ff->negative_edge) {
if (prev->t && !ff->t) {
ff->q = INVERT(ff->q);
}
} else {
if (!prev->t && ff->t) {
ff->q = INVERT(ff->q);
}
}
ff->not_q = INVERT(ff->q);
}
void
print_high_or_low(int x)
{
putchar(x ? '^' : '_');
}
void
print_time_chart(t_ff ff[], int length)
{
int i;
printf(" T ");
for (i = 0; i < length; i++) {
print_high_or_low(ff[i].t);
}
putchar('\n');
printf("\n Q ");
for (i = 0; i < length; i++) {
print_high_or_low(ff[i].q);
}
putchar('\n');
printf("\n!Q ");
for (i = 0; i < length; i++) {
print_high_or_low(ff[i].not_q);
}
putchar('\n');
}
void
simulate_t_ff(
unsigned int pulse_width,
unsigned int interval,
unsigned int length,
int negative_edge
)
{
t_ff *ff;
unsigned int cycle = pulse_width + interval;
unsigned int i;
ff = (t_ff*)malloc(length * sizeof(t_ff));
if (!ff) {
perror("malloc");
exit(1);
}
for (i = 0; i < length; i++) {
unsigned int j = (i - 1) % cycle;
t_ff_init(&ff[i], negative_edge);
if (i > 0) {
if (j < pulse_width) {
ff[i].t = 1;
}
t_ff_update(&ff[i], &ff[i - 1]);
}
}
print_time_chart(ff, length);
free(ff);
}
int
main(void)
{
unsigned int pulse_width, interval, length;
printf("パルス幅: ");
scanf("%u", &pulse_width);
printf("間隔: ");
scanf("%u", &interval);
printf("時間: ");
scanf("%u", &length);
puts("\n[ポジティブエッジ]");
simulate_t_ff(pulse_width, interval, length, 0);
puts("\n[ネガティブエッジ]");
simulate_t_ff(pulse_width, interval, length, 1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment