Skip navigation
2015

Hi Everyone,

 

Attached is video of how this all works. I put everything together to work, but without the clock everything couldn't be demonstrated. I set this up in the basement and couldn't have the lasers work the thermostat as we don't have one where I did the demo. Everything works in the demo as you will see. Hope you enjoy:

 

 

 

 

This is everything until I finish the clock and have it all together. Thank you for your patience and hope you enjoyed. I want to give a very special thank you to my daughter Chrystal (I am now her minion), she taught me a lot.

 

Dale and Chrystal Winhold

 

 

Here is our final (But not final) update for our Enchanted Clock.

 

 

My goal was to create a wooden clock and enchant it with the kits supplied by our generous sponsors, Atmel, Element 14 and Infineon. I wanted to have the clock recognize who was in front of it, control the lights and temperature  by voice command, control the lights by sensing if you were sleeping. There would also be a way to keep the time correct without self-adjusting the clock.

 

Accomplishments:

 

All the clock parts were cut out and partially assembled; due to tearing the ligament in my hand I wasn’t able to complete the clock. Once healed, I will complete the clock and incorporate all the electronics.

 

Voice control is completed and works perfectly. I have the commands Light, Dark, Sleep, Hot, Cold, Off and Timer embedded into the voice controller. Using the command “Light” turns on the lights, “Dark” turns them off and “Sleep” turns them all to dim. “Hot” and “Cold” turns the heater up or down. “Off” stops everything as a back-up command. “Timer” is for future use of setting a sleep timer or cooking timer. The temperature thermostat was across the room so Chrystal (my daughter) thought of using a laser with photo sensors to turn the motor on and off. When the command “Hot” or “Cold” are said the laser would hit the photo sensor and allow the power through to the motor and adjust the temperature.

 

For the clock to have its time correct I added a binary clock to keep track of the correct time. This will be placed with the wood clock as it will control the servo used to adjust time. There is a magnetic sensor in the wood clock to know where the minute hand is located. When the minute hand reaches the hour, the sensor checks the minutes of the binary clock. If it is within a couple of minutes it won’t adjust, if more than that it will activate the servo to turn the minute hand forward or back. The binary clock is complete and works great. I placed the temperature lasers into the board for looks and to be compact.

 

The recognition sensor is an ultrasonic sensor that measures height from the top to the floor. So when someone from the family is standing in front of the clock it takes their height and compares it to the database and displays “Hi (Name)”.

 

Sleeping sensor works with ultrasonic sensors as well. How this works is by sensing movement, if you are on the sofa reading, you constantly move which the sensor recognizes. If you were to fall asleep you moving around is a lot less which will let the sensor know you fell asleep and turn the lights down. Because the sensor knows you’re on the sofa, if someone walks in the room the lights won’t turn on unless the one sleeping moves a pre-set amount.

 

 

Items used and price

 

Arduino (3) - $26.00 each

 

Infineon RGB Board - $34.00

 

LED strip lights - $37.00

 

Arduino prototype board - $12.00

 

Ultrasonic sensors (3) - $12.00

 

Wood for clock – Free

 

Wire & Msc. - $45.00

 

LED Display – Free (Recycled)

 

Voice recognition module - $37.00

 

 

 

Drawing of the final project attached below. Pictures will follow later tonight as I am out of town.

 

Clock diagram.jpg

Thank you all for reading,

 

Dale and Chrystal Winhold

 

Jan Cumps

oh no - deadline passed

Posted by Jan Cumps Top Member Jun 26, 2015

Just too late to meet the timeline

 

I've been telling the story of the brothers Christian and Josef Steidinger here on the blog.

Christian is the one who left the family business and started the Perpetuum Ebner manufacture.

But to be honest, he's the one that didn't succeed. Brother George created the DUAL brand, and that company survived in its original form till the 80's.

 

The photos below are turntables that I have from DUAL. Some are brought back to specs. Others are Work In Progress.

I don't have a museum. Regularly I sell the ones that I have and buy new ones to play with.

 

 


 

{gallery} DUALs

Photo 26-06-15 21 50 58.jpg

DUAL 1010 and amp HS 32 (1960's): revised

Photo 26-06-15 21 53 22.jpg

DUAL 1019 (1960's): revised

Photo 26-06-15 21 53 47.jpg

DUAL 1218: donor for spare parts (1970's)

Photo 26-06-15 21 54 51.jpg

DUAL 1214 in console: wip (1970's)

Photo 26-06-15 21 55 41.jpg

DUAL 1218: WIP (1970's)

Photo 26-06-15 22 00 41.jpg

DUAL 510: revised (1970's)

 

 

 

 

The 1010 I've just purchased and fixed a week ago. That one has outside duty during sunny days. The others I pick and choose whenever I want, until I'm tired (or someone buys one).

 

{gallery} DUAL 510

Photo 16-06-15 09 23 24.jpg

DUAL 510: looks

Photo 16-06-15 09 23 45.jpg

DUAL 510: looks

Photo 16-06-15 09 23 58.jpg

DUAL 510: looks

Photo 16-06-15 09 24 09.jpg

DUAL 510: looks

Photo 16-06-15 09 24 22.jpg

DUAL 510: headshell

Photo 16-06-15 09 24 37.jpg

DUAL 510: cartridge and stylus

Photo 16-06-15 09 25 04.jpg

DUAL 510: tracking force and anti-skate

Photo 16-06-15 09 25 11.jpg

DUAL 510: speed control

Photo 16-06-15 09 25 53.jpg

DUAL 510: looks

 

 

If you're interested in turntable maintenance, I've got a Youtube channel dedicated to that subject.

When subbmiting my application to join this road test, I set myself 4 success citeria:

 

Success Criteria: I will deem the project a success if:

•It can accurately and reliably display the number of messages in my inbox up to 12

•The system can cope with more than 12 messages in a way that does not result in catastrophic failure

•The display can be read in darkness with an LED backlight

•The unit is powered by a single DC wall wart

 

My project has been successful in meeting all four of these criteria. The final version of the multimeter was able to display more messages than expected, and additional messages merely left the needle in the highest position without moving any higher.

The led backlight was also incredibly successful. My original design featured a single blue led to provide illumination due to the requirement to use a motor controller. By hooking the display up to the arduino with resistors I was able to use simple PWM control to manage the display, allowing me to then use an led driver shield to implement an impressive three colour backlight that not only allows the display to be read in darkness, but also provides an additional means of displaying the number of messages. The one failing with the backlight is that it is not quite as bright as I had hoped. Due to space constraints, the LEDs had to be mounted in the case in a way that left them pointing more towards the inside of the case than the top of the display. The backlight is still useable, but the colours are a little less content than I had hoped. However, this shortcoming is partly made up for by the fading effects enabled by the driver shield. Using the shield, I was able to set up a system so that when values on the display changed, the colours of the backlight would neatly fade into the new shade instead of suddenly changing. A similar fade also occurs when the backlight is turned on or off.

  Finally the unit was powered with one dc power brick to the use of a ubec to provide regulated power to the yun. The original idea was to power the unit with a "wall wart" style adapter with the transformer moulded directly into the plug, but I instead opted for a "power brick" unit with the transformer connected to mains via a kettle lead. This makes it fay easier to extend the length of the power cord as the kettle lead can easily be replaced. It also had the advantage of allowing me to recycle a used power adaptor that would otherwise have gone to landfill. The main intention of the "single wallwart" objective was that the unit should not need two plug sockets, so this can be considered a slightly modified objective to better utilise the parts available.

 

My original apapplication also highlighted some areas of the project that appears to potentially be difficult. Theses were:

• Writing the code for the parser

   -Whilst I do have some experience of python, I have only coded something like this once in the past

•Calibrating the pwm

   -I will probably needs a separate program to test pwm values via a serial terminal. I will probably use an arduino Leonardo for this, simply because I feel more confident     using it

•Comunicating between Linux and the Atmega

   -Having never used a Yun, this appears to be one of the challenges specific to the platform

 

Calibrating the PWM turned out to be incredibly easy. The fast upload times of my new Uno board made the use of a serial connection unnecessary, and trial and errror found appropriate values surprisingly quickly. The other two areas were even harder than I expected. IOT is incredibly difficult. The internet is a huge, wonderful resource, but tapping into it can be hard. The yun made the creation of an iot device possible for me, but writing the code for it was incredibly challenging. Plus, it didn't help that the site I was working with had some badly timed issues .

 

I would like to finish this post by thanking all the people who made this project possible.

Thank you to the element 14 staff who arranged this design challenge; your work creates worldwide enthusiasm for electrical engineering and is an excellent opportunity for both aspiring and we'll versed engineers.

Thank you to the network engineers who tracked down the issues with the site and rendered it useable for this project, and sorry about the bad timing.

Thank you to all the people who commented on my posts, you provided rays of inspiration for this project and helped keep me motivated.

Thank you dad for letting me use your multimeter, you can borrow mine if you want.

And finally, thank you Genesis for writing some excellent music for me to listen to whilst working.

 

This project has been an immense journey for me and I am glad that it turned out to be such a success. Once again, my thanks to everyone for making this such a great success.

IMG_20150626_110244.jpg

Today I finished putting the final touches on to the inbox and the code. First of all, the code. Unfortunately, for the past few weeks there has been an intermittent issue with the inbox and activity on the element 14 website. The issue has now been resolved, and was not a major barrier to normal use, but it made prototyping code increasingly difficult as the section of the site the code was trying to observe would fail randomly, making troubleshooting incredibly difficult. As a result of this I was forced to delay writing my code until the site was repaired, hence the rather late nature of this blog post. Eventually I was able to get some python code running to provide the cookies normally seen when logged in to the site and request the HTML of the page. This HTML was then parsed to return just the number of messages in my inbox, and passed this number over to the atmega chip to drive the display to the appropriate value. I made sure that the code waited a full 20 minutes between each time it attempted to check the website. This will ensure that it does not use too much of my internet bandwidth or put an excessive load on element 14s servers.

HTML code featuring the name of my account

/\ Some of my first success with the parser, finding a block of code featuring my account name, also proving the cookies worked

 

After writing the code, the time finally came to mount the circuitry. Installing the display and LEDs was reasonably easy with a little hot glue, and transferring the wiring was simply a case of transferring conditions from the breadboard one at a time. I did however run into some major issues in getting everything to fit into the case. Because of the weight of the various ports on an arduino yun, shields will often not be able to fit onto it properly. My intention was to work around this simply by having the shield at an angle with some pins not fully within the female header. Unfortunately this did not provide a good enough connection in some pins, forcing me to rethink my design. In the end I solved this issue by soldering a second set of male headers directly onto the ones I had already mounted. This effectively gave me double the height and easily allowed me to clear the ports. However, this new set of headers rendered the bord far to thick to fit correctly into the original case. In the end the only way I could solve this problem was by running a ribbon cable from inside the multimeter out to a separate enclosure containing the boards. This worked surprisingly well and the meter was soon up and running.

Two strips of pin headers soldered together

The case I chose for the boards was a cardboard box with a slide off clear colour. When I eventually install this I will try and find a better way to conceal the extra electronics, but for now I thought it would would be better to have them clearly visible for you all to see. With this done the only two parts to add were the voltage regulator for the yun and the switch to turn off the backlight. On my breadboarded version of the circuit I used a tact switch to turn off the backlight when held down. Obviously this is not practice in the actual meter so instead I desoldered one of the original switches from the multimeter circuit board and soldered it in place of the tact switch. Due to the design of the case, the switch would hold itself in place so I did not need to glue it in, allowing me to seperatge the two half's of the case for easy repairs. As for the voltage regulator, I choose to use something called a ubec. Ubecs are switching voltage regulator designed to produce a very low amount of rf noise for rc applications. I choose to use on because they are more efficient than traditional linear regulators. It also helped that I had one in my parts bin. To simplify construction, I attached the two input power lines for the ubec to the 12v power supply simply by soldering them to the underside of the power connector on the led driver board. 5v and ground were connected to appropriate pins on the shield and the whole thing was carefully checked with a multimeter before plugging in the yun. It worked perfectly.

A ubec

The only other addition I made to the board was for photography. Because of the 20 minute delay, filming and photographing the board was going to be a very time consuming process. In order to circumvent this I added two tact switches to pins 2 and 3 using the internal pullups. As in some of the prototypes, these were programmed to increment and decrement the post count allowing me to change the value on the display without having to wait for the system to update. For some additional rigidity glued the switches to a piece of wood. It is important to stress that this was only done for the purpose of photography and is not a required part of the system.

  The system seems to be working fully. I will evaluate the success of the solution against my original specification in a separate post, but for now, here are some posture of the finished unit.

 

IMG_20150626_105827.jpg

/\ The entre setup

 

IMG_20150626_111036.jpg

/\ The inside of the meter

IMG_20150626_110228.jpg

/\ The display in action

In the below presentation on security Rohini Pandhi mentions the problem of keeping your device updated.

 

Unconnected consumer items used to be simply build, distributed and sold with no process for doing any updates. Embedded systems did have options for updating but often this needed to be done by a trained field service engineer or by returning the item to the factory. Small issues spotted post production were fixed in new versions but often not patched in older versions. If there was a significant fault with a system then they would need to be an expensive product recall.

 

With connected devices there is the added issue of security. When there is a security issue these often need to be patched faster or there might be problems for the end users.

The fact that the device is connected means that patches can be downloaded and applied more easily as is done with mobile phones and PC.

 

For embedded products there are additional challenges

  • Lack of user interface
  • Always on
  • Power requirements (flashing a ROM could use a lot of power)
  • Handling failures
  • Automating the installation process

 

I've not really looked into these issues for my project so would be interested to know what other peoples thoughts are?

References

The 10 challenges of securing IoT communications | Atmel | Bits & Pieces

Efficient over-the-air software and firmware updates for the Internet of Things - Embedded Computing Design

Meraki firmware updates while you sleep

Open source solutions ease process of updating leg - AMD – Aerospace Manufacturing and Design

A router firmware update goes bad | Computerworld

amgalbu

MagicHat - 25 - Final demo

Posted by amgalbu Top Member Jun 26, 2015

amgalbu

MagicHat - 24 - Bonus post

Posted by amgalbu Top Member Jun 26, 2015

After building the MagicHat, I was wondering: what if I want to wear the hat at a party? I need a bow tie... so this is a quick tutorial to build the bow tie for your MagicHat

 

IMG_20150626_110333.jpg

IMG_20150626_110655.jpg

IMG_20150626_111033.jpg

IMG_20150626_111105.jpg

IMG_20150626_112729.jpg

IMG_20150626_113052.jpg

 

IMPORTANT NOTES

1. it's better to wear the bow tie with a shirt

2. charge MagicHat battery before the party

3. remember to shave!!

4. say thanks to balearicdynamics  for this wonderful idea

 

Some photos that were taken during the project.

                                                                                                                                                                                                                                                  

 

 

{gallery:width=600,height=600} Photo Story

Cottage.png

Enchanted Cottage: Before it was taken apart.

MechanicalPrototype.jpg

Mechanical Prototype: Cardboard and brass tacks

MultiPrint.png

Multiprint: Printing lots of parts for the mechanism

ServoTestJig.jpg

Test Jig: For testing servos

2015-03-29 20.20.54.jpg

Cutting: Strips of wood for the substructure

Planks.jpg

Planks: Initial pass at the frame parts

Printer in action

Printing: Printign the mechanism

MatildaAndBattery.jpg

Battery Delivery: Matilda checks out the new battery

CaptiveNuts.jpg

Captive Nuts: Nuts to support rods to support PCBs

2015-05-04 20.53.10.jpg

Battery Test: Testing the battery

2015-05-09 20.16.07-1.jpg

Infineon Low Power: Testing low current options with the Infineon RGB Shield

2015-05-11 20.17.28.jpg

LED: A mini PCB

2015-05-12 20.44.33-1.jpg

Golem: Hans and Matilda's Metalworking Friend

PinsAndBoards.jpg

Pins: Pins and Headers

TestFitting.jpgR

PCB Stack: Test Fitting

2015-05-16 20.21.17.jpgR

Battery Box: Folded stainless steel

2015-05-16 21.21.51.jpg

Battery Board: Testing the board

2015-05-30 21.44.00.jpg

Knock Knock: Testing the sensor circuit

ProtoShield.jpg

Protoshield: Surely I can fit more on it than this...

ComparatorStripboard.jpg

Knock Knock: Now on stripboard

2015-06-08 14.59.18.jpg

Fibre Housing: With fibres

2015-06-14 17.37.49.jpg

Just add magnets: Hans and Matilda get an upgrade

2015-06-18 22.33.46.jpg

Top Panel: Buttons and lights

2015-06-20 20.45.05.jpg

Printing Supports: Attempt 6

TopPanelElectronics.jpg

Buttons: Circuit board for the top panel

ButtonsFailures.jpg

Fail: When buttons go bad

MagnetHolders.jpg

Magnet Holders: Hans and Matilda out up front

MagnetCarriers2 (2).jpg

Magnet Carriers: The new mechanism

FinishedCottage.jpg

Posing: finished cottage

2015-06-23 22.41.49.jpg

Electronics: Hans and Matilda admire the finished electronics

2015-06-22 20.58.26.jpg

Weather: Warm, slight chance of rain in Chicago

As mentioned it the demo video and Enchanted Objects Design Challenge - And they all lived happily ever after the Arduino Yún takes a long time to boot. I did notice that there's a bit of a difference between different file systems on the SDA. I also collected together some links in my research which give ideas on speeding up this process.

 

One tool that might help is BootChart that gathers some stats and presents them as a chart, as with a lot of things on the Arduino Yún this is for standard Linux so might not work for the Yún platform.

Boot Chart

 

 

Booting
http://wiki.openwrt.org/doc/techref/process.boot
https://lwn.net/Articles/299483/
http://www.bootchart.org/
http://forum.arduino.cc/index.php?topic=236696.0
http://free-electrons.com/doc/training/boot-time/
http://forum.arduino.cc/index.php?topic=324304.0
http://forum.arduino.cc/index.php?topic=324086.0
http://codesnippets.altervista.org/documentation/yun/boot_running/boot_running.html
http://codesnippets.altervista.org/documentation/yun/boot_process/rcS_process.html
http://forum.arduino.cc/index.php?topic=290149.0
https://gist.github.com/wayoda/db3c023417757f726088

Final builds due tomorrow

Posted by bluescreen element14 Team Jun 25, 2015

Hi Everyone.

 

Just a quick reminder that your final blogs are due tomorrow, June 26 at midnight GMT. Remember that the more rich content you include, like videos and images, the better your chances of winning.

 

We are excited to see all of your builds! You have created some truly amazing, beautiful objects, and we want to thank you all for inspiring all of us at element14 with your creativity.

 

Thanks for all of your hard work, and good luck to you all!

 

Sagar

amgalbu

MagicHat- 23 - Conclusions

Posted by amgalbu Top Member Jun 25, 2015

This week I completed my project for the Enchanted Objects design challenge. It has been funny even if some external activities (namely work and family :-)) didn't allow me to get a more in-depth view of some aspects.

I will now try to assess whether I met the requirements of this challenge

 

Security

The MagicHat does not publish anything on the Internet. Local connections are encrypted through SSL and access to web UI is protected by user authentication

Accuracy: how well does the proposed solution register the information it is intended to assess?

It's difficult to say: the sensor temperature has an accuracy of 0.1 °C, the earth beat detection algorithm has probably tested and works reliably. The blood pressure detection needs to be verified on a larger number of patients (see below)

Convenience: how easy it will be for non-technical personnel to use ?

Very easy: just power it on!

Cost: how much will it cost?  Is it cost effective?

Regarding the hardware and the software, I tried to reduce to the minimum the hardware requirements to run the whole application and I also used standard components that are widely available and very cheap.

The bill of the building materials is very short: plywood, PVC film and screws

However, some optimization could be implemented. In particular the blood pressure measurement method could be changed to make everything happen on the Arduino Yun, thus eliminating the Arduino Mini board. The initial idea was to show the biosignal (which should - at least in my mind- could have been a "wow factor") and to use the biosignal itself to measure both diastolic and systolic pressure. After some experiences, I realized that there are too many factors affecting the amplitude of the biosignal. A better solution could be the approach implemented by balearicdynamics in its meditech. He builds an external board that generates a square wave which frequency matches the number of earth beats per minute. Processing the square wave will be much simpler, freeing enough Arduino Yun's resources to control both servos and mouth's LEDs

Durability: for example, can it withstand everyday life and yet continue to function normally?

Crash tests will are planned after the completion of the demo video :-)

Overview

This particular enchanted object is right out of the storybooks. Deep in the forest is a small cottage owned by a timeless couple, Hans and Matilda who are doomed never to meet. When it is wet he goes outside but when it is dry she must leave the house.

 

The idea was to take an old fashioned "cat gut" based weather house and use the electronic components to bring it up to date. The key features would be servo driven mechanics, LED showing the temperature and the Arduino Yun for getting the weather from the internet.

 

BeforeAfter
WeatherHouse.jpgFinished House~2[1].jpg

 

The project has stayed fairly true to it's original idea, the LED bar graph for the temperature has been swapped with the coloured LED and the need to have a button to check the temperature has been eliminated. The mechanics have been 3D printed and fitted together with magnets under the cottage so that the figures move straight in and out of the house with no obvious form of propulsion.

 

Infomatic.png

 

About me

Before the project I knew a bit about Arduino, nothing of the Linino portion of the Yún and had not touched Linux for years. I also had not coded in Python before or used RGB LEDS and piezo sensors. I'd only just started with 3D printed back in January. I do have some electronics background having done GCSE and AS-Level electronics and then a degree at Imperial college back in early 1990s. I've been in software ever since and just returned to electronics as a hobby in the last couple of years.

 

Thanks

Hans and Matilda are just fictional characters so in reality all the work on this project was done by myself.

IMAG1535[1].jpg

However, I can't take all the credit.

 

Thanks to Atmel, Element14 and Infineon for providing the kit for the project.

A special thanks to Christian DeFeo and team for setting up the challenge.

 

Thanks to everyone who's provided help and support along the way

My wife Rebecca for acting as a sounding board and putting up with the late nights coding and noisy printer in the kitchen.

Alan Barnet for support and ideas

Support and advice from the Element14 community Jan Cumps, Clem Martins, Frederick Vandenbosch, shabaz, Ambrogio Galbusera and Mark Beckett

Inderpreet Singh and peteroakes for their support and RGB lighting code

Charles Gantt for his enthusiastic reports

Eric Styles for advice on magnets

AdaFruit for their splendid Powerboost board and DHT22 library.

Michael Anthony Schwager for the Enable Interrupts Library

Michael Margolis,Philip van Allen and Korman for the variable speed Servo Library

jwaldha for the technique on how to turn off the Linino portion of the Arduino Yún

the members of the Arduino forum for their treasure trove of ideas and information

 

Posts

As well as the weekly "story" posts I added a few out of character ones for interest and to include extra technical details.

 

Enchanted Objects Design Challenge - Disaster strikes the Enchanted Cottage

A big thanks from Hans, Matilda and myself

Enchanted Objects Design Challenge - Remodelling the Enchanted Cottage

Enchanted Objects Design Challenge - Matilda is not happy

Enchanted Objects Design Challenge - The Woodcutter and the Blacksmith

Enchanted Cottage CAD models

Enchanted Objects Design Challenge - Back on the straight and narrow

Servo and mechanics in action

Enchanted Objects Design Challenge - Yum Yum Yun at the Enchanted Cottage

Enchanted Objects Design Challenge - Channels and a special delivery to the Enchanted Cottage

Enchanted Objects Design Challenge - The snake, the troll and the fighting dwarves

Setting up a Python Development Environment

Listening to weather on the radio

Enchanted Objects Design Challenge - The flaming postman, the blind man and a trip to the market

Enchanted Objects Design Challenge - The Blue Haired Woman and Off Grid Living

Enchanted Objects Design Challenge - Hans meets "Injector"

Enchanted Objects Design Challenge - Farmer Hogg and the Lockity Gowan

Enchanted Objects Design Challenge - Taming the Python

Enchanted Objects Design Challenge - The Glowing Golem and shiny battery box

Enchanted Objects Design Challenge - Sleeping Golem

Enchanted Objects Design Challenge - The townsfolk get Rickrolled

Enchanted Objects Design Challenge - This is not the WiFi you are looking for

Enchanted Objects Design Challenge - An unexpected visitor to the Enchanted Cottage

Enchanted Objects Design Challenge - Knock Knock

Enchanted Objects Design Challenge - The Crystal Cave

Enchanted Objects Design Challenge - Turn on and offable

Enchanted Objects Design Challenge - Windows 10

Enchanted Objects Design Challenge - The Lode Stone

Enchanted Objects Design Challenge - A tale of two bridges

Yet another way of blinking an LED on the Arduino

Swapping out the bridge

A bit of 3D Printing

Enchanted Objects Design Challenge - Locking the doors

Enchanted Objects Design Challenge - Tools

Enchanted Objects Design Challenge - Painting, top panel and new magnet carriers

Enchanted Objects Design Challenge - System Overview

Enchanted Objects Design Challenge - Python Start, Python Stop

Enchanted Objects Design Challenge - Planning and Building

Enchanted Objects Design Challenge - Testing

Enchanted Objects Design Challenge - And they all lived happily ever after

 

General Interest

These posts were created for general interest and reference but were not specifically to do with the project.

Superclock

Useful videos and references

Securing IOT devices

Other enchanted objects

More enchanted objects

Extreme Enchanting

 

Technical issues and challenges

The build for the Enchanted Cottage was not all smooth progress. There were a selection of technical challenges and mistakes along the way.

 

The servo provided was a continuous rotation servo, to use that would have made the project particularly challenging. The tinkerkit servo was also a bit large for my house so I purchased a smaller positional servo.

The Arduino Yún provided it's own set of challenges. Firstly was making it connect to the Web API using a HTTPS connection, this required installing the certificates and jumping through some hoops to get the python components needed. Luckily there was more than one Python library to use so I managed to find one that worked and validated the certificates.

The mechanics to make the figure move took a few attempts, firstly to get the correct motion then to get something that could be reliably 3D printed.

The wiring took a couple of goes to get right, I had initially put the cables too far into the sockets leaving no room for the pins. I also used solid core for these wires which is all I really had spare. This mean that the wiring loom was quite stiff and difficult to manoeuvre, swapping this with flexible cable would make sense.

There were some physical issues too, the short cable on the LiPo battery is definitely one to watch for. Generally finding enough space for all of the components so that they did not clash and issues like the height of the components on the Yún and different holes in the proto board meant for a few on the fly changes being needed to the structure. The woodwork would be built differently knowing what I know now. The proto board inevitably ended up a little messy as the layout was revised a few times. Again there was difficulty finding space for the connectors so that they did not clash with the board and mounting struts.

Managing power became one of the key topics as I wanted to run the house on batteries, I found what I needed online for that and my experiments produced good results.

The Infineon RGB shield was easy to use and the previous challengers had generated some good documentation and code libraries. I knew I'd be right on the lower current limits of the board but with the right settings and timings the current was set correctly.

The knock knock circuit was heavily researched before incorporating into the project. The circuit was straight forward to understand and build with just the lack of a pull up resistor on the comparator output causing any delay.

 

I've learnt a few bits of electronics along the way such as driving MOSFETS and handling the signal from the Piezo transducer and I've learnt lots about the Arduino Yún.

 

Circuit Diagrams, 3D Models and Code

 

All of the files for the project can be found on GitHub which I've been using all through the project to manage the project and share files between computers.

 

https://github.com/Workshopshed/EnchantedObjects

GitHub.png

 

Code: https://github.com/Workshopshed/EnchantedObjects/tree/master/Code

 

The code is a combination of C++ on the Arduino side and Python on the Linino side, there are also some shell scripts to help setting up the system. The decision to use C++ classes to segregate the functionality was not done to create re-usable libraries for others but to make the code clear to read and maintain. The decision to use Python was based on that it was an easy language for beginners and that it was already installed on the Yún.

 

As mentioned above there are several libraries incorporated into the code

 

AdaFruit - DHT22 library - https://github.com/adafruit/DHT-sensor-library

Michael Anthony Schwager - Enable Interrupts Library - https://github.com/GreyGnome/EnableInterrupt

Michael Margolis,Philip van Allen and Korman - Variable speed Servo Library - https://github.com/netlabtoolkit/VarSpeedServo

Inderpreet Singh and peteroakes - Infineon RGB lighting Library - https://github.com/inderpreet/infineonrgb_shield

Eberhard Fahle - configuring the handshaking line for the Arduino Yún

 

Electronics: https://github.com/Workshopshed/EnchantedObjects/tree/master/Electronics

 

The original plan was to use Fritizing to document a lot of the circuits. Fritzing provided it's own challenges so a mini tutorial was written on what was learnt. As the project progressed many of the schematics were simply done using Visio as all that was needed was the high level blocks and wires. For the full schematic Eagle was used as it's libraries were more extensive so fewer components needed to be designed.

Many data sheets and websites were referenced and are too plentiful to mention here but they are mentioned on the specific posts that utilised them as a reference section.

 

{gallery:width=500,height=500} Circuit Diagrams

Power Switch

Power Switch: Switches on an off the peripherals

Knock Knock

Knock Knock: Sensor circuit

DHT22

DHT22: Temperature and Humidity Sensor

RGB

RGB: Infineon RGB Shield and LED

Full Schematic

Schematic: Full schematic

 

Mechanics: https://github.com/Workshopshed/EnchantedObjects/tree/master/Mechanics

 

The 3D printed parts were all modelled in OpenSCAD so they have a source code as well as the STL files that were generated for printing.

 

{gallery:width=500,height=500} Printed Parts

Mechanism

Mechanism: Parts for the Watts Linkage

MagnetHousing.png

Magnet Housing: Holder for the magnets

FibreHousing.png

Fibre Housing: Attach fibre optics to the Arduino Yún

WindowFrame.png

Window: Replacement window

Top Panel

Top Panel: Show fibre status and buttons

WifiAndPowerButtons.png

Buttons: A couple of buttons to control the setup

Spacers

Spacers: Different heights of spacers for the boards

Security

Security has always been in the back of my mind whilst working on this project, the wolf is never far from the door.

Wolf.png

The thing that amazed me the most was that there were practically no end to end examples where people had created a secure connection to a HTTPS server. The ones I found had a one liner that mentioned installing certificates but no detail. I suspect this is because the Arduino Yún is targeted and used by hobbyists.

 

Secure communication could be done using a VPN but as the destination is not under our control, that's not possible, so an alternative way to secure the communication was used.

Enchanted Objects Design Challenge - Channels and a special delivery to the Enchanted Cottage

 

The key features of the communication are:

  • Certificates installed from a trusted source
  • Certificate provided by weather server validated to ensure identity of that server
  • Communication from weather server encrypted using TLS as provided by HTTPS end point

Enchanted Objects Design Challenge - Taming the Python

 

The cottage has been made to continue working in the case of a network failure of DOS attack

Enchanted Objects Design Challenge - The townsfolk get Rickrolled

 

The cottage has been made to continue working in the case of a power failure

Enchanted Objects Design Challenge - The Blue Haired Woman and Off Grid Living

 

To lock down the Yún the following principles were applied

  • Users and passwords
  • Handle brute force attacks
  • Remove unused functions
  • Apply principle of least privilege (limited implementation)

Enchanted Objects Design Challenge - Locking the doors

 

Instructions for use

Initial set up

  • The one time set up of the system is the out of the box experience provided by Arduino, you have to configure the WiFi to point to your local network.
  • Unless you live in Chicago,IL you'd also need to set your location in the configuration file.

User Operation

  • Then all the user has to do to get the weather is wait, the figures will automatically adjust their positions and the light changes colour as new data become available.
  • For impatient users they can simply knock on to roof to trigger a system wakeup and check for weather.
  • Rather than needing to read small digits the user can quickly tell the temperature from the LED colour.

 

Story

The story aspect was written each week on the morning commute based on the planned work to be done. As the week progressed this occasionally resorted in a re-writing of the story so that the tale correctly reflected what was actually done, some of the topics were moved to later weeks as needed. Writing in the third person narrative was at times challenging and I decided fairly early on that it would be easier if Matilda did the mechanical aspects and Hans did the coding and electronics. However I did have to re-allocate some tasks between my alter-egos so that it was more evenly shared.

 

Costs and Cost Saving ideas

As mentioned in Enchanted Objects Design Challenge - How much!? there are many opportunities to reduce code on this project.

 

The key points are:

  • Build a single board based on a 3.3v supply, that would reduce a lot of the complexity such as connectors, physical support for the board, power regulators, level shifters etc.
  • Build the house from pre-printed panels that could be laser cut and simply assembled.
  • Simply assembly steps by eliminating some of the screws from the mechanism.

Working project demo

A quick demo of the house in action. The demo mostly shows the long boot time of the Linino portion of the Arduino Yún. It typically takes around 60s to boot and depending on the disk state it could take longer. I did some research into how this time can be reduced but did not have chance to implement anything.

On power up the figures move so that Matilda is just inside and Hans just outside. This would indicate a slight chance of rain.

The flashing light at the start of the process shows the system waiting for the boot. Once it's booted the light changes to indicate that it's processing the weather and then changes again to a the solid light with a  slight movement of the people to the middle position to show that it's going to be a "changeable day in Chicago" which is where I've configured the system to check for weather.

 

 

Improvements?

 

A few enhanced features have been suggested by various engineers, including Christmas lights and posting the status to the internet. Solar panels on the roof were also suggested, some calculations would be needed to determine if that would make a significant difference given the small roof size.

 

For me the biggest thing that could be improved would be reducing the size of the electronics and hence the size of the back if the cottage. With a custom board or simply smaller modules it should be possible to bring that width down to just a little more than the thickness of the servo.

 

It would also be good to have the weather information displayed on some kind of screen, I did look into 8x8 LED matrixes but those would consume a lot of power. The obvious low power option would be a electronic paper display as that only uses power when it updates. The Arduino could stream images from the Linino's storage onto the display to show for example a picture of a cloud when it's cloudy.

 

The software for the system focuses on the functional aspects, moving the servo, getting the weather etc. There is lots that could be done on the user interface such as providing an easy way to set the location and simplifying the UI provided by Arduino.

 

A couple of things planned for the project were dropped along the way. One idea was to use capacitive switches for the controls, however this was dropped in favour of the knock knock switch and simple top panel buttons. A clear plastic housing for the back of the cottage was planned but got cut at the end due to time constraints. A rather crazy idea of using a model railway smoke generator to provide a smoking chimney (on cold days) was also abandoned.

 

The Low Battery signal from the charging board is wired to the protoshield but nothing is done with it. That could be wired to one of the inputs and read in the code.

 

As mentioned above improving the boot speed would be a significant improvement to the system.

 

The Infineon shield was investigated to see if the Flashing and colour cycling functions could be offloaded to it's MCU. This required a special cable and software so was not attempted.

 

Conclusions

 

The design challenge has definitely lived up to it's name, it was very challenging. I've learnt a lot about embedded systems during this project, from interrupts and low power options on the Atmel microcontroller to MOSFETs and power control thanks to Infineon. I've also learnt a lot about 3D printing and designing models to make them print reliably. One of my key lesson's learnt is keeping an eye on the physical space required for connectors so that they don't clash with other components.

 

I'm happy will the end result and enjoyed making the Enchanted Cottage, and I'd like to thank Element14 for giving me the opportunity to participate.

 

Finale

And so our enchanting tale comes to its end. If you go down to the forest, there in a little clearing you will find an Enchanted Cottage. If you knock on the door then a delightful couple will pop out to tell you the weather. But be careful not to stay too long as you might bump into the wolf.

There was a new version of the Arduino IDE, this week was not the best time to download it, so that was left until after the challenge.

 

Due to the modular nature of the design the boards and components could be tested as they were assembled. The boards were tested with modified versions of the example code that were originally used in the development. Prior to assembly the proto-shield was visually inspected for problems.

 

Test code and example: https://github.com/Workshopshed/EnchantedObjects/tree/master/Code/Examples

 

Powerup Test

All the plugged components were removed, the Arduino Yún and Protoshield were plugged together and it was powered up from the micro USB connector. This tests that there are no serious faults with either board. The LED light pipes were visually inspected and although there was a little bleeding of light between the outputs the overall result was acceptable.

 

Knock Knock and Top Panel Buttons

The knock knock sensor was plugged in and tested. This did not work as expected and was tracked to a dry joint on one of the power wires on the protoshield. Whilst trying to diagnose that issue a short sketch was written that output the button status to the serial port for monitoring and this was used to test the top panel buttons. A note was added to ensure connectors pushed on properly.

 

DHT22

This was not testing correctly, the MOSFET switch code was added to ensure that the DHT22 had power but I could not get this to read. I suspected the power switching so investigated that on it's own.

 

Mosfet Test

An LED was attached to the power connector normally used for the Infineon shield, it was a bit of a lashup as the cable was not very long. The problem was identified as a software issue, it was that the pin that turned on the MOSFET had been entered as 11 rather than 12. This was corrected in the test code and project code.

IMAG1547[1].jpg

DHT22

Now that the MOSFET was working, the DHT22 tested correctly, the local temperature was 25.3°C and 43% relative humidity, very pleasant.

 

Mechanism test

The mechanism was tested to ensure that it moved freely and that the figures were running smoothly.

Servo

The servo was tested without the wire link to the mechanism using the slow sweep code.

 

Because the servo had been binding in the previous tests the springy connector was moved to the outer hole on the horn, this meant that the line to the mechanism was straighter eliminating that problem. However, the limits of the movement needed to be recalibrated from the original 50° - 100° values. A new sketch was created that used the top panel buttons to move the servo and output the angle, that allowed new values to be set.

 

 

Battery Test

The power was switched over to the battery to ensure that module was wired correct, that was all fine.

 

Infineon RGB test

LastBoardAssembled.jpg

The last shield was fitted and the wires added. The LED did not turn on and the code froze on LED.begin(), this was identified as the I2C pins connecting the protoshield headers as being open circuit. They were re-soldered and the LED worked.

 

 

Testing the code

RGB Shield

The RGB shield was behaving strangely. It was not flashing the LED correctly, it would go on and then stay off for ages, blink for a very short time and then stay off again. It was setting the intensity to zero that was confusing it. So the solution was to flash between brightness 1 and a larger value.

Serial Bridge

So that the state model and bridge could be tested, the code was scattered with messages to send back to the computer. The state model was working correctly but the weather returned was gibberish.

SoftwareTest.png

The SerialParse script was installed to send the request to the Linino. The weather-daemon was stopped and ran manually.

This returned the error.

 

ERR,[Errno 2] No such file or directory: '/etc/WeatherAPI.conf',3,10.00





 

The missing file was copied on and a new error appeared

OK!,Cloudy,3,26.00
Traceback (most recent call last):
  File "/mnt/sda1/Python/GetWeather.py", line 217, in <module>
    sys.exit(main())
  File "/mnt/sda1/Python/GetWeather.py", line 200, in main
    ser.write(w)
  File "/usr/lib/python2.7/site-packages/serial/serialposix.py", line 363, in write
    raise TypeError('expected str, got %s' % type(data))
TypeError: expected str, got <type 'unicode'>





 

This showed that the weather was being read correctly but the script was failing to send it back to bridge.

Googling showed that this was an encoding issue pyserial ser.write('string') TypeError in OS X | Python | Python

 

The change was made to the code and it correctly returned the weather to the Arduino.

 

        w = getWeather(l['humid'], l['temp'])
        print (w)              # Write to Console, for testing
        ser.write(w.encode('utf-8'))





 

The main code was still erroring, seemingly returning junk back to the Arduino. However, when it was left for a period, subsequent reads did successfully return the weather. This was repeatable.

 

A simple flush command was written to ensure that the serial buffer was cleared of any booting garbage before requesting the weather.

 

void CONTROLLER::flushserial() {
    while (_serial->available()) {
     int inByte = _serial->read();
   }
}





 

This did not help with the problem so a simple retry mechanism was added to the code.

GoodResults.png

That approach worked.

 

The code is not perfect but it's enough for a demo to be recorded.

 

I'm speculating that the handshaking line is going high too soon as it's fired off by a different process to the weather-daemon. Perhaps a resolution would be to toggle that GPIO line in the Python code instead.

 

Next: Enchanted Objects Design Challenge - And they all lived happily ever after

Planning and Research

The project was planned by creating a calendar of the 15 weeks in a spread sheet then mapping the high level tasks to the weeks. Two weeks were left empty to allow for issues and overruns. Critical path items such as the house were ordered early on and potentially long lead time items such as the battery were ordered as soon as possible.

Plan

I knew that I would be out of town for a couple of weeks during the project so I effectively did twice the work in the preceding weeks so that I could have something to show. Many of the posts were drafted well ahead of time and photos or videos were added when they became available, the topics were re-ordered as necessary and some topics dropped or added. The story lines were often written on the way to work in the mornings.

 

I was not familiar with the Arduino Yún and some of the electronics so lots of research was done into these during my commute from work or during lunch times.

 

Nearing the end of the project, roughly around the start of June the remaining tasks were drawn up into a "snagging list" each being a single low level item such as "paint frame", "C++ code for blinking LED" etc. This meant that the list of things to do grew quite rapidly but because each was smaller and more focused they also got completed quickly. It also allowed "non-critical" items to be discarded.

 

The last week was reserved for commissioning but unfortunately some software items over ran and had to be completed that week too.

 

The Build Process

 

The process of building was to strip down the old weather house to analyse how the new mechanism could be added. After removing the old mechanism the house was fixed back together. The roof was made so that it could be lifted on and off. The new framework was intentionally made to be stand-alone, this allowed changes to be made without risking filling the house full of holes. It also allowed testing to be done without risking damaging the house. Where possible the new parts added were from the kits provided. The electronics and coding was done in a modular fashion with each component being constructed and fine tuned before incorporating into the over all design.

 

Next: Enchanted Objects Design Challenge - Testing

crjeder

Finalisation

Posted by crjeder Jun 24, 2015

Time is up! And I am not done yet. So I have to pack my stuff and present what I have achieved in the past 16 weeks.

 

Smart Key Hooks

 

What are smart key hooks? Or what are key hooks anyway?

Basically they are a place to hang your keys like this:

P5052643.JPG

But for me it is a little more. By looking at it I know who's at home and who not and it is used to exchange important messages between family members:

DSC_9100.jpg

(The mess is just utensils you want to reach from the doorstep.)

As is it works perfectly, is accepted by the users, has a intuitive user interface and is highly robust to operating errors by the user. Why does it need to be enchanted then? For integration into a SmartHome system and to make it's functions available online. For the challenge I'v decided to concentrate on on the later.

 

Planed Features

In Smart Key Hooks - Prelude I proposed the following enchantments:

  1. No user interaction necessary besides hanging the keys
  2. RGB-LEDs to display status of the absent persons (i. E. "will come back soon", "away until next day", "at work" ...)
  3. RESTful / IFTTT / Tasker (android) interface

The first feature is needed for user acceptance where the others really add functionality. 3) Provides local, physical functionality to the network and 2) adds information from the "Cloud" back to the physical interface. These are very high-level descriptions of the enchantments which, of course had to be concretised during the challenge.

 

Optional Features

Since I had no clue how long It could me take to implement the basic features or if I can implement them at all I specified a part of the functionality I would like to have as optional, hoping that everything runs smooth and I will be able to implement them as well.

  1. leaving speech messages which get played when the person respective the key returns
  2. Detection of a specific key ring independent of the hook it was hanged on
  3. Placing "ToDo" lists (on paper) on the board and sending "accepted" messages to listeners when it was removed

Item 1) is a huge enchantment which does not only add a lot of hardware (microphone, speaker, button, memory,...) but also the infrastructure for handling audio and adding a new interface, etc. In 3) I would integrate the second function which the physical hooks serve into the smart version. Detecting the changes on the messages and link push notifications to them. Item 2) was optional because I did not know if there is a feasible solution for identifying the individual key rings. The presence of any key ring could always be detected by a simple switch leaving it to the user to select the correct hook.

 

Achievements

 

While testing various methods to detect and identify key rings which are placed on a hook (Identifying Keys) I found one solution which satisfies the optional feature 2).

P5052642.JPG

By using 1-Wire EEPROM or ID devices inside a key tag I am able to identify individual key tags and thus key rings regardless on which hook they were placed as. In theory (but I haven't tested) this should work even when more than one key tag hangs on each hook since 1-Wire is a bus system. This is necessary for the clean and unchanged user interface of the Smart Key Hooks.

For the status LEDs I identified two options: use the provided Infineon RGB Shield and time division multiplex the output to multiple LEDs (preferred) or to use WS2812B LEDs on the SAMA5D4. In Using the RGB LED Lighting Shield on SAMA5D4 Xplained I found out that Linux does not support 10-bit I2C addresses and therefore abandoned this option as to time intensive.

ws28.jpg

Then I turned my attention to the second option which turned out to be a learning experience and not less time consuming. Since there was no library available which allowed interfacing with the WS2812 form Linux or the SAMA5D4 I had to find a solution: using PWM hardware to bit bang the required signal (Generating a Mysterious Signal, Use WS2812B on the SAMA5D4 Xplained and More Datasheet Studying). The code compiles but segfaults when I run it on the board. Unfortunately there is no time left to debug it.

The tasker interface was presented in Smart Key Hooks Client. By replacing the client libraries it should be relatively easy to interface to any HomeAutomation system. Combined with home automation Smart Key Hooks would unfold their full power. Possible application would be to check if doors (e. g. the shed door) are locked when the key is returned or if all windows are closed when the last person leaves. That was my idea when I proposed Smart Key Hooks as my entry in the design completion.


To Help the jury to rate this project I will summarize the all achievements:

Proposed Features:

 

FeatureImplemented?

No user interaction necessary besides hanging the keys

RGB-LEDs to display status

RESTful / IFTTT / Tasker (android) interface

Optional Features:

 

FeatureImplemented?
Leaving speech messages which get played when the person respective the key returns

Detection of a specific key ring independent of the hook it was hanged on

Detecting "ToDo" lists (on paper) on the board

Bonus:

 

AchievementImplemented?
WS2812B using PWM hardware
explanation how to use advanced PWM features on SAMA5D4
101 on logic analyser and debugging hardware
sending encrypted push notifications with pushbullet (or any other push service)
explained basics of 1-wire communication
experiments with "das U-Boot" on SAMA5D4
changing the Infineon RGB Shields firmware to accept 7-bit I2C addresses
identified signal lines which I could used as GPIO

 

Assessment

 

In Enchanted Objects Design Challenge - Detailed Information element14 asked to give an assessment of the enchanted object which I will give in the following paragraph.

 

Durability

It is hard to imagine that normal use could destroy the Smart Key Hooks. Wear-out is not an issue here since no moving parts implement any of the enchantments. The most vulnerable part are the key tags. The prototypes easily can break or lose contact. But they can be easily made more resilient by a steel case and embedding the PCB in resin. A production key tag could look like this:

example.JPG

Since contacts of the 1-Wire bus are exposed (hook and back plane) they are exposed to electrostatic discharge (ESD). The devices I used are all protected to 8 kV (IEC 1000-4-2 Level 4) which is enough under normal circumstances. If you have a nylon carpet then you should think about extra protection (for up to 27 kV).

Therefore I can not see any parts which should need to be replaced due to failure for a very long time.


Cost

Cost for the whole solution is quite moderate:

PartApproximate Cost in € (per key tag)
Silicon ID (for key tag)1,00
PCB, Passive Components, Resin0,50
Key Tag Case1,00

 

That's 2,50 € per key ring where 5 to 10 should be enough for a normal household. Cost for the key rings are between 12,50 and 25 €

The real power of the SAMA5D4 Xpalined is not used therefore the cost for the central component can be significantly reduced by using e. g. the Raspberry PI model B which at the moment sells at around 30 €. Further reduction and WIFI connection (which most people prefer over wired LAN) can be archived by using a ESP8266 module which sell at ebay for around 3 €

 

PartApproximate Cost in €

MCU / Computer / Base Board

(Raspberry PI B)

30,00
WS2812B or similar LEDs 10 pcs.5,00
Passive Components1,00

The system cost is 48,50 to 61 €. Using a ESP8266 it comes down to 21,50 to 34,00 € which is really not bad for a smart home component.

Convenience

The usage is almost exactly as a with the un-enchanted version. Simply hang the key ring on a hook. Only difference is that you have to hang the hole in key tag (like in the photo above). Tasker is not really easy to use but once configured it does its job perfectly. Over all Smart Key Hooks are an easy to use enchanted object.

 

Accuracy

The presence of key tags is tracked with a selectable time resolution - the interval in which the 1-Wire bus is probed for new nodes can be configured. Smart Key Hooks track the presence of keys, not people. While the a person and his / her key ring normally would correlate this is the window of opportunity for imposture. Like in the very good video Andy Clark (Workshopshed) posted as a comment to one of my blog posts. The while solution is absolutely accurate in detecting the presence of key tags it can be arbitrary wrong in detecting the presence of persons.

 

Security

Network security basics as hardening (uninstalling unwanted services, secure configuration for the rest, changing default passwords, etc) and placing a firewall in front of the networked Smart Key Hooks is common practice so that I did not blog about it. A very powerful security measure is reducing the attack surface. This is archived by the fact that the server does not offer anything to the Internet but instead subscribes to a Pushbullet channel. Therefore the firewall allows only connections to (and answers from) the Pushbullet server(s). A hacker would have to attack Pushbullet or inject packages into the communication in order to do any harm to the Smart Key Hooks server. Packet injection is made almost impossible by using https.

An other facet of security is privacy. I do not want Pushbullet or anybody who could listen to the data transfers to learn anything about me and my families presence in the house. To archive this the messages sent are AES encrypted. For a small number of clients a pre shared key is a feasible and easy to implement option. The secure channel to transfer the key for the first time is simply to enter it on the mobile device. This is inconvenient but has to be done only once for every device. Further key changes can be sent as a message to the clients (which, of course, is encrypted by the old key). This is not perfect forward secrecy (see https://en.wikipedia.org/wiki/Forward_secrecy) which means that when one key is compromised all future keys are also known to the enemy, but is IMHO good enough. If you suspect that a key is compromised you always can manually set a new key on every client an be safe again. This is feasible only if you have a small amount of clients to which you have a secure channel (i. e. physical access).

Security is covered in more detail in Smart Key Hooks – The Design.

Use of the Project's Results

 

As is I would use Smart Key Hooks (after ironing out the last problems) for the following:

  • Check if children meet their "curfew"
  • Send reminders based on "leafing" or "returning" conditions (e. g. "don't forget the milk)
  • Send push messages to all persons at home (like "Can anyone please check if I've turned of the electric iron")

 

In conjunction with smart home / home automation I'd have a lot of use cases:

  • Alerting family members when the leave that not all windows / doors are closed
  • Remind them to take a umbrella if it is going to rain within the next hours
  • Check if shed / garage is locked when they enter the house
  • Turn off outdoor lightning when they enter the house
  • Turn on / off security systems based on presence
  • Automatically operate blinds when nobody is at home
  • ...

Smart Key Hooks will be the first smart home piece in my home which definitely will get smarter over the next years.

 

The main project results for me are however the knowledge I gained and the nice people I've met. That alone was worth the effort and is the most valuable take away.

Thanks

 

Finally allow me to thank to element14 and the sponsors for hosting the competition. It has been a pleasure to take part. And thanks to all those who helped me or where just fun to talk to although some of them also compete in the same challenge (in no particular order):

Andy Clark (Workshopshed), clem57, shabaz, mcb1, jancumps, DAB, balearicdynamics

I hope to see you all again

coolbox

Enchanted Window - Video

Posted by coolbox Jun 24, 2015

Here I want share Video about my project:

 

Linux support for 10-bit Slave Addressing

The I2C protocol knows about two kinds of device addresses: normal 7 bit addresses, and an extended set of 10 bit addresses. The sets of addresses
do not intersect: the 7 bit address 0x10 is not the same as the 10 bitaddress 0x10 (though a single device could respond to both of them).
I2C messages to and from 10-bit address devices have a different format.See the I2C specification for the details.
The current 10 bit address support is minimal. It should work, however you can expect some problems along the way:

  • Not all bus drivers support 10-bit addresses. Some don't because the  hardware doesn't support them (SMBus doesn't require 10-bit address  support for example), some don't because nobody bothered adding the code (or it's there but not working properly.) Software implementation  (i2c-algo-bit) is known to work.
  • Some optional features do not support 10-bit addresses. This is the  case of automatic detection and instantiation of devices by their drivers, for example.
  • Many user-space packages (for example i2c-tools) lack support for  10-bit addresses.

 

Note that 10-bit address devices are still pretty rare, so the limitationslisted above could stay for a long time, maybe even forever if nobody
needs them to be fixed.

(linux kernel Documentation/i2c/ten-bit-addresses)

 

That's bad news for me. But there might be a solution.

 

Firmware Modification

Since Infineon provides the source of the firmware of the RGB Shield I can try to change it to use 7-bit addresses.

My first attemt would be to simply modify the address to something 7-bit compatible. Steps to do are:

  1. download Dave
  2. download the firmware source code
  3. import source code in Dave as a project
  4. make changes
  5. compile
  6. program into flash

The steps 2, 3, 5 and 6 are covered in a tutorial by infineon and step 4 was suprisingly easy:

In the App view select the I2C003 APP:

APP.PNG

Then right-click on it and select UIEditor. In UIEditor make the necessary changes:

i2c.PNG

Then compile and download to the board.

Enable I2C

 

The I2C-1 to which the RGB Shield is connected to is not enabled by default. This is done by modifying the device tree file (dts), compile it into a binary (dtb) and save that file to the flash

Device Tree

current dts: https://github.com/linux4sam/linux-at91/blob/master/arch/arm/boot/dts/at91-sama5d4_xplained.dts

I2C-1 is missing

i2c1: i2c@f8018000 {
  status = "okay";
};

and in the included "sama5d4.dtsi"

i2c1: i2c@f8018000 {
  compatible = "atmel,at91sam9x5-i2c";
  reg = <0xf8018000 0x4000>;
  interrupts = <32 IRQ_TYPE_LEVEL_HIGH 6>;
  dmas = <&dma1
  (AT91_XDMAC_DT_MEM_IF(0) | AT91_XDMAC_DT_PER_IF(1)
  | AT91_XDMAC_DT_PERID(2))>,
        <&dma1
  (AT91_XDMAC_DT_MEM_IF(0) | AT91_XDMAC_DT_PER_IF(1)
  | AT91_XDMAC_DT_PERID(3))>;
  dma-names = "tx", "rx";
  pinctrl-names = "default";
  pinctrl-0 = <&pinctrl_i2c0>;
  #address-cells = <1>;
  #size-cells = <0>;
  clocks = <&twi0_clk>;
  status = "disabled";
  };

i2c1 {
  pinctrl_i2c0: i2c1-0 {
  atmel,pins =
  <AT91_PIOE 29 AT91_PERIPH_E AT91_PINCTRL_NONE
  AT91_PIOE 30 AT91_PERIPH_E AT91_PINCTRL_NONE>;
  };
};

Compile device tree

make ARCH=arm dtbs




Should make all .dtb files

make ARCH=arm at91-sama5d4_xplained.dtb




would be enough.

 

Replacing dtb

Replace the current dtb with new one using SAM-BA as described at Linux4SAM

  1. Modify the Address to 0x180000
  2. Choose Send File Name open file dialog and select the dtb binary file and to program the binary to the NandFlash.
  3. Click Send File button to program the binary to the NandFlash in address 0x180000.

samba_send_file_nand.png

Now the Shield can be used on the Xplained board

coolbox

Enchanted Windows

Posted by coolbox Jun 24, 2015

Hi,

Here,I want to post some update about may Enchanted windows project. I was able to control window using arduino yun’s wi-fi.I was not sure about a actual window so I have tried with thermo Cole model.

 

Here I have used 150 RPM DC geared motor with Infineon DC motor control shield.pic connections are:

Digital 2 in yun -> IN1 in motor shield

Digital 3 in yun -> IN2 in motor shield

INH1 and INH2 were connected to 5V in yun. Also I have shorted GND of Infineon shield and yun as power for both board are different. Yun was powered by 5V supply and motor shield was powered by 12V supply same as motor supply.

 

Yun Software:

I have modified Bridge example as per my requirement. Using REST APIs I was able to control motor. Code is as below:

 

 


 

#include <Bridge.h>

#include <YunServer.h>

#include <YunClient.h>

 

// Listen to the default port 5555, the Yún webserver

// will forward there all the HTTP requests you send

 

YunServer server;

boolean JustTwoSeconds;

 

void setup()

{

  // Bridge startup

  pinMode(13, OUTPUT);

  digitalWrite(13, LOW);

  Bridge.begin();

  digitalWrite(13, HIGH);

 

  // Listen for incoming connection only from localhost

  // (no one from the external network could connect)

  server.listenOnLocalhost();

  server.begin();

 

  // For Driving Motor We need this two pins.

  pinMode( 2, OUTPUT ); //IN_1

  pinMode( 3, OUTPUT ); //IN_2

 

 

}

 

void loop()

{

  // Get clients coming from server

  YunClient client = server.accept();

 

  // There is a new client?

  if (client)

  {

    // Process request

    process(client);

 

    // Close connection and free resources.

    client.stop();

  }

 

  delay(50); // Poll every 50ms

 

  if( JustTwoSeconds )

  {

    JustTwoSeconds = 0;

    delay(4900); // 1.5 sec

    digitalWrite( 2, LOW ); //IN_1

    digitalWrite( 3, LOW ); //IN_2   

  }

}

 

 

 

void process(YunClient client) {

  // read the command

  String command = client.readStringUntil('/');

 

  // is "digital" command?

  if (command == "digital") {

    digitalCommand(client);

  }

 

  // is "analog" command?

  if (command == "analog") {

    analogCommand(client);

  }

 

  // is "mode" command?

  if (command == "mode") {

    modeCommand(client);

  }

}

 

 

 

 

void digitalCommand(YunClient client)

{

  int pin, value;

 

     // Read pin number

     pin = client.parseInt();

 

    

   if( pin == 1 )

   {

         digitalWrite( 2, HIGH ); //IN_1

         digitalWrite( 3, LOW ); //IN_2

        

         JustTwoSeconds = 1;

   }

   else if( pin == 2 )

   {

         digitalWrite( 2, LOW ); //IN_1

         digitalWrite( 3, HIGH ); //IN_2

        

         JustTwoSeconds = 1;

   }

   else if( pin == 3 )

   {

         digitalWrite( 2, LOW ); //IN_1

         digitalWrite( 3, LOW ); //IN_2

   }

   else

   {

       ;

   }

}

 

 

 

 

 

 

 

HTML File:

For EASY interface I have created simple HTML file which you can open in any device. Code is as follow:

 

<body bgcolor = "yellow">

 

<a href = "http://192.168.240.1/arduino/digital/1 ">

<h3><center> OPEN WINDOW </center></h3>

</a>

 

</br>

</br>

 

<a href = "http://192.168.240.1/arduino/digital/2 ">

<h3><center> CLOSE WINDOW </center></h3>

</a>

 

</br>

</br>

 

<a href = "http://192.168.240.1/arduino/digital/3 ">

<h3><center> STOP </center></h3>

</a>

 

</body>

 

I will publish a video soon.

Putting on the roof

One of the big physical jobs left for Matilda and Hans was putting the roof back on. They realised that they could not do the job by themselves so they wandered down the Adam and Eve Inn to look for volunteers. It turned out that everyone wanted to help so the barkeeper closed the pub and he and the snake came along too.

 

The helpers were of various use, the Dwarves spent most of the time arguing and Farmer Hogg kept saying things like "I'd not have started from here". However the barkeeper and snake were very useful. Whenever the barkeeper wanted the snake to do something he'd command "Python Start" and whenever a job was done he'd say "Python Stop". The roof was quickly done and Hans and Matilda posed for a photo.

CottageRoofIsOn.jpg

They thanked everyone who in turn decided to go back to the inn to celebrate. Hans and Matilda had plenty to do so celebrating would have to wait.

 

Hans had forgotten

Hans realised he'd forgotten a critical step in the process. How to start and stop his Python script. He looked back over his notes and realised that he could use bits from the Handshaking code and from the Fail2Ban setup.

 

Init script

An initialisation script was created.

 

#!/bin/sh /etc/rc.common
# Initialise Python Listening on Serial Port

workdir=/mnt/sda1/Python
START=8
STOP=14

start() {
    cd $workdir
    /usr/bin/python /mnt/sda1/Python/GetWeather.py &
    echo "Weather Server started."
}

stop() {
    pid=`ps -ef | grep '[p]ython /mnt/sda1/Python/GetWeather.py' | awk '{ print $1 }'`
    echo $pid
    kill $pid
    sleep 2
    echo "Weather Server killed."
}





 

Changes to Python Code

The python code needed minor changes so that it would respond to the shutdown request

# Handle exit and kill from OS
def set_exit_handler(func):
    signal.signal(signal.SIGTERM, func)
def on_exit(sig, func=None):
    print "exit handler triggered"
    sys.exit(1)

# Run program
if __name__ == '__main__':
    set_exit_handler(on_exit)
    sys.exit(main())





 

Testing

The init script was tested with

/etc/init.d/weather-daemon start





and

ps





to check it was running

 

Then shutdown using

/etc/init.d/weather-daemon stop





 

Finally, it was installed using

/etc/init.d/weather-daemon enable




 

Next: Enchanted Objects Design Challenge - Planning and Building

 

References

http://www.pietervanos.net/knowledge/start-python-script-from-init-d/

https://wolfpaulus.com/jounal/software/pythonlauncher/

http://wiki.openwrt.org/doc/techref/initscripts

"Now is the time to add some magic & mystic back into the world of everyday objects"

 

Yup, this fits the brief.... Motorcycle + Toy Horse = MOTORHORSE

 

The Cottage

FinishedHouseFront.jpg

The cottage has been extended at the back to house the electronics and below to hide the mechanism. The front window has a new frame to show off the LED temperature indicator.

Infomatic.png

 

 

Mechanics

The mechanism is a double ended Watt's linkage which gives an approximately linear movement for the figures. This is connected by a sprung stainless steel wire to the micro servo. Diametrically polarised magnets ensure that the characters are always pointing in the right direction.

MechanismB.jpg

Mechanics: https://github.com/Workshopshed/EnchantedObjects/tree/master/Mechanics

 

Electronics

The electronics combines simple circuits and modules.

System Overview

The power control circuit turns on and off the power to the Servo, RGB Shield and DHT22 sensor. The knock knock sensor is left powered so that it can listen for wake up interrupts. The top panel is simple buttons attached to input pins and fibre optics to extend the Arduino's LEDs to the top of the cottage.

 

Electronics: https://github.com/Workshopshed/EnchantedObjects/tree/master/Electronics

 

Code

ClassDiagram.png

When the board wakes up it checks to see if the sleep counter has reached zero or if knock has been detected and if so It starts up. Otherwise it goes back to sleep for another 4seconds.

 

In start up it firstly powers on the peripherals and WiFi module. It then sets the LED colour to be that of the last known temperature. Following this it sets the LED to fast flash to indicate it's going to get the weather. It then gets the local temperature and humidity. Once the WiFi module has booted it will request the weather.

 

On the Linino side the system sends a handshake signal to indicate that it is ready and starts up the Python script to listen to the serial port. The Python script makes an API call to the Yahoo weather service, if that errors or times out it will make a "guess" at the weather based on the local conditions provided by the sensor. The data is parsed and send back to the ATmega as a simple string.

 

Once the weather has been received the system shuts down the WiFi module. It can then update the position and new LED colour which is then solid and starts a timer for 1 minute. Once that timer has expired it will shut down the peripherals and go back to sleep.

 

Code: https://github.com/Workshopshed/EnchantedObjects/tree/master/Code

Code examples: https://github.com/Workshopshed/EnchantedObjects/tree/master/Code/Examples

 

Next: Enchanted Objects Design Challenge - Python Start, Python Stop

The cottage was disassembled so that the base could be painted matt black. This is an old magician's trick to draw the eye away from the base and hidden mechanism underneath.

Painting.jpg

The top panel electronics were also put together with another bit of stripboard, a couple of buttons and a 3 way connector.

2015-06-21 20.40.45.jpg

This was then glued to the top panel using some blobs of Sugru, of course it's best if you can avoid gluing your electronics into the product as it makes the whole thing harder to service. Given that it's the final week of the project, it's not appropriate to redo the whole of the top panel. Retrospectively it would be better to design some supports and slots into the top panel so that the board could simply be pushed into place.

2015-06-21 21.14.37.jpg

As with pretty much all of the connectors, this one had to be bent at right angles so that there was space for the connector to be fitted. For future projects perhaps some preformed right angle connectors would be a good idea.

 

The top panel was added to the cottage and the buttons were tested.

IMAG1546[1].jpg

The newly printed magnet carriers were fitted, and the magnet holders glued on top ensuring the correct orientation.

MagnetCarriers2 (2).jpgMagnetHolders.jpg

Next: Enchanted Objects Design Challenge - System Overview

Cost Analysis

As well as the components kindly provided by Element14, Atmel and Infineon there were several additional components purchased for this project. These were bought as the project progressed or were already in the spares drawer. Where the original supplier was not known the costs were estimated based on current prices. Where more components were purchased than needed the costs were pro-rated. I've tried to include absolutely everything but it is possible that something was missed.

 

Parts provided

An attempt was made to use as many of the provided parts as possible. Although these parts did not cost me, they are incorporated into the cost estimates to give a more realistic reflection of the cost of the project. Rather than incorporating the entire cost for the workshop kit the individual parts used were estimated from the Farnell site. The exact switches could not be found so an equivalent was used.

PartSupplierCost
Ardino YunElement14£49.03
Infineon RGB boardElement14£21.04
Arduino ProtoshieldElement14£3.55
IRF520 Power MosFetElement14£0.61
220R resistorElement14£0.01
2* 330K resistorElement14£0.01
2 * 10k resistorElement14£0.01
1n4007 diodeElement14£0.03
2 * Tactile SwitchElement14£0.18

 

Parts purchased

These were specifically purchased for the project, postage is included in the cost and where multiple items were purchased the cost was pro-rated between the items. For the 3D printed parts the cost was estimated by uploading the items to Shapeways and using their material value to provide an estimate.

PartSupplierCost
Houseuksalesmaster on Ebay£17.38
SD CardWHSmiths£7.00
Mini Servobgood2010 on Ebay£2.19
RGB LEDOomlout£1.50
LM393 ComparatorD&M Components on Ebay£0.50
1M resistorD&M Components on Ebay£0.10
2x 5.1v ZennerD&M Components on Ebay£0.20
Piezo sensorElectronic Bits and Bobs on Ebay£0.40
WoodHobbyCraft£1.93
Stacking headersAdaFruit via CPC£1.59
SignSign-O-Matic£6.70
PaintB&Q tester pot£0.25
Lithium Polymer Battery - 2000mAhCool Components£13.69
Adafruit PowerBoost 500AdaFruit via Cool Components£13.00
Nuts and Threaded RodModel Fixing£4.28
Fibre OpticsFibreopticlightingsolutions on Ebay£0.99
Mechanical componentsWorkshopshed£1.96

 

Parts that were already available

These were found around in the workshop, either from abandoned projects, multipack purchases or salvaged. The solder was estimated using the method found on http://electronics.stackexchange.com/questions/30671/estimating-assembly-cost

PartSupplierCost
DHT22PENGHUIMEI on Ebay£3.74 (2013 cost)
Stripboard / Tri-pad boardRadioShack£0.50
MagnetsFirst4Magnets£3.74
Stainless steel wireHalfords£0.06
Self-tapping ScrewsUnknown£0.70
Sugru x 2Sugru£2.00
Bondloc Structural AdhesiveMaplin£0.50
Heat Shrink TubingProto-Pic£0.04
Connector housingsProto-Pic£0.32
Connector pinsProto-Pic£1.58
SolderUnknown£0.48

 

Totals

Provided parts: £74.66

Additional Components: £73.65

Things I had: £13.65

Grand total: £161.96

 

Reducing costs

The Enchanted Cottage is effectively a prototype so there's plenty of decision that were made along the way. This has resulted in additional materials use and less than optimal design. This means that there is plenty of scope for cost savings.

 

The key tasks to reduce cost are:

 

  • Reduce component count
  • Replace/Remove expensive components
  • Simplify design

 

Also many of the components were bought in small batches so buying components in larger batches the costs would be reduced and multiple different postage costs could be eliminated.

 

Reduce Component Count

 

The Arduino Yún is a good board but its focus is to be a generic prototyping board rather than an embedded solution. Key examples of this are that the ATMega32U4 microcontroller is capable of running at 3.3v same as the Wifi module but the Arduino team chose to run it at 5v to give it maximum compatibility. This means that the board contains lots of level shifters on the board to interface between the two sides. If a custom board was made then this could run at 3.3v and eliminate these level shifters.

 

Also having the 3 boards stacked together with separate power board means that headers, connectors, spacers, struts are used for the board. So again merging all of these onto a single board would bring the costs down as many of these could be eliminated.

 

Expensive Components

 

The Arduino Yún has already been mentioned, that is one of the highest cost items. A "Dragino HE" WiFi module is approx £15 and the ATMega32U4ATMega32U4 is £2.34 when bought in quantities of 10 or above, a few basic components such as capacitors and a crystal are needed.

 

The Infineon RGB LED driver board is again and expensive component, it was used for the project as it provided a quick an easy approach to providing the output. However it is really over specified for the job and is being run right on the lowest level of it's capability. The approach here would be to take swap this out with a driver using discrete MOSFets to power each of the channels for the LED such as the INFINEON  BSS131INFINEON  BSS131 as that's quite capable of being driven by the lower 3.3 supply. To standardise the bill of materials these could also be used to control the power to the servo and temperature sensor. Again the same MOSFet could be used to turn on and off the power to the WiFi module

 

The sign for the back of the cottage was made of plastic and most of it's cost was delivery charges rather than manufacturing costs. If the house was being produced in bulk then this could be swapped out with a sticker rather than a sign which is substantially cheaper.

 

The house itself is quite a large expense so this could be replaced with a hand made version, the wood could also be bought in larger sheets for greater savings.

 

The current power design incorporates a boost regulator to generate 5v from the 3.7v battery. This is then reduced back to 3.3v by two different regulators, one on the Infineon board and one on the Yún. By swapping to a 3.3v design this could be simplified to be a single regulator that would provide 3.3v. Assuming further savings in power can be achieved then the battery capacity could be reduced.

 

The magnets were surplus from a previous project so these could be swapped with cheaper ones for the same results.

 

In general SMD components are cheaper than through hole components and take up less space on the PCB, so this is an area where plenty of savings could be made.

 

Simplify design

 

One of the key improvements of swapping to a single PCB solution would be to remove the need for many connectors and small boards. For example by mounting the LED directly on the board the need for a daughter board, connectors and wires could be eliminated. Similarly by incorporating the power supply parts onto the main PCB further connectors and headers would be removed. The stacking headers needed for the Arduino shield approach would also be eliminated.

As mentioned above one method to reduce costs would be to scratch built the weather house, this would also allow the design to be simplified reducing the wood used and number of components. Rather than having a separate front and back these could be integrated together simplifying the design. Rather than hand cutting the parts these could be laser cut so that there was a single sheet with each of the parts that could be popped out. This would reduce assembly costs. Equally these could be pre-printed as per the original house saving on painting cost and

The 3D printer parts are currently screwed together, if the technique using clips could be made to work, or if these screws were swapped with plastic rivets then the assembly would be simpler and the time taken the make the parts could be easier.

The design incorporates an SDCard to hold some of the code, if the Linino side of the design was optimised then this card could be eliminated and hence component parts and set-up steps for that module would be reduced.

The Knock Knock sensor incorporates a variable resistor to "trim" the level detection. If a series of detectors was checked it might be possible to replace this with a simpler resistor network with a fixed level.

 

Estimated cost savings

 

Based on rough estimates and the changes above to the project components it should be possible to bring the cost down to approx £60, a saving of over £100 on the original bill of materials. No attempt has been made to calculate manufacturing costs but the above suggestions should bring those costs down too.

 

Next: Enchanted Objects Design Challenge - Painting, top panel and new magnet carriers

The Enchanted Cottage build has been a multi faceted project with electronics, micro-controllers, embedded Linux, woodwork, 3D printing and general assembly challenges. To give you a better idea about how I worked on the project I've made a list of all the tools I used.

Tools and equipment

There was a wide variety of tools used for the project. Nothing was bought specifically for the project but a couple of things were made. The Robox 3D printer came in handy as it allowed parts such as the top panel buttons and fibre housing to be made that would otherwise be difficult to make. It also allowed the mechanism to be lightweight.

 

Hand Tools

Pliers, Wire cutters, Wire Strippers, Screw Drivers (various), Coping Saw + table, retractable knife, steel ruler

 

Power tools

Robox 3D Printer, Pillar drill, mini drill + cutting disks + mini milling cutter

 

Electronics / Test Equipment

Multimeter, PC, Laptop, Wifi Router, Tenma Digital Soldering iron, Breadboard from Arduino Workshop kit + wires, LEDs etc.

 

Home Made Tools

A couple of tools were made during the challenge, the first a saw table to help with sawing cut outs in the plywood and the second a simple servo test rig to try out some of the ideas and to check that the servo had sufficient power.

FretSawTableFretSawTable (2).jpgServoTestJig.jpg

Software

The Arduino was programmed using the standard Arduino IDE but that was upgraded to the latest version at the start of the project. The code was uploaded using the USB cable rather than Wifi.

The Python coding was done using PyCharm, an IDE from the people who make Resharper. This was a great tool for learning as it suggested errors and corrections to the code as well as having the usual intellisense expected from a modern IDE.

To help with the Linux side, WinSCP and Putty were used to copy files and connect to SSH.

The schematics were created using Fritzing and Eagle 7.2 (free edition)

The 3D models were created using OpenSCAD.

Some of the graphics were created using Visio and Paintbrush was used to trim the photos to size.

The video was edited using Microsoft Movie Maker.

 

Photography

The photographs were mostly taken with a HTC smart phone, a couple of early ones were taken with an old Olympus C-170, and the video was taken using a Flip HD mini video camera. Where possible a tripod was used.

 

Safety

There were not any particular high risk activities for this challenge. When using power tools appropriate safety gear such as goggles were used, work was secured in a vice or clamp for cutting/drilling. For soldering a simple heat resistant mat was used to protect the bench from damage. Some adhesives were used so these were done in a well ventilated space and left to set out of reach of the family. There was a minor accident with some super glue when the tube was opened the contents squirted everywhere. Soapy water and gentle rocking was applied and the bonded skin was separated. The LiPo battery has been placed in a metal battery box and care has been taken not to short out the connectors. The circuits were tested on breadboard before deploying to the stripboard/protoboard and connections were double checked with a multimeter before powering up.

 

Next: Enchanted Objects Design Challenge - How much!?

20150622

 

 

It's the last week of the Enchanted Objects design challenge. The Enchanted Player plays, the blogs are blogged.


I'm closing with this video. Thank You All!


 

 

What's That Enchanted Player

 

A Perpetuum Ebner turntable from 1958 is controlled by modern technology. Microcontrollers measure the table speed and control the motor.

The audio is sampled and run through Fast Fourier Transform to turn it into chunks of the audio spectrum.

A light organ is hidden inside the belly of the turntable. It uses the spectrum info to flash Bass, Mids and Highs LEDs.

It's motorized, and only appears when there's music playing.

The audio spectrum is published to the cloud, where other applications can tap into it.

Uses Arduino UNO, Arduino Yún, Infineon Motor Shield, Arduino Proto Board

 

tabledrawing.jpg

 

The remote light organ plugs into the cloud to receive the spectrum info published by the player.

Because it uses WiFi, it can operate wireless if we desire to do so. Audio is again split in H/M/B.

This time the LEDs are driven by the RGB shield.

Uses extra Arduino Yún, Infineon RGB LED shield

 

sensorprinciple.jpg

 

The SAMA5D4 is plugged into my home network and also subscribes to the spectrum info. The Xplained Ultra board logs the received info to the console.

A great starting point to build a spectrum analyzer or a graphic spectrum display if screen is added.

All code and libraries are in C, cross-built on a Windows platform.

Uses the SAMA5D4 Xplained Ultra, GNU Toolchan and the Eclipse Paho client libraries.

 

What Happened

 

I've turned a defect 1950's treasure into a working turntable - without making a single scratch or permanent change.

All content from the challenge is used. Both Infineon boards, the Yún, the SAMA5D4, the UNO and the Arduino protoboard.

The servo motor - that didn't make it into the final design, has been featured in two technical blogs.

For the speed measurement and motor steering I've made a custom PCB. I added a single transistor pre-amp - an excuse to show that a very simple electronics design can be valuable.

 

large_i.png

I've made detailed drawings of the design concepts. I've also tried to use graphics to better explain processes and to lighten up the posts.

Photos - plenty of them, including more than 20 oscilloscope captures.

 

schema_kicad.png

 

Videos, plenty of those too. My youtube stats say that I've published 9 videos. That doesn't include the smaller ones that are embedded in the posts but don't tell a story on their own.

40+ blog posts.

There was a very deep dive into the SAMA5D4, and how to develop for it in C. That has resulted into 8 additional side posts on working with this board and reviews.

I've told the History of the Perpetuum Ebner company until World War 1.

dual 1010

 

Going Public

 

All my code and design files are published in the blogs, and where I used someone else's work, I've linked to that.

I've made my plans and progress (sometimes regress) public - including failures, mishaps and flukes.

Whenever I worked with the support teams of the devices, I've shared my experience - and links to the support portal items - to my story.

 

 

perpetuum ebner musical 1

 

And I enjoyed all of this a lot - and I have learned so much on the road.

If you want to check how good the turntable actually sounds, check out the video at the top of this post.

The soundbites you hear at the start and end are directly taken from this project; no tricks - no filtering.

 

You'll hear Eddy Romy telling Swedish Stories (in Dutch ) from this childhood record (Monopole 719 - Belgium, 1971)

enchanted objects enchanted player

 

 

 

 

Table of Contents
Chapter 1: Fix the turntable
1: Perpetuum Ebner Musical 1
2: A Time to Kill and a Time to Heal
3: Preparation for Motor Drive
4: Motor control with Infineon Motor Shield and Arduino UNO
5: Turntable speed sample testbed with Arduino UNO
6: Turntable Speed Sensor design
7: Control Theory - End of Chapter 1
Chapter 2: First Enchantments
8: Digital Light Organ Enchantment
9: Autonomous Servo Lift
10: SMD Time - Solder the IR Speed Sensor PCB
11: Yelp - who can Help me to Compile and Run my First SAMA5D4 C Program
12: Son et Lumiere - End of Chapter 2
Chapter 3: Taming the Board
13: Breakthrough - Run my own C++ Program on the SAMA5D4
14: Digital Light Organ Input Buffer
15: SAMA5D4 Blinky
16: Scope Creep
17: Audio Sampling with 16-bit ADC ADS8343
18: Sending Files to SAMA5D4 over USB
19: Port my Light Organ from Arduino to SAMA5D4
20: Fast Fourier Transform on the SAMA5D4 - End of Chapter 3
Epilogue: Reaching for the Clouds
21: Right-Sizing my Plans
22: My Own C++ Buffered Sampler on the SAMA5D4
Interlude
23: Building In the Motorized Light Organ
24: Up to the Clouds with Yún
25: Publish or Perish
26: Turntable Finished
Stretch & Boni
Bonus 1a: Remote Light Organ with WiFI pt. 1
Bonus 1b: Remote Light Organ with WiFI pt. 2
Grande Finale: Paho MQTT Client on the SAMA5D4
Related blog
Vintage Turntable repair: Can I fix a Perpetuum Ebner from 1958
Review 1: Atmel SMART SAMA5D4 Xplained Ultra Unboxing and First Steps
Review 2: Atmel SMART SAMA5D4 Xplained Ultra - Building the Libraries from Source
Review 3: Digital Continuous Rotation (360°) Servo Part 1
Review 4: Digital Continuous Rotation (360°) Servo Part 2
Review 5: Atmel SMART SAMA5D4 Xplained Ultra - TCP/IP running
Review 6: Atmel SMART SAMA5D4 Xplained Ultra - LINUX Distro with SSH support
poem
Enchanted Objects: Let's work together to tame the ATMEL SMART SAMA5D4 Xplained Ultra kit
17 bis: Off South...
Review 7: Atmel SMART SAMA5D4 Xplained Ultra - C++ ADC Example on Linux
Review 8: Atmel SMART SAMA5D4 Xplained Ultra - Product Review
Review 9a: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 1
Review 9b: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 2
Review 10: Atmel SMART SAMA5D4 Xplained Ultra - New Content on AT91.com
1958 Turntable from the Black Forest - Summary of the Enchanted Player Story

 

 

Bye Bye

Even if the MagicHat is not sending any sensitive data out on the Internet, it's always important to make communication as secure as possible.

For this reason, I will implement HTTPS communication between the web browser and NodeJS running on Arduino Yun. Since the communication is now encrypted, we can use basic authentication (were password is just Base64 coded, but not encrypted)

To add HTTPS support, we need to:

 

Install OpenSSL

OpenSSL setup can be downloaded from here. Installation is plain vanilla

 

Create a self-signed certificate

To create a self-signed certificate, open a command prompt window and type the following commands

set OPENSSL_CONF=C:\Program Files (x86)\GnuWin32\share\openssl.cnf

This commands set the path for the OpenSSL configuration file

 

openssl req -x509 -newkey rsa:2048 -keyout c:\temp\key.pem -out c:\temp\cert.pem -days 365 -nodes







req: PKCS#10 certificate request and certificate generating utility.

-x509: this option outputs a self signed certificate instead of a certificate request. This is typically used to generate a test certificate or a self signed root CA.

-newkey arg this option creates a new certificate request and a new private key. The argument takes one of several forms. rsa:nbits, where nbits is the number of bits, generates an RSA key nbits in size.

-keyout filenamethis gives the filename to write the newly created private key to.

-out filename This specifies the output filename to write to or standard output by default.

-days nwhen the -x509 option is being used this specifies the number of days to certify the certificate for. The default is 30 days.

-nodesif this option is specified then if a private key is created it will not be encrypted. When this option is not added, NodeJS will ask for the private key's passphrase when the private key is used

 

Create a server that support HTTPS

The following code creates a server with HTTPS support

 

var options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

var server = https.createServer(options, app);
server.listen(3000, function(){
  console.log('We have started our server on port 3000');
});





 

Install NodeJS's basic authentication module

Since a  lot of the middleware was pulled out of the Express core in v4 and put into separate modules, the basic auth module needs to be explicitely installed

 

npm install basic-auth-connect

 

Implement basic authentication in node

 

var basicAuth = require('basic-auth-connect');

// NEW CODE BEGINS HERE

// replace 'user' and 'pass' with your username and password

app.use(basicAuth('user', 'pass'));
//NEWCODE ENDS HERE

app.use(express.static(__dirname));
app.use(express.static('.'));



Client side changes

The only change required on the client side Javascript is to changes the websocket URL from ws://<ipaddress> to wss://<ip address> to use Secure web sockets. if standard web sockets are used, web browsers will raise a security error because you are trying to use an unsafe connection

 


With  all these changes in place, we can now connect to the MagicHat web interface using HTTPS. Since the certificate is self-signed and not by a trusted certification authority, web browser will complain about that and will warn you about potential risks

22 - Certificate warning.png


By clicking on the"Continue to this website" link, you will be asked for username and password

 

22 - Authentication.png

Following lots of rude interruptions from the Wolf, Hans decided the Arduino Yún's security needed beefing up. After a bit of reading Hans realised that this could be a 16 week design challenge in it's own right.

 

Hans' plan of action for the lock down was as follows:

 

  • Users and passwords
  • Handle brute force attacks
  • Remove unused functions
  • Apply principle of least privilege

 

Passwords

Hans had already changed the default root password to something unique but realised if he was sending out lots of IOT devices it would make sense to have a mechanism where you could provide everyone of them with a unique default password. This could be printed on a label on the bottom of the device so if it was reset to defaults it would take this rather than something that people could google for.

 

It's possible to check the user accounts by looking at the passwords file.

 

cat /etc/passwd










 

Installed by default on the Yún are the following:

root:x:0:0:root:/root:/bin/ash
daemon:*:1:1:daemon:/var:/bin/false
ftp:*:55:55:ftp:/home/ftp:/bin/false
network:*:101:101:network:/var:/bin/false
nobody:*:65534:65534:nobody:/var:/bin/false









 

Given that there's no FTP then the FTP user is a candidate for removal, although it would make sense to check that is not used for the WebUI.

 

We can disable the accounts using

 

passwd -l username




Brute Force

The Enchanted Cottage has some protection against brute force attacks in that the Linino portion and hence the Wifi is turned off for most the the time hence there is no way to connect. However in the computer world the few seconds that the system is up and connected should sufficient for a break to be attempted.

 

The two areas that could be vulnerable to this are the Web Admin UI provided by Arduino and the SSH port. It might be possible to turn these off. Given that these are used to fix or configure the device that's maybe not a good idea.  It's also possible to configure SSH to use certificates rather than password for login. To do this on the finished product we'd need to have some way of getting the keys back and forth.

 

This can be setup by following the instructions for setting up Drop Bear SSH for Public/Private Key authentication

SSHCertLogin.png

The best method for handling brute force attacks is to use a intruder detection system such as Fail2Ban which uses the inbuilt firewall IPTables to lockout IPaddress that have strange activity patterns. The only dependency for Fail2Ban appears to be Python so for the cottage this seems like a good solution. The module is not yet available as a downloadable OPKG package but it can be installed manually. Fail2ban install on GNU Linux

 

The daemon file need tweeking to run on this platform, one from RedHat was used as a basis.

https://github.com/Workshopshed/EnchantedObjects/blob/master/Code/Scripts/fail2ban-initd

 

and this was tested with

/etc/init.d/fail2ban start






 

and

/etc/init.d/fail2ban stop






 

Removing features

Whilst Hans was researching security he had a visit from the Woodcutter who wanted to see how the build was coming on. Whilst they were wandering around admiring the structure the Woodcutter tripped on a stump and reached out and grabbed the nearest thing to him, a hanging basket of flowers. The chain supporting the basket broken and the basket and Woodcutter went crashing to the ground. The Woodcutter picked himself up and brushed off the soil and flowers. He looked at the basket on the floor and said "a chain is only as strong as it's weakest link". He picked up the basket, passed it to Hans and wandered off into the forest.

 

Hans realised that there were features on the Yún that were not being used. These could be removed to stop them being the weakest link.

 

Looking at the list of installed packages there seems to be some candidates for removal.

 

  • avahi - A Zero Configuration network tool.
  • cpu-mcu-bridge - The bridge, this is already swapped out so is not used.
  • spacebrew - A friendly wrapper for APIs
  • temboo - A friendly wrapper for APIs

 

Hans also wondered about avrdude, the tool for putting new sketches onto the AtMega. But removing that would stop the end user applying patches over the Wifi.

 

opkg remove temboo
opkg remove spacebrew
opkg remove cpu-mcu-bridge






 

Removing avahi raised a warning that it was used by depended on by other package so it was not removed at this time.

 

The other key feature to review is the Rest API, the uhttp webserver publishes data on the Arduino pins and can control the ATMega via a correctly constructed URL.

e.g.

http://<Arduino_Yún_Address>/arduino/mode/13/output





 

We can disable the Arduino specific end points by editing the /etc/httpd.conf file to comment out lines by putting an # in front of them.

 

#A:/arduino:/cgi-bin/luci/arduino%s
 #A:/data:/cgi-bin/luci/data%s
 #A:/mailbox:/cgi-bin/luci/mailbox%s





 

Principles of least privilege

This security concept is basically don't give more permissions that is needed to do the task required. Then if anything goes wrong or there's a security loophole then a hacker is less likely to be able to escalate their privileges further.

 

Again, swapping out the bridge code with the reduced functionality of the python script means that the ATMega has access to less of the Linino side. However, python is running as root, which is a bit much given that it only needs to read a configuration file and get a file off the network to process and send via serial the ATMega.

 

There are tools to help lock down these permissions such as SELinux but it would appear that these would need the Kernel patching which unfortunately means I don't have time to implement this process.

 

Next: Enchanted Objects Design Challenge - Tools

 

References

SSH Tutorial for Linux - Support Documentation

MQTT Security Fundamentals - Securing MQTT Systems

The 10 challenges of securing IoT communications  |  Atmel | Bits & Pieces

Arduino.cc List of Yún packages

https://github.com/arduino/YunBridge/blob/master/bridge/bridge.py

Welcome to pySerial’s documentation — pySerial 2.7 documentation

20 Linux Server Hardening Security Tips

operating systems - Hardening Linux Server - Information Security Stack Exchange

Using REST with Arduino Yun | Open Electronics

Web Server Configuration (uHTTPd)

What is the principle of least privilege?

Minimize Privileges

SELinux The_security_context_of_a_process

Happy Fathers Day everyone (Especially my Dad),

 

So my Dad is real happy with what I have done with the temperature control. He has now challenged me with the issue of the thermostat being across the room from the clock. He has asked me to have the motor run wireless from the Arduino to set the temperature. I have thought this out for the past 2 days and came up with a perfect solution. I designed a way to have the Arduino send a laser beam to a photoresistor on the other side of the room. This will let the power at the motor through and make the temperature raise or lower. Below is a diagram of what I am doing, Pictures will be uploaded today when we have this made and working. Dad is soldering everything right now.

 

Update in a couple of hours!!

 

Chrystal Winhold

 

 

 

Thermostat diagram.jpg

Unfortunately, I was unable to create a video to show you guys how beautifully my magic lamp was working. When I asked the genie to come out and play today he instead thought to introduce me to some magic smoke, and like that he was gone (In other words, my Infineon RGB  Shield went BOOM!). But I had a blast working on this project. I have a quick, very pathetic, mock up of what the final thing would look like.

 

 

The big box around the shield and Arduino is the 3D printed container. The finished product was very simple for any user to use. You only needed to know very basic things about Arduino to get started, (I tested it on my mother). All you needed to know is how to setup the Yun to connect to your home WiFi and how to upload a sketch onto the board. After that was done, the lamp would run on its own. I started looking into possibly even preloading the sketch to the board, but didn't get too far with that. The case I printed was Ivory, and I thought about taking it further and painting it oak, or different colors that matched the surrounding environment. The LED was placed on an Edison screw in bulb, so it fit in most household lamp sockets, however, you'd have to "plug" the lamp into the shield rather than straight into the wall. It was also relatively cheap, other than the case (but I got to print it for free! ).


 

ProductCost
Arduino Yun$55.01
Infineon RGB Shield$23.90
LED Chip and Bulb$20.00
Edison Screw In$15.00
TOTAL$113.91

 

And a lot of these costs can really be lowered depending on what you have already, and whether or not you really need to use the Yun. But I feel as though this product meets the requirements. I believe that it does as intended, even though I unfortunately have no proof other than this screenshot .

I also believe, as I stated before, and my mother would agree, that it is very easy for a non technical person to use. However, the price is a little steep for a lamp, but as I stated it wouldn't be incredibly hard to adapt it some to make it much more cost effective. Also when you realize that it can also act as an alarm clock with a strobing feature at the designated time you wish to wake up, this price begins to be more realistic. And when properly cased, or placed, this would last a one a very long time, I see it as incredibly durable, well it was , but also aesthetically pleasing. I wish I had pictures and videos for you all, and I may later, but for now I believe this to be a farewell, hopefully a see you soon. I had a great time and appreciate all of you! Look forward to seeing the out come of these other projects and who is announced the winner!

Whilst Hans was coding Matilda was fine tuning the mechanism and finishing the housing. When the magnet housings had been tested their positions had put Hans and Matilda a bit far back into the cottage. The magnet carriers were redesigned so that the holes were towards one end, that would move the positions forward by about 7mm and the coverings for the holes turned out not to be needed so those were removed to reduce printing time.

MagnetCarriers1.pngMagnetCarriers2.png

Due to their simple design and shape they printed first time with no issues.

MagnetCarriers2.jpg

However not everything was so simple. After quite a few failures the spacers for supporting the Yún and shields were printed successfully by lying the models down, reducing the printing speed and printing at 1/2 speed for the first few layers. Also a brim was added as the footprint was quite small.

Spacers Printing

Spacers

The final challenge for the printing was two buttons for the top panel. These went through several iterations and failed prints but eventually a design was created that fitted the panel and printed successfully. The small bobble on the stalk stops the buttons falling out when you turn the panel upside down.

Wifi and Power Buttons

ButtonsFailures.jpg

The key lessons learnt here were not to have features too close to the edge, the printer can handle thin slots but not thin solid, adding a brim helps give a crisp edge and when printing the first layer don't make it too thin and print it slowly.

Button Success

There was a little clean up of the wifi logo needed but the power button was simply a case of removing the brim.

 

Source code and models: https://github.com/Workshopshed/EnchantedObjects/tree/master/Mechanics

 

Next: Enchanted Objects Design Challenge - Locking the doors

This is the last week of the challenge

The hardware and software are almost completed, so it's time to build the real hat. In a previous post, I started building some parts of the hat.

First of all, I cut out from plywood a circle that will be the brim of the hat. I then fixed the blood pressure measurements device to the plywood using some self-tapping screws

 

IMG_20150612_084330.jpg

Then I covered everthing with a fabric. It's not very fashion, but that's what my mother has in house

 

IMG_20150620_122836.jpg

 

I then attached the brim to the cone that contains all the electronics

 

IMG_20150620_132025.jpg

 

You can clearly see the LEDs that make up the mouth and the small speaker

Here is more detailed view of the electronic components inside the hat

 

Electronics.jpg

 

Just to recap:

  • Arduino Yun - Atmel side takes care of sampling sensors (temperature, FSR, finger present, pulse)
  • Arduino Yun - Linino side: runs NodeJS, implements Text-To-Speech by invoking a webservice, get Harry Potter-related quotes by invoking a web service
  • Arduino Mini Pro: controls servos and mouth's LEDs

 

Then I fixed (with some hot glue) the temperature sensor to the baseball cap (trust me: it doesn't hurt when you wear the hat)

 

IMG_20150620_230818.jpg

 

Using the same fabric, I cut out a sort of one that covers all the electronic components. Here is the final result

 

IMG_20150620_200822.jpg

Disable the bridge

As mentioned in previous episodes the plan was to remove the bridge as that provided much more functionality than it needed to and it also provided root access to the Linino side from the Arduino code. Hans thought would replace it with direct serial communications between the two CPUs.

 

To stop the bridge /etc/inittab is edited to disable the connection of the console to the serial port ttyATH0, the Yún needs to be rebooted after this change.

 

::sysinit:/etc/init.d/rcS S boot
::shutdown:/etc/init.d/rcS K shutdown
#Disable Bridge
#ttyATH0::askfirst:/bin/ash --login


 

Checking we can communicate

To test the solution Hans produced a simple loopback example

LoopBack.png

 

Python

To get Python to listen to the serial port the PySerial module needs to be installed. That's simply a case of using the package manager.

pyserial.png

 

opkg update
opkg install pyserial




 

The port is configured as /dev/ttyATH0 and when we open the port we can specify the speed and any timeouts. For testing purposes the timeouts were set to 60s each and the test programme simply echoed the inbound stream back down the line.

 

import serial

try:
  ser = serial.Serial('/dev/ttyATH0', 115200, timeout=60, writeTimeout=60) # Baudrate needs to be mirrored on ATMega side
except:
        exit(1)          # quit as we can't start the serial port

line = ser.readline()  # read a '\n' terminated line

while line != "":
    print(line);            # Display on console
    ser.write(line)        # Echo it back
    line = ser.readline()  # read next line

print("timeout")
ser.close()




 

Arduino

On the Arduino side the serial port is configured as Serial1 and the code to communicate over serial is very straight forward we can echo the message to and from the PC across to the Linino.

 

void setup() {
  Serial.begin(115200);  //To PC
  Serial1.begin(115200);  //To Linino
}

void loop() {
  //From PC to Linino
  int c = Serial.read();              // read from USB-CDC
  if (c != -1) {            
    Serial1.write(c);            //        write char to UART
  }

  //From Linino to PC
  c = Serial1.read();                // read from UART
  if (c != -1) {                      // got anything?
    Serial.write(c);                  //    write to USB-CDC
  }
}




 

Test results

The Python script was started up manually using SSH so that the output could be monitored. A sequence of messages were sent from the PC down the USB, over the bridge and then bounced back again.

Serial Loopback Test

Give that the test was successful the next step is to add this functionality into our existing scripts and configure the inittab to run our weather script.

 

Code at: https://github.com/Workshopshed/EnchantedObjects/tree/master/Code/Examples/SerialEcho

 

Next: A bit of 3D Printing

 

Reference

Arduino - Serial

Welcome to pySerial’s documentation — pySerial 2.7 documentation

Startup and Run Levels

UNIX man pages : inittab (5)

18 june 2015

 

As a dramatic closing exercise to the Enchanted Objects parade, I chose to try and build a C MQTT client for the SAMA5D4.

It turned out to be not dramatic at all. It was rather easy. Here's my log of the activities.

 

 

mqtt sama5d4 eclipse paho

 

My ToolSet

 

I'm cross-building the library and executable on a Windows machine.

I used Eclipse for DS-5 - Community Edition as my IDE, and used the built-in ARM GCC 4.x toolchain.

My telnet client is PuTTY, and WinSCP does the file transfer.

I used the GIT command line to retrieve the Paho client code.

The Paho MQTT client utility was my testbed.

 

I've made a how-to on using these tools as part of my blog series.

 

 

Building the MQTT Shared Library

 

The source code for the eclipse Paho libraries is available from github.

You can find the instructions on eclipse's MQTT C Client for Posix and Windows.

Because I'm using DS-5 for the build (and also because the makefile didn't work on my Windows PC), I've only followed the steps to download the code.

 

C:\Users\Jan\Documents\elektronica\atmel\mqtt_lib\paho_from_source>git clone http://git.eclipse.org/gitroot/paho/org.eclipse.paho.mq
tt.c.git
Cloning into 'org.eclipse.paho.mqtt.c'...
remote: Counting objects: 1719, done.
remote: Compressing objects: 100% (5/5), done.
remote: Total 1719 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (1719/1719), 787.24 KiB | 31.00 KiB/s, done.
Resolving deltas: 100% (1177/1177), done.
Checking connectivity... done.









 

Then I created a new Shared Library project in DS-5. I've used the makefile source as guideline to check what files to compile and what command line options to pass to the toolchain.

 

 

I carefully studied the makefile to understand what files to include/exclude from build, and what settings to port from make to DS-5.

I'm building the async lib version without SSL, so I took over the settings from that lib's make commands.

 

blatant promo shot

 

I excluded the files listed in this variable from compilation, just like in the make script.

 

SOURCE_FILES_A = $(filter-out $(srcdir)/MQTTClient.c $(srcdir)/MQTTVersion.c $(srcdir)/SSLSocket.c, $(SOURCE_FILES))









 

 

I also checked where this particular makefile variable was used:

 

MQTTASYNC_INIT = MQTTAsync_init









 

and incorporated it in the linker flags:

 

Then I built the project. That gave me a compiled .so library.

 

Build the MQTT Subscriber App

 

I used the  async subscription example that's available in the same git extract. MQTTAsync_subscribe.c

 

I created a new project in DS-5, and added the source  to that project.

I took care that the async shared library was available to the linker:

 

I modified the source to connect to eclipse's mqtt sandbox, and to listen to my turntable's topic:

 

#define ADDRESS     "tcp://iot.eclipse.org"
#define CLIENTID    "1cfee8dd0afc_SAMA5D4"
#define TOPIC       "PerpetuumEbnerSpectrum"









 

Build, and done!

 

Load and Run

 

I deliberately didn't do all the steps to properly register the shared library.

 

I handled the part of setting the lib search path on the command line when invoking my executable.

There's a nice article on how to do a full-fledged install of a .so here: Shared Libraries.

 

I moved both the .so and the executable to root's home on the SAMA5D4 with WinSCP,

made both the program objects executable:


$ chmod +x Enchanted_Player_MQTT_Client









 

note to self: does an .so really need the exex flag set?

answer to self: no; explanation updated

 

and invoked the whole chebang using:

$ LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH ./Enchanted_Player_MQTT_Client









 

Nothing more to say. Success. It just worked. My audio spectrum, sampled by the Yún inside my turntable, arrives nicely on the SAMA5D4.

 

mqttreceived_frompe.jpg

 

 

Table of Contents
Chapter 1: Fix the turntable
1: Perpetuum Ebner Musical 1
2: A Time to Kill and a Time to Heal
3: Preparation for Motor Drive
4: Motor control with Infineon Motor Shield and Arduino UNO
5: Turntable speed sample testbed with Arduino UNO
6: Turntable Speed Sensor design
7: Control Theory - End of Chapter 1
Chapter 2: First Enchantments
8: Digital Light Organ Enchantment
9: Autonomous Servo Lift
10: SMD Time - Solder the IR Speed Sensor PCB
11: Yelp - who can Help me to Compile and Run my First SAMA5D4 C Program
12: Son et Lumiere - End of Chapter 2
Chapter 3: Taming the Board
13: Breakthrough - Run my own C++ Program on the SAMA5D4
14: Digital Light Organ Input Buffer
15: SAMA5D4 Blinky
16: Scope Creep
17: Audio Sampling with 16-bit ADC ADS8343
18: Sending Files to SAMA5D4 over USB
19: Port my Light Organ from Arduino to SAMA5D4
20: Fast Fourier Transform on the SAMA5D4 - End of Chapter 3
Epilogue: Reaching for the Clouds
21: Right-Sizing my Plans
22: My Own C++ Buffered Sampler on the SAMA5D4
Interlude
23: Building In the Motorized Light Organ
24: Up to the Clouds with Yún
25: Publish or Perish
26: Turntable Finished
Stretch & Boni
Bonus 1a: Remote Light Organ with WiFI pt. 1
Bonus 1b: Remote Light Organ with WiFI pt. 2
Grande Finale: Paho MQTT Client on the SAMA5D4
Related blog
Vintage Turntable repair: Can I fix a Perpetuum Ebner from 1958
Review 1: Atmel SMART SAMA5D4 Xplained Ultra Unboxing and First Steps
Review 2: Atmel SMART SAMA5D4 Xplained Ultra - Building the Libraries from Source
Review 3: Digital Continuous Rotation (360°) Servo Part 1
Review 4: Digital Continuous Rotation (360°) Servo Part 2
Review 5: Atmel SMART SAMA5D4 Xplained Ultra - TCP/IP running
Review 6: Atmel SMART SAMA5D4 Xplained Ultra - LINUX Distro with SSH support
poem
Enchanted Objects: Let's work together to tame the ATMEL SMART SAMA5D4 Xplained Ultra kit
17 bis: Off South...
Review 7: Atmel SMART SAMA5D4 Xplained Ultra - C++ ADC Example on Linux
Review 8: Atmel SMART SAMA5D4 Xplained Ultra - Product Review
Review 9a: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 1
Review 9b: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 2
Review 10: Atmel SMART SAMA5D4 Xplained Ultra - New Content on AT91.com
1958 Turntable from the Black Forest - Summary of the Enchanted Player Story

When I was making the Topsy Turvy Clock I created a non blocking delay class so that the Arduino could be doing other things whilst waiting for a timeout. This avoids the use of the delay function which otherwise "blocks" the operation until the timeout is completed. I realised that this same technique could be used to control the flashing of the RGB LED. This will need to be expanded to handle the colour cycling which will indicate that the Wifi settings need configuring.

 

Code: https://github.com/Workshopshed/EnchantedObjects/tree/master/Code/Examples/Blinker

 

Example Usage

Here's an example of the blinking code using the LED on pin 13.

 

#include "Blink.h"
Blinker b(1,0);

void setup() {
  b.Blink(Short_Blink);
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, b.Level());
  //Do other things here as desired
}



 

 

Virtual Prototyping

 

As an experiment the code was uploaded to 123D circuits.

 

123D

https://123d.circuits.io/circuits/868830-blinker-class

 

This allowed the example to be tested from a web page without the need for actually having an Arduino plugged into the computer.

 

Next: Swapping out the bridge

amgalbu

MagicHat - 20 - Adding wisdom

Posted by amgalbu Top Member Jun 17, 2015

Thanks to the Text-To_Speech engine, I can easily add a nice function to the MagicHat: the capability to say wisdom phrases while it's idling


The implementation will be based on a web service that provides quotes as a JSON document

I found a lot of alternatives on www.mashape.com and I selected the quotes service provided by quotbook.com

The URL to invoke to get a new quote has the following format


https://yusufnb-quotes-v1.p.mashape.com/widget/~{search}.json


where {search} is the topic you are interested to get a quote about. To stay on the challenge topic, I will randomly search for the following topics

  • rowling
  • magician
  • harry potter

 

The quote web service will be queried by theNodeJS application

 

function getQuote(topic) {
  var http = require('http');
  options = { 
    host: 'yusufnb-quotes-v1.p.mashape.com', 
    path: '/widget/~' + topic + '.json',
    port: '1338', 
    headers: {
       'X-Mashape-Key': '<your mashape key>',
       'Accept': 'application/json"

     } }; 
 
 
  callback = function(response) { 
  r str = '';
     response.on('data', function(chunk) { 
      str += chunk; 
    }); 
    response.on('end', function() { 
      console.log(str); 
      var obj = JSON.parse(str);
 
 var mp3url='http://tts-api.com/tts.mp3?q='+encodeURIComponent(obj.quote);
      getMp3(mp3url, filename, function() {
        exec('/usr/bin/madplay -A10 ' + filename);
      });
    }); 
  }
 

  req = http.request(options, callback); 
  req.end();
 };
 


Since the Arduino side is aware whether the MagicHat is idling or not, the quote function will be triggered by Arduino itself by sending a new command


Serial1.println("QUOTE");


This command will be parsed by the serial port's data handler

 

// quote topics
var topics = ['rowling', 'magician', 'harry_potter'];

// generate a random int value between low and high (including limits)
function randomInt (low, high) {
    return Math.floor(Math.random() * (high - low) + low);
}

// serial port data handler

yunPort.on('data', function(data) {

  //console.log('data ' + data);
  
  _data = _data + data;
  var eol = _data.indexOf("\r\n");
  if (eol > 0)
  {
    _data = _data.substring(0, eol);
    if (_data.substring(0,5) == "PLAY ")
    {   
      console.log("Received command " + _data.substring(0,5)+","+_data.substring(5));
      var text = _data.substring(5);
      _data = "";

      text = text.replace(/ /g, '_');
      var filename = '/mnt/sda1/' + text + '.mp3';
      console.log("Checking file " + filename);
      if (fs.existsSync(filename))
      {
        console.log("Playing file " + filename);
        exec('/usr/bin/madplay -A10 ' + filename);
      }
      else
      {
        var mp3url='http://tts-api.com/tts.mp3?q='+encodeURIComponent(text);
        getMp3(mp3url, filename, function() {
          exec('/usr/bin/madplay -A10 ' + filename);
        });
      }
    }
    else if (_data.substring(0,5) == "QUOTE")
    {
      getQuote(topics[randomInt(0,topics.length-1)]);   
    }
    else
    {
      if (_ws)
        _ws.send(_data);
      
      _data = "";
    }  
  }
});

The bridge

Hans had been spending too much time inside coding. So this morning he went for a wander down by the stream. As he neared the town he saw the new bridge that had been put in so that the children could cross the stream to get to the school. The bridge was made of iron and had gates so that cattle did not wander across. There was a solar powered telephone box so that the kids could make calls and send emails and notice board so that the school could leave important bulletins for them to read. The bridge also had a system of bells and whistles to give warning alerts.
Hans spotted the Uart twins, Tex and Rex with their little sister Parity. The three children approached bridge but rather than going through the gates they headed down the side of the bridge and hopped over the stepping stones. Hans remembered how he and Matilda had hopped over those same stones when he was younger.

 

The other bridge

Hans looked at the Arduino code and noticed that the size was 10% bigger when he compiled in the Bridge libraries. Looking at the code it was obvious why. There was code for handling web servers, email and code to start and stop the bridge and check it was running. Following Ambrogio Galbusera's idea, he decided to drop the bridge and use a simple serial communication instead. The Linino side could start up his Python code directly rather than provide a console with root access listening on the serial pins.

 

Are you ready yet?

One of the problems of turning off the Linino portion of the Arduino Yún is that it takes some time to restart and you need to know when it's ready for action.

 

This problem is compounded by the fact that whilst that side is booting the serial connection which is normally used for messaging between the Linino and ATmega sides is used as a console for the Uboot and Linux boot processes. If the ATmega was to send anything across the bridge at that point then it could stop the booting process. The way the Bridge code works is to delay starting until that console has not produced any content for over 1s, however this timing based approach is a little unreliable so some people on the Arduino Forum have suggested adding further delays into the code to ensure that Linux has fully booted.

BridgeBlockDiag.png

Luckily the system has a hand shaking line installed and that can be used to signal that the process is complete. This is connected up via a level shifter which can be turned on and off via one of the AR 9331's GPIOs.

Handshaking

Eberhard Fahle has produced an article that explains what is needed to configure the handshaking line for the Arduino Yún we can then use that either as a digital line or via the interrupts to signal when the boot process is complete.

 

Code

Eberhard's code was combined with the YunSerialTermial code to allow the boot process to be monitored visually as well as via the handshaking line.

 

Code: https://github.com/Workshopshed/EnchantedObjects/tree/master/Code/Examples/HandshakingMonitor

 

Setup

The boot status script was uploaded to the init.d folder and configured for execution.

Shell.png

As suggested in the article the init script was tested with

 

/etc/init.d/boot-status start

Boot On

and with

 

/etc/init.d/boot-status stop

Boot Off

The serial monitor was started and the boot process watched. Shortly after the last message in the console the red #13 light turned on. The boot-status message does not show in the log.

 

Reference


https://gist.github.com/wayoda/db3c023417757f726088

https://www.kernel.org/doc/Documentation/gpio/sysfs.txt

http://www.arduino.cc/en/uploads/Main/arduino-Yun-schematic.pdf

Access GPIO from Linux user space | FalsinSoft

http://wiki.openwrt.org/doc/techref/initscripts

rpbruiser

Quick Update

Posted by rpbruiser Jun 16, 2015

This is just a quick update, I have created a library that will calculate the sunrise and sunset times for any location for the current day, and whether or not that location is currently in daylight savings or not. This is an update here because the library is based on the code I wrote for this project. If you would like to check it out, or us it, you can go here and find it. It has capabilities for those with or without internet access, and has been helpful to me, I hope you guys find it helpful in future, or current, projects.

Hi everyone, it is Chrystal with the update.

 

First of all, my Dad told me that the temperature will be voice controlled, AFTER I GOT IT WORKING!!! So I spent all day today (after school) and added it into the voice program, haha to him, it works. He has no idea yet as he is working on the wooden clock. Below is the Arduino script that is used for the whole voice control, my part is in red so it stands out. I drew a quick picture of how it works, I couldn't get a picture without him finding out... I will tell him after this is posted.

 

#include <SoftwareSerial.h>
#include "VoiceRecognitionV3.h"


VR myVR(2,3); 

uint8_t records[7];
uint8_t buf[64];

int led = 13;
int Hotter = 8;
int Colder = 9;

#define Light (0)
#define Dark (1)
#define Hot (2)
#define Cold (3)
#define Sleep (4)
#define Timer (5)
#define Stop (6)


void printSignature(uint8_t *buf, int len)
{
  int i;
  for(i=0; i<len; i++){
    if(buf[i]>0x19 && buf[i]<0x7F){
      Serial.write(buf[i]);
    }
    else{
      Serial.print("[");
      Serial.print(buf[i], HEX);
      Serial.print("]");
    }
  }
}


*/
void printVR(uint8_t *buf)
{
  Serial.println("VR Index\tGroup\tRecordNum\tSignature");

  Serial.print(buf[2], DEC);
  Serial.print("\t\t");

  if(buf[0] == 0xFF){
    Serial.print("NONE");
  }
  else if(buf[0]&0x80){
    Serial.print("UG ");
    Serial.print(buf[0]&(~0x80), DEC);
  }
  else{
    Serial.print("SG ");
    Serial.print(buf[0], DEC);
  }
  Serial.print("\t");

  Serial.print(buf[1], DEC);
  Serial.print("\t\t");
  if(buf[3]>0){
    printSignature(buf+4, buf[3]);
  }
  else{
    Serial.print("NONE");
  }
  Serial.println("\r\n");
}

void setup()
{

  myVR.begin(9600);
 
  Serial.begin(115200);
  Serial.println("Elechouse Voice Recognition V3 Module\r\nControl Clock");
 
  pinMode(led, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
   
  if(myVR.clear() == 0){
    Serial.println("Recognizer cleared.");
  }else{
    Serial.println("Not find VoiceRecognitionModule.");
    Serial.println("Please check connection and restart Arduino.");
    while(1);
  }
 
    if(myVR.load((uint8_t)Light) >= 0)
      {
        Serial.println("Light loaded");
      }
 
    if(myVR.load((uint8_t)Dark) >= 0)
      {
        Serial.println("Dark loaded");
      }
     
    if(myVR.load((uint8_t)Hot) >= 0)
      {
         Serial.println("Hot loaded");
      }
 
    if(myVR.load((uint8_t)Cold) >= 0)
      {
        Serial.println("Cold loaded");
     
     
    if(myVR.load((uint8_t)Sleep) >= 0)
      {
      Serial.println("Sleep loaded");
      }
 
    if(myVR.load((uint8_t)Timer) >= 0)
      {
        Serial.println("Timer loaded");
      }
     
    if(myVR.load((uint8_t)Stop) >= 0)
      {
        Serial.println("Stop loaded");
      }

}

 

void loop()
{
  int ret;
  ret = myVR.recognize(buf, 50);
  if(ret>0){
    switch(buf[1]){
      case Light:
        /** turn on LED */
        digitalWrite(7, LOW);
        digitalWrite(led, HIGH);
        break;
       
      case Dark:
        /** turn off LED*/
        digitalWrite(led, LOW);
        digitalWrite(7, LOW);
        break;
       
      case Hot:
        /** turn up temperature */
          digitalWrite(Hotter, HIGH);
          delay(1000);
          digitalWrite(Hotter, LOW);
        break;
       
      case Cold:
        /** turn down temperature*/       
          digitalWrite(Colder, HIGH);
          delay(1000);
          digitalWrite(Colder, LOW);       
        break;

 

     case Sleep:
        /** turn down lights */
        digitalWrite(led, LOW);
        digitalWrite(7, HIGH);
        break;
      case Timer:
        /** set 5 minute timer*/
        /** To be determined*/
        break;
      case Stop:
        /** Stop all*/
        digitalWrite(led, LOW);
        digitalWrite(7, LOW);
       
        break;   
      default:
        Serial.println("Record function undefined");
        break;
    }

    printVR(buf);
  }
}

 

As you can see I kind of copied what Dad was doing but I got it to work on my own!!

 

Thermostat.jpg

 

So how this works is when you say "Hot" the motor turns clockwise a bit upping the temperature (I need to calibrate this) and when you say "Cold" the motor turns counter clockwise and turns the temperature down. I feel this was a bit simple for what could have been thought up to use, but it works. I also added 2 LED lights, 1 red and 1 green/blue. The red light turns on (Briefly) when the temperature is raised and the green/blue turns on (Briefly) when the temperature is lowered. This is a visual way to know the command was recognised.

 

Thank you for reading,

 

Chrystal Winhold

 

P.S. My picture is better then my Dad's!!!

28 june 2015

My first bonus design is a remote light organ. I've built it with an Arduino Yún, the Infineon RGB Led Shield and a bunch of LEDs.

Part 1 was my log on the build, and trying out if the Arduino-to-Infineon-toLEDs works.

In part 2, I'm showing off the completed design.

 

paho mqtt enchanted_objects enchanted_player

 

It Didn't Work Just Like That

 

I had issues getting it to work with a 64 char payload. I have some candidate root causes for that, but it's hard to get to the bottom without debugger (I think it is my mechanism to use a char array as payload).

I spent some time riddling my code with println()s and stared at it for a long time, to no avail. So I took the easy way out.

I've reduced my frequency spectrum bucket array from 64 to 32 buckets. That's enough for my purpose - I want to drive a 16*2 LCD in Bonus 2, and 32 data points will be enough..

 

This video shows the action. Appreciate the huge delay that I have This is nowhere near to real time light effects.

The next design challenge I promise to spend more time in sound programming and performance. This time I only spent time in getting things working somehow.

 

 

 

 

Why don't you improve my code? It's all here.

I bet I'm off where I'm reverting the 64 bucket list to smaller on the server, and again when I'm reading that same bucket list on the client.

Go ahead and slam those bugs in my face. That's how I learn.

 

The light organ server code, firmware for the Yún that's built into the turntable

 

// includes for servo
#include <Servo.h>


// includes for light organ
#include <fix_fft.h>




// MQTT  includes start
#include <Bridge.h>
#include <SPI.h>
#include <YunClient.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>


#include <string.h>
// MQTT includes end








// servo declaration


Servo servo;


#define SERVO_PIN 9
#define SERVO_DELAY 25
#define SERVO_BASE 90
#define SERVO_TOP (SERVO_BASE + 61)


int servoPos = SERVO_BASE;
bool servoUp = false;






// light organ declaration


#define MUESTRAS 128           // Numero de muestras para el cálculo de la FFT
#define LOGM 7                 // Logaritmo en base 2 del número de muestras


#define BAJOS_MEDIOS 7         // Nº de banda para el corte entre Bajos y Medios
#define MEDIOS_AGUDOS 35       // Nº de banda para el corte entre Medios y Agudos


#define BPIN  13                // Pin de salida Bajos
#define MPIN  12               // Pin de salida Medios
#define APIN  11               // Pin de salida Agudos
#define TIMERPIN 8




#define MAX_PASADAS 10         // Nº de pasadas para el cálculo de los lÃmites


char data[MUESTRAS];           // Array con los valores muestreados (parte real)
char im[MUESTRAS];             // Array con los valores muestreados (parte imaginaria)


unsigned char salida[MUESTRAS/2];  // Valores obtenidos de la FFT (espectro de 64 bandas)
unsigned char bajos,medios,agudos; // Valores calculados para cada canal


byte  pasada,                            // nº de pasada para el cáculo de los lÃmites
      acumBajos,acumMedios,acumAgudos,   // acumuladores de veces que se supera el lÃmite
      limBajos,limMedios,limAgudos;      // lÃmites calculados para cada canal




// start MQTT declarations
YunClient c; // replace by a YunClient if running on a Yun
IPStack ipstack(c);
MQTT::Client<IPStack, Countdown> client = MQTT::Client<IPStack, Countdown>(ipstack);
char payLoadBuf[MUESTRAS/2] = {}; // I'm going to give one byte per range, so that I can choose to implement a graph if I want.
const char* send_topic = "PerpetuumEbnerSpectrum";
const char* _id = "1cfee8dd0afc_yun_syberia";
// end MQTT declarations






// both:
// decay is a decreasing counter that tells how long the servo will stay up after the last led flashed.
// reset to DECAY each time a led lights up
// looses one live each time no leds are active
#define DECAY 150U
unsigned int uDecay = 0U;




// servo functionality


void servoInit() {
    servoUp = false;
    servo.attach(SERVO_PIN);
    servoPos = SERVO_BASE;
    servo.write(SERVO_BASE);
    delay(1000);
}


void servoGoUp() {

  if (servoPos < SERVO_BASE) {
    servoInit();
  }

  if (servoPos < SERVO_TOP) {
    servoPos++;
    servo.write(servoPos);
    delay(SERVO_DELAY);
  }
}


void servoGoDown() {

  if (servoPos < SERVO_BASE) {
    servoInit();
  }

  if (servoPos > SERVO_BASE) {
    servoPos--;
    servo.write(servoPos);
    delay(SERVO_DELAY);
  }
}


void servoGo() {
  if (servoUp) {
    servoGoUp();
  } else {
    servoGoDown();
  }
}




// light organ fuctions


/*
* Funcion que aplica una ventana de Hann a los datos muestreados para reducir el
* efecto de las discontinuidades en los extremos
*/
void aplicaVentana (char *vData) {
    double muestrasMenosUno = (double(MUESTRAS) - 1.0);
  // Como la ventana es simétrica , se calcula para la mitad y se aplica el factor por los dos extremos
    for (uint8_t i = 0; i < MUESTRAS/2 ; i++) {
        double indiceMenosUno = double(i);
        double ratio = (indiceMenosUno / muestrasMenosUno);
        double factorPeso = 0.5 * (1.0 - cos(6.28 * ratio));
  vData[i] *= factorPeso;
  vData[MUESTRAS - (i + 1)] *= factorPeso;
    }
}




void lightOrganSetup() {
    // Configuramos el prescaler a 32 -> 16Mhz/32 = 500 KHz
    // como cada conversion son 13 ciclos 500/13 ~ 38.4KHz
    // Es decir podemos medir en teoria hasta unos 19KHz,
    // que para este proyecto sobra.
    bitWrite(ADCSRA,ADPS2,1);
    bitWrite(ADCSRA,ADPS1,0);
    bitWrite(ADCSRA,ADPS0,1);


    // Como la señal es muy baja,utilizamos la referencia interna
    // de 1.1 V en vez de la de defecto de 5 V.
    analogReference(INTERNAL);

    // Salidas para los canales de Bajos,Medios y Agudos
    pinMode(BPIN,OUTPUT);
    pinMode(MPIN,OUTPUT);
    pinMode(APIN,OUTPUT);


    // debug
    pinMode(TIMERPIN,OUTPUT);
    Serial.begin(9600);


    // Variables para el cálculo de los lÃmites
    pasada = 0;
    acumBajos = acumMedios = acumAgudos = 0;
    limBajos = limMedios = limAgudos = 50;

  }


void lightOrganGo() {
    // Realizamos el muestreo
//    Serial.println("Start sampling:");
    digitalWrite(TIMERPIN, HIGH);
    for( int i=0; i < MUESTRAS; i++) {
       data[i] = analogRead(0)/4 -128;  //Convertimos de 0..1024 a -128..127                            
       im[i] = 0;                       // parte imaginaria = 0                     
    }
    digitalWrite(TIMERPIN, LOW);

/* 
    {
    Serial.println(" samples\n");
    for( int i=0; i < MUESTRAS; i++) {
      Serial.print(data[i], DEC);
      Serial.print(",");
    }
    Serial.println(" ---");

    }
*/


    // Aplicamos la ventana de Hann
    aplicaVentana (data);


/*
    Serial.println(" window\n");
    for( int i=0; i < MUESTRAS; i++) {
      Serial.print(data[i], DEC);
      Serial.print(",");
    }
    Serial.println(" ---");
*/
    // Calculamos la FFT
    fix_fft(data,im,LOGM,0);

    // Sólo nos interesan los valores absolutos, no las fases, asi que
    // calculamos el módulos de los vectores re*re + im*im.
    // Dado que los valores son pequeños utilizamos el cuadrado
    for (int i=0; i < MUESTRAS/2; i++){
       salida[i] = data[i] * data[i] + im[i] * im[i];
       // the cloud message contains half of the buckets, each pair of buckets is mediated
       if (i % 2) { // uneven
         payLoadBuf[i/2] = (salida[i] + salida [i-1])/2;
       }
    }
/*
    Serial.println(" result\n");
     for( int i=0; i < MUESTRAS/2; i++) {
      Serial.print(salida[i], DEC);
      Serial.print(",");
    }
    Serial.println(" ---");
*/

    // Ahora repartimos las bandas entre las 3 salidas
    // En vez de sacar la media, utilizo sólo el valor máximo de
    // una banda
    bajos = 0;
    for (int i=2; i < BAJOS_MEDIOS; i++){
      bajos += salida[i];
    }
    bajos = bajos/2;

    medios = 0;
    for (int i=BAJOS_MEDIOS ; i < MEDIOS_AGUDOS; i++){
      medios += salida[i];
    }
    medios = medios/2;

    agudos = 0;
    for (int i=MEDIOS_AGUDOS; i < MUESTRAS/2; i++){
      agudos += /*2**/(salida[i]);   // jc 20150604 undid because Yun ADC more sensitive or so // 20150601 doubled the highs sesitivity
    }
    agudos = agudos/2;

   // Calculamos si el canal correspondiente
   // supera le lÃmite para encenderlo
   int siBajos  =  bajos  > limBajos;
   int siMedios =  medios > limMedios;
   int siAgudos =  agudos > limAgudos;

   digitalWrite(BPIN,siBajos ? HIGH : LOW);
   digitalWrite(MPIN,siMedios? HIGH : LOW);
   digitalWrite(APIN,siAgudos? HIGH : LOW);

   // Utilizamos las veces que se supera para
   // recalcular el lÃmite y evitar que con los
   // cambios de volumen los canales se saturen
   // o no funcionen.
   acumBajos  += siBajos;
   acumMedios += siMedios;
   acumAgudos += siAgudos;

   if ( ++pasada > MAX_PASADAS ) {
      pasada = 0;
      limBajos  = 20 + acumBajos*5;
      limMedios = 20 + acumMedios*5;
      limAgudos = 20 + acumAgudos*5;
      acumBajos  = 0;
      acumMedios = 0;
      acumAgudos = 0;
   }


   if (siBajos | siMedios /*| siAgudos*/) { // jc 20150601 renew lift up decay if a led is on,
                                            // ignore highs because I've made them more sensitive above
     uDecay = DECAY;
   } else if (uDecay > 0) {
     uDecay--;
   }

}


// MQTT start


char printbuf[100];




void mqttInit() {
//  Ethernet.begin(mac); // replace by Bridge.begin() if running on a Yun
  Bridge.begin();


  connect();
}


void connect()  // connect to the MQTT broker
{
  char hostname[] = "iot.eclipse.org";
  int port = 1883;
  sprintf(printbuf, "Connecting to %s:%d\n", hostname, port);
  Serial.print(printbuf);


  int rc = ipstack.connect(hostname, port);
  if (rc != 1)
  {
    sprintf(printbuf, "rc from TCP connect is %d\n", rc);
    Serial.print(printbuf);
  }

  Serial.println("MQTT connecting");
  MQTTPacket_connectData data = MQTTPacket_connectData_initializer;  
  data.MQTTVersion = 3;
  data.clientID.cstring = (char*)_id;
  rc = client.connect(data);
  if (rc != 0)
  {
    sprintf(printbuf, "rc from MQTT connect is %d\n", rc);
    Serial.print(printbuf);
  }

  Serial.println("MQTT connected");

}


void sendMessage() {
  if (!client.isConnected())
    connect();

  MQTT::Message message;



  int rc;
  // Send QoS 1 message
  // // Serial.println(payLoadBuf);
  message.qos = MQTT::QOS1;
  message.retained = false;
  message.dup = false;
  message.payload = (void*)payLoadBuf;
//  message.payloadlen = MUESTRAS/2;
  message.payloadlen = MUESTRAS/8;
  rc = client.publish(send_topic, message);
}


// end MQTT functionality ==============================




























// arduino general


void setup()
{


  Serial.begin(9600);
  delay(10000); // give me time to start the yun monitor
servoInit();
  lightOrganSetup();
  // MQTT related tasks
  mqttInit();
}


void loop()
{
static unsigned int counter = 0;


      client.yield(10); // this takes 30 ms. May reduce the parameter // if you get duplicates, increase


  /*
  // lift debug
  while (Serial.available() > 0) {
    uDecay = (Serial.parseInt());
  }
  */




  servoUp = (uDecay > 0);



  servoGo();
  lightOrganGo();
  if (uDecay > 0) {
    counter++;
    if (counter == 30) {


      counter = 0;
      sendMessage();
    }
  }

}





The light organ client code, firmware for the Yún that's built into the remote light organ

 

// needed for MQTT and Process lib
#include <Bridge.h>


// MQTT  includes start
#include <SPI.h>
#include <YunClient.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>


#include <string.h>
// MQTT includes end


// INFINEON includes start
#include <Wire.h>
#include "Infineon.h"




// INFINEON declaration
  Infineon RGBLEDS = Infineon();




// light organ declaration
#define MUESTRAS 128           // Numero de muestras para el cálculo de la FFT


#define BAJOS_MEDIOS 4         // Nº de banda para el corte entre Bajos y Medios
#define MEDIOS_AGUDOS 10       // Nº de banda para el corte entre Medios y Agudos




#define MAX_PASADAS 10         // Nº de pasadas para el cálculo de los lÃmites




unsigned char bajos,medios,agudos; // Valores calculados para cada canal


byte  pasada,                            // nº de pasada para el cáculo de los lÃmites
      acumBajos,acumMedios,acumAgudos,   // acumuladores de veces que se supera el lÃmite








      limBajos,limMedios,limAgudos;      // lÃmites calculados para cada canal




// start MQTT declarations
char printbuf[100];


YunClient yc; // replace by a YunClient if running on a Yun
IPStack ipstack(yc);
MQTT::Client<IPStack, Countdown> client = MQTT::Client<IPStack, Countdown>(ipstack);
char payLoadBuf[MUESTRAS/2] = {}; // I'm going to give one byte per range, so that I can choose to implement a graph if I want.
const char* subscribe_topic = "PerpetuumEbnerSpectrum";
const char* _id = "1cfee8dd0afc_yun_paradise";
boolean bDataReceived = false;
// end MQTT declarations




// start timer functionality ============================================================
boolean bRunSeconds = false;
boolean bIsRunningSeconds = false;
boolean bRunMinutes = false;
boolean bIsRunningMinutes = false;
boolean bRunHours = false;
boolean bIsRunningHours = false;


void runSeconds() {
  bIsRunningSeconds = true;

  Serial.print("s"); // remove when confident


  if (bDataReceived) {
    bDataReceived = false;
    // Ahora repartimos las bandas entre las 3 salidas
    // En vez de sacar la media, utilizo sólo el valor máximo de
    // una banda
    bajos = 0;
    for (int i=2; i < BAJOS_MEDIOS; i++){
      bajos += payLoadBuf[i];
    }
    bajos = bajos/2;

    medios = 0;
    for (int i=BAJOS_MEDIOS ; i < MEDIOS_AGUDOS; i++){
      medios += payLoadBuf[i];
    }
    medios = medios/2;

    agudos = 0;
    for (int i=MEDIOS_AGUDOS; i < MUESTRAS/8; i++){
      agudos += /*2**/(payLoadBuf[i]);   // jc 20150604 undid because Yun ADC more sensitive or so // 20150601 doubled the highs sesitivity
    }
    agudos = agudos/2;

   // Calculamos si el canal correspondiente
   // supera le lÃmite para encenderlo
   int siBajos  =  bajos  > limBajos;
   int siMedios =  medios > limMedios;
   int siAgudos =  agudos > limAgudos;


   /*
   digitalWrite(BPIN,siBajos ? HIGH : LOW);
   digitalWrite(MPIN,siMedios? HIGH : LOW);
   digitalWrite(APIN,siAgudos? HIGH : LOW);
   */

  sprintf(printbuf, "Writing rgb: %d, %d, %d\n",
  siBajos, siMedios, siAgudos);
  Serial.print(printbuf);
    RGBLEDS.I2CWRITE6BYTES(ADDRESS, INTENSITY_RGB, siBajos*0xFFF, siMedios*0xFFF, siAgudos*0xFFF);


   // Utilizamos las veces que se supera para
   // recalcular el lÃmite y evitar que con los
   // cambios de volumen los canales se saturen
   // o no funcionen.
   acumBajos  += siBajos;
   acumMedios += siMedios;
   acumAgudos += siAgudos;

   if ( ++pasada > MAX_PASADAS ) {
      pasada = 0;
      limBajos  = 20 + acumBajos*5;
      limMedios = 20 + acumMedios*5;
      limAgudos = 20 + acumAgudos*5;
      acumBajos  = 0;
      acumMedios = 0;
      acumAgudos = 0;
   }

  }

  bRunSeconds = false;
  bIsRunningSeconds = false;
}


void runMinutes() {
  bIsRunningMinutes = true;



  bRunMinutes = false;
  bIsRunningMinutes = false;
}


void runHours() {
  bIsRunningHours = true;


  bRunHours = false;
  bIsRunningHours = false;
}


void timerInit() {
  // initialize timer1 for 1 second ticks; ISR(TIMER1_COMPA_vect) will be called as interrupt handler
  noInterrupts();           // disable all interrupts
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;


  OCR1A = 62500;            // compare match register 16MHz/256/1Hz
  TCCR1B |= (1 << WGM12);   // CTC mode
  TCCR1B |= (1 << CS12);    // 256 prescaler
  TIMSK1 |= (1 << OCIE1A);  // enable timer compare interrupt
  interrupts();             // enable all interrupts
}


ISR(TIMER1_COMPA_vect)          // timer compare interrupt service routine
{
  static unsigned int uSeconds = 0;
  uSeconds++; // every call is a second
  bRunSeconds = true; // so yes, flag that the seconds handler should be called
  bRunMinutes = ! (uSeconds % 60); // each 60th second, flag that the minutes handler should be called
  if (uSeconds > 3599) { // every hour
    bRunHours = true; // flag that the hours handler should be called
    uSeconds = 0; // and start over
  }
}


void timerTasks() {
  if (bRunSeconds && ! bIsRunningSeconds) { // timer interrupt flagged that seconds handler should be called
    runSeconds(); // but we only run it if it's not active
  }
  if (bRunMinutes && ! bIsRunningMinutes) { // timer interrupt flagged that minutes handler should be called
    runMinutes(); // but we only run it if it's not active
  }
  if (bRunHours && ! bIsRunningHours) { // timer interrupt flagged that hours handler should be called
    runHours(); // but we only run it if it's not active
  }
}


// end timer functionality =====================================




// start MQTT functionality ====================================




void mqttInit() {
//  Ethernet.begin(mac); // replace by Bridge.begin() if running on a Yun
  Bridge.begin();


  Serial.println("Enchanted Objects Remote Light Organ");
  connect();
}


void messageArrived(MQTT::MessageData& md) // this handler is called when a subscribed MQTT message arrives
{
  MQTT::Message &message = md.message;
  bDataReceived = true;

  // big chance that I'm off here by translating bytes, words, chars. But I Don't Have A Debugger in the Arduino IDE to Check.
  for (int ii = 0; ii < message.payloadlen; ii++ ) {
    payLoadBuf[ii] = ((char*)message.payload)[ii];
  }
  // debug code
  sprintf(printbuf, "Message arrived: len %d, retained %d, dup %d, packetid %d\n",
  message.payloadlen, message.retained, message.dup, message.id);
  Serial.print(printbuf);
/*
  sprintf(printbuf, "Payload %s\n", (char*)message.payload);


  Serial.print(printbuf);

  // sprintf(printbuf, "Topic len %d\n", md.topicName.lenstring);
  int i;
  for (i = 0; i < (md.topicName.lenstring.len); i++) {
    printbuf[i] = md.topicName.lenstring.data[i];
  }
  printbuf[(md.topicName.lenstring.len)]=  '\n';
  printbuf[md.topicName.lenstring.len + 1]=  0;

  */
}


void connect()  // connect to the MQTT broker
{
  char hostname[] = "iot.eclipse.org";
  int port = 1883;
  sprintf(printbuf, "Connecting to %s:%d\n", hostname, port);
  Serial.print(printbuf);
  int rc = ipstack.connect(hostname, port);
  if (rc != 1)
  {
    sprintf(printbuf, "rc from TCP connect is %d\n", rc);
    Serial.print(printbuf);
  }

  // // Serial.println("MQTT connecting");
  MQTTPacket_connectData data = MQTTPacket_connectData_initializer;  
  data.MQTTVersion = 3;
  data.clientID.cstring = (char*)_id;
  rc = client.connect(data);
  if (rc != 0)
  {
    sprintf(printbuf, "rc from MQTT connect is %d\n", rc);
    Serial.print(printbuf);
  }
  Serial.println("MQTT connected");
  rc = client.subscribe(subscribe_topic, MQTT::QOS1, messageArrived);
  if (rc != 0)
  {
    sprintf(printbuf, "rc from MQTT subscribe is %d\n", rc);
    Serial.print(printbuf);
  }
  Serial.println("MQTT subscribed");

}




// end MQTT functionality ==============================


// start INFINEON functionality =====


void rgbSetup() {
    Wire.begin();
    Serial.println("polling led shield...");
    while (RGBLEDS.on != 1) // Wait for shield to respond, keep setting the values till it does
    {

      Serial.println("led shield setup");


      RGBLEDS.I2CWRITE2BYTES (ADDRESS, FADERATE, 0x0000); // Immediate fade
      Serial.println("faderate set up");
      RGBLEDS.I2CWRITE2BYTES (ADDRESS, DIMMINGLEVEL, 0x0000); // 0% brightness level
      RGBLEDS.on = RGBLEDS.I2CREAD(ADDRESS, READ_DIMMINGLEVEL); // Request for brightness level
      if (RGBLEDS.message == 1 && RGBLEDS.on == 0) // If message received and dimming level = 0%, "message" is set in the I2CREAD function
      {
        Serial.println("message check for 0");
        RGBLEDS.message = 0;
        RGBLEDS.on = 1; // break out of loop
      }
    }
    RGBLEDS.I2CWRITE2BYTES (ADDRESS, OFFTIME_RED, 0x38); // Set off-time of red channel to 0x38
    RGBLEDS.I2CWRITE2BYTES (ADDRESS, OFFTIME_GREEN, 0x38); // Set off-time of green channel to 0x39
    RGBLEDS.I2CWRITE2BYTES (ADDRESS, OFFTIME_BLUE, 0x38); // Set off-time of blue channel to 0x38
    RGBLEDS.I2CWRITE6BYTES (ADDRESS, CURRENT_RGB, 0x05, 0x05, 0x05); // max:  0x80 = 780mA, I need 15 for standard leds, (0x03), but dimmed down to 0x02 because that's enough as max
    RGBLEDS.I2CWRITE2BYTES (ADDRESS, FADERATE, 0x0000); // Fade Rate between intensities --> 0.0s
    RGBLEDS.I2CWRITE2BYTES (ADDRESS, WALKTIME, 0x0000); // walk time between colors = 0s
    RGBLEDS.I2CWRITE6BYTES (ADDRESS, INTENSITY_RGB, 0x0555, 0x0555, 0x0555); // low level White Light
    RGBLEDS.I2CWRITE2BYTES (ADDRESS, DIMMINGLEVEL, 0x0FFF); // Maximum dimming level means inensity settings are directly used
    Serial.println("led shield active \n");
}






// end infineon functionality ======






void setup()
{


  Serial.begin(9600);
  delay(10000); // give me time to start the yun monitor


  // MQTT related tasks
  mqttInit();

  // INFINEON related tasks
  rgbSetup();


  // timer related tasks
  timerInit();
}


void loop()
{

  timerTasks();











































   // task: keep MQTT alive
  client.yield(10); // this takes 30 ms. May reduce the parameter // if you get duplicates, increase



}





 

 

.

 

Table of Contents
Chapter 1: Fix the turntable
1: Perpetuum Ebner Musical 1
2: A Time to Kill and a Time to Heal
3: Preparation for Motor Drive
4: Motor control with Infineon Motor Shield and Arduino UNO
5: Turntable speed sample testbed with Arduino UNO
6: Turntable Speed Sensor design
7: Control Theory - End of Chapter 1
Chapter 2: First Enchantments
8: Digital Light Organ Enchantment
9: Autonomous Servo Lift
10: SMD Time - Solder the IR Speed Sensor PCB
11: Yelp - who can Help me to Compile and Run my First SAMA5D4 C Program
12: Son et Lumiere - End of Chapter 2
Chapter 3: Taming the Board
13: Breakthrough - Run my own C++ Program on the SAMA5D4
14: Digital Light Organ Input Buffer
15: SAMA5D4 Blinky
16: Scope Creep
17: Audio Sampling with 16-bit ADC ADS8343
18: Sending Files to SAMA5D4 over USB
19: Port my Light Organ from Arduino to SAMA5D4
20: Fast Fourier Transform on the SAMA5D4 - End of Chapter 3
Epilogue: Reaching for the Clouds
21: Right-Sizing my Plans
22: My Own C++ Buffered Sampler on the SAMA5D4
Interlude
23: Building In the Motorized Light Organ
24: Up to the Clouds with Yún
25: Publish or Perish
26: Turntable Finished
Stretch & Boni
Bonus 1a: Remote Light Organ with WiFI pt. 1
Bonus 1b: Remote Light Organ with WiFI pt. 2
Grande Finale: Paho MQTT Client on the SAMA5D4
Related blog
Vintage Turntable repair: Can I fix a Perpetuum Ebner from 1958
Review 1: Atmel SMART SAMA5D4 Xplained Ultra Unboxing and First Steps
Review 2: Atmel SMART SAMA5D4 Xplained Ultra - Building the Libraries from Source
Review 3: Digital Continuous Rotation (360°) Servo Part 1
Review 4: Digital Continuous Rotation (360°) Servo Part 2
Review 5: Atmel SMART SAMA5D4 Xplained Ultra - TCP/IP running
Review 6: Atmel SMART SAMA5D4 Xplained Ultra - LINUX Distro with SSH support
poem
Enchanted Objects: Let's work together to tame the ATMEL SMART SAMA5D4 Xplained Ultra kit
17 bis: Off South...
Review 7: Atmel SMART SAMA5D4 Xplained Ultra - C++ ADC Example on Linux
Review 8: Atmel SMART SAMA5D4 Xplained Ultra - Product Review
Review 9a: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 1
Review 9b: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 2
Review 10: Atmel SMART SAMA5D4 Xplained Ultra - New Content on AT91.com
1958 Turntable from the Black Forest - Summary of the Enchanted Player Story

A trip up the fell

Matilda looked serious, she was dressed in a boiler suit, boots and a hard hat, she was leaning on a pickaxe. "Do you remember that watch my father gave you as a wedding present?", Hans nodded and took it out of his waistcoat pocket. "Put it in the drawer", Matilda commanded "and your reading glasses". Hans put the items in the drawer. "Put on your gear and meet me out front". Hans put on his boiler suit, hat and boots and headed out. He was met by Matilda and Farmer Hogg who was pushing a wheel barrow. "Upt yonder fell", said Farmer Hogg, Hans looked blankly. Farmer Hogg muttered something under his breath and passed a scrap of paper with a hastily drawn map.

 

As they neared the top of the hill, Matilda brought out a compass and started wandering in circles. Suddenly the compass needle twitched and Matilda smiled. She cleared off the turf and almost immediately hit rock. She donned her safety glasses and raised the pick, thud, thud, thud, sparks, "bingo!" cried Matilda. The ore was shovelled into the barrow and wheeled down the hill to C.Defoe's builder's yard.

 

Matilda asked Mr Defoe for 4 diametrically magnetised disk magnets and the Golem smashed up the ore and squashed it into a disk under great heat and pressure. "I'll plate them and drop them around in the morning" said Mr Defoe. The next morning the magnets were delivered with instructions to take care not to trap their fingers between two magnets. The diametrically magnetised magnets ensured that Hans and Matilda would remain facing in the right direction.

Diametrically Magnetised

Diametrically Magnetised Magnets

 

Magnet Holders

The initial thought was that the magnets could be attached to the mechanism using Sugru, however Matilda realised that this was a rubber compound and would cause friction.

Mechanism

There was a nylon bar that could be machined for a housing but that would be problematic to glue to the base / magnets. So a magnet housing was designed for 3D printing that could be clipped/glued onto the mechanism, ABS rubbing against the wood would run quite smoothly.

MagnetHousing.png

MagnetHousings2.jpg

Hans and Matilda's platforms were carefully milled by hand so that magnets could be added to those too.

MagnetsDrilling2.jpg

The magnets were test fitted in preparation for a full system test.

MagnetsInHouse.jpg

Thanks to Eric Styles from First4Magnets for advice on the right type and strength of magnet.

 

Next: Enchanted Objects Design Challenge - A tale of two bridges

rpbruiser

The Lamp Has Been Completed

Posted by rpbruiser Jun 14, 2015

The Genie has finished his renovations and is ready to show off his new crib, unfortunately he went on vacation and will not be able to show any pictures or videos until he returns home, but he has decided to release a listing of the house for all who are interested to see the new things that he has done to his new pimped out crib. Unfortunately the code is too long to post here, and I will add a link to pastebin here. I have also created a library that does a very similar thing to what I have done in my code and you can find it on my GitHub page.

 

I have really enjoyed this experience, and am so glad that this amazing community has given me the chance to explore something I have a passion for. All my competitors are so helpful and friendly, and I just love the atmosphere here, so thank you to all for this amazing opportunity and I hope to see you all again in future challenges or roadtests! And stay tuned for pictures and videos to come!!

Some fantastic examples from model making company Pantograph, I particularly like the binary type writer

typewriter.jpg

 

www.spoon-tamago.com/2015/06/08/pantograph-imagines-gadgets-from-a-parallel-world/

June 13 calendar scan

 

This is my first installment in the BONUS series where I'm tapping into the turntable's audio spectrum data that I'm publishing on the internet.

light organ loads of leds

 

My first bonus design is a remote light organ. I'm building it with an Arduino Yún, the Infineon RGB Led Shield and a bunch of LEDs.

Part 1 is my log on the build, and trying out if the Arduino-to-Infineon-toLEDs works.

 

Re-use and Re-purpose

 

I have kind of a head start here. For a previous element14 event, I have been using the RGB shield before.

That enabled me to just pull up the sketch that I used back then.

(I'll be able to do the same when building an MQTT listener on the Yun - been there done that.)

 

 

It's been a day of old school electronics. I pulled out the trusty soldering iron from my school days and did some trough-hole work.

Photo 12-06-15 09 48 48.jpg

The remote organ will fit in a little shoe box, so I cut out a plate of carton to mount everything on.

Photo 12-06-15 11 08 49.jpg

 

I've connected the things up and tidied the layout a bit.

Photo 12-06-15 12 09 16.jpg Photo 12-06-15 12 09 26.jpg

 

Sketch loaded - and it works. At the moment it's animating each of the 3 rows in 4 intensities.

That 'll change in part 2, where I'll tap into the MQTT data and turn this into a light organ.

 

 

Table of Contents
Chapter 1: Fix the turntable
1: Perpetuum Ebner Musical 1
2: A Time to Kill and a Time to Heal
3: Preparation for Motor Drive
4: Motor control with Infineon Motor Shield and Arduino UNO
5: Turntable speed sample testbed with Arduino UNO
6: Turntable Speed Sensor design
7: Control Theory - End of Chapter 1
Chapter 2: First Enchantments
8: Digital Light Organ Enchantment
9: Autonomous Servo Lift
10: SMD Time - Solder the IR Speed Sensor PCB
11: Yelp - who can Help me to Compile and Run my First SAMA5D4 C Program
12: Son et Lumiere - End of Chapter 2
Chapter 3: Taming the Board
13: Breakthrough - Run my own C++ Program on the SAMA5D4
14: Digital Light Organ Input Buffer
15: SAMA5D4 Blinky
16: Scope Creep
17: Audio Sampling with 16-bit ADC ADS8343
18: Sending Files to SAMA5D4 over USB
19: Port my Light Organ from Arduino to SAMA5D4
20: Fast Fourier Transform on the SAMA5D4 - End of Chapter 3
Epilogue: Reaching for the Clouds
21: Right-Sizing my Plans
22: My Own C++ Buffered Sampler on the SAMA5D4
Interlude
23: Building In the Motorized Light Organ
24: Up to the Clouds with Yún
25: Publish or Perish
26: Turntable Finished
Stretch & Boni
Bonus 1a: Remote Light Organ with WiFI pt. 1
Bonus 1b: Remote Light Organ with WiFI pt. 2
Grande Finale: Paho MQTT Client on the SAMA5D4
Related blog
Vintage Turntable repair: Can I fix a Perpetuum Ebner from 1958
Review 1: Atmel SMART SAMA5D4 Xplained Ultra Unboxing and First Steps
Review 2: Atmel SMART SAMA5D4 Xplained Ultra - Building the Libraries from Source
Review 3: Digital Continuous Rotation (360°) Servo Part 1
Review 4: Digital Continuous Rotation (360°) Servo Part 2
Review 5: Atmel SMART SAMA5D4 Xplained Ultra - TCP/IP running
Review 6: Atmel SMART SAMA5D4 Xplained Ultra - LINUX Distro with SSH support
poem
Enchanted Objects: Let's work together to tame the ATMEL SMART SAMA5D4 Xplained Ultra kit
17 bis: Off South...
Review 7: Atmel SMART SAMA5D4 Xplained Ultra - C++ ADC Example on Linux
Review 8: Atmel SMART SAMA5D4 Xplained Ultra - Product Review
Review 9a: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 1
Review 9b: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 2
Review 10: Atmel SMART SAMA5D4 Xplained Ultra - New Content on AT91.com
1958 Turntable from the Black Forest - Summary of the Enchanted Player Story

Here's a small DEMO video showing working of Enchanted Wardrobe Project. FEEDBACKs

WELCOME

Here's a flowchart explaining the complete working on Enchanted Wardrobe:flowchart_enchanted_objects.jpg

 

I am bit conscious about the suggest clothes feature, Based on temperature and weather conditions outside the wardrobe needed to be suggest clothing for the day to the user and now if user wants to go by the suggestion he can press the button and accordingly the cloth section will come ahead.! say if its a bright sunny day and wardrobe suggests to wear cotton clothes put shades and uv protection cream and if user agrees then the cotton clothes sections should come ahead if user agrees to the suggestion and presses the button, for this the sections should be divided properly in the wardrobe and a motorized mechanism needs to be made. GOOD IDEA to use motor shield but how is the question, SUGGESTIONS ARE WELCOMED .

For Enchanting the suggestions in sound I'll save pre-made MP3 files in root of OPEN-WRT yun os and can envoke them to play within arduino code. I am gonna buy a usb based sound card tomorrow and i wish ALSA(Advanced Linux Sound Architecture) drivers works for me.

Header 1

opkg update

opkg install kmod-usb-audio

opkg install madplay

Commands to bring USB sound functionality to yun.

 

FINGERS CROSSED

In the Last blog post(s) we used Yahoo Weather API under TEMBOO choreo to extract local weather information. The API returned data in XML form which we later parsed using Temboo Output filters and get needed information from the response. Now In this blog I'll show you three more powerful features of Temboo which is helping maker to integrate Digital/Analog input triggers and Actuators with their existing cloud APIs to build Internet Of Things based devices. Consider having a phone call when lights in room goes down a certain threshold now this can be achieved to hook a Light Sensor(LDR) reading continuous readings of ambient lights and monitoring the levels, if the level exceeds threshold it calls an API function which triggers phone, The digit pressed on your phone can be used to turn on the lights, hence this basic IoT device can be broken down into Input(LIGHT) cloud(PHONE CALL API SERVICE like NEXMO and TWILIO) and output say a light bulb. Keeping this approach in mind Temboo makes IoT easy to prototype as follows:

 

We already covered the cloud API part where weather data is coming from Yahoo API but in my project Enchanted Wardrobe I am looking to integrate the whole setup inside my wardrobe and want it to call the api and fetch information only when the wardrobe has been opened by me, this approach will have a lots of advantages like

--> Saving Energy and microcontroller free running cycles because I dont want it active all the time rather it is going to be used only few times in a day so why let it running for no reason?

--> It reduces the number of call to the server. Making unnecessary calls to APIs again and again in short interval of times overload them and they might block you from accessing them.

            The design is therefore smart, consumes less power and work only when needed(WIN).

 

 

Integrating input Trigger:


I want my wardrobe to enchants me weather only when I open it, Therefore I need some kind of mechanism to sense opening and closing of the doors. There are fancy door sensors available in the market in glossy casing but to keep the cost low am going to use a Magnetic REED switch, infact the fancy one has same mechanism inside them so why dont use it barely. This works as a normal switch but with a difference of passing current through them in the presence of a magnet. Hence i can integrate the switch on door of wardrobe connect it to my YUN and have a magnet in periphery opposite to the door hence deactivating it when the door is opened, this way i can sense the trigger. How REED switches work?reed.gif

 

The code is super simple, just use it with normal switch sketch inside arduino with pinMode(REED,INPUT_PULLUP); inside setup() and digitalRead(REED) inside loop before calling the api and using if else to check the opening of door.

 

A fancy way to do this is to tell this requirmentdirectly to temboo. In the page where we configured the API you can find the hyperlink which says is the choreo triggered by an input there you say yes and configured the pin for the api to get triggered as and select digital or analog triggered and suitable pin number with input. You can even hook up analog sensor using this approach.

 

However if you are using active low based triggered I've noticed that temboo generated code doesn't activated the pullup resistorby default so I recomend you doing that to avoid pin floating problems.

button.JPG

 

 

Actuating based on API responses

 

Similarly like triggering API based on input you can trigger an actuator like LED based on results obtained from API for ex: tuning on LED on pin13 if temperature of city >25'c or sooutput.JPG

 

Thats how we can use powerfull feature of Temboo on Arduino Yun without even coding a single line.

 

One more interesting feature that temboo offers is the ability to stream and store sensors reading to online cloud services like Google Big Query and Microsoft power BI, for this you can use WANT TO STREAM SENSOR DATA feature of temboo.stream.JPG

amgalbu

19 - MagicHat first words

Posted by amgalbu Top Member Jun 12, 2015

I completed the mouth and the MagicHat now can speak.

I had to make some changes to the circuit for reading audio output. The new version includes two resistors and a capacitor to shift up voltage level by 2.5V

 

19 - Mouth_bb.png

 

Using an headphone, I cut off one of the speakers and added a connector to be connected to the Arduino board

 

Speaker.jpg

 

The video shows MagicHat saying its first word. "Hello". Unfortunately audio quality is not that good due to my smartphone limitations, but it gives the idea!

In the video, you can also see all the hardware ready to be installed

crjeder

Thoughts on Privacy

Posted by crjeder Jun 12, 2015

An interesting research paper about security vs. privacy. It is about securing the home through "smart" internet connected locks and how it could allow parents to spy on their teenage kids. When the kids circumvent the system in order to regain privacy security is even lower than with a "old-school" solution.

It is relevant to this project because very similar audit logs are produced by the smart key hooks. The information smart key hooks collect is "text-only" which is better accepted by the studies participants than a photo log. The papers authors suggest to reduce the "visibility of the logs":

One way to reduce the visibility of logs is to make the log accessible only on a website (“pull” access), rather than through automatic notification (“push” access)

and:

Another approach to making information less visible without necessarily reducing utility is to present less granular logs. For instance, a teenager who pushes an 11:00 PM curfew would prefer a log that says the teen arived [sic] home “around 11 PM,” as opposed to at “11:13:42 PM.”

That's something worth to consider.

Matilda does not see the light

When Matilda tested the temperature status LED it was clear that it was not going to be visible from outside the cottage. The dark cottage interior sapped away the struggling coloured lumens. However, Matilda spotted that the LED was positioned right opposite the fake painted window on the front of the cottage.

RoofAndLEDHole.jpg

If that could be replaced with a real window then the LED would be clearly visible. Now some people when thinking about new windows would be looking at curtain material and lace edging. Matilda was not that sort of a person, she was thinking about how best to smash a hole the front wall.  Matilda donned her safety glasses and removed the flower box to provide access. She drilled a hole in each corner and then used a cutting disk to join up the sides. Finally the edges were trimmed up to give a clean hole. Matilda was happy with the job.

Windows Cutout

New Windows

Matilda designed some new frames using OpenSCAD and these went through many iterations. The early versions barely looked like Windows at all and an alternative design for Windows 8 was terrible so she returned to a conventional design and Windows 10 turned out ok. She sent the designs off to the blacksmith to be assembled.

 

Frame source: https://github.com/Workshopshed/EnchantedObjects/blob/master/Mechanics/WindowFrame.scad

Frame model: https://github.com/Workshopshed/EnchantedObjects/blob/master/Mechanics/WindowFrame.stl

 

Printing

Remarkably the windows printed correctly first time and the best of the two examples was installed using contact adhesive.

Windows Printed

Windows Installed

Next: Enchanted Objects Design Challenge - The Lode Stone

crjeder

More Datasheet Studying

Posted by crjeder Jun 11, 2015

Some of you might have recognized that I omitted one significant detail in the C code in my last post "Use WS2812B on the SAMA5D4 Xplained":

How is the correct PWM clock frequency of 2.4 MHz configured?

 

Clocks, Clocks and more Clocks

The peripherals of the SAMA5D44 (no, this is not a typo, that's the name of the SOC on the SAMA5D4 Xplainded board) all receive their own clock signal. Relevant for PWM is the peripheral clock as shown in the diagram from the datasheet (page 1448):

clock.png

Most clocks in the SOC are controlled by the Power Management Controller. Contrary to the name this component does not (only) turn the power of integrated devices on and off, it mainly controls the distribution of clock signals. (By not providing a clock signal to a specific component it is turned off.) The programmer can individually request those peripheral clocks to be turned on or off and can select a division factor to be applied to the boards master clock MCK. The factor can be 1, 2, 4 or 8 and is applied to the master clock.

The frequency of the peripheral clock can be calculated by BOARD_MCK / divider. The divider can be read / set through the PMC_PCR register and BOARD_MCK is defined in board.h. This would be nice and easy to use but would work only in a bare metal environment where the clock can not be influenced by other processes. But since I do not intend to dump the Linux running on the board I have to consider these values as variables. Back to the datasheet. It turns out that the relevant values for master clock are the PMC Master Clock Register:

  • CSS: Master/Processor Clock Source Selection
  • PRES: Master/Processor Clock Prescaler
  • MDIV: Master Clock Division

Those values determine the true value of MCK (master clock).

MDIV is an other divisor for the master clock. It can be 1, 2, 3 or 4

The prescaler supports the division by a power of 2 of the selected clock between 1 and 64. The PRES and MDIV fields in PMC_MCKR programm the prescaler.

CSS can have several values to select one of the following clock sources:

  • Slow Clock
  • Main Clock
  • PLLACK
  • UPLL Clock

Now we know which clock source is selected an how it's frequency is divided to yield the peripheral clock. Next step is to find the frequency of the source. All source clocks are provided by the Clock Generator.

Slow clock can be selected to be either the 32 kHz on chip RC oscillator or the external 32768 Hz quartz. Selection is made by the OSCSEL bit in the Slow Clock Controller Configuration Register.

Main clock similarly can be configured to use internal or external 12 MHz sources, therefore is always 12 MHz.

UPLL generates frequencies which are higher than the base frequency (main cock) with a PLL. It is programmed through MULA field of the PMC Clock Generator PLLA Register. The MULA field is the PLLA multiplier factor. This parameter can be programmed between 0 and 127. If MULA is set to 0, PLLA is turned off, otherwise the PLLA output frequency is PLLA input frequency multiplied by (MULA + 1). The output is optionally dived by 2 (selected by PLLADIV2) the to generate PLLACK output.

UPLL Clock is fixed to 480 (40 x 12) MHz for USB High Speed.

The result is divided by the MCK_DIV to yield the frequency of the periphal clock wihch is the input into the PWM clock generation.

In C the above looks like that:

int get_periphal_clock_frequency(uint32_t ID)
 {
    int frequency, mck_div, mula;

    switch(PMC->PMC_MCKR & PMC_MCKR_CSS_Msk)
    {
        case 0:                                 // Slow Clock is selected
            if(SCKC->SCKC_CR & SCKC_CR_OSCSEL)  // XTAL selected
                frequency = 32768;
            else                                // internal RC selected
                frequency = 32000;
            break;
        case 1:                                 // Main Clock is selected
            frequency = 12000000;
            break;
        case 2:                                 // PLLACK is selected
            mula = (PMC->CKGR_PLLAR & CKGR_PLLAR_MULA_Msk) >> CKGR_PLLAR_MULA_Pos;
            frequency = 12000000 * (mula +1);
            break;
        case 3:
            frequency = 480000000;
            break;
    }

    PMC->PMC_PCR = PMC_PCR_PID(ID);     // config PMC register read mode for PWM clock
    mck_div = (PMC->PMC_PCR & 0x00ff00u) >> 8;  // read MCK divider -> PWM clock
    frequency = frequency / mck_div;
    return(frequency);
}
 }

 

Generating the desired frequencies


Back to the original problem, calculate the divisors for the PWM clock:

Now that we know the input to the above diagram we can go ahead and do some basic math. To calculate the parameters PREA and DIVA in order to get the desired frequency we have to calculate and factorize the required divider.

divider = peripheral_clock / desired_frequency

split divider in the form  2^prea×diva

Example:

divider = 260

factors of 260: 2^2×5×13

=> prea = 2 and  diva = 5×13 = 65

How is factorization done? The answer is astonishingly simple: do a trial division! Since we only need to know the factor which is a power of two this is further simplified to this:

int calculate_PWM_dividers(int frequency, int *div, int *pre)
 {
    uint32_t mck_div, f;
    int n;

    frequency = abs(frequency);             // no negative frequency
    f = get_periphal_clock_frequency(ID_PWM);
    *div = f / frequency;                    // required divisor

    // split div into pre and div
    // facorization of divider
    // pre -> power of 2
    // div = all other facors
    for(n=1; n <= 10; n++)
        if(*div % ((int) pow(2, n)) != 0) // if not a multiple of 2^n
            *pre = n - 1;         // then it was a multiple of 2^n-1
    *div = *div / ((int) pow(2, *pre));     // new divisor is the rest
 }

Wrap this code nicely in some error handling code and that's it.

Whilst Matilda worked on the LEDs and top panel, Hans finished off the circuits for the MOSFET power switch and connectors.

 

Circuit Explanation

 

A MOSFET is used as a low side switch to turn the power to the servo, RGB LED controller board and humidity sensor. This is connected to the Arduino output with a few extra components from the Arduino Workshop KitArduino Workshop Kit.

 

The gate of the MOSFET effectively acts like a big capacitor and for a short period before the transistor turns on it can draw a sizeable current. So series resistor R1 is used to limit the current drawn from the pin. A second resistor R2 sinks that charge to ground when the switch is turned off and ensures that the MOSFET remains off when the Arduino is asleep. The ratio of these two resistors needs to be high so that there's not a big voltage drop over R1, as the MOSFET will only switch on when the threshold voltage of 4v is reached. The final component is a protection diode, this dissipates the charge from any inductive loads such as the servo's motor when the MOSTFET is turned off.

 

Power SwitchIRF520 Datasheet

Protoshield

 

By this point the protoshield had been through a few revisions. This was clear by the spaghetti layout of the resulting wires. The headers for the cables were also a problem and had to be bent over to allow the connectors to fit. Some of these also had to be repositioned so that they could fit around the support struts. Given that the MOSFET will mostly be off and switching infrequently, it should not be necessary to attach a heatsink.

ProtoshieldKnock Knock Cable

 

The cable for the new knock knock sensor was also created and Hans realised that the strip board had +V, SIGNAL, GND with the protoshield had SIGNAL, +V, GND as intended so that means the cable will need to be carefully fitted in the correct orientation.  Not an ideal situation but also not a complete disaster.

 

Next: Enchanted Objects Design Challenge - Windows 10

20150609.jpeg

 

 

Today is a turning point for the project. The turntable is finished.

Speed control and light organ with servo lift are built in.

And now that the table is publishing data to the cloud, it's officially a Thing.

 

clean desk

 

If I was a stressful person, a big weight would fall of my shoulders now.

I'm not a stressful person. But I am happy that I reached this point.

A point of luxury and freedom. I still have loads of time to tap into the cloud part. To creativity!

 

 

 

What's Built into the Table

 

There are two Arduinos -Yún and UNO, the Infineon Motor Shield and various electronics.

The Yún has audio sample, light organ+servo lift, and MQTT publishing duty.

 

 

arduino yun under proto board

 

The protoboard on top of the Yún has a one transistor pre-amplifier + DC biaser. The duty of that little circuit is to push the AC audio into the 0->5V range of the Arduino ADC.

It also holds the connectors for the stepper motor and the light organ LEDs.

 

The UNO serves as motor speed controller. It measures the speed from the IR optocoupler that I've built for this project.

 

Photo 15-04-15 17 57 49.jpg

 

The UNO uses the Infineon Motor Shield to control the motor, and also shows what's happening on 3 LEDs (fast - on speed -slow).

 

infineon motor shield

 

Everything runs now, and the Perpetuum Ebner is happily sharing the spectrum analysis on the internet.

 

What Now?

 

I can spend the remaining time on the satellite ideas. They'll tap into that MQTT stream and do something with it.

And unbox the SAMA5D4 again. It's been neglected the last weeks.

And I can also spend a sunny warm evening outside to finalize the mounting of the devices on the sub-chassis.

As you can see on the photo below, there's room for (invisible) improvement there.

 

Photo 09-06-15 20 17 22.jpg

 

 

Table of Contents
Chapter 1: Fix the turntable
1: Perpetuum Ebner Musical 1
2: A Time to Kill and a Time to Heal
3: Preparation for Motor Drive
4: Motor control with Infineon Motor Shield and Arduino UNO
5: Turntable speed sample testbed with Arduino UNO
6: Turntable Speed Sensor design
7: Control Theory - End of Chapter 1
Chapter 2: First Enchantments
8: Digital Light Organ Enchantment
9: Autonomous Servo Lift
10: SMD Time - Solder the IR Speed Sensor PCB
11: Yelp - who can Help me to Compile and Run my First SAMA5D4 C Program
12: Son et Lumiere - End of Chapter 2
Chapter 3: Taming the Board
13: Breakthrough - Run my own C++ Program on the SAMA5D4
14: Digital Light Organ Input Buffer
15: SAMA5D4 Blinky
16: Scope Creep
17: Audio Sampling with 16-bit ADC ADS8343
18: Sending Files to SAMA5D4 over USB
19: Port my Light Organ from Arduino to SAMA5D4
20: Fast Fourier Transform on the SAMA5D4 - End of Chapter 3
Epilogue: Reaching for the Clouds
21: Right-Sizing my Plans
22: My Own C++ Buffered Sampler on the SAMA5D4
Interlude
23: Building In the Motorized Light Organ
24: Up to the Clouds with Yún
25: Publish or Perish
26: Turntable Finished
Stretch & Boni
Bonus 1a: Remote Light Organ with WiFI pt. 1
Bonus 1b: Remote Light Organ with WiFI pt. 2
Grande Finale: Paho MQTT Client on the SAMA5D4
Related blog
Vintage Turntable repair: Can I fix a Perpetuum Ebner from 1958
Review 1: Atmel SMART SAMA5D4 Xplained Ultra Unboxing and First Steps
Review 2: Atmel SMART SAMA5D4 Xplained Ultra - Building the Libraries from Source
Review 3: Digital Continuous Rotation (360°) Servo Part 1
Review 4: Digital Continuous Rotation (360°) Servo Part 2
Review 5: Atmel SMART SAMA5D4 Xplained Ultra - TCP/IP running
Review 6: Atmel SMART SAMA5D4 Xplained Ultra - LINUX Distro with SSH support
poem
Enchanted Objects: Let's work together to tame the ATMEL SMART SAMA5D4 Xplained Ultra kit
17 bis: Off South...
Review 7: Atmel SMART SAMA5D4 Xplained Ultra - C++ ADC Example on Linux
Review 8: Atmel SMART SAMA5D4 Xplained Ultra - Product Review
Review 9a: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 1
Review 9b: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 2
Review 10: Atmel SMART SAMA5D4 Xplained Ultra - New Content on AT91.com
1958 Turntable from the Black Forest - Summary of the Enchanted Player Story

In my last blog post I talk about fetching Weather Information of a desired location using Yahoo Weather API and TEMBOO services on Arduino Yun. The purpose of using Temboo like services in my Design challenge project is to make project as simple as possible and even simpler to replicate so we each can have our own Enchanted Wardrobe in homes . Temboo makes it easy even for non-programmers to have a feel of IoT World and best part it comes pre-bundled with Arduino yun and other Arduino using Ethernet/Wifi/Gsm Shield and some more boards like TI-CC3200, Adafruit CC3000 wifi module and now even with Samsung Artik so you can probably make the same project with any one of them without actually modifying code, Temboo will handle that for you.

 

So progressing ahead, last time we were able to get Weather Information from Yahoo Weather API using Temboo's Choreo but as I mentioned the response from APIs are generally in some encoded form. Similarly Yahoo Weather API returns in  XML(eXtensible Markup Language) or JSON(Java Script Object Notation) which are definitely not human readable but the needed information can be extracted by Parseing this response. For ex to Parse JSON in python we use JSON library similarly we've an ArduinoJsonParser or XML parser library for Arduino which we can use, but Temboo provides more flexibility while handling parseing from APIs it uses in its choreos and similar operation can be performed easily by using what Temboo calls : "OUTPUT FILTERS". Output filters makes easy to parse XML or JSON response from APIs and extract the required information from the returned response container. Here we'll use XML based output filter and you'll see that it is as easy to append just two extra lines in our previous code. So Lets Get Started

 

Before moving Ahead, we should be aware about what different things we can parse from the Yahoo weather API. The WEATHER API by Yahoo provides the following information:

 

>Temperature

>Pressure

>HIGH MARK of Temperature in a day

>LOW MARK of Temperature in a day

>Humidity

>Visibility

>Condition Text(Like Cold/ThunderStorm/Haze etc)

>Condition Code which can be resolved from API's documentation on Yahoo's Website

 

Moving Ahead on Parseing:

 

Step 1>> Complete steps till last blog post .

step2>> Login to Temboo Output Filter webpage, it can also be found on left hand side lowermost tabs on Temboo's homepage.

 

utilities.JPG

 

step 3>> Select XML or JSON if you've requested yahoo to return data in JSON.

step4>> Select Get Values from XML tab.

step5>> In node field you can type data to be extracted say 'temperature' and in XML field add the response(XML) you got from API(in previous blog program).

INPUT.JPG

 

 

step6>> Alternatively you can add following lines of code before  GetWeatherByAddressChoreo.run(); function

 

   GetWeatherByAddressChoreo.addOutputFilter("temperature", "/rss/channel/item/yweather:condition/@temp", "Response");

   GetWeatherByAddressChoreo.addOutputFilter("code", "/rss/channel/item/yweather:condition/@code", "Response");

    GetWeatherByAddressChoreo.addOutputFilter("text", "/rss/channel/item/yweather:condition/@text", "Response");

 

This resolves Temperature, Code and Text from XML in similar fashion you can extract say Humidity.serial.JPG

 

Will be adding a triggered sensor in the next one. Stay Tuned!

More Details on the WS2812B

 

The mysterious signal from my previous post was for a WS2812B LED. It was shown in Fairy Dust has arrived!. It is a RGB LED with integrated controller. The LEDs can be easily chained together:

 

Daisychain

If you are really crazy you can build something like this with those:

 

IMG_7806.jpg

With an estimated power draw of 3 KW and 10.000 WS2812 LEDs this is really insane.

 

But back to the lab:

Besides of the power supply the LEDs use only a single pin for data transfer. The data is transmitted bit-wise by the "mysterious signall" with 8 bit per RGB but in GRB order (for whatever reason). After the last LED a reset signal is sent to start all over again. This is shown in the graph from the datasheet:

 

transmission.PNG

mcb1 pointed me to a link which gives valuable insight into the timing constraints of the protocol. Bottom line: The timing does not matter much as long as you can make sure that around the middle of the period the DIN line has the correct signal applied. No fancy assembly code needed and no high clock frequencies.

 

PWM Implementation of the WS2812B Protocol

 

The Basic flow is straight forward:

WS2812B Driver.png

 

PWM on the SAMA5D4 Xplained

 

There are several options to programm the board. Those I evaluated are (form highest abstraction to lowest):

 

  • Linux driver and API
  • Atmel Software Framework (ASF)
  • Low level GPL API by Atmel

 

The Linux driver does not support any kind of signaling the end of the period. More capable and less abstract is ASF but AFAIK SAMA5 series is not (yet) supported. So back to the ground level and (allmost) manually programm the registers using the GPL API. The following part of the C-code is heavily commented with information from (mainly) the datasheet. It is not yet ready and definitely not tested. But as it has taken me so long to find all this information it is time to publish it anyway:

 


/****
* PWM Initialization
* ------------------
*
* Before using the PWM macrocell, the programmer must first enable the
* peripheral clock in the Power Management Controller (PMC).
  ****/
    PMC_EnablePeripheral(ID_PWM);
    /* Disable to configure the first PWM channel */
    PWMC_DisableChannel(PWM, EXAMPLE_PWM_CHANNEL_INDEX0);

/****
* Before enabling the channels, they must be configured by the software
* application as described below: (p 1466)
* - Unlock User Interface by writing the WPCMD field in the PWM_WPCR.
****/
    PWM.PWM_WPCR |= PWM_WPCR_WPCMD;
/****
* - Configuration of the clock generator (DIVA, PREA, DIVB, PREB in the
*   PWM_CLK register if required).
****/
    mode = PWM_CLK_PREA() | (PWM_CLK_DIVA()); // require 2.4 MHz
    PWMC_ConfigureClocks(PWM, mode);
/****
* - Selection of the clock for each channel (CPRE field in PWM_CMRx)
****/
    mode = 0; // Begin configuring the CPRE register
    mode |= PWM_CMR_CPRE(PWM_CMR_CPRE_CLKA);
/****
* - Configuration of the waveform alignment for each channel
*   (CALG field in PWM_CMRx)
****/
    mode |= !PWM_CMR_CALG; // left alligned
/****
* - Selection of the counter event selection (if CALG = 1) for each
*   channel (CES field in PWM_CMRx)
****/
    mode |= !PWM_CMR_CES; // Don't care since CALG = 0
/****
* - Configuration of the output waveform polarity for each channel
*   (CPOL bit in PWM_CMRx)
  ****/
    mode |= PWM_CMR_CPOL;
    PWM.PWM_CH_NUM[0].PWM_CMR = mode; // Write CMR register
/****
* - Configuration of the period for each channel (CPRD in the
*   PWM_CPRDx register). Writing in PWM_CPRDx register is possible
*   while the channel is disabled. After validation of the channel, the
*   user must use PWM_CPRDUPDx register to update PWM_CPRDx as
*   explained below.
*   Source Clock Selection Criteria (p 1467):
* -- The event number written in the Period Register gives the PWM
*    accuracy. The Duty-Cycle quantum cannot be lower than 1/CPRDx
*    value. The higher the value of PWM_CPRDx, the greater the
*    PWM accuracy.
  ****/
    PWM.PWM_CH_NUM[0].PWM_CPRD |= PWM_CPRD_CPRD(3); // Period length
/****
* - Configuration of the duty-cycle for each channel (CDTY in the
*   PWM_CDTYx register). Writing in PWM_CDTYx register is possible
*   while the channel is disabled. After validation of the channel, the
*   user must use PWM_CDTYUPDx register to update PWM_CDTYx as
*   explained below.
  ****/
    PWM.PWM_CH_NUM[0].PWM_CDTY |= PWM_CDTY_CDTY(0);
/****
* - Configuration of the dead-time generator for each channel (DTH and
*   DTL in PWM_DTx) if enabled (DTE bit in the PWM_CMRx). Writing in
*   the PWM_DTx register is possible while the channel is disabled.
*   After validation of the channel, the user must use PWM_DTUPDx
*   register to update PWM_DTx
  ****/
/****
* - Selection of the synchronous channels (SYNCx in the PWM_SCM
*   register)
  ****/
    PWM.PWM_SCM |= PWM_SCM_SYNC0;
/****
* - Selection of the moment when the WRDY flag and the corresponding
*   DMA transfer request are set (PTRM and PTRCS in the PWM_SCM
*   register)
*
*      PTRM = 0 => DMA transfer request and WRDY are set to ‘1’ as soon as
*   the update period is elapsed
  ****/
    PWM.PWM_SCM |= PWM_SCM_PTRM;
/****
* - Configuration of the update mode (UPDM in PWM_SCM register)
  ****/
    PWM.PWM_SCM |= PPWM_SCM_UPDM_MODE1;
/****
* - Configuration of the update period (UPR in PWM_SCUP register)
*   if needed
  ****/
    PWM.PWM_SCUP = PWM_SCUP_UPR(0); // UPR = 0 -> update every period
/****
* - Configuration of the comparisons (PWM_CMPVx and PWM_CMPMx)
  ****/
    //PWM.PWM_CH_NUM[0] =
/****
* - Configuration of the event lines (PWM_ELMRx)
  ****/
    PWM.PWM_ELMR |= PWM.PWM_ELMR_CSEL0;
/****
* - Configuration of the fault inputs polarity (FPOL in PWM_FMR)
  ****/
    // Unused
/****
* - Configuration of the fault protection (FMOD and FFIL in PWM_FMR,
*   PWM_FPV and PWM_FPE1)
  ****/
    // Unused
/****
* - Enable of the Interrupts (writing CHIDx and FCHIDx in PWM_IER1, and
*   writing WRDYE, ENDTXE,TXBUFE, UNRE, CMPMx and CMPUx in PWM_IER2)
  ****/
    PWM.PWM_IER1 |= PWM_IER1_CHID0;
    PWM.PWM_IER2 |= PWM_IER2_WRDY;
    //PWMC_EnableChannelIt(*PWM, 0); //PWM_IER1 (same?)
/****
* - Enable of the PWM channels (writing CHIDx in the PWM_ENA register)
****/
    PWMC_EnableChannel(PWM, EXAMPLE_PWM_CHANNEL_INDEX0);









 

This is only the setup part, I have still to find out how to calculate the clock frequency / how to programm prescaler and divider to produce a 2.4 MHz PWM signal.

For the beginning I will poll the WRDY signal to find the end of the period an update the CDTY (duty) register manually. For better (multi-tasking) performance I want to update CDTY in the PWM_IrqHandler (interupt handler).

The Crystal Cave

 

It had been a hard week so a trip to the Adam and Eve Inn was in order. Hans and Matilda sat next to the dwarves who for once were not having an argument. The dwarves had recently discovered a new cave lined with amethyst and citrine crystals, they discovered a strange phenomenon that happened on a full moon. Tonight was a full moon so Hans and Matilda were invited to see. They were given hard hats with lights and headed off through the forest to the mine. As they journeyed a wolf howled in the distance. They arrived at the mine and headed into the tunnels. After several turns and forks they arrived at the new workings, "23m below ground" the dwarves told them. As they rounded the corner they were met with purple and yellow twinkles as their torches shone off the mineral deposits. The dwarves told them to find a comfortable place to sit and one by one all of the torches were distinguished. Hans nervously held Matilda's hand, he was not used to such extreme darkness. Matilda on the other hand found it calming and smiled in Hans' direction. Suddenly, light appeared from above, it got rapidly brighter until the whole cave was glowing, it was a magnificent sight. Then as suddenly as it appeared the light faded away. "It happens each day when the sun is overhead" explained the lead dwarf, "but it's better with a full moon as the light is softer". He pointed his torch to a hole in the ceiling, the light reflects of the internal walls of that shaft and bounces all the way down here to the cavern".

 

Extending the LEDs with fibres

 

Matilda realised that this idea of total internal reflection was also how fibre optics works, she wondered if these could be used to extend the LEDs that were deep in the heart of the electronics to the top of the house for display. Some fibres were purchased and Matilda played with bundles of these wrapped in tape to ensure that the light would transmit as desired.

 

She designed a part to fit over the LEDs on the Arduino Yún with slots to take fibres from the LEDs

Fibre Housing R1

The first version of this was printed and had a couple of issues. One of the corners badly distorted where the adhesion to the bed was poor, the second was that the holes were too small so installing the fibres would be challenging. An additional check showed that the holes for the support struts were a bit small so these were increased from 3.2mm to 3.7mm.

Fibre Housing R1 Printed

The new model resolved these issues with bigger slots for fibres, bigger holes and the sharp corners were chopped off.

Fibre Housing R2

That fixed the problems and the new part printed without issue.

FibreHousing2.jpg

A top panel for a couple of switches and 4 lights was also designed, the POWER, WIFI, LED 13 and USB LEDs are to be extended to the panel as all of these can be controlled by our code / hardware.

TopPanel.png

Top Panel

 

Testing the fibres

 

0.5mm fibres were used so that they could be in a straight line for the rectangular LEDs but in a circle on the top panel.

 

 

The fibre housing and top panel work well but the fibres are quite slippy (and have a low melting point) so the heat shrink tubing used to indicate the colours and hold the fibres together is not locking them in place. Some kind of adhesive will need to be added, I suspect Sugru will do the trick.

Fibres Top PanelFibres Arduino

Models

 

Arduino Yún Fibre Housing Design: https://github.com/Workshopshed/EnchantedObjects/blob/master/Mechanics/FibreHousing.scad

Arduino Yún Fibre Housing Model: https://github.com/Workshopshed/EnchantedObjects/blob/master/Mechanics/FibreHousing.stl

 

Top Panel Design: https://github.com/Workshopshed/EnchantedObjects/blob/master/Mechanics/TopPanel.scad

Top Panel Model: https://github.com/Workshopshed/EnchantedObjects/blob/master/Mechanics/FibreHousing.stl

 

Reference

 

Arduino Yun LEDs

 

Next: Enchanted Objects Design Challenge - Turn on and offable

Sorry for the delay in this posting, between working 7 days a week for the past 3 weeks and family I got a bit behind on blogging.

 

Chrystal has been working on the thermostat regulator with the servo for  a bit now. She is wanting to do it on her own so I am letting her learn about the motor and connecting it to the Arduino. She is starting to program it to turn on and off, this has been frustrating at times but she hasn't backed off. I have pictures of her getting mad with frustration but can't post them (She threatened me with pictures she has taken). She is getting it, wait until I tell her it will be integrated into the voice recognition.

 

For the voice recognition update:

 

I am using the Voice Recognition Module V3 "Speak to Control".

 

It is a speaker-dependent voice recognition module. It supports up to 80 voice commands in all. Max 7 voice commands could work at the same time. Any sound could be trained as command. This board has 2 ways to control: Serial Port (full function), General Input Pins (part of function). General Output Pins on the board could generate several kinds of waves while corresponding voice command was recognized.

 

 

Controllers information:

 

 

 

 

 

Parameter

 

 

 

Voltage: 4.5-5.5V

 

Current: <40mA

 

Digital Interface: 5V TTL level for UART interface and GPIO

 

Analog Interface: 3.5mm mono-channel microphone connector + microphone pin interface

 

Size: 31mm x 50mm

 

Recognition accuracy: 99% (under ideal environment)

 

 

 

 

Feature

 

 

 

 

 

Support maximum 80 voice commands, with each voice 1500ms (one or two words speaking)

 

Maximum 7 voice commands effective at same time

 

Arduino library is supplied

 

Easy Control: UART/GPIO

 

 

User-control General Pin Output

 

 

 

Here is a link to the Voice Recognition V3 Arduino library (Download zip file)

 

 

Below are pictures of the module, programming the module and a video of it in operation:

 

Voice recog.jpg

 

Voice recog1.png

 

 

 

The wooden clock is coming along very well, I want to save displaying any pictures of it until I'm complete. This project is the best Chrystal and I have ever done, we continue to learn more about electronics and programming every day.

 

 

Thank you for reading and watching,

 

Dale and Chrystal Winhold

Let us assume that I want to create a signal like this:

 

strange signal

Where:

 

Signal

Name

Duration in

μs ± 150 ns

T0H0.4
T1H0.8
T0L0.85
T1L0.45
Treset> 50

 

The usual way to generate arbitrary signals is called "Bit banging". It requires software to set the output in the "HIGH" and "LOW" state in the exact timing given by the protocol. The timing requirements for this signal look pretty strict that I do not believe that this would be possible or at least not very reliable. So I am looking for some hardware support.

After a lot of head ache and reading datasheets the idea of using the PWM came into my mind.

Bit Banging with PWM

 

Let's look at the signal again:

  • it starts always with "HIGH" and ends with "LOW" (except for reset which is always "LOW")
  • length of signal is 1.25 μs (reset again an exception)
  • 0.05 μs resolution (0.05 is the greatest common divisor of 1.25, 0.4, 0.85 and 0.45)

 

Exact Solution

The signal can be generated with PWM of 1/0.05 μs = 20 MHz frequency. Therefore the "alphabet" above translates to:

 

SymbolDuty %
"0"32
"1"64

 

The PWM frequency of 20 MHz is quite high, can the signal be done approximated with lower frequency?

 

Reasonable Approximation

The odd thing about the spec for this signal is that it is not symmetric, i. E. the high time for "0" is not equal to the low time for "1" as I had expected. Since the rising edge of the signal is every 1.25 μs this allows the receiver to synchronize. The sampling presumably takes place at exactly the half of the time which explains the asymmetry: It gives a safety margin for the timing or rather does not require steep edges.

The tolerance for the falling edge is quite high. I did not recognize it at first sight, but when I converted the whole timing into nano seconds (ns) It's pretty clear:

 

Signal Name

Time of Falling Edge

Nominal [ns]

Time of Falling Edge

Minimal [ns]

Time of Falling Edge

Maximal [ns]

T0H400350550
T1H800650950

 

This allows a much more reasonable approach:

Divide the 125 ns in three sections ad vary the duty cycle between 1/3 and 2/3 or in decimal:

 

SymbolDuty %
"0"33
"1"66

 

The frequency in this case is only 2.4 MHz. That's much better!

 

Reset

 

The reset symbol is an exception - it does not fit in the above timing. It can be generated by 40 periods with a duty cycle of 0%.

Since we are able to generate the signal there is only one question left: What is this for?

 

Usage of the Signal

 

Did you recognize / guess the signal? What do you think it is for?

 

(solution in the next blog post)

rpbruiser

The Genie Takes A Hiatus

Posted by rpbruiser Jun 7, 2015

My apologies for no update this week. This week was exams week leading up to my graduation this Saturday so I had no time to make a post. I attempted to access the Internet through the Yun while at school, but to no avail, unfortunately the Yun does not support WPA2 Enterprise networks. I have finished my code and will post that this upcoming week when I get access to my computer again. I hope everyone else's projects are going well. All I have left is to connect the Yun and double check all runs as it should. This has been a great experience and resume builder and I couldn't have done it without the help all of you provided me. I will update you all later this weeks with the finished product and I hope success comes to all of you and your projects as well.


Thank you,


Parker Ellwanger

amgalbu

MagicHat - 18 - The mouth

Posted by amgalbu Top Member Jun 5, 2015

The last missing piece of hardware to complete the MagicHat is the mouth

The mouth will be a simple VuMeter that continously read the line output from the USB audio card and switch on LEDs accordingly

LEDs will be switched on from the center to the sides to give the impression that the mouth is more open when the sound is louder

 

Here is the circuit schematic

 

18 - Mouth.png

 

and here is the flowchart of the code that switches on and off LEDs

 

18 - The mouth.png

 

NOTE: (threshold1 < threshold2 < threshold3 < threshold4)

In this blog post I'll show you how to fetch weather information from Yahoo Weather API using Temboo services which came pre bundled for Arduino Yun.

 

About TEMBOO:

 

Temboo is an online service which enables developer build Internet enabled applications using 200+ choreos and APIs around the web without actually coding, The temboo generates the required code needed to accomplished work from an API ex Fetching geo coordinates from google services, Weather from yahoo etc. Temboo also supports a large number of boards ranging from Arduino to TEXAS INSTRUMENTS MXP430, CC3200 and now even SAMSUNG ARTIK. You can program them to talk to web using Temboo auto code generation service in IoT mode.

Here I've used Temboo to fetch Weather data of my city using Yahoo Weather API.Sign up on Temboo's Website

 

 

step 1>> Sign up for a Temboo's account on www.temboo.com.

step 2>> Select Arduino Yun as board and turn on IoT mode.

step 3>> On left hand side choose Yahoo Weather > Weather by location choreo.

step 4>> Enter your city credentials and other optional inputs like you want temperature in *c or *f.

step 4>> Copy the generated code and header file.

step 5>> Open Arduino IDE and paste the code, compile and and upload to target board.

step 6>> Open Serial Monitor to check the output.

 

I am attaching the code, just change the header file credentials according to your account info.

 

The data in serial monitor will be a raw XML response from yahoo server from which usefull data can be extracted using Parseing, In next blog post we'll parse the temperature and other data using Temboo output Filters and use them efficiently.

 

2.JPGHomepageWeather ChoreoResponse from API

20150605.jpeg

 

Today I'm taking that great leap to the cloud. The Perpetuum Ebner goes online and publishes what's happening.

 

 

What is the Turntable Publishing?

 

I have 3 interesting sets of data available in my design.

  • The raw sampled data, 128 8-bit samples covering the audio frequency range (signal B).
  • That same information transposed to the frequency domain: 64 buckets, each representing a subset of that frequency spectrum (signal C).
  • Those 64 buckets grouped into a Bass, Mid and High range (signal D). That's the info that drives the LEDs of the light organ.

 

enchanted_objects enchanted_player

 

I could publish any of the three. To make the decision, I thought about what the consumer is going to do with the data.

 

My plan is to make a remote light organ, and a WiFi spectrum display.

For the light organ, signal D would be OK. In that case I could even simplify the signal and stick with 2 bits to hold the on-off information for the 3 LEDs.

But if I want to keep the options open for a wireless spectrum display, I'll need signal C. That signal is also usable as source for the remote light organ.

 

The easiest decision would be to send signal B, the full samples. But engineering is about making decisions and trade-offs.

I'm not painting myself in a corner here. In the future I can always switch to signal B if needed. I could publish them in parallel until all subscribers are converted, and then switch of signal C.

 

Firmware with MQTT Publishing

 

The firmware builds upon the previous versions. The only addition is that I now publish the 64 buckets every 20th sample.

This is again a trade-off. My design can go faster, but I figure that eclipse.org doesn't like to be hammered by my data every few milliseconds.

So I settled for the lowest speed that would still give an interesting and lively visual result.

 

 

I subscribed to my data with eclipse PaHo client. The screen capture above shows the received data. It's normal that the characters don't display right, because the payload isn't text. It's 64 8-bit nuggets of info.

 

And here's the latest firmware:

 

 

// includes for servo
#include <Servo.h>


// includes for light organ
#include <fix_fft.h>




// MQTT  includes start
#include <Bridge.h>
#include <SPI.h>
#include <YunClient.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>


#include <string.h>
// MQTT includes end








// servo declaration


Servo servo;


#define SERVO_PIN 9
#define SERVO_DELAY 25
#define SERVO_BASE 90
#define SERVO_TOP (SERVO_BASE + 61)


int servoPos = SERVO_BASE;
bool servoUp = false;






// light organ declaration


#define MUESTRAS 128           // Numero de muestras para el cálculo de la FFT
#define LOGM 7                 // Logaritmo en base 2 del número de muestras


#define BAJOS_MEDIOS 7         // Nº de banda para el corte entre Bajos y Medios
#define MEDIOS_AGUDOS 35       // Nº de banda para el corte entre Medios y Agudos


#define BPIN  13                // Pin de salida Bajos
#define MPIN  12               // Pin de salida Medios
#define APIN  11               // Pin de salida Agudos
#define TIMERPIN 8




#define MAX_PASADAS 10         // Nº de pasadas para el cálculo de los lÃmites


char data[MUESTRAS];           // Array con los valores muestreados (parte real)
char im[MUESTRAS];             // Array con los valores muestreados (parte imaginaria)


unsigned char salida[MUESTRAS/2];  // Valores obtenidos de la FFT (espectro de 64 bandas)
unsigned char bajos,medios,agudos; // Valores calculados para cada canal


byte  pasada,                            // nº de pasada para el cáculo de los lÃmites
      acumBajos,acumMedios,acumAgudos,   // acumuladores de veces que se supera el lÃmite
      limBajos,limMedios,limAgudos;      // lÃmites calculados para cada canal




// start MQTT declarations
YunClient c; // replace by a YunClient if running on a Yun
IPStack ipstack(c);
MQTT::Client<IPStack, Countdown> client = MQTT::Client<IPStack, Countdown>(ipstack);
char payLoadBuf[MUESTRAS/2] = {}; // I'm going to give one byte per range, so that I can choose to implement a graph if I want.
const char* send_topic = "PerpetuumEbnerSpectrum";
const char* _id = "1cfee8dd0afc_yun";
// end MQTT declarations






// both:
// decay is a decreasing counter that tells how long the servo will stay up after the last led flashed.
// reset to DECAY each time a led lights up
// looses one live each time no leds are active
#define DECAY 150U
unsigned int uDecay = 0U;




// servo functionality


void servoInit() {
    servoUp = false;
    servo.attach(SERVO_PIN);
    servoPos = SERVO_BASE;
    servo.write(SERVO_BASE);
    delay(1000);
}


void servoGoUp() {

  if (servoPos < SERVO_BASE) {
    servoInit();
  }

  if (servoPos < SERVO_TOP) {
    servoPos++;
    servo.write(servoPos);
    delay(SERVO_DELAY);
  }
}


void servoGoDown() {

  if (servoPos < SERVO_BASE) {
    servoInit();
  }

  if (servoPos > SERVO_BASE) {
    servoPos--;
    servo.write(servoPos);
    delay(SERVO_DELAY);
  }
}


void servoGo() {
  if (servoUp) {
    servoGoUp();
  } else {
    servoGoDown();
  }
}




// light organ fuctions


/*
* Funcion que aplica una ventana de Hann a los datos muestreados para reducir el
* efecto de las discontinuidades en los extremos
*/
void aplicaVentana (char *vData) {
    double muestrasMenosUno = (double(MUESTRAS) - 1.0);
  // Como la ventana es simétrica , se calcula para la mitad y se aplica el factor por los dos extremos
    for (uint8_t i = 0; i < MUESTRAS/2 ; i++) {
        double indiceMenosUno = double(i);
        double ratio = (indiceMenosUno / muestrasMenosUno);
        double factorPeso = 0.5 * (1.0 - cos(6.28 * ratio));
  vData[i] *= factorPeso;
  vData[MUESTRAS - (i + 1)] *= factorPeso;
    }
}




void lightOrganSetup() {
    // Configuramos el prescaler a 32 -> 16Mhz/32 = 500 KHz
    // como cada conversion son 13 ciclos 500/13 ~ 38.4KHz
    // Es decir podemos medir en teoria hasta unos 19KHz,
    // que para este proyecto sobra.
    bitWrite(ADCSRA,ADPS2,1);
    bitWrite(ADCSRA,ADPS1,0);
    bitWrite(ADCSRA,ADPS0,1);


    // Como la señal es muy baja,utilizamos la referencia interna
    // de 1.1 V en vez de la de defecto de 5 V.
    analogReference(INTERNAL);  
   
    // Salidas para los canales de Bajos,Medios y Agudos
    pinMode(BPIN,OUTPUT);
    pinMode(MPIN,OUTPUT);
    pinMode(APIN,OUTPUT);
   
   
    // debug
    pinMode(TIMERPIN,OUTPUT);
    Serial.begin(9600);


    // Variables para el cálculo de los lÃmites
    pasada = 0;
    acumBajos = acumMedios = acumAgudos = 0;
    limBajos = limMedios = limAgudos = 50; 

  }


void lightOrganGo() {
    // Realizamos el muestreo
//    Serial.println("Start sampling:");
    digitalWrite(TIMERPIN, HIGH);
    for( int i=0; i < MUESTRAS; i++) {
       data[i] = analogRead(0)/4 -128;  //Convertimos de 0..1024 a -128..127                                
       im[i] = 0;                       // parte imaginaria = 0                         
    }
    digitalWrite(TIMERPIN, LOW);
   
/*     
    {
    Serial.println(" samples\n");
    for( int i=0; i < MUESTRAS; i++) {
      Serial.print(data[i], DEC);
      Serial.print(",");
    }
    Serial.println(" ---");
   
    }
*/   


    // Aplicamos la ventana de Hann
    aplicaVentana (data);


/*
    Serial.println(" window\n");
    for( int i=0; i < MUESTRAS; i++) {
      Serial.print(data[i], DEC);
      Serial.print(",");
    }
    Serial.println(" ---");
*/
    // Calculamos la FFT
    fix_fft(data,im,LOGM,0);
   
    // Sólo nos interesan los valores absolutos, no las fases, asi que
    // calculamos el módulos de los vectores re*re + im*im.
    // Dado que los valores son pequeños utilizamos el cuadrado
    for (int i=0; i < MUESTRAS/2; i++){
       salida[i] = data[i] * data[i] + im[i] * im[i];
       payLoadBuf[i] = salida[i];
    }
/*
    Serial.println(" result\n");
     for( int i=0; i < MUESTRAS/2; i++) {
      Serial.print(salida[i], DEC);
      Serial.print(",");
    }
    Serial.println(" ---");
*/
  
    // Ahora repartimos las bandas entre las 3 salidas
    // En vez de sacar la media, utilizo sólo el valor máximo de
    // una banda
    bajos = 0;
    for (int i=2; i < BAJOS_MEDIOS; i++){
      bajos += salida[i];
    }
    bajos = bajos/2;
   
    medios = 0;
    for (int i=BAJOS_MEDIOS ; i < MEDIOS_AGUDOS; i++){
      medios += salida[i];
    }
    medios = medios/2;
   
    agudos = 0;
    for (int i=MEDIOS_AGUDOS; i < MUESTRAS/2; i++){
      agudos += /*2**/(salida[i]);   // jc 20150604 undid because Yun ADC more sensitive or so // 20150601 doubled the highs sesitivity
    }
    agudos = agudos/2;
   
   // Calculamos si el canal correspondiente
   // supera le lÃmite para encenderlo
   int siBajos  =  bajos  > limBajos;
   int siMedios =  medios > limMedios;
   int siAgudos =  agudos > limAgudos;
  
   digitalWrite(BPIN,siBajos ? HIGH : LOW);
   digitalWrite(MPIN,siMedios? HIGH : LOW);
   digitalWrite(APIN,siAgudos? HIGH : LOW);
  
   // Utilizamos las veces que se supera para
   // recalcular el lÃmite y evitar que con los
   // cambios de volumen los canales se saturen
   // o no funcionen.
   acumBajos  += siBajos;
   acumMedios += siMedios;
   acumAgudos += siAgudos;
  
   if ( ++pasada > MAX_PASADAS ) {
      pasada = 0;
      limBajos  = 20 + acumBajos*5;
      limMedios = 20 + acumMedios*5;
      limAgudos = 20 + acumAgudos*5;
      acumBajos  = 0;
      acumMedios = 0;
      acumAgudos = 0;
   }


   if (siBajos | siMedios /*| siAgudos*/) { // jc 20150601 renew lift up decay if a led is on,
                                            // ignore highs because I've made them more sensitive above
     uDecay = DECAY;
   } else if (uDecay > 0) {
     uDecay--;
   }
  
}


// MQTT start


char printbuf[100];




void mqttInit() {
//  Ethernet.begin(mac); // replace by Bridge.begin() if running on a Yun
  Bridge.begin();


  connect();
} 


void connect()  // connect to the MQTT broker
{
  char hostname[] = "iot.eclipse.org";
  int port = 1883;
  sprintf(printbuf, "Connecting to %s:%d\n", hostname, port);
  Serial.print(printbuf);


  int rc = ipstack.connect(hostname, port);
  if (rc != 1)
  {
    sprintf(printbuf, "rc from TCP connect is %d\n", rc);
    Serial.print(printbuf);
  }

  Serial.println("MQTT connecting");
  MQTTPacket_connectData data = MQTTPacket_connectData_initializer;      
  data.MQTTVersion = 3;
  data.clientID.cstring = (char*)_id;
  rc = client.connect(data);
  if (rc != 0)
  {
    sprintf(printbuf, "rc from MQTT connect is %d\n", rc);
    Serial.print(printbuf);
  }

  Serial.println("MQTT connected");

}


void sendMessage() {
  if (!client.isConnected())
    connect();

  MQTT::Message message;



  int rc;
  // Send QoS 1 message
  // // Serial.println(payLoadBuf);
  message.qos = MQTT::QOS1;
  message.retained = false;
  message.dup = false;
  message.payload = (void*)payLoadBuf;
  message.payloadlen = strlen(payLoadBuf)+1;
  rc = client.publish(send_topic, message);
} 


// end MQTT functionality ==============================




























// arduino general


void setup()
{


  Serial.begin(9600);
  delay(10000); // give me time to start the yun monitor
servoInit();
  lightOrganSetup();
  // MQTT related tasks
  mqttInit();
}


void loop()
{
static unsigned int counter = 0;




  /*
  // lift debug
  while (Serial.available() > 0) {
    uDecay = (Serial.parseInt());
  }
  */




  servoUp = (uDecay > 0);



  servoGo(); 
  lightOrganGo();
  if (uDecay > 0) {
    counter++;
    if (counter == 20) {
      counter = 0;
      sendMessage();
    }
  }

}

 

Feel free to subscribe and animate your own gizmo.

 

 

Table of Contents
Chapter 1: Fix the turntable
1: Perpetuum Ebner Musical 1
2: A Time to Kill and a Time to Heal
3: Preparation for Motor Drive
4: Motor control with Infineon Motor Shield and Arduino UNO
5: Turntable speed sample testbed with Arduino UNO
6: Turntable Speed Sensor design
7: Control Theory - End of Chapter 1
Chapter 2: First Enchantments
8: Digital Light Organ Enchantment
9: Autonomous Servo Lift
10: SMD Time - Solder the IR Speed Sensor PCB
11: Yelp - who can Help me to Compile and Run my First SAMA5D4 C Program
12: Son et Lumiere - End of Chapter 2
Chapter 3: Taming the Board
13: Breakthrough - Run my own C++ Program on the SAMA5D4
14: Digital Light Organ Input Buffer
15: SAMA5D4 Blinky
16: Scope Creep
17: Audio Sampling with 16-bit ADC ADS8343
18: Sending Files to SAMA5D4 over USB
19: Port my Light Organ from Arduino to SAMA5D4
20: Fast Fourier Transform on the SAMA5D4 - End of Chapter 3
Epilogue: Reaching for the Clouds
21: Right-Sizing my Plans
22: My Own C++ Buffered Sampler on the SAMA5D4
Interlude
23: Building In the Motorized Light Organ
24: Up to the Clouds with Yún
25: Publish or Perish
26: Turntable Finished
Stretch & Boni
Bonus 1a: Remote Light Organ with WiFI pt. 1
Bonus 1b: Remote Light Organ with WiFI pt. 2
Grande Finale: Paho MQTT Client on the SAMA5D4
Related blog
Vintage Turntable repair: Can I fix a Perpetuum Ebner from 1958
Review 1: Atmel SMART SAMA5D4 Xplained Ultra Unboxing and First Steps
Review 2: Atmel SMART SAMA5D4 Xplained Ultra - Building the Libraries from Source
Review 3: Digital Continuous Rotation (360°) Servo Part 1
Review 4: Digital Continuous Rotation (360°) Servo Part 2
Review 5: Atmel SMART SAMA5D4 Xplained Ultra - TCP/IP running
Review 6: Atmel SMART SAMA5D4 Xplained Ultra - LINUX Distro with SSH support
poem
Enchanted Objects: Let's work together to tame the ATMEL SMART SAMA5D4 Xplained Ultra kit
17 bis: Off South...
Review 7: Atmel SMART SAMA5D4 Xplained Ultra - C++ ADC Example on Linux
Review 8: Atmel SMART SAMA5D4 Xplained Ultra - Product Review
Review 9a: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 1
Review 9b: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 2
Review 10: Atmel SMART SAMA5D4 Xplained Ultra - New Content on AT91.com
1958 Turntable from the Black Forest - Summary of the Enchanted Player Story

I went through and interesting article here

 

Basically, what they state is that once you got the correspondence between biosignal ADC reading and maximum blood pressure, you can determine systolic and diastolic pressure by applying a linear equation on the minimum and maximum ADC reading for each heart beat

 

So I have a very simple (yet not optimal) solution to the problem of determining the systolic and diastolic pressure

The flow chart of the process for measuring blood pressure is as follow

 

17 - Blood pressure measurement.png

No volts

When Hans wired up the comparator circuit he could not get the output to go high. He swapped out the sensor with a simple voltage divider but still nothing. Thinking that he'd got a duff component he tried another, still the output stayed on 0v. The data sheet provided a clue, the output needed a pull up resistor, it could only act as a current sink.

Driving CMOS

The resistor was added and the voltage divider circuit behaved as expected, switching from low to high as the trim pot was adjusted.

 

Updated circuit

The full circuit was re-instated and that also tested successfully.

Comparator on boardboardPiezo Comparator Circuit 2

This circuit would ideally be tested with an oscilloscope so you could see the low voltage jagged signal from the piezo transducer and the clean output from the comparator. Not having a scope, Hans tested it with his trusty multimeter checking that there was a good swing on the output when he tapped on the transducer. Even on the input, the transducer seemed to be able to create voltages up to 3v which is quite bizarre thinking that it's just a sliced up piece of rock.

 

Boarding it up

Given that there were no special requirements for the board and the component count is low, stripboard was chosen for making up the circuit. Also the protoboard was already full and there was some stripboard in the back of the spares drawer. The board layout was sketched on lined paper and then the parts were test fitted on the board to ensure there was space for everything.

ComparatorStripboard.jpg

There was not much space in their extension so the new board was placed in the loft also meaning that the wiring to the transducer could be kept short.

RoofElectronics.jpg

Another cable was made up to connect this back to the main board and a hole drilled in the back of the roof space to fit the connector through. A wooden support was made to hold the board to the roof and the transducer was connected using double sided tape.

 

Next: Enchanted Objects Design Challenge - The Crystal Cave

enchanted objects

 

It's time to connect my turntable to the internet. We're in the last month, and I haven't sent a single bit to the cloud.

That's about to change.

I'm preparing my fixture to publish information. It's going to be a two-step exercise.

First, I'm going to share the light organ info. I'll send the state of my Highs; Mids and Lows LEDs to the world.

Once I have that working, I'm going to add speed info: is my Perpetuum Ebner running slow, fast or perfect.

 

Arduino Yun

 

 

 

From UNO to Yún

 

My UNO was running the light organ and servo lift code. Today's exercise is taking care that that info is ported to the Yún.

And to check that there's enough space left to talk to the cloud.

That was a fairly easy task. To cut a long story short: the code just ported straight away.

 

 

There's a tendency to play down the Arduino concept. But I'm very sold into it.

It's a great platform to try out new things with an easy step-in cost; there are libraries for so many things.

If you want to go low level, you can just do that. Nothing stops you from going bare metal.

When I have difficulties talking to a particular ship, I often turn to an Arduino to set up a prototype that I can probe with my logic analyzer.

 

And in this particular project, I can just switch to a WiFI enabled Yún. Just like that.

It's at those moments that you really understand why Arduino has had such an impact.

 

There wasn't any software issue during the switch. I changed port and board type, loaded the code, and off I went.

There is a slight difference in sensitivity of the ADC that I have to fine-tune.

I haven't found the reason for it yet, but particularly in the high frequency range, the Yún's ADC is more sensitive than the UNO's.

This results in my green Highs LED being on more often.

That's something I can compensate in software. But I'm still curious on why that happens. I'll have to pull up Atmel's data sheets.

 

The second thing to consider when porting, is the form factor of the Yún. More specific: the USB and ethernet connectors.

The protoboard that's part of the enchanted objects package doesn't fit out of the box.

This is what I have done to it:

 

Photo 28-05-15 10 40 47.jpg

I used my fake dremel and sliced the board in half. That way it fits on the Yún.

I loose the SMD pads - something I would have liked to use, I have some nice Texas Instruments SMD opamps - but you can't have it all.

 

Photo 03-06-15 19 25 59.jpg

 

 

With both hardware and software ported, I'm ready to reach for the clouds.

 

MQTT and Me

 

I have previous experience with the protocol. I've used it for my Christmas Wreath of Things.

If I'm expecting an issue, it would be space or compatibility related.

Regarding space, I'm optimistic. I tried to add the MQTT libraries to my sketch, and initialize some objects to get an appreciation of the memory use.

 

Sketch uses 16,356 bytes (57%) of program storage space. Maximum is 28,672 bytes.
Global variables use 1,138 bytes (44%) of dynamic memory, leaving 1,422 bytes for local variables. Maximum is 2,560 bytes.

 

Nothing alarming there.

 

Library incompatibility is something more difficult in the Arduino world. In particular when libraries are using lower level components of the controller.

I have issues in my design. The motor PWM engine, speed sampler and servo libraries compete for the same hardware timer.(and are incompatible because of that).

I solved that by using two different Arduinos. It's a bit silly because one ATMega has enough juice to do all the work.

The right approach would be to either find libraries that work together, or write my own firmware.

I'll leave that as an academic exercise for the reader.

I'm just hoping here that the Servo lib is compatible with the MQTT and Bridge part...

 

 

Table of Contents
Chapter 1: Fix the turntable
1: Perpetuum Ebner Musical 1
2: A Time to Kill and a Time to Heal
3: Preparation for Motor Drive
4: Motor control with Infineon Motor Shield and Arduino UNO
5: Turntable speed sample testbed with Arduino UNO
6: Turntable Speed Sensor design
7: Control Theory - End of Chapter 1
Chapter 2: First Enchantments
8: Digital Light Organ Enchantment
9: Autonomous Servo Lift
10: SMD Time - Solder the IR Speed Sensor PCB
11: Yelp - who can Help me to Compile and Run my First SAMA5D4 C Program
12: Son et Lumiere - End of Chapter 2
Chapter 3: Taming the Board
13: Breakthrough - Run my own C++ Program on the SAMA5D4
14: Digital Light Organ Input Buffer
15: SAMA5D4 Blinky
16: Scope Creep
17: Audio Sampling with 16-bit ADC ADS8343
18: Sending Files to SAMA5D4 over USB
19: Port my Light Organ from Arduino to SAMA5D4
20: Fast Fourier Transform on the SAMA5D4 - End of Chapter 3
Epilogue: Reaching for the Clouds
21: Right-Sizing my Plans
22: My Own C++ Buffered Sampler on the SAMA5D4
Interlude
23: Building In the Motorized Light Organ
24: Up to the Clouds with Yún
25: Publish or Perish
26: Turntable Finished
Stretch & Boni
Bonus 1a: Remote Light Organ with WiFI pt. 1
Bonus 1b: Remote Light Organ with WiFI pt. 2
Grande Finale: Paho MQTT Client on the SAMA5D4
Related blog
Vintage Turntable repair: Can I fix a Perpetuum Ebner from 1958
Review 1: Atmel SMART SAMA5D4 Xplained Ultra Unboxing and First Steps
Review 2: Atmel SMART SAMA5D4 Xplained Ultra - Building the Libraries from Source
Review 3: Digital Continuous Rotation (360°) Servo Part 1
Review 4: Digital Continuous Rotation (360°) Servo Part 2
Review 5: Atmel SMART SAMA5D4 Xplained Ultra - TCP/IP running
Review 6: Atmel SMART SAMA5D4 Xplained Ultra - LINUX Distro with SSH support
poem
Enchanted Objects: Let's work together to tame the ATMEL SMART SAMA5D4 Xplained Ultra kit
17 bis: Off South...
Review 7: Atmel SMART SAMA5D4 Xplained Ultra - C++ ADC Example on Linux
Review 8: Atmel SMART SAMA5D4 Xplained Ultra - Product Review
Review 9a: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 1
Review 9b: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 2
Review 10: Atmel SMART SAMA5D4 Xplained Ultra - New Content on AT91.com
1958 Turntable from the Black Forest - Summary of the Enchanted Player Story

20150601.jpg

 

In this episode, I'm combining the light organ and the servo control into one Arduino UNO..

It's also the first provisional attempt of mounting into the base of the turntable.

 

 

igonic.jpg

 

How the Light Organ and the Servo Lift Work Together

 

I want the light organ and the lift to just work together, without me having to worry about them.

In previous posts I have introduced the autonomous light organ and the autonomous lift.

They are now combined on a single Arduino, but still have a life of their own.

 

As soon as the music plays, the light organ will do its work and starts flashing its LEDs.

At the same time, it will tell the servo to move up and stay up for a while (its lifespan: 150 while loops).

Each time a LED is active, it renews the lifespan. But when there's no LED on, one point is taken from the lifespan.

If all the lifepoints are taken, the servo retreats and moves the LEDS back inside the case.

 

A video says more than 1000 words:

 

 

The code is simple. Search for the word decay to find out what's happening.

 

 

 

 

 

#include <Servo.h>
#include <fix_fft.h>


// servo declaration


Servo servo;


#define SERVO_PIN 9
#define SERVO_DELAY 25
#define SERVO_BASE 90
#define SERVO_TOP (SERVO_BASE + 61)


int servoPos = SERVO_BASE;
bool servoUp = false;






// light organ declaration


#define MUESTRAS 128           // Numero de muestras para el cálculo de la FFT
#define LOGM 7                 // Logaritmo en base 2 del número de muestras


#define BAJOS_MEDIOS 7         // Nº de banda para el corte entre Bajos y Medios
#define MEDIOS_AGUDOS 35       // Nº de banda para el corte entre Medios y Agudos


#define BPIN  13                // Pin de salida Bajos
#define MPIN  12               // Pin de salida Medios
#define APIN  11               // Pin de salida Agudos
#define TIMERPIN 8




#define MAX_PASADAS 10         // Nº de pasadas para el cálculo de los lÃmites


char data[MUESTRAS];           // Array con los valores muestreados (parte real)
char im[MUESTRAS];             // Array con los valores muestreados (parte imaginaria)


unsigned char salida[MUESTRAS/2];  // Valores obtenidos de la FFT (espectro de 64 bandas)
unsigned char bajos,medios,agudos; // Valores calculados para cada canal


byte  pasada,                            // nº de pasada para el cáculo de los lÃmites
      acumBajos,acumMedios,acumAgudos,   // acumuladores de veces que se supera el lÃmite
      limBajos,limMedios,limAgudos;      // lÃmites calculados para cada canal








// both:
// decay is a decreasing counter that tells how long the servo will stay up after the last led flashed.
// reset to DECAY each time a led lights up
// looses one live each time no leds are active
#define DECAY 150U
unsigned int uDecay = 0U;




// servo functionality


void servoInit() {
    servoUp = false;
    servo.attach(SERVO_PIN);
    servoPos = SERVO_BASE;
    servo.write(SERVO_BASE);
    delay(1000);
}


void servoGoUp() {

  if (servoPos < SERVO_BASE) {
    servoInit();
  }

  if (servoPos < SERVO_TOP) {
    servoPos++;
    servo.write(servoPos);
    delay(SERVO_DELAY);
  }
}


void servoGoDown() {

  if (servoPos < SERVO_BASE) {
    servoInit();
  }

  if (servoPos > SERVO_BASE) {
    servoPos--;
    servo.write(servoPos);
    delay(SERVO_DELAY);
  }
}


void servoGo() {
  if (servoUp) {
    servoGoUp();
  } else {
    servoGoDown();
  }
}




// light organ fuctions


/*
* Funcion que aplica una ventana de Hann a los datos muestreados para reducir el
* efecto de las discontinuidades en los extremos
*/
void aplicaVentana (char *vData) {
    double muestrasMenosUno = (double(MUESTRAS) - 1.0);
  // Como la ventana es simétrica , se calcula para la mitad y se aplica el factor por los dos extremos
    for (uint8_t i = 0; i < MUESTRAS/2 ; i++) {
        double indiceMenosUno = double(i);
        double ratio = (indiceMenosUno / muestrasMenosUno);
        double factorPeso = 0.5 * (1.0 - cos(6.28 * ratio));
  vData[i] *= factorPeso;
  vData[MUESTRAS - (i + 1)] *= factorPeso;
    }
}




void lightOrganSetup() {
    // Configuramos el prescaler a 32 -> 16Mhz/32 = 500 KHz
    // como cada conversion son 13 ciclos 500/13 ~ 38.4KHz
    // Es decir podemos medir en teoria hasta unos 19KHz,
    // que para este proyecto sobra.
    bitWrite(ADCSRA,ADPS2,1);
    bitWrite(ADCSRA,ADPS1,0);
    bitWrite(ADCSRA,ADPS0,1);


    // Como la señal es muy baja,utilizamos la referencia interna
    // de 1.1 V en vez de la de defecto de 5 V.
    analogReference(INTERNAL); 
  
    // Salidas para los canales de Bajos,Medios y Agudos
    pinMode(BPIN,OUTPUT);
    pinMode(MPIN,OUTPUT);
    pinMode(APIN,OUTPUT);
  
  
    // debug
    pinMode(TIMERPIN,OUTPUT);
    Serial.begin(9600);


    // Variables para el cálculo de los lÃmites
    pasada = 0;
    acumBajos = acumMedios = acumAgudos = 0;
    limBajos = limMedios = limAgudos = 50;

  }


void lightOrganGo() {
    // Realizamos el muestreo
//    Serial.println("Start sampling:");
    digitalWrite(TIMERPIN, HIGH);
    for( int i=0; i < MUESTRAS; i++) {
       data[i] = analogRead(0)/4 -128;  //Convertimos de 0..1024 a -128..127                               
       im[i] = 0;                       // parte imaginaria = 0                        
    }
    digitalWrite(TIMERPIN, LOW);
  
/*    
    {
    Serial.println(" samples\n");
    for( int i=0; i < MUESTRAS; i++) {
      Serial.print(data[i], DEC);
      Serial.print(",");
    }
    Serial.println(" ---");
  
    }
*/  


    // Aplicamos la ventana de Hann
    aplicaVentana (data);


/*
    Serial.println(" window\n");
    for( int i=0; i < MUESTRAS; i++) {
      Serial.print(data[i], DEC);
      Serial.print(",");
    }
    Serial.println(" ---");
*/
    // Calculamos la FFT
    fix_fft(data,im,LOGM,0);
  
    // Sólo nos interesan los valores absolutos, no las fases, asi que
    // calculamos el módulos de los vectores re*re + im*im.
    // Dado que los valores son pequeños utilizamos el cuadrado
    for (int i=0; i < MUESTRAS/2; i++){
       salida[i] = data[i] * data[i] + im[i] * im[i];
    }
/*
    Serial.println(" result\n");
     for( int i=0; i < MUESTRAS/2; i++) {
      Serial.print(salida[i], DEC);
      Serial.print(",");
    }
    Serial.println(" ---");
*/

    // Ahora repartimos las bandas entre las 3 salidas
    // En vez de sacar la media, utilizo sólo el valor máximo de
    // una banda
    bajos = 0;
    for (int i=2; i < BAJOS_MEDIOS; i++){
      bajos += salida[i];
    }
    bajos = bajos/2;
  
    medios = 0;
    for (int i=BAJOS_MEDIOS ; i < MEDIOS_AGUDOS; i++){
      medios += salida[i];
    }
    medios = medios/2;
  
    agudos = 0;
    for (int i=MEDIOS_AGUDOS; i < MUESTRAS/2; i++){
      agudos += 2*(salida[i]);   // jc 20150601 doubled the highs sesitivity
    }
    agudos = agudos/2;
  
   // Calculamos si el canal correspondiente
   // supera le lÃmite para encenderlo
   int siBajos  =  bajos  > limBajos;
   int siMedios =  medios > limMedios;
   int siAgudos =  agudos > limAgudos;

   digitalWrite(BPIN,siBajos ? HIGH : LOW);
   digitalWrite(MPIN,siMedios? HIGH : LOW);
   digitalWrite(APIN,siAgudos? HIGH : LOW);

   // Utilizamos las veces que se supera para
   // recalcular el lÃmite y evitar que con los
   // cambios de volumen los canales se saturen
   // o no funcionen.
   acumBajos  += siBajos;
   acumMedios += siMedios;
   acumAgudos += siAgudos;

   if ( ++pasada > MAX_PASADAS ) {
      pasada = 0;
      limBajos  = 20 + acumBajos*5;
      limMedios = 20 + acumMedios*5;
      limAgudos = 20 + acumAgudos*5;
      acumBajos  = 0;
      acumMedios = 0;
      acumAgudos = 0;
   }


   if (siBajos | siMedios /*| siAgudos*/) { // jc 20150601 renew lift up decay if a led is on,
                                            // ignore highs because I've made them more sensitive above
     uDecay = DECAY;
   } else if (uDecay > 0) {
     uDecay--;
   }

}


// arduino general


void setup()
{


  Serial.begin(9600);
  servoInit();
  lightOrganSetup();
//  Serial.println("Menu: Up: 1, Down: 0");
}


void loop()
{
  // lift debug
  while (Serial.available() > 0) {
    uDecay = (Serial.parseInt());
  }




  servoUp = (uDecay > 0);



  servoGo();
  lightOrganGo();

}


 

Next, I,ll move the code to a Yún and include MQTTing of the Highs, Mids and Lows info to the cloud.

 

 

Table of Contents
Chapter 1: Fix the turntable
1: Perpetuum Ebner Musical 1
2: A Time to Kill and a Time to Heal
3: Preparation for Motor Drive
4: Motor control with Infineon Motor Shield and Arduino UNO
5: Turntable speed sample testbed with Arduino UNO
6: Turntable Speed Sensor design
7: Control Theory - End of Chapter 1
Chapter 2: First Enchantments
8: Digital Light Organ Enchantment
9: Autonomous Servo Lift
10: SMD Time - Solder the IR Speed Sensor PCB
11: Yelp - who can Help me to Compile and Run my First SAMA5D4 C Program
12: Son et Lumiere - End of Chapter 2
Chapter 3: Taming the Board
13: Breakthrough - Run my own C++ Program on the SAMA5D4
14: Digital Light Organ Input Buffer
15: SAMA5D4 Blinky
16: Scope Creep
17: Audio Sampling with 16-bit ADC ADS8343
18: Sending Files to SAMA5D4 over USB
19: Port my Light Organ from Arduino to SAMA5D4
20: Fast Fourier Transform on the SAMA5D4 - End of Chapter 3
Epilogue: Reaching for the Clouds
21: Right-Sizing my Plans
22: My Own C++ Buffered Sampler on the SAMA5D4
Interlude
23: Building In the Motorized Light Organ
24: Up to the Clouds with Yún
25: Publish or Perish
26: Turntable Finished
Stretch & Boni
Bonus 1a: Remote Light Organ with WiFI pt. 1
Bonus 1b: Remote Light Organ with WiFI pt. 2
Grande Finale: Paho MQTT Client on the SAMA5D4
Related blog
Vintage Turntable repair: Can I fix a Perpetuum Ebner from 1958
Review 1: Atmel SMART SAMA5D4 Xplained Ultra Unboxing and First Steps
Review 2: Atmel SMART SAMA5D4 Xplained Ultra - Building the Libraries from Source
Review 3: Digital Continuous Rotation (360°) Servo Part 1
Review 4: Digital Continuous Rotation (360°) Servo Part 2
Review 5: Atmel SMART SAMA5D4 Xplained Ultra - TCP/IP running
Review 6: Atmel SMART SAMA5D4 Xplained Ultra - LINUX Distro with SSH support
poem
Enchanted Objects: Let's work together to tame the ATMEL SMART SAMA5D4 Xplained Ultra kit
17 bis: Off South...
Review 7: Atmel SMART SAMA5D4 Xplained Ultra - C++ ADC Example on Linux
Review 8: Atmel SMART SAMA5D4 Xplained Ultra - Product Review
Review 9a: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 1
Review 9b: Atmel SMART SAMA5D4 Xplained Ultra - Set up ADC Buffer with Hardware Trigger Part 2
Review 10: Atmel SMART SAMA5D4 Xplained Ultra - New Content on AT91.com
1958 Turntable from the Black Forest - Summary of the Enchanted Player Story

Who's at the door

 

Hans and Matilda were fast asleep when they heard a knock at the door. He put on a robe and wandered over to the door. "Who is it", he asked, "The postman" replied the stranger. Hans peered through the spyhole and saw the cap of the postman. Why is the postman visiting in the middle of the night thought Hans? He looked again, below the cap he saw a large pair of eyes, above the cap he saw a large pair of hairy ears and through the darkness he saw a large set of sharp teeth. It was the Wolf!

 

Wolf.png

 

He checked the door was securely bolted and headed back to bed. Before he'd even made it to the bedroom there was another knock at the door so he headed back. Peering out of the door this time he saw a bowler hat. "Who is it?" he asked. "It's the Doctor" the hat replied. Hans looked through the hole again. Underneath the hat were two large eyes, a large nose and a large set of teeth. Hans backed away from the door, when there was yet another knock. "Who is he asked", "It's the UPS guy with your Element14 delivery", was the reply. Hans was overjoyed and was just about to open the door when he decided to look through the spyhole again. Again a hatted figure stood outside, and again the figure had large fury ears, large eyes and very large and pointy teeth. Hans went back to bed. That night there was a range of visitors to his door claiming to be the milkman, the window cleaner and finally granny. After that Hans stopped answering the knocks at the door and tried to get to sleep.

 

Knock Knock

 

In the morning Hans had a couple of thoughts, the first was he wanted to upgrade his security and the other was that it might be quite good for the system to check the weather automatically in response to people knocking on the door.

 

Hans realised that there was a buzzer in the Arduino kit and looked into taking that apart to use as a sensor. It did not want to open up easily so he invested in some new sensors, some simple piezo transducers.

PiezoSensor.png

A bit of googling found a suitable circuit for conditioning the sensor signal. The piezo transducer is effectively a voltage source, when the crystal deforms a small voltage is produced. If we put that into a comparator then we can create a strong 0v - 5v swing to indicate the knock. This should be sufficient to wake the Arduino from sleep. A large resistor allows that voltage to discharge and zener diodes stop the inputs being overloaded.

 

Piezo Comparator Circuit

From Thoughts on interfacing piezo vibration sensor - Do It Easy With ScienceProg

 

Looking in the spares cupboard there were a bunch of 741 opamps that could be used for the comparator but checking the spec he realised that they were not designed to work from a 5v supply, and there were also comments that the output swing was less than the rails so some LM393 comparators were also ordered.

 

Excuse me for interrupting

 

Whilst he was waiting for those he did some tests with the interrupts. Reading the Arduino site he learn that only certain pins could be configured as an external interrupt. Looking at the pin out diagram, all of there are taken by the bridge to the Linino module or the I2C bus.