-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathi2c-counter.chip.c
74 lines (60 loc) · 1.82 KB
/
i2c-counter.chip.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "wokwi-api.h"
#include <stdio.h>
#include <stdlib.h>
const int ADDRESS = 0x22;
typedef struct {
pin_t pin_int;
uint8_t counter;
uint32_t threshold_attr;
} chip_state_t;
static bool on_i2c_connect(void *user_data, uint32_t address, bool connect);
static uint8_t on_i2c_read(void *user_data);
static bool on_i2c_write(void *user_data, uint8_t data);
static void on_i2c_disconnect(void *user_data);
void chip_init() {
chip_state_t *chip = malloc(sizeof(chip_state_t));
chip->pin_int = pin_init("INT", INPUT);
chip->counter = 0;
const i2c_config_t i2c_config = {
.user_data = chip,
.address = ADDRESS,
.scl = pin_init("SCL", INPUT),
.sda = pin_init("SDA", INPUT),
.connect = on_i2c_connect,
.read = on_i2c_read,
.write = on_i2c_write,
.disconnect = on_i2c_disconnect, // Optional
};
i2c_init(&i2c_config);
// This attribute can be edited by the user. It's defined in wokwi-custom-part.json:
chip->threshold_attr = attr_init("threshold", 127);
// The following message will appear in the browser's DevTools console:
printf("Hello from custom chip!\n");
}
static void counter_updated(chip_state_t *chip) {
const uint32_t threshold = attr_read(chip->threshold_attr);
if (chip->counter > threshold) {
pin_write(chip->pin_int, LOW);
pin_mode(chip->pin_int, OUTPUT);
} else {
pin_mode(chip->pin_int, INPUT);
}
}
bool on_i2c_connect(void *user_data, uint32_t address, bool connect) {
return true; /* Ack */
}
uint8_t on_i2c_read(void *user_data) {
chip_state_t *chip = user_data;
chip->counter++;
counter_updated(chip);
return chip->counter;
}
bool on_i2c_write(void *user_data, uint8_t data) {
chip_state_t *chip = user_data;
chip->counter = data;
counter_updated(chip);
return true; // Ack
}
void on_i2c_disconnect(void *user_data) {
// Do nothing
}