Wireless Sensor Networks (WSNs) are networks of autonomous nodes used for monitoring an environment. Energy efficiency and secured data transmission are considered as the most important design goals for WSN. As the complexity of computer networks increased, the erudition of network-based attacks drew the attention of various researchers from several sectors. As a result of this, many Intrusion Detection System (IDS) have been deployed in such a way that it resolves various aspects of network security such as DoS, worms, viruses, malware, etc. Automation of IDS has been proposed in order to improve the energy efficient routing in Wireless Sensor Network in a secured manner. The proposed work incorporates the Deterministic Finite Automata (DFA) and Particle Swarm Optimization (PSO) for intrusion detection and the data transmission is done in a secured manner by determining and following the optimized route. A novel LD2FA (Learning Dynamic Deterministic Finite Automata) has been proposed so that the dynamic nature of the network is cultured. In turn, LD2FA - PSO provides the information about the node, packet and route inspection for detection and elimination of intruders so that the data transmission is done in an energy efficient manner through the optimal path. Routing through optimal path improves the overall performance of the sensor network and it has been examined through various metrics such as energy consumption, throughput, network lifetime, alive and dead nodes. The performance is evaluated by simulating in MATLAB with sensor nodes ranging from 100–700 in a region of 500 × 500 m^2 and comparing the obtained experimental results with the existing PSO, Greedy Load Balanced Clustering Algorithm (GLBCA), Genetic Algorithm (GA) based clustering, Least Distance Clustering (LDC), cluster-based IDS, light weight IDS. It is observed that, LD2FA-PSO obtained 16% increase in throughput than cluster-based IDS, almost 70% increase in throughput than light weight IDS, 6% and 32% improvement in network lifetime than PSO and GLBCA respectively, almost 30% and 54% improvement in network lifetime than GA and LDC respectively. The energy consumed is almost 3% and 6% lesser than PSO and GA, and 13% higher energy is consumed than LDC. The alive sensor node becomes nil at 2600th round which is better than cluster-based IDS and light weight IDS.