Wednesday, 16 November 2016

Circles in Minecraft - Minecraft Pi and Python

Circles in Minecraft?

Using Minecraft Pi, you can write code to place blocks. This means, in theory, you can code objects you could never build accurately - like giant circles.

I had a go at some maths around this in a spreadsheet using the formula for a circle



where x and y are coordinates.

It came out like this:



Which is circular if nothing else.

I don't like the gaps near the axes but with some clever programming (which I'll have to google!) I reckon eventually I could get rid of them.


Trig Method


I realised the numbers above follow 2 overlapping sine waves, so a quick search revealed this:

"A circle can be defined as the locus of all points that satisfy the equations
x = r cos(t)    y = r sin(t)
where x,y are the coordinates of any point on the circle, r is the radius of the circle and 
t is the parameter - the angle subtended by the point at the circle's center."
from  http://www.mathopenref.com/coordparamcircle.html (there's an interactive applet)



So  by carefully choosing the angular interval 't' you should be able to put blocks precisely where you want them in the circle.

Here's my first go in the spreadsheet:


You can see there are still gaps and the numbers in the columns are all over the place. Think the trig functions are working in radians but I entered angles in degrees. 

Using radians instead of degrees:


To plot more points, I'd have to reduce the interval in column 1 to give more points between 0 and 2.

Imagine that in Minecraft! 

I've a Pi 3 that I've just set up to run headless, so I'll move onto that next.....

The Results!


nested loop of expanding rising circles. Feels like an amphitheatre inside.

Simple cylinder - circles on top of circles
This one was weird - a cylinder with different block types in each layer. Unfortunately 2 of them were lava and water.
One massive circle. 

 The code for these:



from mcpi.minecraft import Minecraft
import math

mc = Minecraft.create()
#get players position
x,y,z=mc.player.getPos()

#move out of the way, there's something coming
mc.player.setPos (x,y+50,z)


r=15 #radius factor

for q in range (1,4):  #nested loop for when you want multiple circles
    for i in range(0,r*6):  #sets how many blocks comprise the shape
        j = float(i)/(r*3)  #gives max j of 2 (to give  2*pi radians for trig))

        blockXPos = r*math.cos(j*math.pi)  #sets x coordinate of block
        blockZPos = r*math.sin(j*math.pi)  #sets z coordinate of block

        mc.setBlock(blockXPos+x,y+q,blockZPos+z,1) #places a block in the circle



You could use code like this to plot other mathematical functions. Even 3D ones:

Quadric_Hyper_One
Its something called a quadric surface:



Something about that makes me feel like I've earned a glass of wine!




Tuesday, 15 November 2016

Electracker - Domestic Energy Consumption Logger

I've written about this project before but I revived it after a visit to Jersey Tech Fair and meeting the nice chaps at Jersey Electricity. They tried to sell me 'Nest', a home heating automation system (they may have succeeded. Watch this space.) But we also discussed electricity consumption.

I've had a Pi attached to my electricity meter for over a year now, but doing nothing.
Now rekindled, it seems to be happily tracking my energy usage and logging the results at Thingspeak.

I'm going to leave it for a bit and then plan to do a frequency analysis on a few days worth of data.

https://thingspeak.com/channels/182833





I also added this widget to my phone:

https://play.google.com/store/apps/details?id=ua.livi.thingspeakmonitor&hl=en

So now I can see live updates of my energy consumption as long as I have wifi/3G:








The code is here at github:

https://github.com/jcwyatt/electracker/blob/master/electracker_bars.py







Things I've learnt:

1) The wifi connection was really flaky - an Edimax attached to a Pi Zero. I've replaced the Edimax with a bulky Netgear with an ariel but this seems quite erratic too. Tried a better power supply.  Seems slightly better now. Made it a real pain to SSH into the Pi and also writing to Thingspeak.

2) You can't have it all ways (yet). I was initially recording every interval between flashes, and getting a really accurate reading, but couldn't write this to Thingspeak as it took too long and caused missed readings and errors due to the delay.
Now I'm counting the number of flashes in a 2 minute period and writing a calculated consumption based on this to Thingspeak. Advantages are that it give a consistent rate of readings, which looks great on Thingspeak, and at high consumption rates it should be very accurate, albeit for an average consumption over 2 minutes. However at low consumption rates the accuracy drops off; the small number of flashes per 2 minute interval kills the resolution on the measurements.

Solution:


Some kind of hybrid where it records the interval between flashes and averages this out over 2 minutes, and then writes this average data to TS.
Should be possible:

<pseudocode>
while True:
     Reset total time to 0
     Reset flashes to 0
     Wait for a flash
     Start the timer
     For 2 minutes:
            Wait for a flash
            stop the timer
            record the flash interval
            start the timer
            flashes +=1
            total time = total time + flash interval
            wait 0.07s to check the LED is off again
            repeat
      average = totaltime/flashes
      Consumption = 1.125/average
      Write Consumption to Thingspeak
</pseudocode>

Sunday, 30 October 2016

Home Heating IoT Project - Interface Designed

The interface is now built:


It uses PHP to write to a CSV and the interface reads from the current settings (in csv format) where present, and set these as the default selections.

Ideally I'd like to use AJAX to update the info live.

The html and css are here at git hub.

It's meant to be a mobile ready design but although it picks up the mobile version in a small desktop browser window, my phone displays only the desktop version.



Saturday, 22 October 2016

Home Heating IoT Project - Project Planning



Detailed Requirements:

1) each heater should have 2 programmable time slots, for morning and evening heating

2) it should be possible to turn each heater on or off manually from the interface

3) each heater should have a manual override to turn/stay off or on regardless of program.

4) there should be an override to turn all heaters off.

5) it should be possible to set the heat level (using mark space ratio)

6) it could be possible to link the heat level to outside temp.

7) the program data will be stored on a local csv file (or google sheet?)

8) there will be a php-based interface with the csv file to allow changes to be made, and the current status of the heater to be known.

9) a python program will manage the relays, using the csv file to determine required state of the output.



Schedule data (csv):

sleep (all off)
room1, start1, end1, start2, end2, rm1override on, rm1override off, heatlevel1
room2, start1, end1, start2, end2, rm2override on, rm2override off, heatlevel2
room3, start1, end1, start2, end2, rm3override on, rm3override off, heatlevel3
room4, start1, end1, start2, end2, rm4override on, rm4override off, heatlevel4




Monday, 20 June 2016

Day of Random Pi Stuff

Today's Pi Jobs:


1) Prepare SD card for code club project so webcam can be fitted to the front of CamJam 3 robot. The kids have already built the bot and can remote control it via node-red. I used nginx for the first time with zero problems.

2) Reimage 4 new SD cards with latest Raspbian plus a few tweaks - pibrella and tightvncserver.

3) For home set up a camera on one pi that will send its pictures to another using a bash script and scp. The remote pi is feeding the pictures to the web.

I'll publish more details on these projects later.

Thursday, 21 April 2016

Sweet Peas

My wife planted some sweet peas and put them in the conservatory to get started.



I was sorting through my Pi bits and bobs and found the camera module and a project was born.

I made a camera rig from an old bit of wood and a section of bicycle brake cable and used a PoundWorld specs to get the focal length shorter*:


And found the code for the time lapse online here:

(https://picamera.readthedocs.org/en/release-1.10/recipes1.html#capturing-timelapse-sequences)

and only made slight amendments: https://github.com/jcwyatt/sweetpea2016/blob/master/sweetpea.py


After 11 days I copied the files across with scp and deleted all the files smaller than 150k (the dark night time pics) with this great command:

find . -name "*.jpg" -size -150k -delete

Then it was just a matter of using ffmpeg to make the images into a video. A quick search confirmed that it was possible to do this on filenames organised by dates:


ffmpeg -framerate 5 -pattern_type glob -i '*.jpg' -c:v libx264 -r 30 sweetpea01.mp4


5 images per second, 30fps video and it literally took a few seconds to create this:





All done headless and with the command line.

Saturday, 2 April 2016

Arduino - Acceleration Due to Gravity Testing Rig

I made the rig in the picture to measure acceleration due to gravity, just for fun.





The hardware is just a home made electromagnet powered through a ULN2003 (linking  2 channels to boost current). This was controlled using an Arduino Nano. I added an LED to indicate when the electromagnet was activated, and a button to activate it. The switch that detected the ball hitting the ground was also home made from a peg, some paperclips and tin foil:



The plan for the program was:


  • Push a button on the rig to activate the electromagnet for long enough to attach a bearing but not so long it burns out the hardware (4 seconds seemed about right)
  • Switch off the electromagnet automatically and simultaneously start a timer.
  • When the pressure switch is activated by the ball hitting the ground, stop the timer.
  • Work out the acceleration using a = 2s / t**2 
  • (s= distance fallen, t is the time)


I started the code in Ardublock because it avoids typing errors, but the calculations refused to give a valid result even when the timing was giving valid readings. After a frustrating hour of trying to fix it within Ardublock, 3 minutes with the actual code in the Arduino IDE had it working well. The erroneous values are when the ball missed the switch and I had to trigger it manually.



 The code:

https://github.com/jcwyatt/gravityfalls