I have some code in my sketch which connects to wifi with an ip address given by the router dhcp server, if I wanted to give my board a static ip address how could I alter the code ? , I have googled this but it is a bit confusing:
Thanks for this, I will give it a go, I forget to say I am just using the wifi as an mqtt system and there is no internet connected to it so do i need to add the gateway info ?
I am using a D1 mini board and the wifi library looks like it is for the wifi shield for arduino, the examples check to see if a shield is present so not sure how this works as the D1 mini has built in wifi ?
Well, you didn't include the top of your sketch, so we assumed you were using the WiFi shield - apparently the ESP8266WiFi library also has a class of the same name (probably for compatibility) - this is a prime example of why we don't like when people post pieces of their sketch instead of the whole thing.
That said, it looks like they implement the same API.
You need to supply the gateway and subnet as you always do when you are using a static IP. DNS servers are optional, but you probably need to specify them if you want to be able to resolve a domain name.
It's often easier to just configure the router to always give the device the same IP address, and let DHCP handle those other fields - this also seems less prone to problems in general. That's what I do for my connected devices.
As @DrAzzy says it is much cleaner if you can do it in the DHCP configuration of your router. That way your Arduino code stays the same, but it will always get allocated a fixed IP address. If you ever want to change the IP address, you can do it on the router and not have to change your code.
If you do hard code it in the Arduino, you need to make sure you exclude that address from the range of addresses the router uses for DHCP, otherwise the router may allocate it to another device which will cause you an intermittent problem that may be difficult to find.
On my Netgear router, the DHCP settings are under the LAN setup. You need to know the MAC address of the device that you want a static IP address for. Most routers should be able to show the list of connected devices, which will include the MAC address.