数字电路计算机仿真
逻辑电路是现代数字芯片的基础,计算机科学计算,智能时代都是是建立在布尔代数之上的,我们常见的与,或,非,与非,或非,异或门,
由这些门元件搭建各种组合逻辑电路,加法器,乘法器,触发器,时序逻辑电路,这些元件非常多,只有通过EDA这种软件设计和电路仿真,在
芯片生产之前发现设计的缺陷,所以电子电路仿真很重要,从某种观点看这种仿真程序也是科学数值计算的一种,将设计各种元件数学模型,
在下面的例子程序里面,只有一个与门和一个连线类:
#include <iostream> #include <vector> #include <string> #include <set> #include <map> #include <memory> // namespace shangx { typedef unsigned int IdType; // 标识符 // 门 class SxGate { public: SxGate(){} virtual ~SxGate() {} IdType id; // 标识 std::vector<bool> ports; // 端口状态 std::set<int> inPorts; // 端口输入 std::set<int> outPorts; // 端口输出 virtual void run() {} virtual void print() {} }; // 与门 class SxAndGate : public SxGate { public: SxAndGate() { ports.resize(3); inPorts.insert(0); inPorts.insert(1); outPorts.insert(2); } virtual void run() { ports[2] = ports[0] & ports[1]; } virtual void print() { std::cout << "{" << "\n"; std::cout << " type : AND" << "\n"; std::cout << " id : " << id << "\n\n"; std::cout << " p0 : " << ports[0] << "\n"; std::cout << " p1 : " << ports[1] << "\n"; std::cout << " p2 : " << ports[2] << "\n"; std::cout << "}" << "\n"; } }; // 线 class SxWire { public: IdType id; // 标识 std::map<IdType, int> connectPorts; // 连接端口 }; typedef std::shared_ptr<SxGate> SxGateSptr; typedef std::shared_ptr<SxAndGate> SxAndGateSptr; typedef std::shared_ptr<SxWire> SxWireSptr; // 仿真空间 class SxSpace { std::map<IdType, std::shared_ptr<SxGate>> m_gates; std::map<IdType, std::shared_ptr<SxWire>> m_wires; public: std::shared_ptr<SxGate> createAndGate() { std::shared_ptr<SxAndGate> gate = std::make_shared<SxAndGate>(); gate->id = m_gates.size(); m_gates[gate->id] = gate; return gate; } std::shared_ptr<SxWire> createWire() { std::shared_ptr<SxWire> wire(new SxWire); m_wires[m_wires.size()] = wire; return wire; } void connectWireAndPorts(std::shared_ptr<SxWire> wire, std::map<IdType, int> connectPorts) { wire->connectPorts = connectPorts; } void setGateInPortState(std::shared_ptr<SxGate> gate, int portId, bool state) { gate->ports[portId] = state; } void sort() { // 拓扑排序,计算元件运行的先后顺序 } void run() { } }; }; int main() { // 仿真空间 shangx::SxSpace sxs; // 创建一个与门 shangx::SxGateSptr and0 = sxs.createAndGate(); // 设置in端口状态 sxs.setGateInPortState(and0, 0, false); sxs.setGateInPortState(and0, 1, true); // 运行 and0->run(); // 打印元件端口状态 and0->print(); // todo // 创建多个门,创建多个线,线连接门,仿真空间运行 system("pause"); return 0; }
这里还没有连线,只是验证一个与门的真值,打印结果为
{
type : AND
id : 0
p0 : 0
p1 : 1
p2 : 0
}