├── 2.8_LCD_display_on_a_Raspberry_Pi_ft_ILI9341 ├── Adafruit_lib │ ├── Jack-Stanislav-demo-FFP.ttf │ ├── cat.jpg │ ├── image.py │ ├── image_timed.py │ └── shapes.py ├── LCD_Demo.py ├── lib_tft24T.py └── wiring_diagram.png ├── 2.8_LCD_display_on_an_ESP32_ft_ILI9341 ├── esp32_ili9341.ino └── wiring_diagram.png ├── Arduino_USB_volume_controller_&_Macro_Keyboard ├── volume_control.ino └── wiring diagram.PNG ├── ESP12-E_Booting_and_Flashing ├── Blink.ino └── wiring diagram.PNG ├── Improved_Home_Automation ├── ESP8266_MQTT_Part_3 │ ├── esp12e_publish.ino │ ├── esp12e_sub_pub.ino │ └── esp12e_subscribe.ino └── Python_MQTT_Part_2 │ ├── publish.py │ ├── sub_and_pub.py │ └── subscribe.py ├── Neopixel_LEDs_with_ESP32_ft_WB2812B_LED_Pad ├── rgbpad_test.ino └── wiring diagram.png ├── RFID_NFC_reader_writer_with_PN532_ft_Arduino_and_Esp_MC ├── SPI_nano_pn532.PNG ├── i2c_nano_pn532.PNG ├── i2c_pn532_esp32.PNG ├── i2c_pn532_esp8266.PNG ├── mifare_classic_i2c.ino └── mifare_classic_spi.ino ├── RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi ├── Steps to run.txt ├── py532_demo.py ├── py532lib │ ├── __init__.py │ ├── py532lib │ │ ├── LICENSE │ │ ├── __init__.py │ │ ├── constants.py │ │ ├── frame.py │ │ ├── i2c.py │ │ └── mifare.py │ └── quick2wire │ │ ├── GPL.txt │ │ ├── LGPL.txt │ │ ├── LICENSE.md │ │ ├── MIT_LICENSE.txt │ │ ├── README.md │ │ ├── __init__.py │ │ ├── asm_generic_ioctl.py │ │ ├── board_revision.py │ │ ├── eventfd.py │ │ ├── gpio.py │ │ ├── helpers │ │ ├── __init__.py │ │ └── display.py │ │ ├── i2c.py │ │ ├── i2c_ctypes.py │ │ ├── parts │ │ ├── __init__.py │ │ ├── mcp23017.py │ │ ├── mcp23x17.py │ │ └── pcf8591.py │ │ ├── requirements.txt │ │ ├── selector.py │ │ ├── spi.py │ │ ├── spi_ctypes.py │ │ ├── syscall.py │ │ └── timerfd.py └── wiring diagram.jpg ├── RGB_LED_Controller_ft_ESP32_&_ws2812b ├── rgb_controller.ino └── wiring diagram.jpg ├── RPi_and_Arduino_Serial_Communication ├── i2c_nano_pn532.PNG ├── nano_rdif.ino └── serial_test.py ├── amd_bios_modding └── PolarisBiosEditor.zip ├── channel_shilling ├── real_time_clock_ft_ds3231_with_d1_mini ├── ds3231.ino └── rtc_d1_mini.jpg └── rotary_encoder_with_d1_mini ├── rot_encoder.ino └── wiring_diagram.PNG /2.8_LCD_display_on_a_Raspberry_Pi_ft_ILI9341/Adafruit_lib/Jack-Stanislav-demo-FFP.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/2.8_LCD_display_on_a_Raspberry_Pi_ft_ILI9341/Adafruit_lib/Jack-Stanislav-demo-FFP.ttf -------------------------------------------------------------------------------- /2.8_LCD_display_on_a_Raspberry_Pi_ft_ILI9341/Adafruit_lib/cat.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/2.8_LCD_display_on_a_Raspberry_Pi_ft_ILI9341/Adafruit_lib/cat.jpg -------------------------------------------------------------------------------- /2.8_LCD_display_on_a_Raspberry_Pi_ft_ILI9341/Adafruit_lib/image.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2014 Adafruit Industries 2 | # Author: Tony DiCola 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a copy 5 | # of this software and associated documentation files (the "Software"), to deal 6 | # in the Software without restriction, including without limitation the rights 7 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | # copies of the Software, and to permit persons to whom the Software is 9 | # furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | # THE SOFTWARE. 21 | from PIL import Image 22 | 23 | import Adafruit_ILI9341 as TFT 24 | import Adafruit_GPIO as GPIO 25 | import Adafruit_GPIO.SPI as SPI 26 | 27 | 28 | # Raspberry Pi configuration. 29 | DC = 18 30 | RST = 23 31 | SPI_PORT = 0 32 | SPI_DEVICE = 0 33 | 34 | # BeagleBone Black configuration. 35 | # DC = 'P9_15' 36 | # RST = 'P9_12' 37 | # SPI_PORT = 1 38 | # SPI_DEVICE = 0 39 | 40 | # Create TFT LCD display class. 41 | disp = TFT.ILI9341(DC, rst=RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=64000000)) 42 | 43 | # Initialize display. 44 | disp.begin() 45 | 46 | # Load an image. 47 | print('Loading image...') 48 | image = Image.open('cat.jpg') 49 | 50 | # Resize the image and rotate it so it's 240x320 pixels. 51 | image = image.rotate(180).resize((240, 320)) 52 | 53 | # Draw the image on the display hardware. 54 | print('Drawing image') 55 | disp.display(image) 56 | -------------------------------------------------------------------------------- /2.8_LCD_display_on_a_Raspberry_Pi_ft_ILI9341/Adafruit_lib/image_timed.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2014 Adafruit Industries 2 | # Author: Tony DiCola 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a copy 5 | # of this software and associated documentation files (the "Software"), to deal 6 | # in the Software without restriction, including without limitation the rights 7 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | # copies of the Software, and to permit persons to whom the Software is 9 | # furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | # THE SOFTWARE. 21 | from PIL import Image 22 | import time 23 | import Adafruit_ILI9341 as TFT 24 | import Adafruit_GPIO as GPIO 25 | import Adafruit_GPIO.SPI as SPI 26 | 27 | 28 | # Raspberry Pi configuration. 29 | DC = 18 30 | RST = 23 31 | SPI_PORT = 0 32 | SPI_DEVICE = 0 33 | 34 | # BeagleBone Black configuration. 35 | #DC = 'P9_15' 36 | #RST = 'P9_12' 37 | #SPI_PORT = 1 38 | #SPI_DEVICE = 0 39 | 40 | # Create TFT LCD display class. 41 | disp = TFT.ILI9341(DC, rst=RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=64000000)) 42 | 43 | # Initialize display. 44 | disp.begin() 45 | 46 | # Load an image. 47 | print('Loading image...') 48 | image = Image.open('cat.jpg') 49 | 50 | # Resize the image and rotate it so it's 240x320 pixels. 51 | image = image.rotate(90).resize((240, 320)) 52 | 53 | print('Press Ctrl-C to exit') 54 | while(True): 55 | # Draw the image on the display hardware. 56 | print('Drawing image') 57 | start_time = time.time() 58 | disp.display(image) 59 | end_time = time.time() 60 | print('Time to draw image: ' + str(end_time - start_time)) 61 | disp.clear((0, 0, 0)) 62 | disp.display() 63 | -------------------------------------------------------------------------------- /2.8_LCD_display_on_a_Raspberry_Pi_ft_ILI9341/Adafruit_lib/shapes.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2014 Adafruit Industries 2 | # Author: Tony DiCola 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a copy 5 | # of this software and associated documentation files (the "Software"), to deal 6 | # in the Software without restriction, including without limitation the rights 7 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | # copies of the Software, and to permit persons to whom the Software is 9 | # furnished to do so, subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be included in 12 | # all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | # THE SOFTWARE. 21 | from PIL import Image 22 | from PIL import ImageDraw 23 | from PIL import ImageFont 24 | 25 | import Adafruit_ILI9341 as TFT 26 | import Adafruit_GPIO as GPIO 27 | import Adafruit_GPIO.SPI as SPI 28 | 29 | 30 | # Raspberry Pi configuration. 31 | DC = 18 32 | RST = 23 33 | SPI_PORT = 0 34 | SPI_DEVICE = 0 35 | 36 | # BeagleBone Black configuration. 37 | # DC = 'P9_15' 38 | # RST = 'P9_12' 39 | # SPI_PORT = 1 40 | # SPI_DEVICE = 0 41 | 42 | # Create TFT LCD display class. 43 | disp = TFT.ILI9341(DC, rst=RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=500000000)) 44 | 45 | # Initialize display. 46 | disp.begin() 47 | 48 | # Clear the display to a red background. 49 | # Can pass any tuple of red, green, blue values (from 0 to 255 each). 50 | disp.clear((255, 0, 0)) 51 | 52 | # Alternatively can clear to a black screen by calling: 53 | # disp.clear() 54 | 55 | # Get a PIL Draw object to start drawing on the display buffer. 56 | draw = disp.draw() 57 | 58 | # Draw some shapes. 59 | # Draw a blue ellipse with a green outline. 60 | draw.ellipse((10, 10, 110, 80), outline=(0,255,0), fill=(0,0,255)) 61 | 62 | # Draw a purple rectangle with yellow outline. 63 | draw.rectangle((10, 90, 110, 160), outline=(255,255,0), fill=(255,0,255)) 64 | 65 | # Draw a white X. 66 | draw.line((10, 170, 110, 230), fill=(255,255,255)) 67 | draw.line((10, 230, 110, 170), fill=(255,255,255)) 68 | 69 | # Draw a cyan triangle with a black outline. 70 | draw.polygon([(10, 275), (110, 240), (110, 310)], outline=(0,0,0), fill=(0,255,255)) 71 | 72 | # Load default font. 73 | #font = ImageFont.load_default() 74 | 75 | # Alternatively load a TTF font. 76 | # Some other nice fonts to try: http://www.dafont.com/bitmap.php 77 | #font = ImageFont.truetype('Jack-Stanislav-demo-FFP.ttf', 16) 78 | 79 | # Define a function to create rotated text. Unfortunately PIL doesn't have good 80 | # native support for rotated fonts, but this function can be used to make a 81 | # text image and rotate it so it's easy to paste in the buffer. 82 | def draw_rotated_text(image, text, position, angle, font, fill=(255,255,255)): 83 | # Get rendered font width and height. 84 | draw = ImageDraw.Draw(image) 85 | width, height = draw.textsize(text, font=font) 86 | # Create a new image with transparent background to store the text. 87 | textimage = Image.new('RGBA', (width, height), (0,0,0,0)) 88 | # Render the text. 89 | textdraw = ImageDraw.Draw(textimage) 90 | textdraw.text((0,0), text, font=font, fill=fill) 91 | # Rotate the text image. 92 | rotated = textimage.rotate(angle, expand=1) 93 | # Paste the text into the image, using it as a mask for transparency. 94 | image.paste(rotated, position, rotated) 95 | 96 | # Write two lines of white text on the buffer, rotated 90 degrees counter clockwise. 97 | font = ImageFont.load_default() 98 | draw_rotated_text(disp.buffer, 'Hello World!', (150, 120), 90, font, fill=(255,255,255)) 99 | font = ImageFont.truetype('Jack-Stanislav-demo-FFP.ttf', 16) 100 | draw_rotated_text(disp.buffer, 'This is a line of text.', (170, 90), 90, font, fill=(255,255,255)) 101 | 102 | # Write buffer to display hardware, must be called to make things visible on the 103 | # display! 104 | disp.display() 105 | -------------------------------------------------------------------------------- /2.8_LCD_display_on_a_Raspberry_Pi_ft_ILI9341/LCD_Demo.py: -------------------------------------------------------------------------------- 1 | from PIL import Image 2 | from PIL import ImageDraw 3 | from PIL import ImageFont 4 | 5 | from lib_tft24T import TFT24T 6 | import RPi.GPIO as GPIO 7 | GPIO.setmode(GPIO.BCM) 8 | GPIO.setwarnings(False) 9 | 10 | import spidev 11 | from time import sleep 12 | 13 | #For LCD SCREEN: 14 | DC = 18 15 | RST = 23 16 | 17 | # Create TFT LCD/TOUCH object: 18 | TFT = TFT24T(spidev.SpiDev(), GPIO, landscape=False) 19 | 20 | # Initialize display. 21 | TFT.initLCD(DC, RST) 22 | # If rst is omitted then tie rst pin to +3.3V 23 | # If led is omitted then tie led pin to +3.3V 24 | 25 | # Get the PIL Draw object to start drawing on the display buffer. 26 | draw = TFT.draw() 27 | 28 | while 1: 29 | TFT.clear((255, 0, 0)) 30 | # Alternatively can clear to a black screen by simply calling: 31 | TFT.clear() 32 | print('Loading image...') 33 | image = Image.open('cat.jpg') 34 | # Resize the image and rotate it so it's 240x320 pixels. 35 | image = image.rotate(90,0,1).resize((240, 320)) 36 | # Draw the image on the display hardware. 37 | print('Drawing image') 38 | TFT.display(image) 39 | sleep(3) 40 | print ("Test a long para of text, auto-wrapped into screen lines.") 41 | TFT.clear() 42 | font=ImageFont.truetype('FreeSans.ttf', 18) 43 | text1 = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. In quis justo quis tortor pellentesque malesuada. Donec eleifend lorem vel blandit condimentum. Vivamus risus sapien, iaculis id dictum ut, porta quis. """ 44 | draw.textwrapped((0,0), text1, 38, 20, font, "lightblue") 45 | TFT.display() 46 | sleep(1) 47 | 48 | TFT.clear((90,90,255)) 49 | print ("show a font in giant letters") 50 | font = ImageFont.truetype('FreeSerifItalic.ttf', 40) 51 | draw.textrotated((100,10), 'TEST DERP',90 ,font=font, fill="RED") 52 | 53 | TFT.display() 54 | sleep(2) -------------------------------------------------------------------------------- /2.8_LCD_display_on_a_Raspberry_Pi_ft_ILI9341/lib_tft24T.py: -------------------------------------------------------------------------------- 1 | # tft24T V0.3 April 2015 Brian Lavery TJCTM24024-SPI 2.4 inch Touch 320x240 SPI LCD 2 | # 3 | # Permission is hereby granted, free of charge, to any person obtaining a copy 4 | # of this software and associated documentation files (the "Software"), to deal 5 | # in the Software without restriction, including without limitation the rights 6 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | # copies of the Software, and to permit persons to whom the Software is 8 | # furnished to do so. 9 | 10 | # Calibration scaling values from the calibration utility: 11 | # Makes touchscreen coordinates agree with TFT coordinates (240x320) for YOUR device 12 | # You may need to adjust these values for YOUR device 13 | calib_scale240 = 272 14 | calib_scale320 = -364 15 | calib_offset240 = 16 16 | calib_offset320 = -354 17 | 18 | margin = 13 19 | # "margin" is a no-go perimeter (in pixels). [Stylus at very edge of touchscreen is rather jitter-prone.] 20 | 21 | 22 | import numbers 23 | import time 24 | 25 | from PIL import Image 26 | from PIL import ImageDraw 27 | import textwrap 28 | 29 | from types import MethodType 30 | 31 | # Constants for interacting with display registers. 32 | ILI9341_TFTWIDTH = 240 33 | ILI9341_TFTHEIGHT = 320 34 | 35 | ILI9341_SWRESET = 0x01 36 | ILI9341_SLPOUT = 0x11 37 | ILI9341_INVOFF = 0x20 38 | ILI9341_INVON = 0x21 39 | ILI9341_GAMMASET = 0x26 40 | ILI9341_DISPON = 0x29 41 | ILI9341_CASET = 0x2A 42 | ILI9341_PASET = 0x2B 43 | ILI9341_RAMWR = 0x2C 44 | ILI9341_RAMRD = 0x2E 45 | ILI9341_MADCTL = 0x36 46 | ILI9341_PIXFMT = 0x3A 47 | ILI9341_FRMCTR1 = 0xB1 48 | ILI9341_DFUNCTR = 0xB6 49 | 50 | ILI9341_PWCTR1 = 0xC0 51 | ILI9341_PWCTR2 = 0xC1 52 | ILI9341_VMCTR1 = 0xC5 53 | ILI9341_VMCTR2 = 0xC7 54 | ILI9341_GMCTRP1 = 0xE0 55 | ILI9341_GMCTRN1 = 0xE1 56 | 57 | 58 | Buffer = None 59 | # textrotated custom method for our "draw" cannot find TFT's canvas buffer if it is not global. 60 | # This method obviously precludes multiple instances of TFT running independently, 61 | # but we use both CE0/CE1 of the Raspberry Pi anyway, so how could we have another display? 62 | # (Want the second SPI of the RPI2? - Not considered in this library) 63 | 64 | class TFT24T(): 65 | def __init__(self, spi, gpio, landscape=False): 66 | 67 | 68 | self.is_landscape = landscape 69 | self._spi = spi 70 | self._gpio = gpio 71 | 72 | # TOUCHSCREEN HARDWARE PART 73 | 74 | # ads7843 max spi speed 2 MHz? 75 | X = 0xD0 76 | Y = 0x90 77 | Z1 = 0xB0 78 | Z2 = 0xC0 79 | 80 | def initTOUCH(self, pen, ce=0, spi_speed=100000): 81 | self._ce_tch = ce 82 | self._spi_speed_tch=spi_speed 83 | self._pen = pen 84 | self._gpio.setup(pen, self._gpio.IN) 85 | 86 | def penDown(self): 87 | # reads True when stylus is in contact 88 | return not self._gpio.input(self._pen) 89 | 90 | def readValue(self, channel): 91 | # self._spi.open(0, self._ce_tch) 92 | self._spi.open(1,self._ce_tch) 93 | self._spi.max_speed_hz=self._spi_speed_tch 94 | 95 | responseData = self._spi.xfer([channel , 0, 0]) 96 | self._spi.close() 97 | return (responseData[1] << 5) | (responseData[2] >> 3) 98 | # Pick off the 12-bit reply 99 | 100 | def penPosition(self): 101 | self.readValue(self.X) 102 | self.readValue(self.Y) 103 | self.readValue(self.X) 104 | self.readValue(self.Y) 105 | # burn those 106 | x=0 107 | y=0 108 | for k in range(10): 109 | x += self.readValue(self.X) 110 | y += self.readValue(self.Y) 111 | # average those 112 | x = x / 10 113 | y = y / 10 114 | # empirically set calibration factors: 115 | x2 = (4096 -x) * calib_scale240 / 4096 -calib_offset240 116 | y2 = y * calib_scale320 / 4096 - calib_offset320 117 | # So far, these co-ordinates are the native portrait mode 118 | 119 | if y2(319-margin) or x2 (239-margin): 120 | x2=0 121 | y2=0 122 | # The fringes of touchscreen give a lot of erratic/spurious results 123 | # Don't allow fringes to return anything. 124 | # (Also, user should not program hotspots/icons out in the margin, to discourage pointing pen there) 125 | # a return of (0,0) is considered a nul return 126 | 127 | if self.is_landscape: 128 | # rotate the coordinates 129 | x3 = x2 130 | x2 = 319-y2 131 | y2 = x3 132 | return [x2, y2] 133 | 134 | 135 | # TFT/LCD part 136 | 137 | def send2lcd(self, data, is_data=True, chunk_size=4096): 138 | 139 | # Set DC low for command, high for data. 140 | self._gpio.output(self._dc, is_data) 141 | self._spi.open(0, self._ce_lcd) 142 | self._spi.max_speed_hz=self._spi_speed_lcd 143 | 144 | # Convert scalar argument to list so either can be passed as parameter. 145 | if isinstance(data, numbers.Number): 146 | data = [data & 0xFF] 147 | # Write data a chunk at a time. 148 | for start in range(0, len(data), chunk_size): 149 | end = min(start+chunk_size, len(data)) 150 | self._spi.writebytes(data[start:end]) 151 | self._spi.close() 152 | 153 | def command(self, data): 154 | """Write a byte or array of bytes to the display as command data.""" 155 | self.send2lcd(data, False) 156 | 157 | def data(self, data): 158 | """Write a byte or array of bytes to the display as display data.""" 159 | self.send2lcd(data, True) 160 | 161 | def resetlcd(self): 162 | if self._rst is not None: 163 | self._gpio.output(self._rst, self._gpio.HIGH) 164 | time.sleep(0.005) 165 | self._gpio.output(self._rst, self._gpio.LOW) 166 | time.sleep(0.02) 167 | self._gpio.output(self._rst, self._gpio.HIGH) 168 | time.sleep(0.150) 169 | else: 170 | self.command(ILI9341_SWRESET) 171 | sleep(1) 172 | 173 | def _init9341(self): 174 | self.command(ILI9341_PWCTR1) 175 | self.data(0x23) 176 | self.command(ILI9341_PWCTR2) 177 | self.data(0x10) 178 | self.command(ILI9341_VMCTR1) 179 | self.data([0x3e, 0x28]) 180 | self.command(ILI9341_VMCTR2) 181 | self.data(0x86) 182 | self.command(ILI9341_MADCTL) 183 | self.data(0x48) 184 | self.command(ILI9341_PIXFMT) 185 | self.data(0x55) 186 | self.command(ILI9341_FRMCTR1) 187 | self.data([0x00, 0x18]) 188 | self.command(ILI9341_DFUNCTR) 189 | self.data([0x08, 0x82, 0x27]) 190 | self.command(0xF2) 191 | self.data(0x00) 192 | self.command(ILI9341_GAMMASET) 193 | self.data(0x01) 194 | self.command(ILI9341_GMCTRP1) 195 | self.data([0x0F, 0x31, 0x2b, 0x0c, 0x0e, 0x08, 0x4e, 0xf1, 0x37, 0x07, 0x10, 0x03, 0x0e, 0x09, 0x00]) 196 | self.command(ILI9341_GMCTRN1) 197 | self.data([0x00, 0x0e, 0x14, 0x03, 0x11, 0x07, 0x31, 0xc1, 0x48, 0x08, 0x0f, 0x0c, 0x31, 0x36, 0x0f]) 198 | self.command(ILI9341_SLPOUT) 199 | time.sleep(0.120) 200 | self.command(ILI9341_DISPON) 201 | 202 | def initLCD(self, dc=None, rst=None, led=None, ce=0, spi_speed=32000000): 203 | global Buffer 204 | self._dc = dc 205 | self._rst = rst 206 | self._led = led 207 | self._ce_lcd = ce 208 | self._spi_speed_lcd=spi_speed 209 | # Set DC as output. 210 | self._gpio.setup(dc, self._gpio.OUT) 211 | # Setup reset as output (if provided). 212 | if rst is not None: 213 | self._gpio.setup(rst, self._gpio.OUT) 214 | if led is not None: 215 | self._gpio.setup(led, self._gpio.OUT) 216 | self._gpio.output(led, self._gpio.HIGH) 217 | 218 | # Create an image buffer. 219 | if self.is_landscape: 220 | Buffer = Image.new('RGB', (ILI9341_TFTHEIGHT, ILI9341_TFTWIDTH)) 221 | else: 222 | Buffer = Image.new('RGB', (ILI9341_TFTWIDTH, ILI9341_TFTHEIGHT)) 223 | # and a backup buffer for backup/restore 224 | self.buffer2 = Buffer.copy() 225 | self.resetlcd() 226 | self._init9341() 227 | 228 | def set_frame(self, x0=0, y0=0, x1=None, y1=None): 229 | 230 | if x1 is None: 231 | x1 = ILI9341_TFTWIDTH-1 232 | if y1 is None: 233 | y1 = ILI9341_TFTHEIGHT-1 234 | self.command(ILI9341_CASET) # Column addr 235 | self.data([x0 >> 8, x0, x1 >> 8, x1]) 236 | self.command(ILI9341_PASET) # Row addr 237 | self.data([y0 >> 8, y0, y1 >> 8, y1]) 238 | self.command(ILI9341_RAMWR) 239 | 240 | def display(self, image=None): 241 | """Write the display buffer or provided image to the hardware. If no 242 | image parameter is provided the display buffer will be written to the 243 | hardware. If an image is provided, it should be RGB format and the 244 | same dimensions as the display hardware. 245 | """ 246 | # By default write the internal buffer to the display. 247 | if image is None: 248 | image = Buffer 249 | if image.size[0] == 320: 250 | image = image.rotate(90) 251 | 252 | # Set address bounds to entire display. 253 | self.set_frame() 254 | # Convert image to array of 16bit 565 RGB data bytes. 255 | pixelbytes = list(self.image_to_data(image)) 256 | # Write data to hardware. 257 | self.data(pixelbytes) 258 | 259 | def penprint(self, position, size, color=(0,0,0) ): 260 | x=position[0] 261 | y=position[1] 262 | if self.is_landscape: 263 | # rotate the coordinates. The intrinsic hardware is portrait 264 | x3 = x 265 | x = y 266 | y = 319-x3 267 | self.set_frame(x, y-size, x+size, y+size) 268 | pixelbytes=[0]*(size*size*8) 269 | self.data(pixelbytes) 270 | 271 | 272 | def clear(self, color=(0,0,0)): 273 | """ 274 | Clear the image buffer to the specified RGB color (default black). 275 | USE (r, g, b) NOTATION FOR THE COLOUR !! 276 | """ 277 | 278 | if type(color) != type((0,0,0)): 279 | print ("clear() function colours must be in (255,255,0) form") 280 | exit() 281 | width, height = Buffer.size 282 | Buffer.putdata([color]*(width*height)) 283 | self.display() 284 | 285 | def draw(self): 286 | """Return a PIL ImageDraw instance for drawing on the image buffer.""" 287 | d = ImageDraw.Draw(Buffer) 288 | # Add custom methods to the draw object: 289 | # d.textrotated = MethodType(_textrotated, d, ImageDraw.Draw) 290 | # d.pasteimage = MethodType(_pasteimage, d, ImageDraw.Draw) 291 | # d.textwrapped = MethodType(_textwrapped, d, ImageDraw.Draw) 292 | d.textrotated = MethodType(_textrotated, d) 293 | d.pasteimage = MethodType(_pasteimage, d) 294 | d.textwrapped = MethodType(_textwrapped, d) 295 | return d 296 | 297 | def load_wallpaper(self, filename): 298 | # The image should be 320x240 or 240x320 only (full wallpaper!). Errors otherwise. 299 | # We need to cope with whatever orientations file image and TFT canvas are. 300 | image = Image.open(filename) 301 | if image.size[0] > Buffer.size[0]: 302 | Buffer.paste(image.rotate(90)) 303 | elif image.size[0] < Buffer.size[0]: 304 | Buffer.paste(image.rotate(-90)) 305 | else: 306 | Buffer.paste(image) 307 | 308 | def backup_buffer(self): 309 | self.buffer2.paste(Buffer) 310 | 311 | def restore_buffer(self): 312 | Buffer.paste(self.buffer2) 313 | 314 | def invert(self, onoff): 315 | if onoff: 316 | self.command(ILI9341_INVON) 317 | else: 318 | self.command(ILI9341_INVOFF) 319 | 320 | def backlite(self, onoff): 321 | if self._led is not None: 322 | self._gpio.output(self._led, onoff) 323 | 324 | def image_to_data(self, image): 325 | """Generator function to convert a PIL image to 16-bit 565 RGB bytes.""" 326 | # Source of this code: Adafruit ILI9341 python project 327 | pixels = image.convert('RGB').load() 328 | width, height = image.size 329 | for y in range(height): 330 | for x in range(width): 331 | r,g,b = pixels[(x,y)] 332 | color = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3) 333 | yield (color >> 8) & 0xFF 334 | yield color & 0xFF 335 | 336 | 337 | def textdirect(self, pos, text, font, fill="white"): 338 | 339 | width, height = self.draw().textsize(text, font=font) 340 | # Create a new image with transparent background to store the text. 341 | textimage = Image.new('RGBA', (width, height), (255,255,255,0)) 342 | # Render the text. 343 | textdraw = ImageDraw.Draw(textimage) 344 | textdraw.text((0,0), text, font=font, fill=fill) 345 | self.set_frame(pos[0], pos[1], pos[0]+width-1, pos[1]+height-1) 346 | # Convert image to array of 16bit 565 RGB data bytes. 347 | pixelbytes = list(self.image_to_data(textimage)) 348 | # Write data to hardware. 349 | self.data(pixelbytes) 350 | 351 | def penOnHotspot(self, HSlist, pos): 352 | # HotSpot list of "hotspots" - of form [(x0,y0,x1,y1,returnvalue)]*numOfSpots 353 | # if cursor position "pos" is within a hotspot box x0y0:x1y1, then "returnvalue" is returned 354 | x=pos[0] 355 | y=pos[1] 356 | for hs in HSlist: 357 | if x >= hs[0] and x<= hs[2] and y>= hs[1] and y<=hs[3]: 358 | return hs[4] 359 | return None 360 | 361 | # CUSTOM FUNCTIONS FOR draw() IN LCD CANVAS SYSTEM 362 | 363 | # We import these extra functions below as new custom methods of the PIL "draw" function: 364 | # Hints on this custom method technique: 365 | # http://www.ianlewis.org/en/dynamically-adding-method-classes-or-class-instanc 366 | 367 | def _textrotated(self, position, text, angle, font, fill="white"): 368 | # Define a function to create rotated text. 369 | # Source of this rotation coding: Adafruit ILI9341 python project 370 | # "Unfortunately PIL doesn't have good 371 | # native support for rotated fonts, but this function can be used to make a 372 | # text image and rotate it so it's easy to paste in the buffer." 373 | width, height = self.textsize(text, font=font) 374 | # Create a new image with transparent background to store the text. 375 | textimage = Image.new('RGBA', (width, height), (0,0,0,0)) 376 | # Render the text. 377 | textdraw = ImageDraw.Draw(textimage) 378 | textdraw.text((0,0), text, font=font, fill=fill) 379 | # Rotate the text image. 380 | rotated = textimage.rotate(angle, expand=1) 381 | # Paste the text into the TFT canvas image, using text itself as a mask for transparency. 382 | Buffer.paste(rotated, position, rotated) # into the global Buffer 383 | # example: draw.textrotated(position, text, angle, font, fill) 384 | 385 | def _pasteimage(self, filename, position): 386 | Buffer.paste(Image.open(filename), position) 387 | # example: draw.pasteimage('bl.jpg', (30,80)) 388 | 389 | def _textwrapped(self, position, text1, length, height, font, fill="white"): 390 | text2=textwrap.wrap(text1, length) 391 | y=position[1] 392 | for t in text2: 393 | self.text((position[0],y), t, font=font, fill=fill) 394 | y += height 395 | # example: draw.textwrapped((2,0), "but a lot longer", 50, 18, myFont, "black") 396 | 397 | # All colours may be any notation: 398 | # (255,0,0) =red (R, G, B) 399 | # 0x0000FF =red BBGGRR 400 | # "#FF0000" =red RRGGBB 401 | # "red" =red html colour names, insensitive 402 | -------------------------------------------------------------------------------- /2.8_LCD_display_on_a_Raspberry_Pi_ft_ILI9341/wiring_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/2.8_LCD_display_on_a_Raspberry_Pi_ft_ILI9341/wiring_diagram.png -------------------------------------------------------------------------------- /2.8_LCD_display_on_an_ESP32_ft_ILI9341/esp32_ili9341.ino: -------------------------------------------------------------------------------- 1 | /*************************************************** 2 | Modified graphics demo for the ESP-WROVER-KIT and equivalent 3 | projects using Ardiono-ESP32 with an ILI9341 LCD display 4 | By Martin Falatic 5 | ****************************************************/ 6 | /*************************************************** 7 | This is our GFX example for the Adafruit ILI9341 Breakout and Shield 8 | ----> http://www.adafruit.com/products/1651 9 | 10 | Check out the links above for our tutorials and wiring diagrams 11 | These displays use SPI to communicate, 4 or 5 pins are required to 12 | interface (RST is optional) 13 | Adafruit invests time and resources providing this open source code, 14 | please support Adafruit and open-source hardware by purchasing 15 | products from Adafruit! 16 | 17 | Written by Limor Fried/Ladyada for Adafruit Industries. 18 | MIT license, all text above must be included in any redistribution 19 | ****************************************************/ 20 | 21 | 22 | #include "SPI.h" 23 | #include "Adafruit_GFX.h" 24 | #include "Adafruit_ILI9341.h" 25 | 26 | // For the ESP-WROVER_KIT, these are the default. 27 | #define TFT_CS 5 28 | #define TFT_DC 16 29 | #define TFT_MOSI 23 30 | #define TFT_CLK 18 31 | #define TFT_RST 17 32 | #define TFT_MISO 19 33 | #define TFT_LED 4 // GPIO not managed by library 34 | 35 | Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RST, TFT_MISO); 36 | 37 | void backlighting(bool state) { 38 | if (state) { 39 | digitalWrite(TFT_LED, LOW); 40 | } 41 | else { 42 | digitalWrite(TFT_LED, HIGH); 43 | } 44 | } 45 | 46 | void setup() { 47 | Serial.begin(115200); 48 | Serial.println("ILI9341 Test!"); 49 | 50 | tft.begin(); 51 | pinMode(TFT_LED, OUTPUT); 52 | backlighting(true); 53 | 54 | // read diagnostics (optional but can help debug problems) 55 | uint8_t x = tft.readcommand8(ILI9341_RDMODE); 56 | Serial.print("Display Power Mode: 0x"); Serial.println(x, HEX); 57 | x = tft.readcommand8(ILI9341_RDMADCTL); 58 | Serial.print("MADCTL Mode: 0x"); Serial.println(x, HEX); 59 | x = tft.readcommand8(ILI9341_RDPIXFMT); 60 | Serial.print("Pixel Format: 0x"); Serial.println(x, HEX); 61 | x = tft.readcommand8(ILI9341_RDIMGFMT); 62 | Serial.print("Image Format: 0x"); Serial.println(x, HEX); 63 | x = tft.readcommand8(ILI9341_RDSELFDIAG); 64 | Serial.print("Self Diagnostic: 0x"); Serial.println(x, HEX); 65 | } 66 | 67 | void loop(void) { 68 | Serial.println(F("Benchmark Time (microseconds)")); 69 | delay(10); 70 | Serial.print(F("Screen fill ")); 71 | Serial.println(testFillScreen()); 72 | delay(250); 73 | 74 | for(uint8_t rotation=0; rotation<4; rotation++) { 75 | Serial.print(F("Text (rotation=")); 76 | Serial.print(rotation); 77 | Serial.print(F(") ")); 78 | tft.setRotation(rotation); 79 | Serial.println(testText()); 80 | delay(1000); 81 | } 82 | 83 | Serial.print(F("Lines ")); 84 | Serial.println(testLines(ILI9341_CYAN)); 85 | delay(250); 86 | 87 | Serial.print(F("Horiz/Vert Lines ")); 88 | Serial.println(testFastLines(ILI9341_RED, ILI9341_BLUE)); 89 | delay(250); 90 | 91 | Serial.print(F("Rectangles (outline) ")); 92 | Serial.println(testRects(ILI9341_GREEN)); 93 | delay(250); 94 | 95 | Serial.print(F("Rectangles (filled) ")); 96 | Serial.println(testFilledRects(ILI9341_YELLOW, ILI9341_MAGENTA)); 97 | delay(250); 98 | 99 | Serial.print(F("Circles (filled) ")); 100 | Serial.println(testFilledCircles(10, ILI9341_MAGENTA)); 101 | 102 | Serial.print(F("Circles (outline) ")); 103 | Serial.println(testCircles(10, ILI9341_WHITE)); 104 | delay(250); 105 | 106 | Serial.print(F("Triangles (outline) ")); 107 | Serial.println(testTriangles()); 108 | delay(250); 109 | 110 | Serial.print(F("Triangles (filled) ")); 111 | Serial.println(testFilledTriangles()); 112 | delay(250); 113 | 114 | Serial.print(F("Rounded rects (outline) ")); 115 | Serial.println(testRoundRects()); 116 | delay(250); 117 | 118 | Serial.print(F("Rounded rects (filled) ")); 119 | Serial.println(testFilledRoundRects()); 120 | delay(250); 121 | 122 | Serial.println(F("Done!")); 123 | Serial.println(); 124 | delay(3000); 125 | } 126 | 127 | unsigned long testFillScreen() { 128 | unsigned long start = micros(); 129 | tft.fillScreen(ILI9341_BLACK); 130 | yield(); 131 | tft.fillScreen(ILI9341_RED); 132 | yield(); 133 | tft.fillScreen(ILI9341_GREEN); 134 | yield(); 135 | tft.fillScreen(ILI9341_BLUE); 136 | yield(); 137 | tft.fillScreen(ILI9341_BLACK); 138 | yield(); 139 | return micros() - start; 140 | } 141 | 142 | unsigned long testText() { 143 | tft.fillScreen(ILI9341_BLACK); 144 | unsigned long start = micros(); 145 | tft.setCursor(0, 0); 146 | tft.setTextColor(ILI9341_WHITE); tft.setTextSize(1); 147 | tft.println("Hello World!"); 148 | tft.setTextColor(ILI9341_YELLOW); tft.setTextSize(2); 149 | tft.println(1234.56); 150 | tft.setTextColor(ILI9341_RED); tft.setTextSize(3); 151 | tft.println(0xDEADBEEF, HEX); 152 | tft.println(); 153 | tft.setTextColor(ILI9341_GREEN); 154 | tft.setTextSize(5); 155 | tft.println("Groop"); 156 | tft.setTextSize(2); 157 | tft.println("I implore thee,"); 158 | tft.setTextSize(1); 159 | tft.println("my foonting turlingdromes."); 160 | tft.println("And hooptiously drangle me"); 161 | tft.println("with crinkly bindlewurdles,"); 162 | tft.println("Or I will rend thee"); 163 | tft.println("in the gobberwarts"); 164 | tft.println("with my blurglecruncheon,"); 165 | tft.println("see if I don't!"); 166 | return micros() - start; 167 | } 168 | 169 | unsigned long testLines(uint16_t color) { 170 | unsigned long start, t; 171 | int x1, y1, x2, y2, 172 | w = tft.width(), 173 | h = tft.height(); 174 | 175 | tft.fillScreen(ILI9341_BLACK); 176 | yield(); 177 | 178 | x1 = y1 = 0; 179 | y2 = h - 1; 180 | start = micros(); 181 | for(x2=0; x20; i-=6) { 266 | i2 = i / 2; 267 | start = micros(); 268 | tft.fillRect(cx-i2, cy-i2, i, i, color1); 269 | t += micros() - start; 270 | // Outlines are not included in timing results 271 | tft.drawRect(cx-i2, cy-i2, i, i, color2); 272 | yield(); 273 | } 274 | 275 | return t; 276 | } 277 | 278 | unsigned long testFilledCircles(uint8_t radius, uint16_t color) { 279 | unsigned long start; 280 | int x, y, w = tft.width(), h = tft.height(), r2 = radius * 2; 281 | 282 | tft.fillScreen(ILI9341_BLACK); 283 | start = micros(); 284 | for(x=radius; x10; i-=5) { 338 | start = micros(); 339 | tft.fillTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i, 340 | tft.color565(0, i*10, i*10)); 341 | t += micros() - start; 342 | tft.drawTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i, 343 | tft.color565(i*10, i*10, 0)); 344 | yield(); 345 | } 346 | 347 | return t; 348 | } 349 | 350 | unsigned long testRoundRects() { 351 | unsigned long start; 352 | int w, i, i2, 353 | cx = tft.width() / 2 - 1, 354 | cy = tft.height() / 2 - 1; 355 | 356 | tft.fillScreen(ILI9341_BLACK); 357 | w = min(tft.width(), tft.height()); 358 | start = micros(); 359 | for(i=0; i20; i-=6) { 376 | i2 = i / 2; 377 | tft.fillRoundRect(cx-i2, cy-i2, i, i, i/8, tft.color565(0, i, 0)); 378 | yield(); 379 | } 380 | 381 | return micros() - start; 382 | } 383 | -------------------------------------------------------------------------------- /2.8_LCD_display_on_an_ESP32_ft_ILI9341/wiring_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/2.8_LCD_display_on_an_ESP32_ft_ILI9341/wiring_diagram.png -------------------------------------------------------------------------------- /Arduino_USB_volume_controller_&_Macro_Keyboard/volume_control.ino: -------------------------------------------------------------------------------- 1 | // Rotary Encoder 2 | #include "ESPRotary.h"; 3 | #define ROTARY_PIN_1 4 4 | #define ROTARY_PIN_2 3 5 | int moves_per_click = 2; 6 | ESPRotary r = ESPRotary(ROTARY_PIN_1, ROTARY_PIN_2, moves_per_click) ; 7 | int old_pos = 0; 8 | int new_pos = 0; 9 | 10 | // Keyboard Library 11 | #include "HID-Project.h" 12 | 13 | // keys 14 | int keypadPins[9] = {2, 15, 10, 16, 6, 14, 8, 7, 9}; 15 | int keypadStatus; // Used to monitor which buttons are pressed. 16 | int timeout; // timeout variable used in loop 17 | int UpDownArr, SideArr = 0; 18 | int MainVol = 1; 19 | 20 | void setup() { 21 | Serial.begin(115200); 22 | // Rotate 23 | r.setChangedHandler(rotate); 24 | for (int i = 0; i < 9; i++) { 25 | pinMode(keypadPins[i], INPUT); // Set all keypad pins as inputs 26 | digitalWrite(keypadPins[i], HIGH); // pull all keypad pins high 27 | } 28 | Consumer.begin(); 29 | } 30 | 31 | void loop() { 32 | r.loop(); 33 | keypadStatus = getKeypadStatus(); // read which buttons are pressed 34 | if (keypadStatus != 0) { 35 | sendKeyPress(keypadStatus); // send the button over USB 36 | timeout = 2000; // top of the repeat delay 37 | while ((keypadStatus == getKeypadStatus()) && (--timeout)) // Decrement timeout and check if key is being held down 38 | delayMicroseconds(400); 39 | while (getKeypadStatus() == keypadStatus) // while the same button is held down 40 | { 41 | sendKeyPress(keypadStatus); // continue to send the button over USB 42 | delay(250); 43 | } 44 | } 45 | } 46 | 47 | void rotate(ESPRotary & r) { 48 | new_pos = r.getPosition(); 49 | if ( old_pos > new_pos) { 50 | old_pos = new_pos ; 51 | if ( MainVol == 1) { 52 | Serial.println("MEDIA_VOLUME_UP"); 53 | Consumer.write(MEDIA_VOLUME_UP); 54 | } 55 | else if ( SideArr == 1) { 56 | Serial.println("KEY_RIGHT_ARROW"); 57 | Keyboard.press(KEY_RIGHT_ARROW); 58 | Keyboard.releaseAll(); 59 | } 60 | else if ( UpDownArr == 1) { 61 | Serial.println("KEY_DOWN_ARROW"); 62 | Keyboard.press(KEY_DOWN_ARROW); 63 | Keyboard.releaseAll(); 64 | } 65 | } else { 66 | old_pos = new_pos ; 67 | if ( MainVol == 1) { 68 | Serial.println("MEDIA_VOLUME_DOWN"); 69 | Consumer.write(MEDIA_VOLUME_DOWN); 70 | } 71 | else if ( SideArr == 1) { 72 | Serial.println("KEY_LEFT_ARROW"); 73 | Keyboard.press(KEY_LEFT_ARROW); 74 | Keyboard.releaseAll(); 75 | } 76 | else if ( UpDownArr == 1) { 77 | Serial.println("KEY_UP_ARROW"); 78 | Keyboard.press(KEY_UP_ARROW); 79 | Keyboard.releaseAll(); 80 | } 81 | } 82 | } 83 | 84 | void sendKeyPress(int key) { 85 | switch (key) { 86 | case 1: // 0x001 87 | Serial.println("MEDIA_VOLUME_MUTE"); 88 | Consumer.write(MEDIA_VOLUME_MUTE); 89 | break; 90 | case 2: // 0x002 91 | Serial.println("KEY_LEFT_CTRL+C"); 92 | Keyboard.press(KEY_LEFT_CTRL); 93 | Keyboard.press(KEY_C); 94 | Keyboard.releaseAll(); 95 | delay(75); 96 | break; 97 | case 4: // 0x004 98 | Serial.println("KEY_LEFT_CTRL+V"); 99 | Keyboard.press(KEY_LEFT_CTRL); 100 | Keyboard.press(KEY_V); 101 | Keyboard.releaseAll(); 102 | delay(75); 103 | break; 104 | case 8: // 0x008 105 | Serial.println("KEY_LEFT_CTRL+X"); 106 | Keyboard.press(KEY_LEFT_CTRL); 107 | Keyboard.press(KEY_X); 108 | Keyboard.releaseAll(); 109 | delay(75); 110 | break; 111 | case 16: // 0x010 112 | Serial.println("KEY_LEFT_ARROW"); 113 | Keyboard.press(KEY_LEFT_ARROW); 114 | Keyboard.releaseAll(); 115 | delay(75); 116 | break; 117 | case 32: // 0x020 118 | Serial.println("KEY_DOWN_ARROW"); 119 | Keyboard.press(KEY_DOWN_ARROW); 120 | Keyboard.releaseAll(); 121 | delay(75); 122 | break; 123 | case 64: // 0x040 124 | Serial.println("KEY_RIGHT_ARROW"); 125 | Keyboard.press(KEY_RIGHT_ARROW); 126 | Keyboard.releaseAll(); 127 | delay(75); 128 | break; 129 | case 128: // 0x080 130 | Serial.println("KEY_UP_ARROW"); 131 | Keyboard.press(KEY_UP_ARROW); 132 | Keyboard.releaseAll(); 133 | delay(75); 134 | break; 135 | case 256: // 0x100 136 | Serial.println(key); 137 | if ( MainVol == 1 ) { 138 | UpDownArr = 1; 139 | SideArr = 0; 140 | MainVol = 0; 141 | } 142 | else if ( UpDownArr == 1 ) { 143 | UpDownArr = 0; 144 | SideArr = 1; 145 | MainVol = 0; 146 | } 147 | else { 148 | UpDownArr = 0; 149 | SideArr = 0; 150 | MainVol = 1; 151 | } 152 | break; 153 | } 154 | } 155 | 156 | int getKeypadStatus() { 157 | int keypadStatus = 0; // this will be what's returned 158 | 159 | /* initialize all pins, inputs w/ pull-ups */ 160 | for (int i = 0; i < 9; i++) { 161 | if (!digitalRead(keypadPins[i])) { 162 | keypadStatus |= 1 << i; // set the status bit of the keypad return value 163 | } 164 | } 165 | return keypadStatus; 166 | } 167 | -------------------------------------------------------------------------------- /Arduino_USB_volume_controller_&_Macro_Keyboard/wiring diagram.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/Arduino_USB_volume_controller_&_Macro_Keyboard/wiring diagram.PNG -------------------------------------------------------------------------------- /ESP12-E_Booting_and_Flashing/Blink.ino: -------------------------------------------------------------------------------- 1 | // the setup function runs once when you press reset or power the board 2 | void setup() { 3 | // initialize digital pin LED_BUILTIN as an output. 4 | pinMode(2, OUTPUT); 5 | } 6 | 7 | // the loop function runs over and over again forever 8 | void loop() { 9 | digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level) 10 | delay(1000); // wait for a second 11 | digitalWrite(2, LOW); // turn the LED off by making the voltage LOW 12 | delay(1000); // wait for a second 13 | } 14 | -------------------------------------------------------------------------------- /ESP12-E_Booting_and_Flashing/wiring diagram.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/ESP12-E_Booting_and_Flashing/wiring diagram.PNG -------------------------------------------------------------------------------- /Improved_Home_Automation/ESP8266_MQTT_Part_3/esp12e_publish.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | const char* ssid = "VRHQ"; 5 | const char* password = "juice098"; 6 | const char* mqtt_server = "192.168.1.9"; 7 | 8 | WiFiClient espClient; 9 | PubSubClient client(espClient); 10 | long lastMsg = 0; 11 | char msg[50]; 12 | int value = 0; 13 | 14 | void setup_wifi() { 15 | delay(10); 16 | // We start by connecting to a WiFi network 17 | Serial.println(); 18 | Serial.print("Connecting to "); 19 | Serial.println(ssid); 20 | 21 | WiFi.begin(ssid, password); 22 | 23 | while (WiFi.status() != WL_CONNECTED) { 24 | delay(500); 25 | Serial.print("."); 26 | } 27 | 28 | Serial.println(""); 29 | Serial.println("WiFi connected"); 30 | Serial.println("IP address: "); 31 | Serial.println(WiFi.localIP()); 32 | } 33 | 34 | void reconnect() { 35 | // Loop until we're reconnected 36 | while (!client.connected()) { 37 | Serial.print("Attempting MQTT connection..."); 38 | // Create a random client ID 39 | String clientId = "ESP8266Client-"; 40 | clientId += String(random(0xffff), HEX); 41 | // Attempt to connect 42 | if (client.connect(clientId.c_str())) { 43 | Serial.println("connected"); 44 | // Once connected, publish an announcement 45 | client.publish("outTopic", "hello world"); 46 | } else { 47 | Serial.print("failed, rc="); 48 | Serial.print(client.state()); 49 | Serial.println(" try again in 5 seconds"); 50 | // Wait 5 seconds before retrying 51 | delay(5000); 52 | } 53 | } 54 | } 55 | 56 | void setup() { 57 | Serial.begin(115200); 58 | setup_wifi(); 59 | client.setServer(mqtt_server, 1883); 60 | } 61 | 62 | void loop() { 63 | if (!client.connected()) { 64 | reconnect(); 65 | } 66 | client.loop(); 67 | 68 | long now = millis(); 69 | if (now - lastMsg > 5000) { 70 | lastMsg = now; 71 | ++value; 72 | snprintf (msg, 50, "Message #%ld", value); 73 | Serial.print("Publish message: "); 74 | Serial.println(msg); 75 | client.publish("outTopic", msg); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /Improved_Home_Automation/ESP8266_MQTT_Part_3/esp12e_sub_pub.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | const char* ssid = "VRHQ"; 5 | const char* password = "juice098"; 6 | const char* mqtt_server = "192.168.1.9"; 7 | 8 | WiFiClient espClient; 9 | PubSubClient client(espClient); 10 | long lastMsg = 0; 11 | char msg[50]; 12 | int value = 0; 13 | 14 | void setup_wifi() { 15 | delay(10); 16 | // We start by connecting to a WiFi network 17 | Serial.println(); 18 | Serial.print("Connecting to "); 19 | Serial.println(ssid); 20 | 21 | WiFi.begin(ssid, password); 22 | 23 | while (WiFi.status() != WL_CONNECTED) { 24 | delay(500); 25 | Serial.print("."); 26 | } 27 | 28 | Serial.println(""); 29 | Serial.println("WiFi connected"); 30 | Serial.println("IP address: "); 31 | Serial.println(WiFi.localIP()); 32 | } 33 | 34 | void callback(char* topic, byte* payload, unsigned int length) { 35 | Serial.print("Message arrived ["); 36 | Serial.print(topic); 37 | Serial.print("] "); 38 | for (int i = 0; i < length; i++) { 39 | Serial.print((char)payload[i]); 40 | } 41 | Serial.println(); 42 | 43 | // Switch on the LED if an 1 was received as first character 44 | if ((char)payload[0] == '1') { 45 | digitalWrite(BUILTIN_LED, LOW); 46 | } 47 | // Switch off the LED if an 0 was received as first character 48 | if ((char)payload[0] == '0') { 49 | digitalWrite(BUILTIN_LED, HIGH); 50 | } 51 | } 52 | 53 | void reconnect() { 54 | // Loop until we're reconnected 55 | while (!client.connected()) { 56 | Serial.print("Attempting MQTT connection..."); 57 | // Create a random client ID 58 | String clientId = "ESP8266Client-"; 59 | clientId += String(random(0xffff), HEX); 60 | // Attempt to connect 61 | if (client.connect(clientId.c_str())) { 62 | Serial.println("connected"); 63 | // Once connected, publish an announcement... 64 | client.publish("outTopic", "hello world"); 65 | // ... and resubscribe 66 | client.subscribe("#"); 67 | } else { 68 | Serial.print("failed, rc="); 69 | Serial.print(client.state()); 70 | Serial.println(" try again in 5 seconds"); 71 | // Wait 5 seconds before retrying 72 | delay(5000); 73 | } 74 | } 75 | } 76 | 77 | void setup() { 78 | pinMode(BUILTIN_LED, OUTPUT); 79 | Serial.begin(115200); 80 | setup_wifi(); 81 | client.setServer(mqtt_server, 1883); 82 | client.setCallback(callback); 83 | digitalWrite(BUILTIN_LED, HIGH); 84 | } 85 | 86 | void loop() { 87 | if (!client.connected()) { 88 | reconnect(); 89 | } 90 | client.loop(); 91 | 92 | long now = millis(); 93 | if (now - lastMsg > 5000) { 94 | lastMsg = now; 95 | ++value; 96 | snprintf (msg, 50, "Message #%ld", value); 97 | Serial.print("Publish message: "); 98 | Serial.println(msg); 99 | client.publish("outTopic", msg); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /Improved_Home_Automation/ESP8266_MQTT_Part_3/esp12e_subscribe.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | const char* ssid = "VRHQ"; 5 | const char* password = "juice098"; 6 | const char* mqtt_server = "192.168.1.9"; 7 | 8 | WiFiClient espClient; 9 | PubSubClient client(espClient); 10 | long lastMsg = 0; 11 | char msg[50]; 12 | 13 | void setup_wifi() { 14 | delay(10); 15 | // We start by connecting to a WiFi network 16 | Serial.println(); 17 | Serial.print("Connecting to "); 18 | Serial.println(ssid); 19 | 20 | WiFi.begin(ssid, password); 21 | 22 | while (WiFi.status() != WL_CONNECTED) { 23 | delay(500); 24 | Serial.print("."); 25 | } 26 | 27 | Serial.println(""); 28 | Serial.println("WiFi connected"); 29 | Serial.println("IP address: "); 30 | Serial.println(WiFi.localIP()); 31 | } 32 | 33 | void callback(char* topic, byte* payload, unsigned int length) { 34 | Serial.print("Message arrived ["); 35 | Serial.print(topic); 36 | Serial.print("] "); 37 | for (int i = 0; i < length; i++) { 38 | Serial.print((char)payload[i]); 39 | } 40 | Serial.println(); 41 | 42 | // Switch on the LED if an 1 was received as first character 43 | if ((char)payload[0] == '1') { 44 | digitalWrite(BUILTIN_LED, LOW); 45 | } 46 | // Switch off the LED if an 0 was received as first character 47 | if ((char)payload[0] == '0') { 48 | digitalWrite(BUILTIN_LED, HIGH); 49 | } 50 | } 51 | 52 | void reconnect() { 53 | // Loop until we're reconnected 54 | while (!client.connected()) { 55 | Serial.print("Attempting MQTT connection..."); 56 | // Create a random client ID 57 | String clientId = "ESP8266Client-"; 58 | clientId += String(random(0xffff), HEX); 59 | // Attempt to connect 60 | if (client.connect(clientId.c_str())) { 61 | Serial.println("connected"); 62 | // Once connected, resubscribe 63 | client.subscribe("#"); 64 | } else { 65 | Serial.print("failed, rc="); 66 | Serial.print(client.state()); 67 | Serial.println(" try again in 5 seconds"); 68 | // Wait 5 seconds before retrying 69 | delay(5000); 70 | } 71 | } 72 | } 73 | 74 | void setup() { 75 | pinMode(BUILTIN_LED, OUTPUT); 76 | Serial.begin(115200); 77 | setup_wifi(); 78 | client.setServer(mqtt_server, 1883); 79 | client.setCallback(callback); 80 | digitalWrite(BUILTIN_LED, HIGH); 81 | } 82 | 83 | void loop() { 84 | if (!client.connected()) { 85 | reconnect(); 86 | } 87 | client.loop(); 88 | } 89 | -------------------------------------------------------------------------------- /Improved_Home_Automation/Python_MQTT_Part_2/publish.py: -------------------------------------------------------------------------------- 1 | # Publish 2 | import paho.mqtt.client as paho 3 | 4 | broker = "192.168.1.9" 5 | port = 1883 6 | 7 | def on_publish(client,userdata,result): 8 | print("\ndata published \n") 9 | pass 10 | 11 | 12 | mqtt_pub = paho.Client("PubDevice") 13 | mqtt_pub.on_publish = on_publish 14 | mqtt_pub.connect(broker,port) 15 | ret = mqtt_pub.publish("topic","Some data") 16 | -------------------------------------------------------------------------------- /Improved_Home_Automation/Python_MQTT_Part_2/sub_and_pub.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import paho.mqtt.client as paho 4 | from datetime import datetime 5 | 6 | broker = "192.168.1.9" 7 | port = 1883 8 | 9 | def on_publish(client,userdata,result): 10 | print("data published \n") 11 | pass 12 | 13 | 14 | def on_message(mosq, obj, msg): 15 | pri_str = msg.topic + " " + msg.payload.decode("utf-8") 16 | print(pri_str) 17 | pass 18 | 19 | 20 | mqtt_sub = paho.Client() 21 | mqtt_sub.on_message = on_message 22 | mqtt_sub.connect(broker, port) 23 | mqtt_sub.loop_start() 24 | mqtt_sub.subscribe("#") 25 | 26 | OldSec = 0 27 | 28 | while True: 29 | Sec = (datetime.now().second) % 3 30 | if OldSec != Sec: 31 | mqtt_pub = paho.Client("PubDevice") 32 | mqtt_pub.on_publish = on_publish 33 | mqtt_pub.connect(broker,port) 34 | ret = mqtt_pub.publish("topic","Seconds from Publish Device : {}\n".format(Sec)) 35 | OldSec = Sec 36 | -------------------------------------------------------------------------------- /Improved_Home_Automation/Python_MQTT_Part_2/subscribe.py: -------------------------------------------------------------------------------- 1 | # Subscribe 2 | import sys 3 | import os 4 | import paho.mqtt.client as paho 5 | 6 | broker = "192.168.1.9" 7 | port = 1883 8 | 9 | def on_message(mosq, obj, msg): 10 | pri_str = msg.topic + " " + msg.payload.decode("utf-8") 11 | print(pri_str) 12 | pass 13 | 14 | 15 | mqtt_sub = paho.Client() 16 | mqtt_sub.on_message = on_message 17 | mqtt_sub.connect(broker, port) 18 | mqtt_sub.loop_start() 19 | mqtt_sub.subscribe("#") 20 | #mqtt_sub.subscribe("topic1/something") 21 | #mqtt_sub.subscribe("topic2/something") 22 | 23 | while True: 24 | pass -------------------------------------------------------------------------------- /Neopixel_LEDs_with_ESP32_ft_WB2812B_LED_Pad/rgbpad_test.ino: -------------------------------------------------------------------------------- 1 | #include "FastLED.h" 2 | 3 | #define NUM_LEDS 16 4 | #define DATA_PIN 13 5 | 6 | int i, j, k; 7 | CRGB leds[NUM_LEDS]; 8 | 9 | void setup() { 10 | delay(2000); 11 | FastLED.addLeds(leds, NUM_LEDS); 12 | FastLED.setBrightness(10); 13 | } 14 | 15 | void loop() { 16 | for (i = 0 ; i < 256 ; i = i + 51) { 17 | for (j = 0 ; j < 256 ; j = j + 51) { 18 | for (k = 0 ; k < 256 ; k = k + 51) { 19 | leds[0] = CRGB(i, j, k); 20 | leds[1] = CRGB(i, j, k); 21 | leds[2] = CRGB(i, j, k); 22 | leds[3] = CRGB(i, j, k); 23 | leds[4] = CRGB(i, j, k); 24 | leds[5] = CRGB(i, j, k); 25 | leds[6] = CRGB(i, j, k); 26 | leds[7] = CRGB(i, j, k); 27 | leds[8] = CRGB(i, j, k); 28 | leds[9] = CRGB(i, j, k); 29 | leds[10] = CRGB(i, j, k); 30 | leds[11] = CRGB(i, j, k); 31 | leds[12] = CRGB(i, j, k); 32 | leds[13] = CRGB(i, j, k); 33 | leds[14] = CRGB(i, j, k); 34 | leds[15] = CRGB(i, j, k); 35 | FastLED.show(); 36 | delay(1000); 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Neopixel_LEDs_with_ESP32_ft_WB2812B_LED_Pad/wiring diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/Neopixel_LEDs_with_ESP32_ft_WB2812B_LED_Pad/wiring diagram.png -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Arduino_and_Esp_MC/SPI_nano_pn532.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/RFID_NFC_reader_writer_with_PN532_ft_Arduino_and_Esp_MC/SPI_nano_pn532.PNG -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Arduino_and_Esp_MC/i2c_nano_pn532.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/RFID_NFC_reader_writer_with_PN532_ft_Arduino_and_Esp_MC/i2c_nano_pn532.PNG -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Arduino_and_Esp_MC/i2c_pn532_esp32.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/RFID_NFC_reader_writer_with_PN532_ft_Arduino_and_Esp_MC/i2c_pn532_esp32.PNG -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Arduino_and_Esp_MC/i2c_pn532_esp8266.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/RFID_NFC_reader_writer_with_PN532_ft_Arduino_and_Esp_MC/i2c_pn532_esp8266.PNG -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Arduino_and_Esp_MC/mifare_classic_i2c.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // If using the breakout or shield with I2C, define just the pins connected 5 | // to the IRQ and reset lines. Use the values below (2, 3) for the shield! 6 | #define PN532_IRQ (2) 7 | #define PN532_RESET (3) // Not connected by default on the NFC Shield 8 | 9 | // Or use this line for a breakout or shield with an I2C connection: 10 | Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET); 11 | 12 | void setup(void) { 13 | Serial.begin(115200); 14 | Serial.println("Hello!"); 15 | 16 | nfc.begin(); 17 | 18 | uint32_t versiondata = nfc.getFirmwareVersion(); 19 | if (! versiondata) { 20 | Serial.print("Didn't find PN53x board"); 21 | while (1); // halt 22 | } 23 | 24 | Serial.print("Found chip PN5"); Serial.println((versiondata >> 24) & 0xFF, HEX); 25 | Serial.print("Firmware ver. "); Serial.print((versiondata >> 16) & 0xFF, DEC); 26 | Serial.print('.'); Serial.println((versiondata >> 8) & 0xFF, DEC); 27 | 28 | // configure board to read RFID tags 29 | nfc.SAMConfig(); 30 | 31 | Serial.println("Waiting for an ISO14443A Card ..."); 32 | } 33 | 34 | 35 | void loop(void) { 36 | uint8_t success; 37 | uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID 38 | uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type) 39 | 40 | // Wait for an ISO14443A type cards (Mifare, etc.). When one is found 41 | // 'uid' will be populated with the UID, and uidLength will indicate 42 | // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight) 43 | success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength); 44 | 45 | if (success) { 46 | // Display some basic information about the card 47 | Serial.println("Found an ISO14443A card"); 48 | Serial.print(" UID Length: "); Serial.print(uidLength, DEC); Serial.println(" bytes"); 49 | Serial.print(" UID Value: "); 50 | nfc.PrintHex(uid, uidLength); 51 | 52 | if (uidLength == 4) { 53 | // We probably have a Mifare Classic card ... 54 | uint32_t cardid = uid[0]; 55 | cardid <<= 8; 56 | cardid |= uid[1]; 57 | cardid <<= 8; 58 | cardid |= uid[2]; 59 | cardid <<= 8; 60 | cardid |= uid[3]; 61 | Serial.print("Seems to be a Mifare Classic card #"); 62 | Serial.println(cardid); 63 | } 64 | delay(2000); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Arduino_and_Esp_MC/mifare_classic_spi.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // If using the breakout with SPI, define the pins for SPI communication. 6 | #define PN532_SCK (13) 7 | #define PN532_MISO (12) 8 | #define PN532_MOSI (11) 9 | #define PN532_SS (10) 10 | 11 | // Use this line for a breakout with a SPI connection: 12 | Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS); 13 | 14 | void setup(void) { 15 | Serial.begin(115200); 16 | Serial.println("Hello!"); 17 | nfc.begin(); 18 | uint32_t versiondata = nfc.getFirmwareVersion(); 19 | if (! versiondata) { 20 | Serial.print("Didn't find PN53x board"); 21 | while (1); // halt 22 | } 23 | 24 | Serial.print("Found chip PN5"); Serial.println((versiondata >> 24) & 0xFF, HEX); 25 | Serial.print("Firmware ver. "); Serial.print((versiondata >> 16) & 0xFF, DEC); 26 | Serial.print('.'); Serial.println((versiondata >> 8) & 0xFF, DEC); 27 | 28 | // configure board to read RFID tags 29 | nfc.SAMConfig(); 30 | 31 | Serial.println("Waiting for an ISO14443A Card ..."); 32 | } 33 | 34 | 35 | void loop(void) { 36 | uint8_t success; 37 | uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID 38 | uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type) 39 | 40 | // Wait for an ISO14443A type cards (Mifare, etc.). When one is found 41 | // 'uid' will be populated with the UID, and uidLength will indicate 42 | // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight) 43 | success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength); 44 | 45 | if (success) { 46 | // Display some basic information about the card 47 | Serial.println("Found an ISO14443A card"); 48 | Serial.print(" UID Length: "); Serial.print(uidLength, DEC); Serial.println(" bytes"); 49 | Serial.print(" UID Value: "); 50 | nfc.PrintHex(uid, uidLength); 51 | 52 | if (uidLength == 4) { 53 | // We probably have a Mifare Classic card ... 54 | uint32_t cardid = uid[0]; 55 | cardid <<= 8; 56 | cardid |= uid[1]; 57 | cardid <<= 8; 58 | cardid |= uid[2]; 59 | cardid <<= 8; 60 | cardid |= uid[3]; 61 | Serial.print("Seems to be a Mifare Classic card #"); 62 | Serial.println(cardid); 63 | Serial.println(""); 64 | Serial.println(""); 65 | } 66 | delay(2000); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/Steps to run.txt: -------------------------------------------------------------------------------- 1 | First run : 2 | i2cdetect -y 1 3 | sudo apt install libnfc5 libnfc-bin libnfc-examples 4 | 5 | Once done , run : 6 | nfc-list -v 7 | nfc-scan-device -v 8 | 9 | And if it doesn't show the reader , open this : 10 | sudo nano /etc/nfc/libnfc.conf 11 | 12 | and add these 2 lines to the end of the file : 13 | device.name = "PN532 over I2C" 14 | device.connstring = "pn532_i2c:/dev/i2c-1" 15 | 16 | Then running this , will show the device : 17 | nfc-scan-device -v 18 | 19 | And then run this and it will read the card's data : 20 | nfc-poll -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532_demo.py: -------------------------------------------------------------------------------- 1 | """This module provides convenient tools for the communication with 2 | Mifare cards via the PN532. 3 | 4 | Some knowledge of a Mifare card's layout and general access procedure 5 | is needed to use this class effectively. Special care needs to be 6 | taken when modifying trailer blocks because you may shut yourself 7 | out of your card! Google "MF1S703x" for a good introduction to 8 | Mifare cards. 9 | 10 | A typical scenario would be: 11 | 12 | card = Mifare() 13 | card.SAMconfigure() 14 | card.set_max_retries(MIFARE_SAFE_RETRIES) 15 | uid = card.scan_field() 16 | if uid: 17 | address = card.mifare_address(0,1) 18 | card.mifare_auth_a(address,MIFARE_FACTORY_KEY) 19 | data = card.mifare_read(address) 20 | card.in_deselect() # In case you want to authorize a different sector. 21 | 22 | """ 23 | 24 | import py532lib.i2c as i2c 25 | from py532lib.frame import Pn532Frame as Pn532Frame 26 | from py532lib.constants import * 27 | import logging 28 | import math 29 | 30 | MIFARE_COMMAND_AUTH_A = 0x60 31 | MIFARE_COMMAND_AUTH_B = 0x61 32 | MIFARE_COMMAND_READ = 0x30 33 | MIFARE_COMMAND_WRITE_16 = 0xA0 34 | MIFARE_COMMAND_WRITE_4 = 0xA2 35 | MIFARE_FACTORY_KEY = b"\xFF\xFF\xFF\xFF\xFF\xFF" 36 | MIFARE_WAIT_FOR_ENTRY = 0xFF # MxRtyPassiveActivation value: wait until card enters field. 37 | MIFARE_SAFE_RETRIES = 5 # This number of retries seems to detect most cards properlies. 38 | 39 | class Mifare(i2c.Pn532_i2c): 40 | 41 | """This class allows for the communication with Mifare cards via 42 | the PN532. 43 | 44 | Compared to its superclass, this class provides a bit more 45 | sophisticated tools such as reading the contents of a Mifare 46 | card or writing to them, access restrictions, and key management. 47 | """ 48 | 49 | def __init__(self): 50 | """Set up and configure PN532.""" 51 | i2c.Pn532_i2c.__init__(self) 52 | self._uid = False 53 | 54 | def set_max_retries(self,mx_rty_passive_activation): 55 | """Configure the PN532 for the number of retries attempted 56 | during the InListPassiveTarget operation (set to 57 | MIFARE_SAFE_RETRIES for a safe one-time check, set to 58 | MIFARE_WAIT_FOR_ENTRY so it waits until entry of a card). 59 | """ 60 | # We set MxRtyPassiveActivation to 5 because it turns out that one 61 | # try sometimes does not detect the card properly. 62 | frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, 63 | data=bytearray([PN532_COMMAND_RFCONFIGURATION, 64 | PN532_RFCONFIGURATION_CFGITEM_MAXRETRIES, 65 | 0xFF,0x01,mx_rty_passive_activation])) 66 | self.send_command_check_ack(frame) 67 | self.read_response() 68 | 69 | def scan_field(self): 70 | """Scans the PN532's field for a Mifare card using the 71 | InListPassiveTarget operation. 72 | 73 | Returns the card's UID (a bytearray) if a card was in the field 74 | or False if no card was in the field. Only one card is 75 | detected at a time (the PN532 can handle two but this is not 76 | implemented here). False is never returned if the number of 77 | retries (see set_max_retries()) is set to MIFARE_WAIT_FOR_ENTRY. 78 | """ 79 | frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, 80 | data=bytearray([PN532_COMMAND_INLISTPASSIVETARGET, 0x01, 0x00])) 81 | self.send_command_check_ack(frame) 82 | response = self.read_response().get_data() 83 | target_count = response[1] 84 | if not target_count: 85 | self._uid = False 86 | return False 87 | uid_length = response[6] 88 | self._uid = response[7:7 + uid_length] 89 | return self._uid 90 | 91 | def in_data_exchange(self,data): 92 | """Sends a (Mifare) command to the currently active target. 93 | 94 | The "data" parameter contains the command data as a bytearray. 95 | Returns the data returned by the command (as a bytearray). 96 | Raises an IOError if the command failed. 97 | """ 98 | logging.debug("InDataExchange sending: " + " ".join("{0:02X}".format(k) for k in data)) 99 | logging.debug(data) 100 | frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, data=bytearray([PN532_COMMAND_INDATAEXCHANGE, 0x01]) + data) 101 | self.send_command_check_ack(frame) 102 | response_frame = self.read_response() 103 | if response_frame.get_frame_type() == PN532_FRAME_TYPE_ERROR: 104 | raise IOError("InDataExchange failed (error frame returned)") 105 | response = response_frame.get_data() 106 | logging.debug("InDataExchange response: " + " ".join("{0:02X}".format(k) for k in response)) 107 | if response[1] != 0x00: 108 | # Only the status byte was returned. There was an error. 109 | if response[1] == 0x14: 110 | raise IOError("Mifare authentication failed") 111 | else: 112 | raise IOError("InDataExchange returned error status: {0:#x}".format(response[1])) 113 | return response[2:] 114 | 115 | def in_deselect(self): 116 | """Deselects the current target.""" 117 | logging.debug("InDeselect sending...") 118 | frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, data=bytearray([PN532_COMMAND_INDESELECT, 0x01])) 119 | self.send_command_check_ack(frame) 120 | response_frame = self.read_response() 121 | if response_frame.get_frame_type() == PN532_FRAME_TYPE_ERROR: 122 | raise IOError("InDeselect failed (error frame returned)") 123 | response = response_frame.get_data() 124 | logging.debug("InDeselect response: " + " ".join("{0:02X}".format(k) for k in response)) 125 | if response[1] != 0x00: 126 | # Only the status byte was returned. There was an error. 127 | raise IOError("InDataExchange returned error status: {0:#x}".format(response[1])) 128 | 129 | def mifare_address(self,sector,block): 130 | """Returns a one byte address for the given Mifare sector and block.""" 131 | if sector < 32: 132 | if sector < 0 or block > 3 or block < 0: 133 | raise IndexError("Invalid sector / block: {0} / {1}".format(sector,block)) 134 | return sector * 4 + block 135 | else: 136 | if sector > 39 or block < 0 or block > 15: 137 | raise IndexError("Invalid sector / block: {0} / {1}".format(sector,block)) 138 | return 32 * 4 + (sector - 32) * 16 + block 139 | 140 | def mifare_sector_block(self,address): 141 | """Returns a tuple (sector,block) for the given address.""" 142 | if address > 255 or address < 0: 143 | raise IndexError("Invalid Mifare block address: {0}".format(address)) 144 | if address < 128: 145 | return (address >> 2,address & 3) 146 | else: 147 | return (32 + ((address - 128) >> 4),(address - 128) & 15) 148 | 149 | def mifare_auth_a(self,address,key_a): 150 | """Authenticate the Mifare card with key A. 151 | 152 | The "key_a" parameter is a bytearray that contains key A. 153 | You may specify an address directly or use the mifare_address() 154 | function to calculate it. Raises an IOError if authentication failed. 155 | """ 156 | if self._uid == False: 157 | raise RuntimeError("No Mifare card currently activated.") 158 | if len(self._uid) == 4: 159 | uid = self._uid 160 | elif len(self._uid) == 7: # 10-byte UID cards don't exist yet. 161 | uid = self._uid[3:7] # Sequence 1, keep it simple. 162 | self.in_data_exchange(bytearray([MIFARE_COMMAND_AUTH_A,address]) + key_a + uid) 163 | 164 | def mifare_auth_b(self,address,key_b): 165 | """Authenticate the Mifare card with key B. 166 | 167 | The "key_a" parameter is a bytearray that contains key B. 168 | You may specify an address directly or use the mifare_address() 169 | function to calculate it. Raises an IOError if authentication failed. 170 | """ 171 | if self._uid == False: 172 | raise RuntimeError("No Mifare card currently activated.") 173 | if len(self._uid) == 4: 174 | uid = self._uid 175 | elif len(self._uid) == 7: # 10-byte UID cards don't exist yet. 176 | uid = self._uid[3:7] # Sequence 1, keep it simple. 177 | self.in_data_exchange(bytearray([MIFARE_COMMAND_AUTH_B,address]) + key_b + uid) 178 | 179 | def mifare_read(self,address): 180 | """Read and return 16 bytes from the data block at the given address.""" 181 | return self.in_data_exchange(bytearray([MIFARE_COMMAND_READ,address])) 182 | 183 | def mifare_write_standard(self,address,data): 184 | """Write 16 bytes to the data block on a Mifare Standard card 185 | at the given address.""" 186 | if len(data) > 16: 187 | raise IndexError("Data cannot exceed 16 bytes (is {0} bytes)".format(len(data))) 188 | self.in_data_exchange(bytearray([MIFARE_COMMAND_WRITE_16,address]) + data + (b'\x00' * (16 - len(data)))) 189 | 190 | def mifare_write_ultralight(self,address,data): 191 | """Write 4 bytes to the data block on a Mifare Ultralight card 192 | at the given address.""" 193 | if len(data) > 4: 194 | raise IndexError("Data cannot exceed 4 bytes (is {0} bytes)".format(len(data))) 195 | self.in_data_exchange(bytearray([MIFARE_COMMAND_WRITE_4,address]) + data + (b'\x00' * (4 - len(data)))) 196 | 197 | def mifare_read_access(self,address): 198 | """Returns the access conditions for the block at the given address 199 | in a three-tuple of booleans (C1,C2,C3).""" 200 | sector, index = self.mifare_sector_block(address) 201 | if address < 128: 202 | data = self.mifare_read(address | 3) 203 | else: 204 | data = self.mifare_read(address | 15) 205 | index = math.floor(index / 5) 206 | return (data[7] & 1 << 4 + index > 0,data[8] & 1 << index > 0,data[8] & 1 << 4 + index > 0) 207 | 208 | def mifare_write_access(self,address,c1,c2,c3,key_a,key_b): 209 | """Changes the access conditions for the block at the given address 210 | to the three booleans c1,c2,c3. 211 | 212 | YOU SHOULD REALLY KNOW WHAT YOU'RE DOING HERE! With the wrong, 213 | settings, you may shut yourself out of your card. The keys A 214 | and B must also be provided because they cannot be read and 215 | may therefore be overwritten by zeroes (as returned by a 216 | regular read on the trailer sector). 217 | """ 218 | sector, index = self.mifare_sector_block(address) 219 | if address < 128: 220 | trailer_address = address | 3 221 | else: 222 | trailer_address = address | 15 223 | index = math.floor(index / 5) 224 | data = self.mifare_read(trailer_address) 225 | if c1: 226 | data[7] |= 1 << 4 + index 227 | data[6] &= ~(1 << index) 228 | else: 229 | data[7] &= ~(1 << 4 + index) 230 | data[6] |= 1 << index 231 | if c2: 232 | data[8] |= 1 << index 233 | data[6] &= ~(1 << 4 + index) 234 | else: 235 | data[8] &= ~(1 << index) 236 | data[6] |= 1 << 4 + index 237 | if c3: 238 | data[8] |= 1 << 4 + index 239 | data[7] &= ~(1 << index) 240 | else: 241 | data[8] &= ~(1 << 4 + index) 242 | data[7] |= 1 << index 243 | data = key_a + data[6:10] + key_b 244 | self.mifare_write_standard(trailer_address,data) 245 | 246 | def mifare_change_keys(self,address,key_a,key_b): 247 | """Changes the authorization keys A and B for the block at 248 | the given address. 249 | 250 | KEYS MAY NOT BE READABLE SO MAKE SURE YOU WRITE THEM DOWN! 251 | If you forget a key (especially key A), you may not be able 252 | to authenticate a block anymore and therefore not read it 253 | or write to it. The factory preset for keys is always 254 | b'\xFF\xFF\xFF\xFF\xFF\xFF' as defined in MIFARE_FACTORY_KEY. 255 | """ 256 | if address < 128: 257 | trailer_address = address | 3 258 | else: 259 | trailer_address = address | 15 260 | data = self.mifare_read(trailer_address) 261 | data = key_a + data[6:10] + key_b 262 | self.mifare_write_standard(trailer_address,data) 263 | 264 | 265 | 266 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/__init__.py: -------------------------------------------------------------------------------- 1 | """@package py532lib 2 | This package contains the useful stuff to communicate with a PN532 NFC chip in Python. 3 | 4 | @author: DanyO 5 | @license: The source code within this file is licensed under the BSD 2 Clause license. 6 | See LICENSE file for more information. 7 | 8 | Built for Python3, using Quick2Wire's Python APIs for the RaspberryPI. 9 | 10 | Losely inspired from Adafruit's PN532 I2C library. 11 | 12 | Pull requests are welcomed. 13 | 14 | """ -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/py532lib/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012, Dany Ouellette 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 5 | 6 | -Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 7 | -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 8 | 9 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/py532lib/__init__.py: -------------------------------------------------------------------------------- 1 | """@package py532lib 2 | This package contains the useful stuff to communicate with a PN532 NFC chip in Python. 3 | 4 | @author: DanyO 5 | @license: The source code within this file is licensed under the BSD 2 Clause license. 6 | See LICENSE file for more information. 7 | 8 | Built for Python3, using Quick2Wire's Python APIs for the RaspberryPI. 9 | 10 | Losely inspired from Adafruit's PN532 I2C library. 11 | 12 | Pull requests are welcomed. 13 | 14 | """ -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/py532lib/constants.py: -------------------------------------------------------------------------------- 1 | """@package py532lib.constants 2 | This module contains the constants related to py532lib. 3 | 4 | @author: DanyO 5 | @license: The source code within this file is licensed under the BSD 2 Clause license. 6 | See LICENSE file for more information. 7 | 8 | """ 9 | 10 | # RaspberryPI Constants. 11 | RPI_DEFAULT_I2C_NEW = 0x01 # New RPi models, like the 512MB Model. 12 | RPI_DEFAULT_I2C_OLD = 0x00 # Old RPi Models. 13 | 14 | # Typical PN532 slave address on RPi. 15 | PN532_I2C_SLAVE_ADDRESS = 0x24 16 | 17 | # PN532 Commands 18 | PN532_COMMAND_GETFIRMWAREVERSION = 0x02 19 | PN532_COMMAND_SAMCONFIGURATION = 0x14 20 | PN532_COMMAND_INLISTPASSIVETARGET = 0x4A 21 | PN532_COMMAND_RFCONFIGURATION = 0x32 22 | PN532_COMMAND_INDATAEXCHANGE = 0x40 23 | PN532_COMMAND_INDESELECT = 0x44 24 | 25 | # Frame Identifiers 26 | PN532_IDENTIFIER_HOST_TO_PN532 = 0xD4 27 | PN532_IDENTIFIER_PN532_TO_HOST = 0xD5 28 | 29 | # Values for PN532's SAMCONFIGURATION function. 30 | PN532_SAMCONFIGURATION_MODE_NORMAL = 0x01 31 | PN532_SAMCONFIGURATION_MODE_VIRTUAL_CARD = 0x02 32 | PN532_SAMCONFIGURATION_MODE_WIRED_CARD = 0x03 33 | PN532_SAMCONFIGURATION_MODE_DUAL_CARD = 0X04 34 | 35 | PN532_SAMCONFIGURATION_TIMEOUT_50MS = 0x01 36 | 37 | PN532_SAMCONFIGURATION_IRQ_OFF = 0x00 38 | PN532_SAMCONFIGURATION_IRQ_ON = 0x01 39 | 40 | # Values for the PN532's RFCONFIGURATION function. 41 | PN532_RFCONFIGURATION_CFGITEM_MAXRETRIES = 0x05 42 | 43 | # Typical frame values. 44 | PN532_PREAMBLE = 0x00 45 | PN532_START_CODE_1 = 0x00 46 | PN532_START_CODE_2 = 0xFF 47 | PN532_POSTAMBLE = 0x00 48 | 49 | # Position of info within the communication's frame. 50 | PN532_FRAME_POSITION_STATUS_CODE = 0 51 | PN532_FRAME_POSITION_PREAMBLE = 1 52 | PN532_FRAME_POSITION_START_CODE_1 = 2 53 | PN532_FRAME_POSITION_START_CODE_2 = 3 54 | PN532_FRAME_POSITION_LENGTH = 4 55 | PN532_FRAME_POSITION_LENGTH_CHECKSUM = 5 56 | PN532_FRAME_POSITION_FRAME_IDENTIFIER = 6 57 | PN532_FRAME_POSITION_DATA_START = 7 58 | 59 | # Type of frame. 60 | PN532_FRAME_TYPE_DATA = 0 61 | PN532_FRAME_TYPE_ACK = 1 62 | PN532_FRAME_TYPE_NACK = 2 63 | PN532_FRAME_TYPE_ERROR = 3 64 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/py532lib/frame.py: -------------------------------------------------------------------------------- 1 | """@package py532lib.frame 2 | This module contains classes and functions related to communication frames for the PN532 NFC Chip. 3 | 4 | @author: DanyO 5 | @license: The source code within this file is licensed under the BSD 2 Clause license. 6 | See LICENSE file for more information. 7 | 8 | """ 9 | 10 | import os 11 | import sys 12 | lib_path = os.path.abspath('../') 13 | sys.path.append(lib_path) 14 | 15 | from py532lib.i2c import * 16 | from py532lib.frame import * 17 | from py532lib.constants import * 18 | 19 | 20 | class Pn532Frame: 21 | """Pn532Frame represents a single communication frame for 22 | communication with the PN532 NFC Chip. 23 | 24 | """ 25 | def __init__( 26 | self, frame_type=PN532_FRAME_TYPE_DATA, 27 | preamble=PN532_PREAMBLE, 28 | start_code_1=PN532_START_CODE_1, 29 | start_code_2=PN532_START_CODE_2, 30 | frame_identifier=0xD4, 31 | data=bytearray(), 32 | postamble=PN532_POSTAMBLE): 33 | """Constructor for the Pn532Frame class. 34 | 35 | Arguments: 36 | @param[in] frame_type Type of current frame. 37 | (default = PN532_FRAME_TYPE_DATA) 38 | 39 | @param[in] preamble Preamble to be used. 40 | (default = PN532_PREAMBLE) 41 | 42 | @param[in] start_code_1 First byte of frame's start code. 43 | (default = PN532_START_CODE_1) 44 | 45 | @param[in] start_code_2 Last byte of frame's start code. 46 | (default = PN532_START_CODE_2) 47 | 48 | @param[in] frame_identifier Frame Identifier. 49 | (default = PN532_IDENTIFIER_HOST_TO_PN532) 50 | 51 | @param[in] data Frame's data in a bytearray(). 52 | 53 | @param[in] postamble Postamble to be used. 54 | (default = PN532_PREAMBLE) 55 | 56 | """ 57 | self._frame_type = frame_type 58 | self._preamble = preamble 59 | self._startCode1 = start_code_1 60 | self._startCode2 = start_code_2 61 | self._frameIdentifier = frame_identifier 62 | self._data = data 63 | self._postamble = postamble 64 | 65 | def get_length(self): 66 | """Gets the frame's data length.""" 67 | return len(self._data) + 1 68 | 69 | def get_length_checksum(self): 70 | """Gets the checksum of get_length().""" 71 | return (~self.get_length() & 0xFF) + 0x01 72 | 73 | def get_data(self): 74 | """Gets the frame's data.""" 75 | return self._data 76 | 77 | def get_data_checksum(self): 78 | """Gets a checksum for the frame's data.""" 79 | byte_array = bytearray() 80 | 81 | for byte in self._data: 82 | byte_array.append(byte) 83 | 84 | byte_array.append(self._frameIdentifier) 85 | 86 | inverse = (~sum(byte_array) & 0xFF) + 0x01 87 | 88 | if inverse > 255: 89 | inverse = inverse - 255 90 | 91 | return inverse 92 | 93 | def get_frame_type(self): 94 | """Gets the frame's type.""" 95 | return self._frame_type 96 | 97 | def to_tuple(self): 98 | byte_array = bytearray() 99 | 100 | if self._frame_type == PN532_FRAME_TYPE_ACK: 101 | byte_array.append(PN532_PREAMBLE) 102 | byte_array.append(PN532_START_CODE_1) 103 | byte_array.append(PN532_START_CODE_2) 104 | byte_array.append(PN532_START_CODE_1) 105 | byte_array.append(PN532_START_CODE_2) 106 | byte_array.append(PN532_POSTAMBLE) 107 | 108 | return (byte_array) 109 | 110 | byte_array.append(self._preamble) 111 | byte_array.append(self._startCode1) 112 | byte_array.append(self._startCode2) 113 | byte_array.append(self.get_length()) 114 | byte_array.append(self.get_length_checksum()) 115 | byte_array.append(self._frameIdentifier) 116 | 117 | for byte in self._data: 118 | byte_array.append(byte) 119 | 120 | byte_array.append(self.get_data_checksum()) 121 | byte_array.append(self._postamble) 122 | 123 | return (byte_array) 124 | 125 | @staticmethod 126 | def from_response(response): 127 | """Fractory that generates a Pn532Frame from a response from the PN532.""" 128 | if Pn532Frame.is_valid_response(response) is not True: 129 | raise RuntimeError("Invalid Response") 130 | 131 | if Pn532Frame.is_ack(response): 132 | return Pn532Frame(frame_type=PN532_FRAME_TYPE_ACK, 133 | frame_identifier=0x00) 134 | 135 | if Pn532Frame.is_error(response): 136 | return Pn532Frame(frame_type=PN532_FRAME_TYPE_ERROR, 137 | frame_identifier=0x7F,data=b'\x81') 138 | 139 | response_length = response[0][PN532_FRAME_POSITION_LENGTH] + 1 140 | data = bytearray( 141 | response[0][PN532_FRAME_POSITION_DATA_START:PN532_FRAME_POSITION_DATA_START + response_length - 2]) 142 | 143 | return Pn532Frame( 144 | preamble=response[0][PN532_FRAME_POSITION_PREAMBLE], 145 | start_code_1=response[0][PN532_FRAME_POSITION_START_CODE_1], 146 | start_code_2=response[0][PN532_FRAME_POSITION_START_CODE_2], 147 | frame_identifier=response[0][ 148 | PN532_FRAME_POSITION_FRAME_IDENTIFIER], 149 | data=data, 150 | postamble=response[0][PN532_FRAME_POSITION_DATA_START + response_length + 2]) 151 | 152 | @staticmethod 153 | def is_valid_response(response): 154 | """Checks if a response from the PN532 is valid.""" 155 | if (response[0][0] & 0x01) == 0x01: 156 | if response[0][PN532_FRAME_POSITION_PREAMBLE] == PN532_PREAMBLE: 157 | if response[0][PN532_FRAME_POSITION_START_CODE_1] == PN532_START_CODE_1: 158 | if response[0][PN532_FRAME_POSITION_START_CODE_2] == PN532_START_CODE_2: 159 | return True 160 | 161 | return False 162 | 163 | @staticmethod 164 | def is_ack(response): 165 | """Checks if the response is an ACK frame.""" 166 | if response[0][PN532_FRAME_POSITION_LENGTH] == 0x00: 167 | if response[0][PN532_FRAME_POSITION_LENGTH_CHECKSUM] == 0xFF: 168 | if response[0][PN532_FRAME_POSITION_FRAME_IDENTIFIER] == 0x00: 169 | return True 170 | 171 | return False 172 | 173 | @staticmethod 174 | def is_error(response): 175 | """ Checks if the response is an error frame.""" 176 | if response[0][PN532_FRAME_POSITION_LENGTH] == 0x01: 177 | if response[0][PN532_FRAME_POSITION_LENGTH_CHECKSUM] == 0xFF: 178 | if response[0][PN532_FRAME_POSITION_FRAME_IDENTIFIER] == 0x7F: 179 | if response[0][PN532_FRAME_POSITION_DATA_START] == 0x81: 180 | return True 181 | 182 | return False 183 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/py532lib/i2c.py: -------------------------------------------------------------------------------- 1 | """@package py532lib.i2c 2 | This module contains classes and functions related to I2C communication for the PN532 NFC Chip. 3 | 4 | @author: DanyO 5 | @license: The source code within this file is licensed under the BSD 2 Clause license. 6 | See LICENSE file for more information. 7 | 8 | """ 9 | 10 | import os 11 | import sys 12 | lib_path = os.path.abspath('../') 13 | sys.path.append(lib_path) 14 | 15 | from time import sleep 16 | import logging 17 | from quick2wire.i2c import I2CMaster, reading, writing 18 | from py532lib.i2c import * 19 | from py532lib.frame import * 20 | from py532lib.constants import * 21 | 22 | 23 | LOGGING_ENABLED = False 24 | LOG_LEVEL = logging.DEBUG 25 | DEFAULT_DELAY = 0.005 26 | 27 | 28 | class Pn532_i2c: 29 | """Pn532_i2c abstracts away the details related to 30 | I2C communication with the PN532. 31 | 32 | """ 33 | PN532 = None 34 | address = None 35 | i2c_channel = None 36 | logger = None 37 | 38 | def __init__(self, address=PN532_I2C_SLAVE_ADDRESS, i2c_channel=RPI_DEFAULT_I2C_NEW): 39 | """Constructor for the Pn532_i2c class. 40 | 41 | Arguments: 42 | @param[in] address I2C slave address for the PN532 43 | (default = PN532_FRAME_TYPE_DATA) 44 | 45 | @param[in] i2c_channel I2C channel to use. 46 | (default = RPI_DEFAULT_I2C_NEW) 47 | 48 | """ 49 | self.logger = logging.getLogger() 50 | self.logger.propagate = LOGGING_ENABLED 51 | if self.logger.propagate: 52 | self.logger.setLevel("DEBUG") 53 | 54 | self.address = address 55 | self.i2c_channel = i2c_channel 56 | self.PN532 = I2CMaster(self.i2c_channel) 57 | 58 | def send_command_check_ack(self, frame): 59 | """Sends a command frame, and waits for an ACK frame. 60 | 61 | Arguments: 62 | @param[in] frame Pn532Frame to send. 63 | 64 | """ 65 | self.send_command(frame) 66 | if self.read_ack(): 67 | return True 68 | else: 69 | return False 70 | 71 | def read_response(self): 72 | """Wait, then read for a response from the PN532.""" 73 | logging.debug("readResponse...") 74 | response = [b'\x00\x00\x00\x00\x00\x00\x00'] 75 | 76 | while True: 77 | 78 | try: 79 | logging.debug("readResponse..............Reading.") 80 | 81 | sleep(DEFAULT_DELAY) 82 | response = self.PN532.transaction( 83 | reading(self.address, 255)) 84 | logging.debug(response) 85 | logging.debug("readResponse..............Read.") 86 | except Exception: 87 | pass 88 | else: 89 | try: 90 | frame = Pn532Frame.from_response(response) 91 | 92 | # Acknowledge Data frames coming from the PN532 93 | if frame.get_frame_type() == PN532_FRAME_TYPE_DATA: 94 | self.send_command(Pn532Frame( 95 | frame_type=PN532_FRAME_TYPE_ACK)) 96 | 97 | except Exception as ex: 98 | logging.debug(ex) 99 | logging.debug(ex.args) 100 | pass 101 | else: 102 | return frame 103 | 104 | def send_command(self, frame): 105 | """Sends a command frame to the PN532. 106 | 107 | Arguments: 108 | @param[in] frame Pn532Frame to send. 109 | 110 | """ 111 | logging.debug("send_command...") 112 | 113 | while True: 114 | try: 115 | logging.debug("send_command...........Sending.") 116 | 117 | sleep(DEFAULT_DELAY) 118 | self.PN532.transaction( 119 | writing(self.address, frame.to_tuple())) 120 | 121 | logging.debug(frame.to_tuple()) 122 | 123 | logging.debug("send_command...........Sent.") 124 | except Exception as ex: 125 | logging.debug(ex) 126 | 127 | self.reset_i2c() 128 | sleep(DEFAULT_DELAY) 129 | else: 130 | return True 131 | 132 | def read_ack(self): 133 | """Wait for a valid ACK frame to be returned.""" 134 | logging.debug("read_ack...") 135 | 136 | while True: 137 | sleep(DEFAULT_DELAY) 138 | response_frame = self.read_response() 139 | 140 | if response_frame.get_frame_type() == PN532_FRAME_TYPE_ACK: 141 | return True 142 | else: 143 | pass 144 | 145 | def read_mifare(self): 146 | """Wait for a MiFARE card to be in the PN532's field, and read it's UID.""" 147 | frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, data=bytearray([PN532_COMMAND_INLISTPASSIVETARGET, 0x01, 0x00])) 148 | self.send_command_check_ack(frame) 149 | 150 | return self.read_response() 151 | 152 | def reset_i2c(self): 153 | """Reset the I2C communication connection.""" 154 | logging.debug("I2C Reset...") 155 | 156 | self.PN532.close() 157 | del self.PN532 158 | self.PN532 = I2CMaster(self.i2c_channel) 159 | 160 | logging.debug("I2C Reset............Created.") 161 | 162 | def SAMconfigure(self, frame=None): 163 | """Send a SAMCONFIGURATION command to the PN532. 164 | 165 | Arguments: 166 | @param[in] frame Custom SAMconfigure options can be passed here. 167 | 168 | """ 169 | if frame is None: 170 | frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, 171 | data=bytearray( 172 | [PN532_COMMAND_SAMCONFIGURATION, 173 | PN532_SAMCONFIGURATION_MODE_NORMAL, 174 | PN532_SAMCONFIGURATION_TIMEOUT_50MS, 175 | PN532_SAMCONFIGURATION_IRQ_OFF])) 176 | 177 | self.send_command_check_ack(frame) 178 | 179 | def __exit__(self, type, value, traceback): 180 | """Make sure the I2C communication channel is closed.""" 181 | self.PN532.close() 182 | del self.PN532 183 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/py532lib/mifare.py: -------------------------------------------------------------------------------- 1 | """This module provides convenient tools for the communication with 2 | Mifare cards via the PN532. 3 | 4 | Some knowledge of a Mifare card's layout and general access procedure 5 | is needed to use this class effectively. Special care needs to be 6 | taken when modifying trailer blocks because you may shut yourself 7 | out of your card! Google "MF1S703x" for a good introduction to 8 | Mifare cards. 9 | 10 | A typical scenario would be: 11 | 12 | card = Mifare() 13 | card.SAMconfigure() 14 | card.set_max_retries(MIFARE_SAFE_RETRIES) 15 | uid = card.scan_field() 16 | if uid: 17 | address = card.mifare_address(0,1) 18 | card.mifare_auth_a(address,MIFARE_FACTORY_KEY) 19 | data = card.mifare_read(address) 20 | card.in_deselect() # In case you want to authorize a different sector. 21 | 22 | """ 23 | 24 | import py532lib.i2c as i2c 25 | from py532lib.frame import Pn532Frame as Pn532Frame 26 | from py532lib.constants import * 27 | import logging 28 | import math 29 | 30 | MIFARE_COMMAND_AUTH_A = 0x60 31 | MIFARE_COMMAND_AUTH_B = 0x61 32 | MIFARE_COMMAND_READ = 0x30 33 | MIFARE_COMMAND_WRITE_16 = 0xA0 34 | MIFARE_COMMAND_WRITE_4 = 0xA2 35 | MIFARE_FACTORY_KEY = b"\xFF\xFF\xFF\xFF\xFF\xFF" 36 | MIFARE_WAIT_FOR_ENTRY = 0xFF # MxRtyPassiveActivation value: wait until card enters field. 37 | MIFARE_SAFE_RETRIES = 5 # This number of retries seems to detect most cards properlies. 38 | 39 | class Mifare(i2c.Pn532_i2c): 40 | 41 | """This class allows for the communication with Mifare cards via 42 | the PN532. 43 | 44 | Compared to its superclass, this class provides a bit more 45 | sophisticated tools such as reading the contents of a Mifare 46 | card or writing to them, access restrictions, and key management. 47 | """ 48 | 49 | def __init__(self): 50 | """Set up and configure PN532.""" 51 | i2c.Pn532_i2c.__init__(self) 52 | self._uid = False 53 | 54 | def set_max_retries(self,mx_rty_passive_activation): 55 | """Configure the PN532 for the number of retries attempted 56 | during the InListPassiveTarget operation (set to 57 | MIFARE_SAFE_RETRIES for a safe one-time check, set to 58 | MIFARE_WAIT_FOR_ENTRY so it waits until entry of a card). 59 | """ 60 | # We set MxRtyPassiveActivation to 5 because it turns out that one 61 | # try sometimes does not detect the card properly. 62 | frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, 63 | data=bytearray([PN532_COMMAND_RFCONFIGURATION, 64 | PN532_RFCONFIGURATION_CFGITEM_MAXRETRIES, 65 | 0xFF,0x01,mx_rty_passive_activation])) 66 | self.send_command_check_ack(frame) 67 | self.read_response() 68 | 69 | def scan_field(self): 70 | """Scans the PN532's field for a Mifare card using the 71 | InListPassiveTarget operation. 72 | 73 | Returns the card's UID (a bytearray) if a card was in the field 74 | or False if no card was in the field. Only one card is 75 | detected at a time (the PN532 can handle two but this is not 76 | implemented here). False is never returned if the number of 77 | retries (see set_max_retries()) is set to MIFARE_WAIT_FOR_ENTRY. 78 | """ 79 | frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, 80 | data=bytearray([PN532_COMMAND_INLISTPASSIVETARGET, 0x01, 0x00])) 81 | self.send_command_check_ack(frame) 82 | response = self.read_response().get_data() 83 | target_count = response[1] 84 | if not target_count: 85 | self._uid = False 86 | return False 87 | uid_length = response[6] 88 | self._uid = response[7:7 + uid_length] 89 | return self._uid 90 | 91 | def in_data_exchange(self,data): 92 | """Sends a (Mifare) command to the currently active target. 93 | 94 | The "data" parameter contains the command data as a bytearray. 95 | Returns the data returned by the command (as a bytearray). 96 | Raises an IOError if the command failed. 97 | """ 98 | logging.debug("InDataExchange sending: " + " ".join("{0:02X}".format(k) for k in data)) 99 | logging.debug(data) 100 | frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, data=bytearray([PN532_COMMAND_INDATAEXCHANGE, 0x01]) + data) 101 | self.send_command_check_ack(frame) 102 | response_frame = self.read_response() 103 | if response_frame.get_frame_type() == PN532_FRAME_TYPE_ERROR: 104 | raise IOError("InDataExchange failed (error frame returned)") 105 | response = response_frame.get_data() 106 | logging.debug("InDataExchange response: " + " ".join("{0:02X}".format(k) for k in response)) 107 | if response[1] != 0x00: 108 | # Only the status byte was returned. There was an error. 109 | if response[1] == 0x14: 110 | raise IOError("Mifare authentication failed") 111 | else: 112 | raise IOError("InDataExchange returned error status: {0:#x}".format(response[1])) 113 | return response[2:] 114 | 115 | def in_deselect(self): 116 | """Deselects the current target.""" 117 | logging.debug("InDeselect sending...") 118 | frame = Pn532Frame(frame_type=PN532_FRAME_TYPE_DATA, data=bytearray([PN532_COMMAND_INDESELECT, 0x01])) 119 | self.send_command_check_ack(frame) 120 | response_frame = self.read_response() 121 | if response_frame.get_frame_type() == PN532_FRAME_TYPE_ERROR: 122 | raise IOError("InDeselect failed (error frame returned)") 123 | response = response_frame.get_data() 124 | logging.debug("InDeselect response: " + " ".join("{0:02X}".format(k) for k in response)) 125 | if response[1] != 0x00: 126 | # Only the status byte was returned. There was an error. 127 | raise IOError("InDataExchange returned error status: {0:#x}".format(response[1])) 128 | 129 | def mifare_address(self,sector,block): 130 | """Returns a one byte address for the given Mifare sector and block.""" 131 | if sector < 32: 132 | if sector < 0 or block > 3 or block < 0: 133 | raise IndexError("Invalid sector / block: {0} / {1}".format(sector,block)) 134 | return sector * 4 + block 135 | else: 136 | if sector > 39 or block < 0 or block > 15: 137 | raise IndexError("Invalid sector / block: {0} / {1}".format(sector,block)) 138 | return 32 * 4 + (sector - 32) * 16 + block 139 | 140 | def mifare_sector_block(self,address): 141 | """Returns a tuple (sector,block) for the given address.""" 142 | if address > 255 or address < 0: 143 | raise IndexError("Invalid Mifare block address: {0}".format(address)) 144 | if address < 128: 145 | return (address >> 2,address & 3) 146 | else: 147 | return (32 + ((address - 128) >> 4),(address - 128) & 15) 148 | 149 | def mifare_auth_a(self,address,key_a): 150 | """Authenticate the Mifare card with key A. 151 | 152 | The "key_a" parameter is a bytearray that contains key A. 153 | You may specify an address directly or use the mifare_address() 154 | function to calculate it. Raises an IOError if authentication failed. 155 | """ 156 | if self._uid == False: 157 | raise RuntimeError("No Mifare card currently activated.") 158 | if len(self._uid) == 4: 159 | uid = self._uid 160 | elif len(self._uid) == 7: # 10-byte UID cards don't exist yet. 161 | uid = self._uid[3:7] # Sequence 1, keep it simple. 162 | self.in_data_exchange(bytearray([MIFARE_COMMAND_AUTH_A,address]) + key_a + uid) 163 | 164 | def mifare_auth_b(self,address,key_b): 165 | """Authenticate the Mifare card with key B. 166 | 167 | The "key_a" parameter is a bytearray that contains key B. 168 | You may specify an address directly or use the mifare_address() 169 | function to calculate it. Raises an IOError if authentication failed. 170 | """ 171 | if self._uid == False: 172 | raise RuntimeError("No Mifare card currently activated.") 173 | if len(self._uid) == 4: 174 | uid = self._uid 175 | elif len(self._uid) == 7: # 10-byte UID cards don't exist yet. 176 | uid = self._uid[3:7] # Sequence 1, keep it simple. 177 | self.in_data_exchange(bytearray([MIFARE_COMMAND_AUTH_B,address]) + key_b + uid) 178 | 179 | def mifare_read(self,address): 180 | """Read and return 16 bytes from the data block at the given address.""" 181 | return self.in_data_exchange(bytearray([MIFARE_COMMAND_READ,address])) 182 | 183 | def mifare_write_standard(self,address,data): 184 | """Write 16 bytes to the data block on a Mifare Standard card 185 | at the given address.""" 186 | if len(data) > 16: 187 | raise IndexError("Data cannot exceed 16 bytes (is {0} bytes)".format(len(data))) 188 | self.in_data_exchange(bytearray([MIFARE_COMMAND_WRITE_16,address]) + data + (b'\x00' * (16 - len(data)))) 189 | 190 | def mifare_write_ultralight(self,address,data): 191 | """Write 4 bytes to the data block on a Mifare Ultralight card 192 | at the given address.""" 193 | if len(data) > 4: 194 | raise IndexError("Data cannot exceed 4 bytes (is {0} bytes)".format(len(data))) 195 | self.in_data_exchange(bytearray([MIFARE_COMMAND_WRITE_4,address]) + data + (b'\x00' * (4 - len(data)))) 196 | 197 | def mifare_read_access(self,address): 198 | """Returns the access conditions for the block at the given address 199 | in a three-tuple of booleans (C1,C2,C3).""" 200 | sector, index = self.mifare_sector_block(address) 201 | if address < 128: 202 | data = self.mifare_read(address | 3) 203 | else: 204 | data = self.mifare_read(address | 15) 205 | index = math.floor(index / 5) 206 | return (data[7] & 1 << 4 + index > 0,data[8] & 1 << index > 0,data[8] & 1 << 4 + index > 0) 207 | 208 | def mifare_write_access(self,address,c1,c2,c3,key_a,key_b): 209 | """Changes the access conditions for the block at the given address 210 | to the three booleans c1,c2,c3. 211 | 212 | YOU SHOULD REALLY KNOW WHAT YOU'RE DOING HERE! With the wrong, 213 | settings, you may shut yourself out of your card. The keys A 214 | and B must also be provided because they cannot be read and 215 | may therefore be overwritten by zeroes (as returned by a 216 | regular read on the trailer sector). 217 | """ 218 | sector, index = self.mifare_sector_block(address) 219 | if address < 128: 220 | trailer_address = address | 3 221 | else: 222 | trailer_address = address | 15 223 | index = math.floor(index / 5) 224 | data = self.mifare_read(trailer_address) 225 | if c1: 226 | data[7] |= 1 << 4 + index 227 | data[6] &= ~(1 << index) 228 | else: 229 | data[7] &= ~(1 << 4 + index) 230 | data[6] |= 1 << index 231 | if c2: 232 | data[8] |= 1 << index 233 | data[6] &= ~(1 << 4 + index) 234 | else: 235 | data[8] &= ~(1 << index) 236 | data[6] |= 1 << 4 + index 237 | if c3: 238 | data[8] |= 1 << 4 + index 239 | data[7] &= ~(1 << index) 240 | else: 241 | data[8] &= ~(1 << 4 + index) 242 | data[7] |= 1 << index 243 | data = key_a + data[6:10] + key_b 244 | self.mifare_write_standard(trailer_address,data) 245 | 246 | def mifare_change_keys(self,address,key_a,key_b): 247 | """Changes the authorization keys A and B for the block at 248 | the given address. 249 | 250 | KEYS MAY NOT BE READABLE SO MAKE SURE YOU WRITE THEM DOWN! 251 | If you forget a key (especially key A), you may not be able 252 | to authenticate a block anymore and therefore not read it 253 | or write to it. The factory preset for keys is always 254 | b'\xFF\xFF\xFF\xFF\xFF\xFF' as defined in MIFARE_FACTORY_KEY. 255 | """ 256 | if address < 128: 257 | trailer_address = address | 3 258 | else: 259 | trailer_address = address | 15 260 | data = self.mifare_read(trailer_address) 261 | data = key_a + data[6:10] + key_b 262 | self.mifare_write_standard(trailer_address,data) 263 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/LGPL.txt: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/LICENSE.md: -------------------------------------------------------------------------------- 1 | You may use this library under the terms of either the MIT License or the GNU Lesser General Public License (LGPL) Version 3 2 | 3 | The MIT License is recommended for most projects. It is simple and easy to understand and it places almost no restrictions on what you can do with the library. 4 | 5 | If the LGPL suits your project better you are also free to use the library under that license. 6 | 7 | You don’t have to do anything special to choose one license or the other and you don’t have to notify anyone which license you are using. You are free to use this library in commercial projects as long as the copyright header is left intact. 8 | 9 | Licenses 10 | 11 | [MIT License](MIT_LICENSE.txt) ([More Information](http://en.wikipedia.org/wiki/MIT_License)) 12 | 13 | [LGPL](LGPL.txt) ([More Information](http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License)) 14 | 15 | Since the LGPL extends the [GPL](GPL.txt), that license has been also included in this distribution. -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/MIT_LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 Quick2Wire Limited 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/README.md: -------------------------------------------------------------------------------- 1 | Quick2Wire Python API 2 | ===================== 3 | 4 | A Python library for controlling the hardware attached to the 5 | Raspberry Pi's header pins, [without running as the root user](http://quick2wire.com/articles/working-safely-with-your-pi/). 6 | 7 | 8 | Dependencies 9 | ------------ 10 | 11 | The library depends on Python 3. To install Python 3 run this command from an administrator account, such as `pi`: 12 | 13 | sudo apt-get install python3 14 | 15 | You'll also find the python tools 16 | [virtualenv](http://www.virtualenv.org/en/latest/index.html) and 17 | [pip](http://www.pip-installer.org/en/latest/index.html) useful: 18 | 19 | sudo apt-get install python-pip 20 | sudo apt-get install python-virtualenv 21 | 22 | 23 | The GPIO API depends on Quick2Wire GPIO Admin. To install Quick2Wire 24 | GPIO Admin, follow the instructions at 25 | http://github.com/quick2wire/quick2wire-gpio-admin 26 | 27 | The I2C and SPI API depend on support in the kernel. Recent raspbian kernels should be fine. 28 | 29 | 30 | Installation 31 | ------------ 32 | 33 | The library is currently under active development, so we do not 34 | recommend installing it into the system-wide Python libraries. 35 | Instead, you can either use it without installation or install it into 36 | an isolated Python development environment created with 37 | [`virtualenv`](http://www.virtualenv.org/). 38 | 39 | To use the library without installation, add the full path of the 40 | source tree to the `PYTHONPATH` environment variable. For example: 41 | 42 | export QUICK2WIRE_API_HOME=[the directory cloned from Git or unpacked from the source archive] 43 | export PYTHONPATH=$PYTHONPATH:$QUICK2WIRE_API_HOME 44 | 45 | If you're using virtualenv, make your virtualenv 46 | [active](http://www.virtualenv.org/en/latest/index.html#activate-script), 47 | and then run: 48 | 49 | python3 setup.py install 50 | 51 | Getting Started 52 | --------------- 53 | 54 | * [Getting Started with GPIO](http://github.com/quick2wire/quick2wire-python-api/blob/master/doc/getting-started-with-gpio.md) 55 | * [Getting Started with I2C](http://github.com/quick2wire/quick2wire-python-api/blob/master/doc/getting-started-with-i2c.md) 56 | 57 | 58 | Help and Support 59 | ---------------- 60 | 61 | There is a [discussion group](https://groups.google.com/group/quick2wire-users) in which you can ask questions about the library. 62 | 63 | If you have discovered a bug or would like to request a feature, raise an issue in the [issue tracker](https://github.com/quick2wire/quick2wire-python-api/issues). 64 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/__init__.py -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/asm_generic_ioctl.py: -------------------------------------------------------------------------------- 1 | # Warning: not part of the published Quick2Wire API. 2 | # 3 | # Converted from 4 | 5 | # ioctl command encoding: 32 bits total, command in lower 16 bits, 6 | # size of the parameter structure in the lower 14 bits of the 7 | # upper 16 bits. 8 | # 9 | # Encoding the size of the parameter structure in the ioctl request 10 | # is useful for catching programs compiled with old versions 11 | # and to avoid overwriting user space outside the user buffer area. 12 | # The highest 2 bits are reserved for indicating the ``access mode''. 13 | # 14 | # NOTE: This limits the max parameter size to 16kB -1 ! 15 | 16 | # The following is for compatibility across the various Linux 17 | # platforms. The generic ioctl numbering scheme doesn't really enforce 18 | # a type field. De facto, however, the top 8 bits of the lower 16 19 | # bits are indeed used as a type field, so we might just as well make 20 | # this explicit here. Please be sure to use the decoding macros 21 | # below from now on. 22 | 23 | import ctypes 24 | 25 | _IOC_NRBITS = 8 26 | _IOC_TYPEBITS = 8 27 | 28 | _IOC_SIZEBITS = 14 29 | _IOC_DIRBITS = 2 30 | 31 | _IOC_NRMASK = (1 << _IOC_NRBITS) - 1 32 | _IOC_TYPEMASK = (1 << _IOC_TYPEBITS) - 1 33 | _IOC_SIZEMASK = (1 << _IOC_SIZEBITS) - 1 34 | _IOC_DIRMASK = (1 << _IOC_DIRBITS) - 1 35 | 36 | _IOC_NRSHIFT = 0 37 | _IOC_TYPESHIFT = _IOC_NRSHIFT + _IOC_NRBITS 38 | _IOC_SIZESHIFT = _IOC_TYPESHIFT + _IOC_TYPEBITS 39 | _IOC_DIRSHIFT = _IOC_SIZESHIFT + _IOC_SIZEBITS 40 | 41 | # Direction bits 42 | 43 | _IOC_NONE = 0 44 | _IOC_WRITE = 1 45 | _IOC_READ = 2 46 | 47 | def _IOC(dir, type, nr, size): 48 | return (dir << _IOC_DIRSHIFT) | \ 49 | (type << _IOC_TYPESHIFT) | \ 50 | (nr << _IOC_NRSHIFT) | \ 51 | (size << _IOC_SIZESHIFT) 52 | 53 | def _IOC_TYPECHECK(t): 54 | return ctypes.sizeof(t) 55 | 56 | 57 | # used to create ioctl numbers 58 | 59 | def _IO(type, nr): 60 | return _IOC(_IOC_NONE, type, nr, 0) 61 | 62 | def _IOR(type, nr, size): 63 | return _IOC(_IOC_READ, type, nr, _IOC_TYPECHECK(size)) 64 | 65 | def _IOW(type, nr, size): 66 | return _IOC(_IOC_WRITE, type, nr, _IOC_TYPECHECK(size)) 67 | 68 | def _IOWR(type,nr,size): 69 | return _IOC(_IOC_READ|_IOC_WRITE, type, nr, _IOC_TYPECHECK(size)) 70 | 71 | def _IOR_BAD(type,nr,size): 72 | return _IOC(_IOC_READ, type, nr, sizeof(size)) 73 | 74 | def _IOW_BAD(type,nr,size): 75 | return _IOC(_IOC_WRITE,type,nr, sizeof(size)) 76 | 77 | def _IOWR_BAD(type,nr,size): 78 | return _IOC(_IOC_READ|_IOC_WRITE, type, nr, sizeof(size)) 79 | 80 | 81 | # ...and for the drivers/sound files... 82 | 83 | IOC_IN = _IOC_WRITE << _IOC_DIRSHIFT 84 | IOC_OUT = _IOC_READ << _IOC_DIRSHIFT 85 | IOC_INOUT = (_IOC_WRITE|_IOC_READ) << _IOC_DIRSHIFT 86 | IOCSIZE_MASK = _IOC_SIZEMASK << _IOC_SIZESHIFT 87 | IOCSIZE_SHIFT = _IOC_SIZESHIFT 88 | 89 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/board_revision.py: -------------------------------------------------------------------------------- 1 | def revision(): 2 | try: 3 | with open('/proc/cpuinfo','r') as f: 4 | for line in f: 5 | if line.startswith('Revision'): 6 | return 1 if line.rstrip()[-1] in ['2','3'] else 2 7 | else: 8 | return 0 9 | except: 10 | return 0 11 | 12 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/eventfd.py: -------------------------------------------------------------------------------- 1 | 2 | from ctypes import * 3 | import quick2wire.syscall as syscall 4 | import os 5 | import errno 6 | 7 | # From sys/eventfd.h 8 | 9 | EFD_SEMAPHORE = 1 10 | EFD_CLOEXEC = 0o2000000 11 | EFD_NONBLOCK = 0o4000 12 | 13 | _libc = CDLL(None, use_errno=True) 14 | 15 | eventfd_t = c_uint64 16 | 17 | eventfd = syscall.lookup(c_int, "eventfd", (c_uint, c_int)) 18 | 19 | 20 | class Semaphore(syscall.SelfClosing): 21 | """A Semaphore implemented with eventfd that can be added to a Selector.""" 22 | 23 | def __init__(self, count=0, blocking=True): 24 | """Creates a Semaphore with an initial count. 25 | 26 | Arguments: 27 | count -- the initial count. 28 | blocking -- if False calls to wait() do not block if the Semaphore 29 | has a count of zero. (default = True) 30 | """ 31 | self._fd = eventfd(count, EFD_SEMAPHORE|((not blocking)*EFD_NONBLOCK)) 32 | 33 | def close(self): 34 | """Closes the Semaphore and releases its file descriptor.""" 35 | os.close(self._fd) 36 | 37 | def fileno(self): 38 | """Returns the Semaphore's file descriptor.""" 39 | return self._fd 40 | 41 | def signal(self): 42 | """Signal the semaphore. 43 | 44 | Signalling a semaphore increments its count by one and wakes a 45 | blocked task that is waiting on the semaphore. 46 | """ 47 | return os.write(self._fd, eventfd_t(1)) 48 | 49 | def wait(self): 50 | """Receive a signal from the Semaphore, decrementing its count by one. 51 | 52 | If the Semaphore is already has a count of zero, either wait 53 | for a signal if the Semaphore is in blocking mode, or return 54 | False immediately. 55 | 56 | Returns: 57 | True -- the Semaphore received a signal. 58 | False -- the Semaphore did not receive a signal and is in 59 | non-blocking mode. 60 | """ 61 | try: 62 | os.read(self._fd, 8) 63 | return True 64 | except OSError as e: 65 | if e.errno == errno.EAGAIN: 66 | return False 67 | else: 68 | raise 69 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/gpio.py: -------------------------------------------------------------------------------- 1 | """A convenient API to access the GPIO pins of the Raspberry Pi. 2 | 3 | """ 4 | 5 | import os 6 | import subprocess 7 | from contextlib import contextmanager 8 | from quick2wire.board_revision import revision 9 | from quick2wire.selector import EDGE 10 | 11 | 12 | def gpio_admin(subcommand, pin, pull=None): 13 | if pull: 14 | subprocess.check_call(["gpio-admin", subcommand, str(pin), pull]) 15 | else: 16 | subprocess.check_call(["gpio-admin", subcommand, str(pin)]) 17 | 18 | 19 | Out = "out" 20 | In = "in" 21 | 22 | Rising = "rising" 23 | Falling = "falling" 24 | Both = "both" 25 | 26 | PullDown = "pulldown" 27 | PullUp = "pullup" 28 | 29 | 30 | 31 | class PinAPI(object): 32 | def __init__(self, bank, index): 33 | self._bank = bank 34 | self._index = index 35 | 36 | @property 37 | def index(self): 38 | return self._index 39 | 40 | @property 41 | def bank(self): 42 | return self._bank 43 | 44 | def __enter__(self): 45 | self.open() 46 | return self 47 | 48 | def __exit__(self, exc_type, exc_value, traceback): 49 | self.close() 50 | 51 | value = property(lambda p: p.get(), 52 | lambda p,v: p.set(v), 53 | doc="""The value of the pin: 1 if the pin is high, 0 if the pin is low.""") 54 | 55 | 56 | class PinBankAPI(object): 57 | def __getitem__(self, n): 58 | if 0 < n < len(self): 59 | raise ValueError("no pin index {n} out of range", n=n) 60 | return self.pin(n) 61 | 62 | def write(self): 63 | pass 64 | 65 | def read(self): 66 | pass 67 | 68 | 69 | 70 | class Pin(PinAPI): 71 | """Controls a GPIO pin.""" 72 | 73 | __trigger__ = EDGE 74 | 75 | def __init__(self, bank, index, soc_pin_number, direction=In, interrupt=None, pull=None): 76 | """Creates a pin 77 | 78 | Parameters: 79 | user_pin_number -- the identity of the pin used to create the derived class. 80 | soc_pin_number -- the pin on the header to control, identified by the SoC pin number. 81 | direction -- (optional) the direction of the pin, either In or Out. 82 | interrupt -- (optional) 83 | pull -- (optional) 84 | 85 | Raises: 86 | IOError -- could not export the pin (if direction is given) 87 | """ 88 | super(Pin,self).__init__(None, index) 89 | self._soc_pin_number = soc_pin_number 90 | self._file = None 91 | self._direction = direction 92 | self._interrupt = interrupt 93 | self._pull = pull 94 | 95 | 96 | @property 97 | def soc_pin_number(self): 98 | return self._soc_pin_number 99 | 100 | def open(self): 101 | gpio_admin("export", self.soc_pin_number, self._pull) 102 | self._file = open(self._pin_path("value"), "r+") 103 | self._write("direction", self._direction) 104 | if self._direction == In: 105 | self._write("edge", self._interrupt if self._interrupt is not None else "none") 106 | 107 | def close(self): 108 | if not self.closed: 109 | if self.direction == Out: 110 | self.value = 0 111 | self._file.close() 112 | self._file = None 113 | self._write("direction", In) 114 | self._write("edge", "none") 115 | gpio_admin("unexport", self.soc_pin_number) 116 | 117 | def get(self): 118 | """The current value of the pin: 1 if the pin is high or 0 if the pin is low. 119 | 120 | The value can only be set if the pin's direction is Out. 121 | 122 | Raises: 123 | IOError -- could not read or write the pin's value. 124 | """ 125 | self._check_open() 126 | self._file.seek(0) 127 | v = self._file.read() 128 | return int(v) if v else 0 129 | 130 | def set(self, new_value): 131 | self._check_open() 132 | if self._direction != Out: 133 | raise ValueError("not an output pin") 134 | self._file.seek(0) 135 | self._file.write(str(int(new_value))) 136 | self._file.flush() 137 | 138 | @property 139 | def direction(self): 140 | """The direction of the pin: either In or Out. 141 | 142 | The value of the pin can only be set if its direction is Out. 143 | 144 | Raises: 145 | IOError -- could not set the pin's direction. 146 | """ 147 | return self._direction 148 | 149 | @direction.setter 150 | def direction(self, new_value): 151 | self._write("direction", new_value) 152 | self._direction = new_value 153 | 154 | @property 155 | def interrupt(self): 156 | """The interrupt property specifies what event (if any) will raise an interrupt. 157 | 158 | One of: 159 | Rising -- voltage changing from low to high 160 | Falling -- voltage changing from high to low 161 | Both -- voltage changing in either direction 162 | None -- interrupts are not raised 163 | 164 | Raises: 165 | IOError -- could not read or set the pin's interrupt trigger 166 | """ 167 | return self._interrupt 168 | 169 | @interrupt.setter 170 | def interrupt(self, new_value): 171 | self._write("edge", new_value) 172 | self._interrupt = new_value 173 | 174 | @property 175 | def pull(self): 176 | return self._pull 177 | 178 | def fileno(self): 179 | """Return the underlying file descriptor. Useful for select, epoll, etc.""" 180 | return self._file.fileno() 181 | 182 | @property 183 | def closed(self): 184 | """Returns if this pin is closed""" 185 | return self._file is None or self._file.closed 186 | 187 | def _check_open(self): 188 | if self.closed: 189 | raise IOError(str(self) + " is closed") 190 | 191 | def _write(self, filename, value): 192 | with open(self._pin_path(filename), "w+") as f: 193 | f.write(value) 194 | 195 | def _pin_path(self, filename=""): 196 | return "/sys/devices/virtual/gpio/gpio%i/%s" % (self.soc_pin_number, filename) 197 | 198 | def __repr__(self): 199 | return self.__module__ + "." + str(self) 200 | 201 | def __str__(self): 202 | return "{type}({index})".format( 203 | type=self.__class__.__name__, 204 | index=self.index) 205 | 206 | 207 | 208 | 209 | 210 | class PinBank(PinBankAPI): 211 | def __init__(self, index_to_soc_fn, count=None): 212 | super(PinBank,self).__init__() 213 | self._index_to_soc = index_to_soc_fn 214 | self._count = count 215 | 216 | def pin(self, index, *args, **kwargs): 217 | return Pin(self, index, self._index_to_soc(index), *args, **kwargs) 218 | 219 | @property 220 | def has_len(self): 221 | return self._count is not None 222 | 223 | def __len__(self): 224 | if self._count is not None: 225 | return self._count 226 | else: 227 | raise TypeError(self.__class__.__name__ + " has no len") 228 | 229 | 230 | BUTTON = 0 231 | LED = 1 232 | SPI_INTERRUPT = 6 233 | I2C_INTERRUPT = 7 234 | 235 | 236 | _pi_revision = revision() 237 | 238 | if _pi_revision == 0: 239 | # Not running on the Raspberry Pi, so define no-op pin banks 240 | pins = PinBank(lambda p: p) 241 | pi_broadcom_soc = pins 242 | pi_header_1 = pins 243 | 244 | else: 245 | def by_revision(d): 246 | return d[_pi_revision] 247 | 248 | 249 | # Maps header pin numbers to SoC GPIO numbers 250 | # See http://elinux.org/RPi_Low-level_peripherals 251 | # 252 | # Note: - header pins are numbered from 1, SoC GPIO from zero 253 | # - the Pi documentation identifies some header pins as GPIO0, 254 | # GPIO1, etc., but these are not the same as the SoC GPIO 255 | # numbers. 256 | 257 | _pi_header_1_pins = { 258 | 3: by_revision({1:0, 2:2}), 259 | 5: by_revision({1:1, 2:3}), 260 | 7: 4, 261 | 8: 14, 262 | 10: 15, 263 | 11: 17, 264 | 12: 18, 265 | 13: by_revision({1:21, 2:27}), 266 | 15: 22, 267 | 16: 23, 268 | 18: 24, 269 | 19: 10, 270 | 21: 9, 271 | 22: 25, 272 | 23: 11, 273 | 24: 8, 274 | 26: 7 275 | } 276 | 277 | _pi_gpio_pins = [_pi_header_1_pins[i] for i in [11, 12, 13, 15, 16, 18, 22, 7]] 278 | 279 | 280 | def lookup(pin_mapping, i): 281 | try: 282 | if i >= 0: 283 | return pin_mapping[i] 284 | except LookupError: 285 | pass 286 | 287 | raise IndexError(str(i) + " is not a valid pin index") 288 | 289 | def map_with(pin_mapping): 290 | return lambda i: lookup(pin_mapping,i) 291 | 292 | 293 | pi_broadcom_soc = PinBank(lambda p: p) 294 | pi_header_1 = PinBank(map_with(_pi_header_1_pins)) 295 | pins = PinBank(map_with(_pi_gpio_pins), len(_pi_gpio_pins)) 296 | 297 | 298 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/helpers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/helpers/__init__.py -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/helpers/display.py: -------------------------------------------------------------------------------- 1 | class AnalogueDisplay(): 2 | def __init__(self, max, *pins): 3 | self._pins = pins 4 | self._pin_levels = [(pins[index], index * max / len(pins)) for index in range(len(pins))] 5 | 6 | def display(self, value): 7 | for (pin, level) in self._pin_levels: 8 | pin.value = 1 if value < level else 0 9 | 10 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/i2c.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | from contextlib import closing 4 | import posix 5 | from fcntl import ioctl 6 | from quick2wire.i2c_ctypes import * 7 | from ctypes import create_string_buffer, sizeof, c_int, byref, pointer, addressof, string_at 8 | from quick2wire.board_revision import revision 9 | 10 | assert sys.version_info.major >= 3, __name__ + " is only supported on Python 3" 11 | 12 | 13 | default_bus = 1 if revision() > 1 else 0 14 | 15 | class I2CMaster(object): 16 | """Performs I2C I/O transactions on an I2C bus. 17 | 18 | Transactions are performed by passing one or more I2C I/O messages 19 | to the transaction method of the I2CMaster. I2C I/O messages are 20 | created with the reading, reading_into, writing and writing_bytes 21 | functions defined in the quick2wire.i2c module. 22 | 23 | An I2CMaster acts as a context manager, allowing it to be used in a 24 | with statement. The I2CMaster's file descriptor is closed at 25 | the end of the with statement and the instance cannot be used for 26 | further I/O. 27 | 28 | For example: 29 | 30 | from quick2wire.i2c import I2CMaster, writing 31 | 32 | with I2CMaster() as i2c: 33 | i2c.transaction( 34 | writing(0x20, bytes([0x01, 0xFF]))) 35 | """ 36 | 37 | def __init__(self, n=default_bus, extra_open_flags=0): 38 | """Opens the bus device. 39 | 40 | Arguments: 41 | n -- the number of the bus (default is 42 | the bus on the Raspberry Pi accessible 43 | via the header pins). 44 | extra_open_flags -- extra flags passed to posix.open when 45 | opening the I2C bus device file (default 0; 46 | e.g. no extra flags). 47 | """ 48 | self.fd = posix.open("/dev/i2c-%i"%n, posix.O_RDWR|extra_open_flags) 49 | 50 | def __enter__(self): 51 | return self 52 | 53 | def __exit__(self, exc_type, exc_value, traceback): 54 | self.close() 55 | 56 | def close(self): 57 | """ 58 | Closes the I2C bus device. 59 | """ 60 | posix.close(self.fd) 61 | 62 | def transaction(self, *msgs): 63 | """ 64 | Perform an I2C I/O transaction. 65 | 66 | Arguments: 67 | *msgs -- I2C messages created by one of the reading, reading_into, 68 | writing or writing_bytes functions. 69 | 70 | Returns: a list of byte sequences, one for each read operation 71 | performed. 72 | """ 73 | 74 | msg_count = len(msgs) 75 | msg_array = (i2c_msg*msg_count)(*msgs) 76 | ioctl_arg = i2c_rdwr_ioctl_data(msgs=msg_array, nmsgs=msg_count) 77 | 78 | ioctl(self.fd, I2C_RDWR, ioctl_arg) 79 | 80 | return [i2c_msg_to_bytes(m) for m in msgs if (m.flags & I2C_M_RD)] 81 | 82 | 83 | 84 | def reading(addr, n_bytes): 85 | """An I2C I/O message that reads n_bytes bytes of data""" 86 | return reading_into(addr, create_string_buffer(n_bytes)) 87 | 88 | def reading_into(addr, buf): 89 | """An I2C I/O message that reads into an existing ctypes string buffer.""" 90 | return _new_i2c_msg(addr, I2C_M_RD, buf) 91 | 92 | def writing_bytes(addr, *bytes): 93 | """An I2C I/O message that writes one or more bytes of data. 94 | 95 | Each byte is passed as an argument to this function. 96 | """ 97 | return writing(addr, bytes) 98 | 99 | def writing(addr, byte_seq): 100 | """An I2C I/O message that writes one or more bytes of data. 101 | 102 | The bytes are passed to this function as a sequence. 103 | """ 104 | buf = bytes(byte_seq) 105 | return _new_i2c_msg(addr, 0, create_string_buffer(buf, len(buf))) 106 | 107 | 108 | def _new_i2c_msg(addr, flags, buf): 109 | return i2c_msg(addr=addr, flags=flags, len=sizeof(buf), buf=buf) 110 | 111 | 112 | def i2c_msg_to_bytes(m): 113 | return string_at(m.buf, m.len) 114 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/i2c_ctypes.py: -------------------------------------------------------------------------------- 1 | # Warning: not part of the published Quick2Wire API. 2 | # 3 | # Converted from i2c.h and i2c-dev.h 4 | # I2C only, no SMB definitions 5 | 6 | from ctypes import c_int, c_uint16, c_ushort, c_short, c_ubyte, c_char, POINTER, Structure 7 | 8 | # /usr/include/linux/i2c-dev.h: 38 9 | class i2c_msg(Structure): 10 | """ struct i2c_msg""" 11 | 12 | _fields_ = [ 13 | ('addr', c_uint16), 14 | ('flags', c_ushort), 15 | ('len', c_short), 16 | ('buf', POINTER(c_char))] 17 | 18 | __slots__ = [name for name,type in _fields_] 19 | 20 | 21 | 22 | # i2c_msg flags 23 | I2C_M_TEN = 0x0010 # this is a ten bit chip address 24 | I2C_M_RD = 0x0001 # read data, from slave to master 25 | I2C_M_NOSTART = 0x4000 # if I2C_FUNC_PROTOCOL_MANGLING 26 | I2C_M_REV_DIR_ADDR = 0x2000 # if I2C_FUNC_PROTOCOL_MANGLING 27 | I2C_M_IGNORE_NAK = 0x1000 # if I2C_FUNC_PROTOCOL_MANGLING 28 | I2C_M_NO_RD_ACK = 0x0800 # if I2C_FUNC_PROTOCOL_MANGLING 29 | I2C_M_RECV_LEN = 0x0400 # length will be first received byte 30 | 31 | 32 | # /usr/include/linux/i2c-dev.h: 155 33 | class i2c_rdwr_ioctl_data(Structure): 34 | """ struct i2c_rdwr_ioctl_data""" 35 | _fields_ = [ 36 | ('msgs', POINTER(i2c_msg)), 37 | ('nmsgs', c_int)] 38 | 39 | __slots__ = [name for name,type in _fields_] 40 | 41 | I2C_FUNC_I2C = 0x00000001 42 | I2C_FUNC_10BIT_ADDR = 0x00000002 43 | I2C_FUNC_PROTOCOL_MANGLING = 0x00000004 # I2C_M_NOSTART etc. 44 | 45 | 46 | # ioctls 47 | 48 | I2C_SLAVE = 0x0703 # Change slave address 49 | # Attn.: Slave address is 7 or 10 bits 50 | I2C_SLAVE_FORCE = 0x0706 # Change slave address 51 | # Attn.: Slave address is 7 or 10 bits 52 | # This changes the address, even if it 53 | # is already taken! 54 | I2C_TENBIT = 0x0704 # 0 for 7 bit addrs, != 0 for 10 bit 55 | I2C_FUNCS = 0x0705 # Get the adapter functionality 56 | I2C_RDWR = 0x0707 # Combined R/W transfer (one stop only) 57 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/parts/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/parts/__init__.py -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/parts/mcp23017.py: -------------------------------------------------------------------------------- 1 | """ 2 | Low-level register access and a high-level application-programming 3 | interface for the MCP23017 I2C GPIO expander. 4 | """ 5 | 6 | from quick2wire.i2c import writing_bytes, reading 7 | import quick2wire.parts.mcp23x17 as mcp23x17 8 | from quick2wire.parts.mcp23x17 import deferred_read, immediate_read, deferred_write, immediate_write, In, Out 9 | 10 | class MCP23017(mcp23x17.PinBanks): 11 | """Application programming interface to the MCP23017 GPIO extender""" 12 | 13 | def __init__(self, master, address=0x20): 14 | """Initialise to control an MCP23017 at the specified address via the given I2CMaster. 15 | 16 | Parameters: 17 | master -- the quick2wire.i2c.I2CMaster used to communicate with the chip. 18 | address -- the address of the chip on the I2C bus (defaults to 0x20). 19 | """ 20 | super().__init__(Registers(master, address)) 21 | 22 | 23 | class Registers(mcp23x17.Registers): 24 | """Low level access to the MCP23017 registers 25 | 26 | The MCP23017 has two register addressing modes, depending on the 27 | value of bit7 of IOCON. We assume bank=0 addressing (which is the 28 | POR default value). 29 | """ 30 | 31 | def __init__(self, master, address): 32 | """Initialise to control an MCP23017 at the specified address via the given I2CMaster. 33 | 34 | Parameters: 35 | master -- the quick2wire.i2c.I2CMaster used to communicate with the chip. 36 | address -- the address of the chip on the I2C bus (defaults to 0x20). 37 | """ 38 | self.master = master 39 | self.address = address 40 | 41 | def write_register(self, register_id, byte): 42 | """Write the value of a register. 43 | 44 | Parameters: 45 | reg -- the register address 46 | value -- the new value of the register 47 | """ 48 | self.master.transaction( 49 | writing_bytes(self.address, register_id, byte)) 50 | 51 | def read_register(self, register_id): 52 | """Read the value of a register. 53 | 54 | Parameters: 55 | reg -- the register address 56 | 57 | Returns: the value of the register. 58 | """ 59 | return self.master.transaction( 60 | writing_bytes(self.address, register_id), 61 | reading(self.address, 1))[0][0] 62 | 63 | 64 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/parts/mcp23x17.py: -------------------------------------------------------------------------------- 1 | """ 2 | Low-level register access and a high-level application-programming 3 | interface for the MCP23x17 series of GPIO expanders. 4 | 5 | The definitions in this module are common to the I2C MCP23017 and SPI 6 | MCP23S17. Only the methods for reading and writing to registers 7 | differ, and they must be defined by subclassing the Registers class. 8 | """ 9 | 10 | import contextlib 11 | from warnings import warn 12 | from quick2wire.gpio import PinAPI, PinBankAPI 13 | 14 | # TODO - import from GPIO or common definitions module 15 | In = "in" 16 | Out = "out" 17 | 18 | # Bits within the IOCON regiseter 19 | IOCON_INTPOL=1 20 | IOCON_ODR=2 21 | IOCON_MIRROR=6 22 | 23 | # Register names within a bank 24 | IODIR=0 25 | IPOL=1 26 | GPINTEN=2 27 | DEFVAL=3 28 | INTCON=4 29 | IOCON=5 30 | GPPU=6 31 | INTF=7 32 | INTCAP=8 33 | GPIO=9 34 | OLAT=10 35 | 36 | bank_register_names = sorted([s for s in globals().keys() if s.upper() == s], 37 | key=lambda s: globals()[s]) 38 | 39 | 40 | BANK_SIZE = 11 41 | 42 | _BankA = 0 43 | _BankB = 1 44 | 45 | def _banked_register(bank, reg): 46 | return reg*2 + bank 47 | 48 | IODIRA = _banked_register(_BankA, IODIR) 49 | IODIRB = _banked_register(_BankB, IODIR) 50 | IPOLA = _banked_register(_BankA, IPOL) 51 | IPOLB = _banked_register(_BankB, IPOL) 52 | GPINTENA =_banked_register(_BankA, GPINTEN) 53 | GPINTENB = _banked_register(_BankB, GPINTEN) 54 | DEFVALA = _banked_register(_BankA, DEFVAL) 55 | DEFVALB = _banked_register(_BankB, DEFVAL) 56 | INTCONA = _banked_register(_BankA, INTCON) 57 | INTCONB = _banked_register(_BankB, INTCON) 58 | IOCONA = _banked_register(_BankA, IOCON) 59 | IOCONB = _banked_register(_BankB, IOCON) # Actually addresses the same register as IOCONA 60 | IOCON_BOTH = IOCONA 61 | GPPUA = _banked_register(_BankA, GPPU) 62 | GPPUB = _banked_register(_BankB, GPPU) 63 | INTFA = _banked_register(_BankA, INTF) 64 | INTFB = _banked_register(_BankB, INTF) 65 | INTCAPA = _banked_register(_BankA, INTCAP) 66 | INTCAPB = _banked_register(_BankB, INTCAP) 67 | GPIOA = _banked_register(_BankA, GPIO) 68 | GPIOB = _banked_register(_BankB, GPIO) 69 | OLATA = _banked_register(_BankA, OLAT) 70 | OLATB = _banked_register(_BankB, OLAT) 71 | 72 | register_names = sorted([s for s in globals().keys() if s[-1] in ('A','B') and s.upper() == s], 73 | key=lambda s: globals()[s]) 74 | 75 | _initial_register_values = ( 76 | ((IODIR,), 0xFF), 77 | ((IPOL, GPINTEN, DEFVAL, INTCON, GPPU, INTF, INTCAP, GPIO, OLAT), 0x00)) 78 | 79 | def _reset_sequence(): 80 | return [(reg,value) for regs, value in _initial_register_values for reg in regs] 81 | 82 | 83 | class Registers(object): 84 | """Abstract interface for reading/writing MCP23x17 registers over the I2C or SPI bus. 85 | 86 | You shouldn't normally need to use this class. 87 | 88 | The MCP23x17 has two register addressing modes, depending on the 89 | value of bit7 of IOCON. We assume bank=0 addressing (which is the 90 | POR default value). 91 | """ 92 | 93 | def reset(self, iocon=0x00): 94 | """Reset to power-on state 95 | """ 96 | self.write_register(IOCON_BOTH, iocon) 97 | 98 | for reg, value in _reset_sequence(): 99 | self.write_banked_register(_BankA, reg, value) 100 | self.write_banked_register(_BankB, reg, value) 101 | 102 | def write_banked_register(self, bank, reg, value): 103 | """Write the value of a register within a bank. 104 | """ 105 | self.write_register(_banked_register(bank, reg), value) 106 | 107 | def read_banked_register(self, bank, reg): 108 | """Read the value of a register within a bank. 109 | """ 110 | return self.read_register(_banked_register(bank, reg)) 111 | 112 | def write_register(self, reg, value): 113 | """Write the value of a register. 114 | 115 | Implement in subclasses. 116 | 117 | Parameters: 118 | reg -- the register address 119 | value -- the new value of the register 120 | """ 121 | pass 122 | 123 | def read_register(self, reg): 124 | """Read the value of a register. 125 | 126 | Implement in subclasses. 127 | 128 | Parameters: 129 | reg -- the register address 130 | 131 | Returns: the value of the register. 132 | """ 133 | pass 134 | 135 | 136 | 137 | def _set_bit(current_value, bit_index, new_value): 138 | bit_mask = 1 << bit_index 139 | return (current_value | bit_mask) if new_value else (current_value & ~bit_mask) 140 | 141 | 142 | class PinBanks(object): 143 | """The pin banks of an MCP23x17 chip.""" 144 | 145 | def __init__(self, registers): 146 | self.registers = registers 147 | self._banks = (PinBank(self, 0), PinBank(self, 1)) 148 | 149 | def __len__(self): 150 | """Returns the number of pin banks. (2 for the MCP23x17)""" 151 | return len(self._banks) 152 | 153 | def bank(self, n): 154 | """Returns bank n.""" 155 | return self._banks[n] 156 | 157 | __getitem__ = bank 158 | 159 | def reset(self, interrupt_polarity=0, interrupt_open_drain=False, interrupt_mirror=True): 160 | """Resets the chip to power-on state and sets configuration flags in the IOCON register 161 | 162 | Parameters: 163 | interrupt_polarity -- sets the polarity of the interrupt output 164 | pin: 1 = active-high. 0 = active-low. 165 | interrupt_open_drain -- configures the interrupt output pin as an 166 | open-drain output. 167 | True = Open-drain output (overrides the 168 | interrupt_polarity). 169 | False = Active driver output (the 170 | interrupt_polarity parameter sets the 171 | polarity). 172 | interrupt_mirror -- Sets the interrupt output mirroring. 173 | True = the interrupt output pins are 174 | internally connected. 175 | False = the interrupt output pins are 176 | not connected, INTA is associated with 177 | PortA and INTB is associated with PortB. 178 | Should be set to True (the default) if 179 | using the Quick2Wire MCP23017 expander 180 | board. 181 | """ 182 | 183 | self.registers.reset((interrupt_polarity << IOCON_INTPOL) 184 | |(interrupt_open_drain << IOCON_ODR) 185 | |(interrupt_mirror << IOCON_MIRROR)) 186 | 187 | for bank in self._banks: 188 | bank._reset_cache() 189 | 190 | 191 | # Read and write modes 192 | 193 | def deferred_read(f): 194 | """A PinBank read mode: read() must be called explicitly.""" 195 | pass 196 | 197 | def immediate_read(f): 198 | """A PinBank read mode: read() is called automatically whenever a pin value is read. 199 | 200 | Note: this mode is not compatible with interrupts. A warning will 201 | be issued if interrupts are enabled on a PinBank that is in 202 | immediate_read mode. 203 | """ 204 | f() 205 | 206 | def deferred_write(f): 207 | """A PinBank write mode: write() must be called explicitly.""" 208 | pass 209 | 210 | def immediate_write(f): 211 | """A PinBank write mode: registers are written whenever Pin attributes are set.""" 212 | f() 213 | 214 | 215 | class PinBank(PinBankAPI): 216 | """A bank of 8 GPIO pins""" 217 | 218 | def __init__(self, chip, bank_id): 219 | self.chip = chip 220 | self._bank_id = bank_id 221 | self._pins = tuple([Pin(self, i) for i in range(8)]) 222 | self._register_cache = [None]*BANK_SIZE # self._register_cache[IOCON] is ignored 223 | self._outstanding_writes = [] 224 | self.read_mode = immediate_read 225 | self.write_mode = immediate_write 226 | self._reset_cache() 227 | 228 | @property 229 | def index(self): 230 | """The index of this bank (0 or 1).""" 231 | return self._bank_id 232 | 233 | 234 | def __len__(self): 235 | """The number of pins in the bank. (8 for the MCP23x17)""" 236 | return len(self._pins) 237 | 238 | 239 | def pin(self, n): 240 | """Returns pin n.""" 241 | pin = self._pins[n] 242 | return pin 243 | 244 | __getitem__ = pin 245 | 246 | 247 | def read(self): 248 | """Read the GPIO input and interrupt capture registers from the chip. 249 | 250 | If the bank's read_mode is set to deferred_read, this must be 251 | called to make value property of the bank's Pins reflect the 252 | state of the chip's physical input pins. 253 | 254 | If the bank's read_mode is set to immediate_read, read() is 255 | called whenever the value property of any of the bank's Pins 256 | is read. 257 | """ 258 | self._read_register(INTCAP) 259 | self._read_register(GPIO) 260 | 261 | 262 | def write(self): 263 | """Write changes to the pin's state capture and GPIO input registers from the chip. 264 | 265 | If the bank's write_mode is set to deferred_write, this must be 266 | update the chip's physical input pins so that they reflect the 267 | value property of the bank's Pins. 268 | 269 | If the bank's write_mode is set to immediate_write, write() is 270 | called whenever the value property of any of the bank's Pins 271 | is set. 272 | """ 273 | for r in self._outstanding_writes: 274 | self._write_register(r, self._register_cache[r]) 275 | self._outstanding_writes = [] 276 | 277 | 278 | def _get_register_bit(self, register, bit_index): 279 | self.read_mode(lambda:self._read_register(register)) 280 | 281 | if self._register_cache[register] is None: 282 | self._read_register(register) 283 | 284 | return bool(self._register_cache[register] & (1<= 3, __name__ + " is only supported on Python 3" 10 | 11 | 12 | class SPIDevice: 13 | """Communicates with a hardware device over an SPI bus. 14 | 15 | Transactions are performed by passing one or more SPI I/O requests 16 | to the transaction method of the SPIDevice. SPI I/O requests are 17 | created with the reading, writing, writing_bytes, duplex and 18 | duplex_bytes functions defined in the quick2wire.spi module. 19 | 20 | An SPIDevice acts as a context manager, allowing it to be used in 21 | a with statement. The SPIDevice's file descriptor is closed at 22 | the end of the with statement and the instance cannot be used for 23 | further I/O. 24 | 25 | For example: 26 | 27 | from quick2wire.spi import SPIDevice, writing 28 | 29 | with SPIDevice(0) as spi0: 30 | spi0.transaction( 31 | writing(0x20, bytes([0x01, 0xFF]))) 32 | """ 33 | 34 | def __init__(self, chip_select, bus=0): 35 | """Opens the SPI device. 36 | 37 | Arguments: 38 | chip_select -- the SPI chip select line to use. The Raspberry Pi 39 | only has two chip select lines, numbered 0 and 1. 40 | bus -- the number of the bus (default 0, the only SPI bus 41 | on the Raspberry Pi). 42 | """ 43 | self.fd = posix.open("/dev/spidev%i.%i"%(bus,chip_select), posix.O_RDWR) 44 | 45 | def transaction(self, *transfers): 46 | """ 47 | Perform an SPI I/O transaction. 48 | 49 | Arguments: 50 | *transfers -- SPI transfer requests created by one of the reading, 51 | writing, writing_bytes, duplex or duplex_bytes 52 | functions. 53 | 54 | Returns: a list of byte sequences, one for each read or duplex 55 | operation performed. 56 | """ 57 | transfer_count = len(transfers) 58 | ioctl_arg = (spi_ioc_transfer*transfer_count)() 59 | 60 | # populate array from transfers 61 | for i, transfer in enumerate(transfers): 62 | ioctl_arg[i] = transfers[i].to_spi_ioc_transfer() 63 | 64 | ioctl(self.fd, SPI_IOC_MESSAGE(transfer_count), addressof(ioctl_arg)) 65 | 66 | return [transfer.to_read_bytes() for t in transfers if t.has_read_buf] 67 | 68 | def close(self): 69 | """ 70 | Closes the file descriptor. 71 | """ 72 | posix.close(self.fd) 73 | 74 | @property 75 | def clock_mode(self): 76 | """ 77 | Returns the current clock mode for the SPI bus 78 | """ 79 | return ord(struct.unpack('c', ioctl(self.fd, SPI_IOC_RD_MODE, " "))[0]) 80 | 81 | @clock_mode.setter 82 | def clock_mode(self,mode): 83 | """ 84 | Changes the clock mode for this SPI bus 85 | 86 | For example: 87 | #start clock low, sample trailing edge 88 | spi.clock_mode = SPI_MODE_1 89 | """ 90 | ioctl(self.fd, SPI_IOC_WR_MODE, struct.pack('I', mode)) 91 | 92 | @property 93 | def speed_hz(self): 94 | """ 95 | Returns the current speed in Hz for this SPI bus 96 | """ 97 | return struct.unpack('I', ioctl(self.fd, SPI_IOC_RD_MAX_SPEED_HZ, " "))[0] 98 | 99 | @speed_hz.setter 100 | def speed_hz(self,speedHz): 101 | """ 102 | Changes the speed in Hz for this SPI bus 103 | """ 104 | ioctl(self.fd, SPI_IOC_WR_MAX_SPEED_HZ, struct.pack('I', speedHz)) 105 | 106 | def __enter__(self): 107 | return self 108 | 109 | def __exit__(self, exc_type, exc_val, exc_tb): 110 | self.close() 111 | 112 | 113 | class _SPITransfer: 114 | def __init__(self, write_byte_seq = None, read_byte_count = None): 115 | if write_byte_seq is not None: 116 | self.write_bytes = bytes(write_byte_seq) 117 | self.write_buf = create_string_buffer(self.write_bytes, len(self.write_bytes)) 118 | else: 119 | self.write_bytes = None 120 | self.write_buf = None 121 | 122 | if read_byte_count is not None: 123 | self.read_buf = create_string_buffer(read_byte_count) 124 | else: 125 | self.read_buf = None 126 | 127 | def to_spi_ioc_transfer(self): 128 | return spi_ioc_transfer( 129 | tx_buf=_safe_address_of(self.write_buf), 130 | rx_buf=_safe_address_of(self.read_buf), 131 | len=_safe_size_of(self.write_buf, self.read_buf)) 132 | 133 | @property 134 | def has_read_buf(self): 135 | return self.read_buf is not None 136 | 137 | def to_read_bytes(self): 138 | return string_at(self.read_buf, sizeof(self.read_buf)) 139 | 140 | 141 | def _safe_size_of(write_buf, read_buf): 142 | if write_buf is not None and read_buf is not None: 143 | assert sizeof(write_buf) == sizeof(read_buf) 144 | return sizeof(write_buf) 145 | elif write_buf is not None: 146 | return sizeof(write_buf) 147 | else: 148 | return sizeof(read_buf) 149 | 150 | def _safe_address_of(buf): 151 | return 0 if buf is None else addressof(buf) 152 | 153 | def duplex(write_byte_sequence): 154 | """An SPI transfer that writes the write_byte_sequence to the device and reads len(write_byte_sequence) bytes from the device. 155 | 156 | The bytes to be written are passed to this function as a sequence. 157 | """ 158 | return _SPITransfer(write_byte_seq=write_byte_sequence, read_byte_count=len(write_byte_sequence)) 159 | 160 | def duplex_bytes(*write_bytes): 161 | """An SPI transfer that writes the write_bytes to the device and reads len(write_bytes) bytes from the device. 162 | 163 | Each byte to be written is passed as an argument to this function. 164 | """ 165 | return duplex(write_bytes) 166 | 167 | def reading(byte_count): 168 | """An SPI transfer that shifts out byte_count zero bytes and reads byte_counts bytes from the device.""" 169 | return _SPITransfer(read_byte_count=byte_count) 170 | 171 | def writing(byte_sequence): 172 | """An SPI transfer that writes one or more bytes of data and ignores any bytes read from the device. 173 | 174 | The bytes are passed to this function as a sequence. 175 | """ 176 | return _SPITransfer(write_byte_seq=byte_sequence) 177 | 178 | def writing_bytes(*byte_values): 179 | """An SPI transfer that writes one or more bytes of data and ignores any bytes read from the device. 180 | 181 | Each byte is passed as an argument to this function. 182 | """ 183 | return writing(byte_values) 184 | 185 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/spi_ctypes.py: -------------------------------------------------------------------------------- 1 | # Warning: not part of the published Quick2Wire API. 2 | # 3 | # User space versions of kernel symbols for SPI clocking modes, 4 | # matching 5 | # 6 | # Ported to Python ctypes from 7 | 8 | from ctypes import * 9 | from quick2wire.asm_generic_ioctl import _IOR, _IOW, _IOC_SIZEBITS 10 | 11 | SPI_CPHA = 0x01 12 | SPI_CPOL = 0x02 13 | 14 | SPI_MODE_0 = 0 15 | SPI_MODE_1 = SPI_CPHA 16 | SPI_MODE_2 = SPI_CPOL 17 | SPI_MODE_3 = SPI_CPOL|SPI_CPHA 18 | 19 | SPI_CS_HIGH = 0x04 20 | SPI_LSB_FIRST = 0x08 21 | SPI_3WIRE = 0x10 22 | SPI_LOOP = 0x20 23 | SPI_NO_CS = 0x40 24 | SPI_READY = 0x80 25 | 26 | 27 | # IOCTL commands */ 28 | 29 | SPI_IOC_MAGIC = 107 # ord('k') 30 | 31 | 32 | # struct spi_ioc_transfer - describes a single SPI transfer 33 | # 34 | # tx_buf: Holds pointer to userspace buffer with transmit data, or null. 35 | # If no data is provided, zeroes are shifted out. 36 | # rx_buf: Holds pointer to userspace buffer for receive data, or null. 37 | # len: Length of tx and rx buffers, in bytes. 38 | # speed_hz: Temporary override of the device's bitrate. 39 | # bits_per_word: Temporary override of the device's wordsize. 40 | # delay_usecs: If nonzero, how long to delay after the last bit transfer 41 | # before optionally deselecting the device before the next transfer. 42 | # cs_change: True to deselect device before starting the next transfer. 43 | # 44 | # This structure is mapped directly to the kernel spi_transfer structure; 45 | # the fields have the same meanings, except of course that the pointers 46 | # are in a different address space (and may be of different sizes in some 47 | # cases, such as 32-bit i386 userspace over a 64-bit x86_64 kernel). 48 | # Zero-initialize the structure, including currently unused fields, to 49 | # accomodate potential future updates. 50 | # 51 | # SPI_IOC_MESSAGE gives userspace the equivalent of kernel spi_sync(). 52 | # Pass it an array of related transfers, they'll execute together. 53 | # Each transfer may be half duplex (either direction) or full duplex. 54 | # 55 | # struct spi_ioc_transfer mesg[4]; 56 | # ... 57 | # status = ioctl(fd, SPI_IOC_MESSAGE(4), mesg); 58 | # 59 | # So for example one transfer might send a nine bit command (right aligned 60 | # in a 16-bit word), the next could read a block of 8-bit data before 61 | # terminating that command by temporarily deselecting the chip; the next 62 | # could send a different nine bit command (re-selecting the chip), and the 63 | # last transfer might write some register values. 64 | 65 | class spi_ioc_transfer(Structure): 66 | """ struct spi_ioc_transfer""" 67 | 68 | _fields_ = [ 69 | ("tx_buf", c_uint64), 70 | ("rx_buf", c_uint64), 71 | ("len", c_uint32), 72 | ("speed_hz", c_uint32), 73 | ("delay_usecs", c_uint16), 74 | ("bits_per_word", c_uint8), 75 | ("cs_change", c_uint8), 76 | ("pad", c_uint32)] 77 | 78 | __slots__ = [name for name,type in _fields_] 79 | 80 | 81 | # not all platforms use or _IOC_TYPECHECK() ... 82 | def SPI_MSGSIZE(N): 83 | if ((N)*(sizeof(spi_ioc_transfer))) < (1 << _IOC_SIZEBITS): 84 | return (N)*(sizeof(spi_ioc_transfer)) 85 | else: 86 | return 0 87 | 88 | def SPI_IOC_MESSAGE(N): 89 | return _IOW(SPI_IOC_MAGIC, 0, c_char*SPI_MSGSIZE(N)) 90 | 91 | # Read / Write of SPI mode (SPI_MODE_0..SPI_MODE_3) 92 | SPI_IOC_RD_MODE = _IOR(SPI_IOC_MAGIC, 1, c_uint8) 93 | SPI_IOC_WR_MODE = _IOW(SPI_IOC_MAGIC, 1, c_uint8) 94 | 95 | # Read / Write SPI bit justification 96 | SPI_IOC_RD_LSB_FIRST = _IOR(SPI_IOC_MAGIC, 2, c_uint8) 97 | SPI_IOC_WR_LSB_FIRST = _IOW(SPI_IOC_MAGIC, 2, c_uint8) 98 | 99 | # Read / Write SPI device word length (1..N) 100 | SPI_IOC_RD_BITS_PER_WORD = _IOR(SPI_IOC_MAGIC, 3, c_uint8) 101 | SPI_IOC_WR_BITS_PER_WORD = _IOW(SPI_IOC_MAGIC, 3, c_uint8) 102 | 103 | # Read / Write SPI device default max speed hz 104 | SPI_IOC_RD_MAX_SPEED_HZ = _IOR(SPI_IOC_MAGIC, 4, c_uint32) 105 | SPI_IOC_WR_MAX_SPEED_HZ = _IOW(SPI_IOC_MAGIC, 4, c_uint32) 106 | 107 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/syscall.py: -------------------------------------------------------------------------------- 1 | 2 | import os 3 | import errno 4 | import ctypes 5 | 6 | libc = ctypes.CDLL(None, use_errno=True) 7 | 8 | def errcheck(result, func, args): 9 | if result < 0: 10 | e = ctypes.get_errno() 11 | raise OSError(e, errno.strerror(e)) 12 | return result 13 | 14 | def lookup(restype, name, argtypes): 15 | f = libc[name] 16 | f.restye = restype 17 | f.argtypes = argtypes 18 | f.errcheck = errcheck 19 | return f 20 | 21 | 22 | class SelfClosing(object): 23 | def __enter__(self): 24 | return self 25 | 26 | def __exit__(self, *exc): 27 | self.close() 28 | return False 29 | 30 | 31 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/py532lib/quick2wire/timerfd.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import math 4 | import os 5 | from ctypes import * 6 | import struct 7 | from contextlib import closing 8 | import quick2wire.syscall as syscall 9 | 10 | 11 | # From 12 | 13 | time_t = c_long 14 | 15 | clockid_t = c_ulong 16 | 17 | class timespec(Structure): 18 | _fields_ = [("sec", time_t), 19 | ("nsec", c_long)] 20 | 21 | __slots__ = [name for name,type in _fields_] 22 | 23 | @classmethod 24 | def from_seconds(cls, secs): 25 | t = cls() 26 | t.seconds = secs 27 | return t 28 | 29 | @property 30 | def seconds(self): 31 | if self.nsec == 0: 32 | return self.sec 33 | else: 34 | return self.sec + self.nsec / 1000000000.0 35 | 36 | @seconds.setter 37 | def seconds(self, secs): 38 | fractional, whole = math.modf(secs) 39 | self.sec = int(whole) 40 | self.nsec = int(fractional * 1000000000) 41 | 42 | 43 | class itimerspec(Structure): 44 | _fields_ = [("interval", timespec), 45 | ("value", timespec)] 46 | 47 | __slots__ = [name for name,type in _fields_] 48 | 49 | @classmethod 50 | def from_seconds(cls, offset, interval): 51 | spec = cls() 52 | spec.value.seconds = offset 53 | spec.interval.seconds = interval 54 | return spec 55 | 56 | 57 | # from 58 | 59 | CLOCK_REALTIME = 0 # Identifier for system-wide realtime clock. 60 | CLOCK_MONOTONIC = 1 # Monotonic system-wide clock. 61 | CLOCK_PROCESS_CPUTIME_ID = 2 # High-resolution timer from the CPU 62 | CLOCK_THREAD_CPUTIME_ID = 3 # Thread-specific CPU-time clock. 63 | CLOCK_MONOTONIC_RAW = 4 # Monotonic system-wide clock, not adjusted for frequency scaling. 64 | CLOCK_REALTIME_COARSE = 5 # Identifier for system-wide realtime clock, updated only on ticks. 65 | CLOCK_MONOTONIC_COARSE = 6 # Monotonic system-wide clock, updated only on ticks. 66 | CLOCK_BOOTTIME = 7 # Monotonic system-wide clock that includes time spent in suspension. 67 | CLOCK_REALTIME_ALARM = 8 # Like CLOCK_REALTIME but also wakes suspended system. 68 | CLOCK_BOOTTIME_ALARM = 9 # Like CLOCK_BOOTTIME but also wakes suspended system. 69 | 70 | 71 | # From 72 | 73 | # Bits to be set in the FLAGS parameter of `timerfd_create'. 74 | TFD_CLOEXEC = 0o2000000, 75 | TFD_NONBLOCK = 0o4000 76 | 77 | # Bits to be set in the FLAGS parameter of `timerfd_settime'. 78 | TFD_TIMER_ABSTIME = 1 << 0 79 | 80 | 81 | 82 | # Return file descriptor for new interval timer source. 83 | # 84 | # extern int timerfd_create (clockid_t __clock_id, int __flags) 85 | 86 | timerfd_create = syscall.lookup(c_int, "timerfd_create", (clockid_t, c_int)) 87 | 88 | # Set next expiration time of interval timer source UFD to UTMR. If 89 | # FLAGS has the TFD_TIMER_ABSTIME flag set the timeout value is 90 | # absolute. Optionally return the old expiration time in OTMR. 91 | # 92 | # extern int timerfd_settime (int __ufd, int __flags, 93 | # __const struct itimerspec *__utmr, 94 | # struct itimerspec *__otmr) 95 | timerfd_settime = syscall.lookup(c_int, "timerfd_settime", (c_int, c_int, POINTER(itimerspec), POINTER(itimerspec))) 96 | 97 | # Return the next expiration time of UFD. 98 | # 99 | # extern int timerfd_gettime (int __ufd, struct itimerspec *__otmr) 100 | 101 | timerfd_gettime = syscall.lookup(c_int, "timerfd_gettime", (c_int, POINTER(itimerspec))) 102 | 103 | 104 | class Timer(syscall.SelfClosing): 105 | """A one-shot or repeating timer that can be added to a Selector.""" 106 | 107 | def __init__(self, offset=0, interval=0, blocking=True, clock=CLOCK_REALTIME): 108 | """Creates a new Timer. 109 | 110 | Arguments: 111 | offset -- the initial expiration time, measured in seconds from 112 | the call to start(). 113 | interval -- if non-zero, the interval for periodic timer expirations, 114 | measured in seconds. 115 | blocking -- if False calls to wait() do not block until the timer 116 | expires but return 0 if the timer has not expired. 117 | (default = True) 118 | clock -- the system clock used to measure time: 119 | CLOCK_REALTIME -- system-wide realtime clock. 120 | CLOCK_MONOTONIC -- monotonic system-wide clock. 121 | """ 122 | self._fd = timerfd_create(clock, (not blocking)*TFD_NONBLOCK) 123 | self._offset = offset 124 | self._interval = interval 125 | self._started = False 126 | 127 | def close(self): 128 | """Closes the Timer and releases its file descriptor.""" 129 | os.close(self._fd) 130 | self._fd = None 131 | 132 | def fileno(self): 133 | """Returns the Timer's file descriptor.""" 134 | return self._fd 135 | 136 | @property 137 | def offset(self): 138 | """the initial expiration time, measured in seconds from the call to start().""" 139 | return self._offset 140 | 141 | @offset.setter 142 | def offset(self, new_offset): 143 | self._offset = new_offset 144 | if self._started: 145 | self._apply_schedule() 146 | 147 | @property 148 | def interval(self): 149 | """The interval, specified in seconds, with which the timer will repeat. 150 | 151 | If zero, the timer only fires once, when the offset expires. 152 | """ 153 | return self._interval 154 | 155 | @interval.setter 156 | def interval(self, new_interval): 157 | self._interval = new_interval 158 | if self._started: 159 | self._apply_schedule() 160 | 161 | def start(self): 162 | """Starts the timer running. 163 | 164 | Raises: 165 | ValueError -- if offset and interval are both zero. 166 | """ 167 | if self._offset == 0 and self._interval == 0: 168 | raise ValueError("timer will not fire because offset and interval are both zero") 169 | 170 | self._apply_schedule() 171 | self._started = True 172 | 173 | def stop(self): 174 | """Stops the timer running. Any scheduled timer events will not fire.""" 175 | self._schedule(0, 0) 176 | self._started = False 177 | 178 | def wait(self): 179 | """Receives timer events. 180 | 181 | If the timer has already expired one or more times since its 182 | settings were last modified or wait() was last called then 183 | wait() returns the number of expirations that have occurred. 184 | 185 | If no timer expirations have occurred, then the call either 186 | blocks until the next timer expiration, or returns 0 if the 187 | Timer is non-blocking (was created with the blocking parameter 188 | set to False). 189 | 190 | Raises: 191 | OSError -- an OS error occurred reading the state of the timer. 192 | """ 193 | try: 194 | buf = os.read(self._fd, 8) 195 | return struct.unpack("Q", buf)[0] 196 | except OSError as e: 197 | if e.errno == errno.EAGAIN: 198 | return 0 199 | else: 200 | raise e 201 | 202 | def _apply_schedule(self): 203 | self._schedule(self._offset or self._interval, self._interval) 204 | 205 | def _schedule(self, offset, interval): 206 | spec = itimerspec.from_seconds(offset, interval) 207 | timerfd_settime(self._fd, 0, byref(spec), None) 208 | 209 | -------------------------------------------------------------------------------- /RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/wiring diagram.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/RFID_NFC_reader_writer_with_PN532_ft_Raspberry_Pi/wiring diagram.jpg -------------------------------------------------------------------------------- /RGB_LED_Controller_ft_ESP32_&_ws2812b/rgb_controller.ino: -------------------------------------------------------------------------------- 1 | #include "FastLED.h" 2 | 3 | #define NUM_LEDS 16 4 | #define DATA_PIN 13 5 | 6 | #define r 4 7 | #define g 0 8 | #define b 2 9 | #define bri 15 10 | 11 | int r_value, g_value, b_value, bri_value; 12 | 13 | CRGB leds[NUM_LEDS]; 14 | 15 | int fmap(float x, float in_min, float in_max, float out_min, float out_max) 16 | { 17 | return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; 18 | } 19 | 20 | void setup() { 21 | Serial.begin(115200); 22 | delay(2000); 23 | FastLED.addLeds(leds, NUM_LEDS); 24 | FastLED.setBrightness(10); 25 | } 26 | 27 | void loop() { 28 | r_value = analogRead(r); 29 | r_value = fmap(r_value, 0, 4095, 0, 255); 30 | g_value = analogRead(g); 31 | g_value = fmap(g_value, 0, 4095, 0, 255); 32 | b_value = analogRead(b); 33 | b_value = fmap(b_value, 0, 4095, 0, 255); 34 | bri_value = analogRead(bri); 35 | bri_value = fmap(bri_value, 0, 4095, 0, 100); 36 | 37 | Serial.print(r_value); 38 | Serial.print(','); 39 | Serial.print(g_value); 40 | Serial.print(','); 41 | Serial.print(b_value); 42 | Serial.print(','); 43 | Serial.println(bri_value); 44 | FastLED.setBrightness(bri_value); 45 | leds[0] = CRGB(r_value, g_value, b_value); 46 | leds[1] = CRGB(r_value, g_value, b_value); 47 | leds[2] = CRGB(r_value, g_value, b_value); 48 | leds[3] = CRGB(r_value, g_value, b_value); 49 | leds[4] = CRGB(r_value, g_value, b_value); 50 | leds[5] = CRGB(r_value, g_value, b_value); 51 | leds[6] = CRGB(r_value, g_value, b_value); 52 | leds[7] = CRGB(r_value, g_value, b_value); 53 | leds[8] = CRGB(r_value, g_value, b_value); 54 | leds[9] = CRGB(r_value, g_value, b_value); 55 | leds[10] = CRGB(r_value, g_value, b_value); 56 | leds[11] = CRGB(r_value, g_value, b_value); 57 | leds[12] = CRGB(r_value, g_value, b_value); 58 | leds[13] = CRGB(r_value, g_value, b_value); 59 | leds[14] = CRGB(r_value, g_value, b_value); 60 | leds[15] = CRGB(r_value, g_value, b_value); 61 | FastLED.show(); 62 | } 63 | -------------------------------------------------------------------------------- /RGB_LED_Controller_ft_ESP32_&_ws2812b/wiring diagram.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/RGB_LED_Controller_ft_ESP32_&_ws2812b/wiring diagram.jpg -------------------------------------------------------------------------------- /RPi_and_Arduino_Serial_Communication/i2c_nano_pn532.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/RPi_and_Arduino_Serial_Communication/i2c_nano_pn532.PNG -------------------------------------------------------------------------------- /RPi_and_Arduino_Serial_Communication/nano_rdif.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define PN532_IRQ (2) 5 | #define PN532_RESET (3) 6 | Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET); 7 | 8 | int ledPin = LED_BUILTIN; 9 | String readString; 10 | 11 | void setup(void) { 12 | Serial.begin(115200); 13 | nfc.begin(); 14 | uint32_t versiondata = nfc.getFirmwareVersion(); 15 | if (! versiondata) { 16 | while (1); // halt 17 | } 18 | nfc.SAMConfig(); 19 | pinMode(ledPin, OUTPUT); 20 | } 21 | 22 | void loop(void) { 23 | uint8_t success; 24 | uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; 25 | uint8_t uidLength; 26 | success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength); 27 | if (success) { 28 | nfc.PrintHex(uid, uidLength); 29 | if (uidLength == 4) { 30 | uint32_t cardid = uid[0]; 31 | cardid <<= 8; 32 | cardid |= uid[1]; 33 | cardid <<= 8; 34 | cardid |= uid[2]; 35 | cardid <<= 8; 36 | cardid |= uid[3]; 37 | String ab1 = String(cardid) + "," + String(uid[0]) + "," + String(uid[1]) + "," + String(uid[2]) + "," + String(uid[3]) ; 38 | Serial.println(ab1); 39 | while (1) { 40 | while (Serial.available()) { 41 | char c = Serial.read(); 42 | readString += c; 43 | } 44 | readString.trim(); 45 | if (readString.length() > 0) { 46 | if (readString == "DerpHashTurnOn") { 47 | digitalWrite(ledPin, HIGH); 48 | break; 49 | } 50 | if (readString == "off") { 51 | digitalWrite(ledPin, LOW); 52 | break; 53 | } 54 | } 55 | } 56 | readString = ""; 57 | } 58 | } 59 | delay(2000); 60 | } 61 | -------------------------------------------------------------------------------- /RPi_and_Arduino_Serial_Communication/serial_test.py: -------------------------------------------------------------------------------- 1 | from serial import Serial 2 | 3 | ser = Serial('/dev/ttyUSB0',115200) 4 | 5 | while True: 6 | read_serial = ser.readline() 7 | read_serial = read_serial.decode("utf-8") 8 | # print (read_serial) 9 | read_serial = read_serial.split(",") 10 | if len(read_serial) > 1 : 11 | read_serial[-1] = read_serial[-1].replace("\r\n","") 12 | print (read_serial) 13 | if read_serial == ['3686744587', '219', '191', '66', '11'] : 14 | print("True") 15 | ser.write("DerpHashTurnOn".encode()) 16 | else: 17 | print("False") 18 | ser.write("off".encode()) 19 | -------------------------------------------------------------------------------- /amd_bios_modding/PolarisBiosEditor.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/amd_bios_modding/PolarisBiosEditor.zip -------------------------------------------------------------------------------- /channel_shilling: -------------------------------------------------------------------------------- 1 | Here is a link to my YouTube channel : https://www.youtube.com/c/VirusHQ 2 | -------------------------------------------------------------------------------- /real_time_clock_ft_ds3231_with_d1_mini/ds3231.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | const char* ssid = "Sagar's"; 4 | const char* password = "juice098"; 5 | WiFiUDP ntpUDP; 6 | 7 | #include 8 | #include 9 | DS3231 Clock; 10 | #include 11 | // wifi_udp , time_server_pool , offset_in_sec , update_interval_in_sec 12 | NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 19800, 60000); 13 | // Read time 14 | bool Century=false; 15 | bool h12; 16 | bool PM; 17 | byte ADay, AHour, AMinute, ASecond, ABits; 18 | bool ADy, A12h, Apm; 19 | #define LEAP_YEAR(Y) ( (Y>0) && !(Y%4) && ( (Y%100) || !(Y%400) )) // from time-lib 20 | // Set time 21 | String formattedDate, dateStamp, formattedTime, TimeStamp, h1_str, t_str; 22 | int splitT, y_dt, m_dt, d_dt, h_tm, m_tm, s_tm, DoW, c_dt, t_num ; 23 | String Ydt_str, Mdt_str, Ddy_str, Htm_str, Mtm_str, Stm_str, Time_str, Date_str, Temp_str, Day_str, ab; 24 | 25 | 26 | void setup() { 27 | Serial.begin(115200); 28 | Serial.println(""); 29 | Wire.begin(); 30 | set_new_time(); 31 | } 32 | 33 | void loop() { 34 | update_lcd_time(); 35 | //set_new_time(); 36 | } 37 | 38 | void update_lcd_time() { 39 | // send what's going on to the serial monitor. 40 | // Start with the year 41 | Serial.print("2"); 42 | if (Century) { // Won't need this for 89 years. 43 | Serial.print("1"); 44 | } else { 45 | Serial.print("0"); 46 | } 47 | Serial.print(Clock.getYear(), DEC); 48 | Serial.print(' '); 49 | // then the month 50 | Serial.print(Clock.getMonth(Century), DEC); 51 | Serial.print(' '); 52 | // then the date 53 | Serial.print(Clock.getDate(), DEC); 54 | Serial.print(' '); 55 | // and the day of the week 56 | Serial.print(Clock.getDoW(), DEC); 57 | Serial.print(' '); 58 | // Finally the hour, minute, and second 59 | Serial.print(Clock.getHour(h12, PM), DEC); 60 | Serial.print(' '); 61 | Serial.print(Clock.getMinute(), DEC); 62 | Serial.print(' '); 63 | Serial.print(Clock.getSecond(), DEC); 64 | // Add AM/PM indicator 65 | if (h12) { 66 | if (PM) { 67 | Serial.print(" PM "); 68 | } else { 69 | Serial.print(" AM "); 70 | } 71 | } else { 72 | Serial.print(" 24h "); 73 | } 74 | // Display the temperature 75 | Serial.print("T="); 76 | Serial.print(Clock.getTemperature(), 2); 77 | // Tell whether the time is (likely to be) valid 78 | if (Clock.oscillatorCheck()) { 79 | Serial.print(" O+"); 80 | } else { 81 | Serial.print(" O-"); 82 | } 83 | // Indicate whether an alarm went off 84 | if (Clock.checkIfAlarm(1)) { 85 | Serial.print(" A1!"); 86 | } 87 | if (Clock.checkIfAlarm(2)) { 88 | Serial.print(" A2!"); 89 | } 90 | // New line on display 91 | Serial.print('\n'); 92 | // Display Alarm 1 information 93 | Serial.print("Alarm 1: "); 94 | Clock.getA1Time(ADay, AHour, AMinute, ASecond, ABits, ADy, A12h, Apm); 95 | Serial.print(ADay, DEC); 96 | if (ADy) { 97 | Serial.print(" DoW"); 98 | } else { 99 | Serial.print(" Date"); 100 | } 101 | Serial.print(' '); 102 | Serial.print(AHour, DEC); 103 | Serial.print(' '); 104 | Serial.print(AMinute, DEC); 105 | Serial.print(' '); 106 | Serial.print(ASecond, DEC); 107 | Serial.print(' '); 108 | if (A12h) { 109 | if (Apm) { 110 | Serial.print('pm '); 111 | } else { 112 | Serial.print('am '); 113 | } 114 | } 115 | if (Clock.checkAlarmEnabled(1)) { 116 | Serial.print("enabled"); 117 | } 118 | Serial.print('\n'); 119 | // Display Alarm 2 information 120 | Serial.print("Alarm 2: "); 121 | Clock.getA2Time(ADay, AHour, AMinute, ABits, ADy, A12h, Apm); 122 | Serial.print(ADay, DEC); 123 | if (ADy) { 124 | Serial.print(" DoW"); 125 | } else { 126 | Serial.print(" Date"); 127 | } 128 | Serial.print(' '); 129 | Serial.print(AHour, DEC); 130 | Serial.print(' '); 131 | Serial.print(AMinute, DEC); 132 | Serial.print(' '); 133 | if (A12h) { 134 | if (Apm) { 135 | Serial.print('pm'); 136 | } else { 137 | Serial.print('am'); 138 | } 139 | } 140 | if (Clock.checkAlarmEnabled(2)) { 141 | Serial.print("enabled"); 142 | } 143 | // display alarm bits 144 | Serial.print('\nAlarm bits: '); 145 | Serial.print(ABits, BIN); 146 | 147 | Serial.print('\n'); 148 | Serial.print('\n'); 149 | delay(1000); 150 | } 151 | 152 | 153 | void set_new_time() { 154 | Serial.println("Connecting Wi-Fi"); 155 | WiFi.begin(ssid, password); 156 | delay(500); 157 | while ( WiFi.status() != WL_CONNECTED ) { 158 | delay(500); 159 | } 160 | Serial.println("WiFi Connected"); 161 | Serial.println("Getting new Date and Time"); 162 | timeClient.begin(); 163 | timeClient.update(); 164 | 165 | formattedDate = timeClient.getFormattedDate(); 166 | splitT = formattedDate.indexOf("T"); 167 | dateStamp = formattedDate.substring(0, splitT); 168 | formattedDate.remove(splitT); 169 | splitT = formattedDate.indexOf("-"); 170 | dateStamp = formattedDate.substring(0, splitT); 171 | y_dt = dateStamp.toInt(); 172 | splitT = splitT + 1; 173 | formattedDate.remove(0, splitT); 174 | splitT = formattedDate.indexOf("-"); 175 | dateStamp = formattedDate.substring(0, splitT); 176 | m_dt = dateStamp.toInt(); 177 | splitT = splitT + 1; 178 | formattedDate.remove(0, splitT); 179 | splitT = formattedDate.indexOf("-"); 180 | dateStamp = formattedDate.substring(0, splitT); 181 | d_dt = dateStamp.toInt(); 182 | 183 | formattedTime = timeClient.getFormattedTime(); 184 | splitT = formattedTime.indexOf(":"); 185 | TimeStamp = formattedTime.substring(0, splitT); 186 | h_tm = TimeStamp.toInt(); 187 | splitT = splitT + 1; 188 | formattedTime.remove(0, splitT); 189 | splitT = formattedTime.indexOf(":"); 190 | TimeStamp = formattedTime.substring(0, splitT); 191 | m_tm = TimeStamp.toInt(); 192 | splitT = splitT + 1; 193 | formattedTime.remove(0, splitT); 194 | splitT = formattedTime.indexOf(":"); 195 | TimeStamp = formattedTime.substring(0, splitT); 196 | s_tm = TimeStamp.toInt(); 197 | DoW = dayOfWeek(y_dt, m_dt, d_dt); 198 | 199 | y_dt = y_dt - 48; 200 | Clock.setClockMode(true); 201 | Clock.setSecond(s_tm); 202 | Clock.setMinute(m_tm); 203 | Clock.setHour(h_tm); 204 | Clock.setDate(d_dt); 205 | Clock.setMonth(m_dt); 206 | Clock.setYear(y_dt); 207 | Clock.setDoW(DoW); 208 | WiFi.mode(WIFI_OFF); 209 | 210 | Serial.print("Hour : "); 211 | Serial.println(h_tm); 212 | Serial.print("Minute : "); 213 | Serial.println(m_tm); 214 | Serial.print("Second : "); 215 | Serial.println(s_tm); 216 | Serial.print("Year : "); 217 | Serial.println(y_dt); 218 | Serial.print("Hour : "); 219 | Serial.println(m_dt); 220 | Serial.print("Hour : "); 221 | Serial.println(d_dt); 222 | Serial.print("Day of week : "); 223 | Serial.println(DoW); 224 | } 225 | 226 | int dayOfWeek(uint16_t year, uint8_t month, uint8_t day) { 227 | uint16_t months[] = { 228 | 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 229 | }; 230 | uint32_t days = year * 365; 231 | for (uint16_t i = 4; i < year; i += 4) if (LEAP_YEAR(i) ) days++; 232 | days += months[month - 1] + day; 233 | if ((month > 2) && LEAP_YEAR(year)) days++; 234 | return days % 7; 235 | } 236 | -------------------------------------------------------------------------------- /real_time_clock_ft_ds3231_with_d1_mini/rtc_d1_mini.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/real_time_clock_ft_ds3231_with_d1_mini/rtc_d1_mini.jpg -------------------------------------------------------------------------------- /rotary_encoder_with_d1_mini/rot_encoder.ino: -------------------------------------------------------------------------------- 1 | /*******Interrupt-based Rotary Encoder Sketch******* 2 | by Simon Merrett, based on insight from Oleg Mazurov, Nick Gammon, rt, Steve Spence 3 | */ 4 | 5 | static int pinA = 2; // Our first hardware interrupt pin is digital pin 2 6 | static int pinB = 3; // Our second hardware interrupt pin is digital pin 3 7 | volatile byte aFlag = 0; // let's us know when we're expecting a rising edge on pinA to signal that the encoder has arrived at a detent 8 | volatile byte bFlag = 0; // let's us know when we're expecting a rising edge on pinB to signal that the encoder has arrived at a detent (opposite direction to when aFlag is set) 9 | int encoderPos = 0; //this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255 10 | int oldEncPos = 0; //stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor) 11 | int reading = 0; //somewhere to store the direct values we read from our interrupt pins before checking to see if we have moved a whole detent 12 | 13 | void setup() { 14 | pinMode(pinA, INPUT_PULLUP); // set pinA as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases) 15 | pinMode(pinB, INPUT_PULLUP); // set pinB as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases) 16 | attachInterrupt(0,PinA,RISING); // set an interrupt on PinA, looking for a rising edge signal and executing the "PinA" Interrupt Service Routine (below) 17 | attachInterrupt(1,PinB,RISING); // set an interrupt on PinB, looking for a rising edge signal and executing the "PinB" Interrupt Service Routine (below) 18 | Serial.begin(115200); // start the serial monitor link 19 | } 20 | 21 | void PinA(){ 22 | cli(); //stop interrupts happening before we read pin values 23 | reading = PIND & 0xC; // read all eight pin values then strip away all but pinA and pinB's values 24 | if(reading == B00001100 && aFlag) { //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge 25 | encoderPos = encoderPos - 2; //decrement the encoder's position count 26 | bFlag = 0; //reset flags for the next turn 27 | aFlag = 0; //reset flags for the next turn 28 | } 29 | else if (reading == B00000100) bFlag = 1; //signal that we're expecting pinB to signal the transition to detent from free rotation 30 | sei(); //restart interrupts 31 | } 32 | 33 | void PinB(){ 34 | cli(); //stop interrupts happening before we read pin values 35 | reading = PIND & 0xC; //read all eight pin values then strip away all but pinA and pinB's values 36 | if (reading == B00001100 && bFlag) { //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge 37 | encoderPos = encoderPos + 2; //increment the encoder's position count 38 | bFlag = 0; //reset flags for the next turn 39 | aFlag = 0; //reset flags for the next turn 40 | } 41 | else if (reading == B00001000) aFlag = 1; //signal that we're expecting pinA to signal the transition to detent from free rotation 42 | sei(); //restart interrupts 43 | } 44 | 45 | void loop(){ 46 | if(oldEncPos != encoderPos) { 47 | Serial.println(encoderPos); 48 | oldEncPos = encoderPos; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /rotary_encoder_with_d1_mini/wiring_diagram.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VirusHQ/youtube_video_tutorial_codes/f2707310380338051635bee88614641c2890855e/rotary_encoder_with_d1_mini/wiring_diagram.PNG --------------------------------------------------------------------------------