Is there a way to protect humanity against the impending singularity?
What you are talking about is known as the Control Problem. We have our own tag for this specific topic here, which you can use for this and similar questions.

How to address the control problem is heavily discussed and still considered unsolved. Two of the important approaches are motivation control and capability control.

Motivation control aims at creating suitable reward functions that only reward behavior that's beneficial to the human race. This topic alone is so complex that many different competing theories exist. Minor errors in the definition of an AI's goal might lead to catastrophe.

Capability control aims at limiting the possible scope of action for the AI. The main problem here is, that most restrictions make the AI less useful. And to ensure robust control a lot of restrictions must be put in place. Finding the right tradeoff is a challenge we need to solve.

In addition to those two mechanisms we must think about how we create a superintelligence. One of the major aspects here is our understanding of the underlying technologies. If we create a self-optimizing neural network from scratch, which we do not understand in depth, it is very likely that we will not understand the potential threats before it is to late. Creating a digital copy of a human brain as a starting point on the other hand is a little saver, because we can assume that it will be driven by similar factors as a real human being. If that's desirable is a totally different discussion of course. But the general idea is, that understanding the motivation of a superintelligence is key for steering it in the right direction.

For more details about the topics I scratched in my answer and the control problem in general, I recommend reading Superintelligence by Nick Bostrom. He spends many chapters on those problems and possible solutions.

If you have more in-depth questions concerning specific topics, please open a new question to get a more detailed answer.