Debian Codegraph @

docs/workshop.md

raw symbols SCIP
1
2
3 `Tutorial for learning to use KuttyPy - A Python to real world bridge - in a 2 hour workshop session`
4
5 !!! info "Intended audience"
6 * Beginners who would like to explore microcontroller functions via Python without the compile+upload hassle.
7 * Hobbyists who want a way to control external parameters such as lights, fans, and [robots](../programming/intro/#slightly-complex-example) from their Python programs
8 * 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.
9
10
11 !!! info ""
12 ![Screenshot](images/kuttypyplus.jpg){: style="position:relative;left:0px;right:0px;"}
13
14 ## Software Installation
15
16 Given the paucity of time, the fastest ways for [installing](https://csparkresearch.in/kuttypyplus) the toolchain on different operating systems are listed. Click to expand.
17
18 ??? abstract "Windows with Python3 installed"
19 * [Python3](https://www.python.org/ftp/python/3.8.0/python-3.8.0-amd64.exe) must be installed, and `pip` should be accessible.
20 * Open a command prompt as administrator, and use pip3 to install the KuttyPy package
21 ```
22 py -3 -m pip install KuttyPy
23 ```
24 * Download and install the [CH341 USB Driver](../assets/CH341SER.EXE)
25 * You will now be able to launch `kuttypyplus` from the prompt, and import the `kuttyPy` library from any Python script.
26 * you can also launch `kuttypyide`
27 * If you wish to compile C code and upload to the KuttyPy hardware, winavr must be installed, and `avr-gcc` must be accessible from a command prompt.
28 * Download and install `winavr` from [winavr.sourceforge.net](https://sourceforge.net/projects/winavr/files/WinAVR/20100110/WinAVR-20100110-install.exe/download)
29
30 ??? warning "Windows bundled installer"
31 * The bundled installer includes Python3 and dependencies and KuttyPy software. Also includes winavr, usb driver.
32
33 [Download Bundled Installer](https://drive.google.com/uc?export=download&id=18PD-Llx12PTfMRWlHA447TCMxTA6smWZ)
34
35 !!! error "Made with Pyinstaller: Python will not be accessible globally"
36 Since the installer was made using PyInstaller, Python3 will not be accessible globally, and you will be limited to the ipython console within the KuttyPy software.
37 A better option would be to use pip to fetch PyQT5, qtconsole, pyserial, pyqtgraph, scipy , and KuttyPy . Winavr and the driver can be installed separately. Refer to the previous section.
38
39
40
41 ??? abstract "Ubuntu"
42 * Download the [deb file from here](https://csparkresearch.in/assets/installers/KuttyPy-1.0.25.deb)
43 * Navigate to the Downloaded deb file location, and install it. This also fetches dependencies : scipy, qtconsole, avr-gcc etc
44 ```
45 sudo apt install ./KuttyPy-1.0.25.deb
46 ```
47 * launch the kuttyPy GUI from the command prompt using the command
48 ```
49 kuttypyplus
50 ```
51
52 It is also present in the applications menu as `KuttyPy GUI` .
53
54 * You can also launch the kuttyPy IDE from the menu, or using the command
55 ```
56 kuttypyide
57 ```
58
59
60 ??? abstract "Using PIP on other OSes"
61 * Python3 must be installed
62 * Open a command prompt as administrator, and use pip3 to install the KuttyPy package
63 ```
64 pip3 install kuttyPy
65 ```
66 * You will now be able to launch `kuttypy` from the prompt, and import the `kuttyPy` library from Python.
67 * If you wish to compile C code, `avr-gcc` must be accessible from a command prompt. Install it from the package manager of your OS.
68
69 ???warning "setting permissions on Linux based systems "
70 Accessing the hardware on linux requires certain permissions to be set.
71 Due to an apparent bug with pip3, the install script may fail to do this.
72
73 As a workaround, you can run the program as root to verify the permissions issue
74 ```
75 sudo kuttypy
76 ```
77 For a more permanent fix for regular users, please download and execute this
78 [post installation script](../assets/postinst.sh)
79
80 ```bash
81 chmod +x postinst.sh
82 sudo ./postinst.sh
83 kuttypy
84 ```
85
86
87 ???abtract " Installing from source code "
88 ```bash
89 sudo apt install python3-serial python3-pyqt5 python3-pyqt5.qtsvg gcc-avr avr-libc python3-qtconsole python3-scipy python3-pyqtgraph
90 git clone http://github.com/csparkresearch/kuttypy-gui
91 cd kuttypy-gui
92 python3 KuttyPyPlus.py
93 ```
94 For setting hardware permissions, refer to the previous section
95
96
97 ## KuttyPy Software
98
99 ???+ success "Screenshot of the Graphical interface after launching `kuttypy` "
100 ![](../images/main.png)
101 The title will show `Hardware not Detected` if not connected, or if a permissions issue exists
102
103 ### Explore the functions
104
105 * You have already noticed that the User Interface(UI) resembles the kuttyPy board.
106 * It has four ports `PORTA, B , C, D` with 8 pins each, and each pin has a row representing it: ![](../images/PD5.png)
107
108 ---
109
110 * 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.
111 * 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`
112 * Since the inputs are `floating`, merely touching the pins with your fingers will cause the inputs to fluctuate between `RED` and `GREEN` status. ![](../images/noise.gif)
113
114 ---
115
116 * Each pin can be reconfigured as an `OUTPUT` type by clicking on the `INPUT` button next to it.
117 * 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!
118
119
120
121 ## Hello World
122
123
124 ### Introduction to Registers
125
126
127 Programs executing on Microcontrollers use [special function registers(SFRs)](../programming/basics) to manipulate the hardware(Inputs, outputs, ADCs etc).
128 These are basically predefined variables, where each bit is associated with a hardware change.
129
130 ??? tip " Binary conversion example "
131 ![](../images/binary.png){: style="width:100%"}
132
133 setReg and getReg Python function calls in the kuttyPy library can be used to read and write these registers.
134 Here's an example. Run it in a python3 shell.
135
136 ```python
137 from kuttyPy import * #Import the library. also automatically connects to any available kuttypy hardware.
138 setReg('DDRD',160) #0b10100000 PD7(BLUE LED) and PD5(GREEN LED) made output type
139 setReg('PORTD',160) # PD5 and PD7 set to HIGH. Both LEDs start glowing. Colour looks like cyan.
140 ```
141
142 For detailed examples, visit the [python coding page](../programming/intro).
143
144 You may skip to the [I/O examples](../programming/basics) page which will cover the following topics:
145
146 * Turning on an LED connected to any PIN
147
148 * Reading a voltage from an ADC enabled PIN
149
150 * Plotting with Matplotlib
151
152 * Using the iPython console
153
154 * Reading from I2C sensors
155
156
157
158
159 !!! note "Exercise : Python script for digital I/O"
160 * Write a python script to make PD5 and PD7 output type.
161 * Set PD5 HIGH (Green LED will glow)
162 * wait half a second ( time.sleep(0.5) )
163 * Set PD7 also HIGH. (Blue and Green will glow. resulting colour is Cyan )
164 * wait half a second ( time.sleep(0.5) )
165 * Set both LOW. (Nothing glows)
166
167 ---
168 * Some pins have additional functionality:
169 * Analog to Digital Convertor enabled inputs:
170 * All pins on `PORTA (PA0 - PA7)` for this microcontroller have a 10-bit ADC functionality.
171 * Make it an `OUTPUT`, and click again to see a variable slider and an LCD number show a value between 0-1023 ![](../images/extra_adc.gif)
172 * 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!
173 * PWM outputs. PB3, PD5, PD7 . Adjust the RGB LED intensity using the sliders.
174 ![](../images/extra_pwm.gif)
175
176 !!! note "Exercise : Python script for reading ADC"
177 * Enable ADC on PA0 via the graphical interface.
178 * Click on the LCD display, and from the dialog, check 'show register manipulations'
179 * Note the registers being written and read
180 * Disable the ADC (Set to input)
181 * `Go to the scripting tab, and write a program to read 10 values from PA0`
182
183 !!! tip "Stuff seems to be working?"
184 Now that we have skimmed over the basics of the graphical utility's `playground`, it would appear that the board is capable
185 of controlling real-world events from Python. For further details on the hardware schematic, [visit the page](../hw/) .
186
187 The pinout diagram will be very useful although the board itself is well labelled. The ATMEGA32 datasheet will be handy as well.
188
189
190 ---
191
192 ## Sensors using I2C communication
193
194 [Skip to the relevant page](../sensors/)
195
196 * [I2C Sensors](../sensors) for a range of physical parameters such as pressure, acceleration etc can be connected using PC0(SCL), and PC1(SDA).
197 * Use the graphical interface to scan for sensors and view readings
198 * Check out functionality, and explore potential applications.
199 * Write Python code to read data from an accelerometer.
200
201 !!! note "Sensors Exercise : Write a python program to read data from an accelerometer"
202 * The complete [docs are here](../programming/i2c) .
203 * `MPU6050_init()`
204 * `values = MPU6050_all()`
205 * Using the above two functions, one can get data from this sensor, where `values` is a 7 item long list.
206 * [Ax, Ay, Az, T, Gx, Gy, Gz] . A = acceleration. G = angular velocity
207
208 !!! note "Sensors Exercise #2: Plot 200 values from MPU6050 (Ax) using matplotlib"
209 * `pip3 install matplotlib` or `py -3 -m pip install matplotlib`
210 * The complete [docs are here](../programming/i2c) .
211 ```python
212 from kuttyPy import *
213 from matplotlib import pyplot as plt
214 MPU6050_init() #Initialize the sensor
215 points = 0
216 for a in range(200):
217 x = MPU6050_all() #Fetch readings
218 if x is not None:
219 plt.scatter(points,x[0])
220 points +=1
221 plt.pause(0.01) #10ms delay.
222 ```
223 * Replace the x-axis with timestamps instead of point numbers.
224 * Store 200 values, and timestamps in two lists, and plot using `plt.plot(x[],y[])` and `plt.show()`
225
226 !!! note "Sensors Exercise #3: Extract the oscillation frequency from the data using scipy's leastsq fitting "
227
228 ```python
229 import numpy as np
230 from scipy import optimize
231 #-------------------------- Fourier Transform ------------------------------------
232 def fft(ya, si):
233 '''
234 Returns positive half of the Fourier transform of the signal ya.
235 Sampling interval 'si', in Seconds
236 '''
237 NP = len(ya)
238 if NP%2: #odd number
239 ya = ya[:-1]
240 NP-=1
241 v = np.array(ya)
242 tr = abs(np.fft.fft(v))/NP
243 frq = np.fft.fftfreq(NP, si)
244 x = frq.reshape(2,int(NP/2))
245 y = tr.reshape(2,int(NP/2))
246 return x[0], y[0]
247
248 def find_frequency(x,y): # Returns the fundamental frequency using FFT
249 tx,ty = fft(y, x[1]-x[0])
250 index = find_peak(ty)
251 if index == 0:
252 return None
253 else:
254 return tx[index]
255
256 def sine_eval(x,p): # y = a * sin(2*pi*f*x + phi)+ offset
257 return p[0] * np.sin(2*np.pi*p[1]*x+p[2])-p[3]
258
259 def sine_erf(p,x,y):
260 return y - sine_eval(x,p)
261
262
263 def fit_sine(xa,ya, freq = 0): # Time in S, V in volts, freq in Hz, accepts numpy arrays
264 size = len(ya)
265 mx = max(ya)
266 mn = min(ya)
267 amp = (mx-mn)/2
268 if freq == 0: # Guess frequency not given
269 freq = find_frequency(xa,ya)
270 if freq == None:
271 return None
272 #print 'guess a & freq = ', amp, freq
273 par = [amp, freq, 0.0, 0.0] # Amp, freq, phase , offset
274 par, pcov = optimize.leastsq(sine_erf, par, args=(xa, ya))
275 return par
276
277 ####
278 #### YOU NEED TO WRITE CODE TO COLLECT data points and store timestamps to `TIMESTAMPS`
279 #### and values to `DATAPOINTS` here.
280 ####
281
282 results=fit_sine(TIMESTAMPS,DATAPOINTS) #Returns : Amp, freq, phase , offset
283 if results is not None:
284 amp=abs(results[0])
285 freq=results[1]
286 print('Results: %5.2f amp, %5.3f Hz<br>'%(amp,freq))
287
288
289 ```
290
291 ---
292
293
294
295
296 ## Basic C code
297
298 All the register manipulation commands issued by Python running on your laptop are interpreted by a bootloader firmware
299 executing on the microcontroller. In addition to this, you can also compile C code, and flash it to the remaining storage space
300 on the microcontroller, thereby making it independent and capable of functioning from any 5V power supply.
301
302 [Relevant section](../programming/c)
303
304 !!! note "Exercise : C program for digital I/O"
305 * Write a C program to make PD5 and PD7 output type.
306 * Set PD5 HIGH (Green LED will glow)
307 * wait half a second ( delay_ms(500); imported from "mh-utils.c" )
308 * Set PD7 also HIGH. (Blue and Green will glow. resulting colour is Cyan )
309 * wait half a second ( delay_ms(500); imported from "mh-utils.c" )
310 * Set both LOW. (Nothing glows)