Skip to content

Instantly share code, notes, and snippets.

@urish
Last active May 10, 2022 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save urish/e67f4089cb3d772079459c006fb0ef6f to your computer and use it in GitHub Desktop.
Save urish/e67f4089cb3d772079459c006fb0ef6f to your computer and use it in GitHub Desktop.
// Wokwi Custom Chip - For information and examples see:
// https://link.wokwi.com/custom-chips-alpha
//
// SPDX-License-Identifier: MIT
// Copyright (C) 2022 Uri Shaked / wokwi.com
#include "wokwi-api.h"
#include <stdio.h>
#include <stdlib.h>
const int ADDRESS = 0x22;
DEFINE_PIN(VCC);
DEFINE_PIN(GND);
DEFINE_PIN(SCL);
DEFINE_PIN(SDA);
DEFINE_PIN(INT);
typedef struct {
pin_t pin_int;
uint8_t counter;
uint32_t threshold_attr;
} chip_state_t;
+static bool i2c_connect(void *chip, uint32_t address, bool connect);
+static uint8_t i2c_read(void *chip);
+static bool i2c_write(void *chip, uint8_t data);
+static void i2c_disconnect(void *chip);
+
-chip_state_t* EXPORT(chip_init)(void) {
+void* chip_init() {
chip_state_t *chip = malloc(sizeof(chip_state_t));
chip->pin_int = pin_init("INT", INPUT);
chip->counter = 0;
- const pin_t scl = pin_init("SCL", INPUT);
- const pin_t sda = pin_init("SDA", INPUT);
- i2c_init(ADDRESS, scl, sda);
+ const i2c_dev_t i2c_dev = {
+ .address = ADDRESS,
+ .scl = pin_init("SCL", INPUT),
+ .sda = pin_init("SDA", INPUT),
+ .connect = i2c_connect,
+ .read = i2c_read,
+ .write = i2c_write,
+ .disconnect = i2c_disconnect, // Optional
+ };
+ i2c_init(chip, &i2c_dev);
// 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");
return chip;
}
static void counter_updated(chip_state_t *chip) {
const uint32_t threshold = attr_read(chip->threshold_attr);
if (chip->counter > threshold) {
- digital_write(chip->pin_int, LOW);
+ pin_write(chip->pin_int, LOW);
pin_mode(chip->pin_int, OUTPUT);
} else {
pin_mode(chip->pin_int, INPUT);
}
}
-bool EXPORT(chip_i2c_connect)(chip_state_t *chip, uint32_t address, bool connect) {
+bool i2c_connect(void *user_ctx, uint32_t address, bool connect) {
return true; /* Ack */
}
-uint8_t EXPORT(chip_i2c_read)(chip_state_t *chip) {
+uint8_t i2c_read(void *user_ctx) {
+ chip_state_t *chip = user_ctx;
chip->counter++;
counter_updated(chip);
return chip->counter;
}
-bool EXPORT(chip_i2c_write)(chip_state_t *chip, uint8_t data) {
+bool i2c_write(void *user_ctx, uint8_t data) {
+ chip_state_t *chip = user_ctx;
chip->counter = data;
counter_updated(chip);
return true; // Ack
}
-void EXPORT(chip_i2c_disconnect)(chip_state_t *chip) {
+void i2c_disconnect(void *user_ctx) {
// Do nothing
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment