| 1 | {: style="position:relative;left:0px;right:0px;"} |
| 2 | |
| 3 | ## About this 2 Day Workshop |
| 4 | |
| 5 | `Tutorial for learning to use KuttyPy - A fun tool to learn science and electronics.` |
| 6 | |
| 7 | !!! info "" |
| 8 | {: style="position:relative;left:0px;right:0px;"} |
| 9 | |
| 10 | !!! tip "You will need" |
| 11 | * A kuttypy Device (Shown in the photo above) |
| 12 | * A USB Mini B cable |
| 13 | * An OTG cable : used to connect the Usb cable of the KuttyPy to your Android phone |
| 14 | |
| 15 | !!! info "Intended audience" |
| 16 | * Students who want to learn to code. This workshop will cover all basic concepts using Visual Programming. So there's no need to be scared of syntax and typing. |
| 17 | * Beginners who would like to explore microcontroller functions via the android app |
| 18 | * Hobbyists who want a way to control external parameters such as lights, fans, and [robots](../programming/intro/#slightly-complex-example) from their Visual programs. |
| 19 | * Citizen Scientists who want to use affordable and [easily available sensors](../sensors) for physical parameters( temperature, humidity, pressure...) without having to learn embedded systems and communications. |
| 20 | |
| 21 | |
| 22 | |
| 23 | For more information about the device, you can visit the [Manufacturer's page](https://csparkresearch.in/kuttypyplus) |
| 24 | |
| 25 | ## Software Installation |
| 26 | |
| 27 | The Android App is available on the [Google Play Store](https://play.google.com/store/apps/details?id=com.cspark.kuttypy) |
| 28 | |
| 29 | After downloading , simply launch the app, and connect the KuttyPy device to your phone using the OTG cable |
| 30 | and the USB mini Cable. |
| 31 | |
| 32 | !!! tip "Granting permissions to access the device" |
| 33 | The phone will show a popup window asking you to grant permissions to access 'CH240 Serial Port'. Click OK. |
| 34 | Once the connection is successful, the titlebar of the app will turn from <span style="color:red">RED</span> to <span style="color:green">GREEN</span> in color. |
| 35 | |
| 36 | ## The KuttyPy App |
| 37 | |
| 38 |  |
| 39 | |
| 40 | There are four significant parts to this app. You can select the tile/icon as per the task at hand. |
| 41 | |
| 42 | + Playground |
| 43 | + Visual Programming |
| 44 | + Data Logger |
| 45 | + Code Editor |
| 46 | |
| 47 | The Playground is a simple way to read each input of the KuttyPy board. Inputs in HIGH state are shown in GREEN, and LOW state is shown in RED. |
| 48 | It can also be used to measure voltage from the PORTA pins( PA0 to PA7). |
| 49 | |
| 50 | The Visual Programming window is where we will spend most of our time for this workshop. It is an interface where |
| 51 | you can drag and drop logical blocks to assemble simple programs to complex things like gesture controlled games. |
| 52 | |
| 53 | The data logger is used to record information from various sensors which use the I2C inteface to communicate with the KuttyPy |
| 54 | device. It is a useful tool to study variations in physical parameters such as humidity, luminosity, air pressure etc. |
| 55 | |
| 56 | Code editor is used to write programs in the C language. We may touch upon this part by the end of the workshop. Once you understand |
| 57 | how to control microcontrollers through `registers`, you will eventually need to learn to write programs in C. |
| 58 | |
| 59 | |
| 60 | ## The kuttypy device |
| 61 | |
| 62 | You have noticed that there are many things on the circuit board such as ICs, LEDs, switches, connectors etc . |
| 63 | Your instructor will explain these, and their funtions |
| 64 | |
| 65 | USB Connector : A Mini B type USB socket which is used to connect the kuttypy to other device. |
| 66 | 500mA Fuse: A fuse protects devices from excess current flow. It will automatically cut off supply when the current goes above 500mA, and will restore the connection when the current reduces. |
| 67 | Microcontroller: ATMEGA32 . The brain of the device. Contains CPU, RAM, STORAGE, and INPUT OUTPUT pins |
| 68 | LEDs : There are many LEDs on this board. A Power LED , An RGB LED , and 16 LEDs connected to pins of the microcontroller which will let you blink them by writing programs. |
| 69 | SWITCH : there is a red coloured package containing 8 sliding switches. Each of these is connected to a pin from PORTA (PA0 pin to PA7). It is an input device. |
| 70 | |
| 71 | |
| 72 | ## Visual Programming |
| 73 | |
| 74 | ### Hello World |
| 75 | |
| 76 | |
| 77 | |
| 78 | ## Explore the functions |
| 79 | |
| 80 | * You have already noticed that the User Interface(UI) resembles the kuttyPy board. |
| 81 | * It has four ports `PORTA, B , C, D` with 8 pins each, and each pin has a row representing it:  |
| 82 | --- |
| 83 | * Each Pin is configured as an input by default, and the RED coloured box next to it indicates the input is `LOW` or near 0 Volts. |
| 84 | * If the input is `HIGH`, which can be accomplished by connecting it to 5V, or enabling the `pull-up` checkbox, the RED box will turn to `GREEN` |
| 85 | * Since the inputs are `floating`, merely touching the pins with your fingers will cause the inputs to fluctuate between `RED` and `GREEN` status.  |
| 86 | --- |
| 87 | * Each pin can be reconfigured as an `OUTPUT` type by clicking on the `INPUT` button next to it. |
| 88 | * Make any of the pins `PD5`, `PD7`, or `PB3` an output type, and click on its square RED button to set it to `HIGH`. These pins are connected to the RGB LED on the board, so the LED will glow! |
| 89 | |
| 90 | |
| 91 | |
| 92 | ## Hello World |
| 93 | |
| 94 | |
| 95 | ### Introduction to Registers |
| 96 | |
| 97 | |
| 98 | Programs executing on Microcontrollers use [special function registers(SFRs)](../programming/basics) to manipulate the hardware(Inputs, outputs, ADCs etc). |
| 99 | These are basically predefined variables, where each bit is associated with a hardware change. |
| 100 | |
| 101 | ??? tip " Binary conversion example " |
| 102 | {: style="width:100%"} |
| 103 | |
| 104 | setReg and getReg Python function calls in the kuttyPy library can be used to read and write these registers. |
| 105 | Here's an example. Run it in a python3 shell. |
| 106 | |
| 107 | ```python |
| 108 | from kuttyPy import * #Import the library. also automatically connects to any available kuttypy hardware. |
| 109 | setReg('DDRD',160) #0b10100000 PD7(BLUE LED) and PD5(GREEN LED) made output type |
| 110 | setReg('PORTD',160) # PD5 and PD7 set to HIGH. Both LEDs start glowing. Colour looks like cyan. |
| 111 | ``` |
| 112 | |
| 113 | For detailed examples, visit the [python coding page](../programming/intro). |
| 114 | |
| 115 | You may skip to the [I/O examples](../programming/basics) page which will cover the following topics: |
| 116 | |
| 117 | * Turning on an LED connected to any PIN |
| 118 | |
| 119 | * Reading a voltage from an ADC enabled PIN |
| 120 | |
| 121 | * Plotting with Matplotlib |
| 122 | |
| 123 | * Using the iPython console |
| 124 | |
| 125 | * Reading from I2C sensors |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | !!! note "Exercise : Python script for digital I/O" |
| 131 | * Write a python script to make PD5 and PD7 output type. |
| 132 | * Set PD5 HIGH (Green LED will glow) |
| 133 | * wait half a second ( time.sleep(0.5) ) |
| 134 | * Set PD7 also HIGH. (Blue and Green will glow. resulting colour is Cyan ) |
| 135 | * wait half a second ( time.sleep(0.5) ) |
| 136 | * Set both LOW. (Nothing glows) |
| 137 | |
| 138 | --- |
| 139 | * Some pins have additional functionality: |
| 140 | * Analog to Digital Convertor enabled inputs: |
| 141 | * All pins on `PORTA (PA0 - PA7)` for this microcontroller have a 10-bit ADC functionality. |
| 142 | * Make it an `OUTPUT`, and click again to see a variable slider and an LCD number show a value between 0-1023  |
| 143 | * You can use this as an [8 channel, 0-5V voltmeter](../adc) for testing analog joysticks, sensors etc. Click on the LCD number to reveal a gauge and data logger! |
| 144 | * PWM outputs. PB3, PD5, PD7 . Adjust the RGB LED intensity using the sliders. |
| 145 |  |
| 146 | |
| 147 | !!! note "Exercise : Python script for reading ADC" |
| 148 | * Enable ADC on PA0 via the graphical interface. |
| 149 | * Click on the LCD display, and from the dialog, check 'show register manipulations' |
| 150 | * Note the registers being written and read |
| 151 | * Disable the ADC (Set to input) |
| 152 | * `Go to the scripting tab, and write a program to read 10 values from PA0` |
| 153 | |
| 154 | !!! tip "Stuff seems to be working?" |
| 155 | Now that we have skimmed over the basics of the graphical utility's `playground`, it would appear that the board is capable |
| 156 | of controlling real-world events from Python. For further details on the hardware schematic, [visit the page](../hw/) . |
| 157 | |
| 158 | The pinout diagram will be very useful although the board itself is well labelled. The ATMEGA32 datasheet will be handy as well. |
| 159 | |
| 160 | |
| 161 | --- |
| 162 | |
| 163 | ## Sensors using I2C communication |
| 164 | |
| 165 | [Skip to the relevant page](../sensors/) |
| 166 | |
| 167 | * [I2C Sensors](../sensors) for a range of physical parameters such as pressure, acceleration etc can be connected using PC0(SCL), and PC1(SDA). |
| 168 | * Use the graphical interface to scan for sensors and view readings |
| 169 | * Check out functionality, and explore potential applications. |
| 170 | * Write Python code to read data from an accelerometer. |
| 171 | |
| 172 | !!! note "Sensors Exercise : Write a python program to read data from an accelerometer" |
| 173 | * The complete [docs are here](../programming/i2c) . |
| 174 | * `MPU6050_init()` |
| 175 | * `values = MPU6050_all()` |
| 176 | * Using the above two functions, one can get data from this sensor, where `values` is a 7 item long list. |
| 177 | * [Ax, Ay, Az, T, Gx, Gy, Gz] . A = acceleration. G = angular velocity |
| 178 | |
| 179 | !!! note "Sensors Exercise #2: Plot 200 values from MPU6050 (Ax) using matplotlib" |
| 180 | * `pip3 install matplotlib` or `py -3 -m pip install matplotlib` |
| 181 | * The complete [docs are here](../programming/i2c) . |
| 182 | ```python |
| 183 | from kuttyPy import * |
| 184 | from matplotlib import pyplot as plt |
| 185 | MPU6050_init() #Initialize the sensor |
| 186 | points = 0 |
| 187 | for a in range(200): |
| 188 | x = MPU6050_all() #Fetch readings |
| 189 | if x is not None: |
| 190 | plt.scatter(points,x[0]) |
| 191 | points +=1 |
| 192 | plt.pause(0.01) #10ms delay. |
| 193 | ``` |
| 194 | * Replace the x-axis with timestamps instead of point numbers. |
| 195 | * Store 200 values, and timestamps in two lists, and plot using `plt.plot(x[],y[])` and `plt.show()` |
| 196 | |
| 197 | !!! note "Sensors Exercise #3: Extract the oscillation frequency from the data using scipy's leastsq fitting " |
| 198 | |
| 199 | ```python |
| 200 | import numpy as np |
| 201 | from scipy import optimize |
| 202 | #-------------------------- Fourier Transform ------------------------------------ |
| 203 | def fft(ya, si): |
| 204 | ''' |
| 205 | Returns positive half of the Fourier transform of the signal ya. |
| 206 | Sampling interval 'si', in Seconds |
| 207 | ''' |
| 208 | NP = len(ya) |
| 209 | if NP%2: #odd number |
| 210 | ya = ya[:-1] |
| 211 | NP-=1 |
| 212 | v = np.array(ya) |
| 213 | tr = abs(np.fft.fft(v))/NP |
| 214 | frq = np.fft.fftfreq(NP, si) |
| 215 | x = frq.reshape(2,int(NP/2)) |
| 216 | y = tr.reshape(2,int(NP/2)) |
| 217 | return x[0], y[0] |
| 218 | |
| 219 | def find_frequency(x,y): # Returns the fundamental frequency using FFT |
| 220 | tx,ty = fft(y, x[1]-x[0]) |
| 221 | index = find_peak(ty) |
| 222 | if index == 0: |
| 223 | return None |
| 224 | else: |
| 225 | return tx[index] |
| 226 | |
| 227 | def sine_eval(x,p): # y = a * sin(2*pi*f*x + phi)+ offset |
| 228 | return p[0] * np.sin(2*np.pi*p[1]*x+p[2])-p[3] |
| 229 | |
| 230 | def sine_erf(p,x,y): |
| 231 | return y - sine_eval(x,p) |
| 232 | |
| 233 | |
| 234 | def fit_sine(xa,ya, freq = 0): # Time in S, V in volts, freq in Hz, accepts numpy arrays |
| 235 | size = len(ya) |
| 236 | mx = max(ya) |
| 237 | mn = min(ya) |
| 238 | amp = (mx-mn)/2 |
| 239 | if freq == 0: # Guess frequency not given |
| 240 | freq = find_frequency(xa,ya) |
| 241 | if freq == None: |
| 242 | return None |
| 243 | #print 'guess a & freq = ', amp, freq |
| 244 | par = [amp, freq, 0.0, 0.0] # Amp, freq, phase , offset |
| 245 | par, pcov = optimize.leastsq(sine_erf, par, args=(xa, ya)) |
| 246 | return par |
| 247 | |
| 248 | #### |
| 249 | #### YOU NEED TO WRITE CODE TO COLLECT data points and store timestamps to `TIMESTAMPS` |
| 250 | #### and values to `DATAPOINTS` here. |
| 251 | #### |
| 252 | |
| 253 | results=fit_sine(TIMESTAMPS,DATAPOINTS) #Returns : Amp, freq, phase , offset |
| 254 | if results is not None: |
| 255 | amp=abs(results[0]) |
| 256 | freq=results[1] |
| 257 | print('Results: %5.2f amp, %5.3f Hz<br>'%(amp,freq)) |
| 258 | |
| 259 | |
| 260 | ``` |
| 261 | |
| 262 | --- |
| 263 | |
| 264 | |
| 265 | |
| 266 | |
| 267 | ## Basic C code |
| 268 | |
| 269 | All the register manipulation commands issued by Python running on your laptop are interpreted by a bootloader firmware |
| 270 | executing on the microcontroller. In addition to this, you can also compile C code, and flash it to the remaining storage space |
| 271 | on the microcontroller, thereby making it independent and capable of functioning from any 5V power supply. |
| 272 | |
| 273 | [Relevant section](../programming/c) |
| 274 | |
| 275 | !!! note "Exercise : C program for digital I/O" |
| 276 | * Write a C program to make PD5 and PD7 output type. |
| 277 | * Set PD5 HIGH (Green LED will glow) |
| 278 | * wait half a second ( delay_ms(500); imported from "mh-utils.c" ) |
| 279 | * Set PD7 also HIGH. (Blue and Green will glow. resulting colour is Cyan ) |
| 280 | * wait half a second ( delay_ms(500); imported from "mh-utils.c" ) |
| 281 | * Set both LOW. (Nothing glows) |