library(deSolve) yini <- c(temp = 18, heating_on = 1) temp <- function(t,y, parms) { dy1 <- ifelse(y[2] == 1, 1.0, -0.5) dy2 <- 0 list(c(dy1, dy2)) } rootfunc <- function(t, y, parms) { yroot <- c(y[1] - 18, y[1] - 20) return(yroot) } eventfunc <- function(t, y, parms) { yroot <- c(y[1] - 18, y[1] - 20) whichroot <- which(abs(yroot) < 1e-6) # specify tolerance y[2] <- if(whichroot == 2) 0 else 1 return(y) } times <- seq(from=0, to=20,by=0.1) out <- lsode(times=times, y=yini, func = temp, parms = NULL, rootfun = rootfunc, events = list(func=eventfunc, root = TRUE)) head(out, n=200)