├── .gitignore ├── C ├── 01_dule_color_led │ ├── README │ └── dule_color_led.c ├── 02_rgb_led │ └── rgb_led.c ├── 04_relay │ ├── README │ └── relay.c ├── 05_laser │ └── laser.c ├── 06_button │ └── button.c ├── 07_tilt_switch │ └── tilt_switch.c ├── 08_mercury_switch │ └── mercury_switch.c ├── 08_vibration_switch │ └── vibration_switch.c ├── 09_ir_receiver │ └── ir_receiver.c ├── 10_active_buzzer │ └── active_buzzer.c ├── 10_passive_buzzer │ └── passive_buzzer.c ├── 11_reed_switch │ └── reed_switch.c ├── 12_photo_interrupter │ └── photo_interrupter.c ├── 13_pcf8591 │ └── pcf8591.c ├── 14_rain_detector │ └── rain_detector.c ├── 15_joystick_PS2 │ └── joystick_PS2.c ├── 16_potentiometer │ └── potentiometer.c ├── 17_analog_hall_switch │ └── analog_hall_switch.c ├── 17_switch_hall │ └── switch_hall.c ├── 18_thermistor │ └── thermistor.c ├── 19_sound_sensor │ └── sound_sensor.c ├── 20_photoresistor │ └── photoresistor.c ├── 21_flame_sensor │ └── flame_sensor.c ├── 22_gas_sensor │ └── gas_sensor.c ├── 23_ircontrol │ ├── ircontrol.c │ └── lircrc ├── 24_touch_switch │ └── touch_switch.c ├── 25_ultrasonic_ranging │ └── ultrasonic_ranging.c ├── 26_ds18b20 │ └── ds18b20.c ├── 27_rotary_encoder │ └── rotary_encoder.c ├── 28_humiture │ └── humiture.c ├── 29_ir_obstacle │ └── ir_obstacle.c ├── 30_i2c_lcd1602 │ └── i2c_lcd1602.c ├── 31_barometer │ ├── Makefile │ ├── barometer.c │ ├── bmp180.c │ ├── bmp180.h │ └── bmp280.c ├── 32_mpu6050 │ └── 32_mpu6050.c ├── 33_ds1302 │ └── rtc_ds1302.c ├── 34_tracking │ └── tracking.c ├── 35_expand02 │ └── temp_monitor.c ├── README.md └── cleanout.sh ├── Fritzing ├── 01_dual_color_led.fzz ├── 02_RGB_LED.fzz ├── 03_AutoFlashLED.fzz ├── 04_Relay module.fzz ├── 05_Laser.fzz ├── 06_Button.fzz ├── 07_Tilt-Switch.fzz ├── 08_Vibration Switch.fzz ├── 09_IR Receiver.svg.fzz ├── 10_Active Buzzer.fzz ├── 10_Passive Buzzer.fzz ├── 11_Reed switch.fzz ├── 12_Photo interrupter.fzz ├── 13_PCF8591.fzz ├── 14_Rain Detection.fzz ├── 15_JoyStick_PS2.fzz ├── 16_Potentiometer.fzz ├── 17_Analog_Hall_Switch.svg.fzz ├── 17_Switch_Hall.svg.fzz ├── 18_Analog_Temperature.fzz ├── 18_Thermistor.fzz ├── 19_Sound Sensor.fzz ├── 20_Photoresistor.fzz ├── 21_Flame_Sensor.fzz ├── 22_Gas Sensor.fzz ├── 23_IR remote control.fzz ├── 24_Touch_Switch.fzz ├── 25_Ultrasonic_Ranging.fzz ├── 26_DS18B20.fzz ├── 27_Rotary Encode.fzz ├── 28_Humiture.fzz ├── 29_IR Obstacle.fzz ├── 30_I2C LCD1602.fzz ├── 31_Barometer.fzz ├── 32_MPU6050.fzz ├── 33_DS1302.fzz ├── 34_Tracking.fzz └── 35_Expand02.fzz ├── LICENSE ├── Python ├── 01_dule_color_led.py ├── 02_rgb_led.py ├── 04_relay.py ├── 05_laser.py ├── 06_button.py ├── 07_tilt_switch.py ├── 08_mecury_switch.py ├── 08_vibration_switch.py ├── 09_ir_receiver.py ├── 10_active_buzzer.py ├── 10_passive_buzzer.py ├── 11_reed_switch.py ├── 12_photo_interrupter.py ├── 13_pcf8591.py ├── 14_rain_detector.py ├── 15_joystick_PS2.py ├── 16_potentiometer.py ├── 17_analog_hall_switch.py ├── 17_switch_hall.py ├── 18_thermistor.py ├── 19_sound_sensor.py ├── 20_photoresistor.py ├── 21_flame_sensor.py ├── 22_gas_sensor.py ├── 23_ircontrol.py ├── 24_touch_switch.py ├── 25_ultrasonic_ranging.py ├── 26_ds18b20.py ├── 27_rotary_encoder.py ├── 28_humiture.py ├── 29_ir_obstacle.py ├── 30_i2c_lcd1602.py ├── 31_barometer.py ├── 31_bmp280.py ├── 32_mpu6050.py ├── 33_ds1302.py ├── 34_tracking.py ├── 35_temp_monitor.py ├── Adafruit_Python_BMP │ ├── .gitignore │ ├── Adafruit_BMP │ │ ├── BMP085.py │ │ └── __init__.py │ ├── LICENSE │ ├── README.md │ ├── examples │ │ ├── google_spreadsheet.py │ │ └── simpletest.py │ ├── ez_setup.py │ ├── munin │ │ ├── i2c_pressure │ │ └── i2c_temperature │ └── setup.py ├── LCD1602.py ├── PCF8591.py ├── README.md ├── ds1302.py ├── lircrc └── rpi_time_bak2.py ├── README.md ├── lircd.conf └── show /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | a.out 3 | -------------------------------------------------------------------------------- /C/01_dule_color_led/README: -------------------------------------------------------------------------------- 1 | Run to compile the code. 2 | gcc dule_color_led.c –lwiringPi -lpthread 3 | -------------------------------------------------------------------------------- /C/01_dule_color_led/dule_color_led.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define uchar unsigned char 6 | 7 | #define LedPinRed 0 8 | #define LedPinGreen 1 9 | 10 | void ledInit(void) 11 | { 12 | softPwmCreate(LedPinRed, 0, 100); 13 | softPwmCreate(LedPinGreen,0, 100); 14 | } 15 | 16 | void ledColorSet(uchar r_val, uchar g_val) 17 | { 18 | softPwmWrite(LedPinRed, r_val); 19 | softPwmWrite(LedPinGreen, g_val); 20 | } 21 | 22 | int main(void) 23 | { 24 | int i; 25 | 26 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 27 | printf("setup wiringPi failed !"); 28 | return 1; 29 | } 30 | //printf("linker LedPin : GPIO %d(wiringPi pin)\n",LedPin); //when initialize wiring successfully,print message to screen 31 | 32 | ledInit(); 33 | 34 | while(1){ 35 | ledColorSet(0xff,0x00); //red 36 | delay(500); 37 | ledColorSet(0x00,0xff); //green 38 | delay(500); 39 | ledColorSet(0xff,0x45); 40 | delay(500); 41 | ledColorSet(0xff,0xff); 42 | delay(500); 43 | ledColorSet(0x7c,0xfc); 44 | delay(500); 45 | } 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /C/02_rgb_led/rgb_led.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define uchar unsigned char 6 | 7 | #define LedPinRed 0 8 | #define LedPinGreen 1 9 | #define LedPinBlue 2 10 | 11 | void ledInit(void) 12 | { 13 | softPwmCreate(LedPinRed, 0, 100); 14 | softPwmCreate(LedPinGreen,0, 100); 15 | softPwmCreate(LedPinBlue, 0, 100); 16 | } 17 | 18 | void ledColorSet(uchar r_val, uchar g_val, uchar b_val) 19 | { 20 | softPwmWrite(LedPinRed, r_val); 21 | softPwmWrite(LedPinGreen, g_val); 22 | softPwmWrite(LedPinBlue, b_val); 23 | } 24 | 25 | int main(void) 26 | { 27 | int i; 28 | 29 | if(wiringPiSetup() == -1){ //when initialize wiring failed, print message to screen 30 | printf("setup wiringPi failed !"); 31 | return 1; 32 | } 33 | //printf("linker LedPin : GPIO %d(wiringPi pin)\n",LedPin); //when initialize wiring successfully,print message to screen 34 | 35 | ledInit(); 36 | 37 | while(1){ 38 | ledColorSet(0xff,0x00,0x00); //red 39 | delay(500); 40 | ledColorSet(0x00,0xff,0x00); //green 41 | delay(500); 42 | ledColorSet(0x00,0x00,0xff); //blue 43 | delay(500); 44 | 45 | ledColorSet(0xff,0xff,0x00); //yellow 46 | delay(500); 47 | ledColorSet(0xff,0x00,0xff); //pick 48 | delay(500); 49 | ledColorSet(0xc0,0xff,0x3e); 50 | delay(500); 51 | 52 | ledColorSet(0x94,0x00,0xd3); 53 | delay(500); 54 | ledColorSet(0x76,0xee,0x00); 55 | delay(500); 56 | ledColorSet(0x00,0xc5,0xcd); 57 | delay(500); 58 | 59 | } 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /C/04_relay/README: -------------------------------------------------------------------------------- 1 | '+' on relay must be connected +5V 2 | -------------------------------------------------------------------------------- /C/04_relay/relay.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define RelayPin 0 5 | 6 | int main(void) 7 | { 8 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 9 | printf("setup wiringPi failed !"); 10 | return 1; 11 | } 12 | // printf("linker LedPin : GPIO %d(wiringPi pin)\n",VoicePin); //when initialize wiring successfully,print message to screen 13 | 14 | pinMode(RelayPin, OUTPUT); 15 | 16 | while(1){ 17 | digitalWrite(RelayPin, LOW); 18 | delay(1000); 19 | digitalWrite(RelayPin, HIGH); 20 | delay(1000); 21 | } 22 | 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /C/05_laser/laser.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define LaserPin 0 5 | 6 | int main(void) 7 | { 8 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 9 | printf("setup wiringPi failed !"); 10 | return 1; 11 | } 12 | //printf("linker LedPin : GPIO %d(wiringPi pin)\n",LedPin); //when initialize wiring successfully,print message to screen 13 | 14 | pinMode(LaserPin, OUTPUT); 15 | 16 | while(1){ 17 | digitalWrite(LaserPin, HIGH); 18 | delay(500); 19 | digitalWrite(LaserPin, LOW); 20 | delay(500); 21 | } 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /C/06_button/button.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define BtnPin 0 5 | #define Gpin 1 6 | #define Rpin 2 7 | 8 | void LED(char* color) 9 | { 10 | pinMode(Gpin, OUTPUT); 11 | pinMode(Rpin, OUTPUT); 12 | if (color == "RED") 13 | { 14 | digitalWrite(Rpin, HIGH); 15 | digitalWrite(Gpin, LOW); 16 | } 17 | else if (color == "GREEN") 18 | { 19 | digitalWrite(Rpin, LOW); 20 | digitalWrite(Gpin, HIGH); 21 | } 22 | else 23 | printf("LED Error"); 24 | } 25 | 26 | int main(void) 27 | { 28 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 29 | printf("setup wiringPi failed !"); 30 | return 1; 31 | } 32 | 33 | pinMode(BtnPin, INPUT); 34 | LED("GREEN"); 35 | 36 | while(1){ 37 | if(0 == digitalRead(BtnPin)){ 38 | delay(10); 39 | if(0 == digitalRead(BtnPin)){ 40 | LED("RED"); 41 | printf("Button is pressed\n"); 42 | } 43 | } 44 | else if(1 == digitalRead(BtnPin)){ 45 | delay(10); 46 | if(1 == digitalRead(BtnPin)){ 47 | while(!digitalRead(BtnPin)); 48 | LED("GREEN"); 49 | } 50 | } 51 | } 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /C/07_tilt_switch/tilt_switch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define TiltPin 0 5 | #define Gpin 2 6 | #define Rpin 1 7 | 8 | void LED(char* color) 9 | { 10 | pinMode(Gpin, OUTPUT); 11 | pinMode(Rpin, OUTPUT); 12 | if (color == "RED") 13 | { 14 | digitalWrite(Rpin, HIGH); 15 | digitalWrite(Gpin, LOW); 16 | } 17 | else if (color == "GREEN") 18 | { 19 | digitalWrite(Rpin, LOW); 20 | digitalWrite(Gpin, HIGH); 21 | } 22 | else 23 | printf("LED Error"); 24 | } 25 | 26 | int main(void) 27 | { 28 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 29 | printf("setup wiringPi failed !"); 30 | return 1; 31 | } 32 | 33 | pinMode(TiltPin, INPUT); 34 | LED("GREEN"); 35 | 36 | while(1){ 37 | if(0 == digitalRead(TiltPin)){ 38 | delay(10); 39 | if(0 == digitalRead(TiltPin)){ 40 | LED("RED"); 41 | printf("Tilt!\n"); 42 | } 43 | } 44 | else if(1 == digitalRead(TiltPin)){ 45 | delay(10); 46 | if(1 == digitalRead(TiltPin)){ 47 | while(!digitalRead(TiltPin)); 48 | LED("GREEN"); 49 | } 50 | } 51 | } 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /C/08_mercury_switch/mercury_switch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MPin 0 5 | #define Gpin 1 6 | #define Rpin 2 7 | 8 | void LED(char* color) 9 | { 10 | pinMode(Gpin, OUTPUT); 11 | pinMode(Rpin, OUTPUT); 12 | if (color == "RED") 13 | { 14 | digitalWrite(Rpin, HIGH); 15 | digitalWrite(Gpin, LOW); 16 | } 17 | else if (color == "GREEN") 18 | { 19 | digitalWrite(Rpin, LOW); 20 | digitalWrite(Gpin, HIGH); 21 | } 22 | else 23 | printf("LED Error"); 24 | } 25 | 26 | int main(void) 27 | { 28 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 29 | printf("setup wiringPi failed !"); 30 | return 1; 31 | } 32 | 33 | pinMode(MPin, INPUT); 34 | LED("GREEN"); 35 | 36 | while(1){ 37 | if(0 == digitalRead(MPin)){ 38 | delay(10); 39 | if(0 == digitalRead(MPin)){ 40 | LED("RED"); 41 | printf("Mecury Tilt!\n"); 42 | } 43 | } 44 | else if(1 == digitalRead(MPin)){ 45 | delay(10); 46 | if(1 == digitalRead(MPin)){ 47 | while(!digitalRead(MPin)); 48 | LED("GREEN"); 49 | } 50 | } 51 | } 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /C/08_vibration_switch/vibration_switch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define VibratePin 0 5 | #define Gpin 2 6 | #define Rpin 1 7 | 8 | void LED(int color) 9 | { 10 | pinMode(Gpin, OUTPUT); 11 | pinMode(Rpin, OUTPUT); 12 | if (color == 0) 13 | { 14 | digitalWrite(Rpin, HIGH); 15 | digitalWrite(Gpin, LOW); 16 | } 17 | else if (color == 1) 18 | { 19 | digitalWrite(Rpin, LOW); 20 | digitalWrite(Gpin, HIGH); 21 | } 22 | else 23 | printf("LED Error"); 24 | } 25 | 26 | int main(void) 27 | { 28 | int status = 0; 29 | int tmp = 1; 30 | int value = 1; 31 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 32 | printf("setup wiringPi failed !"); 33 | return 1; 34 | } 35 | 36 | pinMode(VibratePin, INPUT); 37 | 38 | while(1){ 39 | value = digitalRead(VibratePin); 40 | if (tmp != value){ 41 | status ++; 42 | if (status > 1){ 43 | status = 0; 44 | } 45 | LED(status); 46 | delay(1000); 47 | } 48 | } 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /C/09_ir_receiver/ir_receiver.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define IR 0 5 | 6 | int cnt = 0; 7 | 8 | void myISR(void) 9 | { 10 | printf("Received infrared. cnt = %d\n", ++cnt); 11 | } 12 | 13 | int main(void) 14 | { 15 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 16 | printf("setup wiringPi failed !"); 17 | return 1; 18 | } 19 | 20 | if(wiringPiISR(IR, INT_EDGE_FALLING, &myISR) == -1){ 21 | printf("setup ISR failed !"); 22 | return 1; 23 | } 24 | 25 | //pinMode(IR, INPUT); 26 | 27 | while(1); 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /C/10_active_buzzer/active_buzzer.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define BuzzerPin 0 5 | 6 | int main(void) 7 | { 8 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 9 | printf("setup wiringPi failed !"); 10 | return 1; 11 | } 12 | // printf("linker LedPin : GPIO %d(wiringPi pin)\n",VoicePin); //when initialize wiring successfully,print message to screen 13 | 14 | pinMode(BuzzerPin, OUTPUT); 15 | 16 | while(1){ 17 | digitalWrite(BuzzerPin, HIGH); 18 | delay(100); 19 | digitalWrite(BuzzerPin, LOW); 20 | delay(100); 21 | } 22 | 23 | return 0; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /C/10_passive_buzzer/passive_buzzer.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define BuzPin 0 6 | 7 | #define CL1 131 8 | #define CL2 147 9 | #define CL3 165 10 | #define CL4 175 11 | #define CL5 196 12 | #define CL6 221 13 | #define CL7 248 14 | 15 | #define CM1 262 16 | #define CM2 294 17 | #define CM3 330 18 | #define CM4 350 19 | #define CM5 393 20 | #define CM6 441 21 | #define CM7 495 22 | 23 | #define CH1 525 24 | #define CH2 589 25 | #define CH3 661 26 | #define CH4 700 27 | #define CH5 786 28 | #define CH6 882 29 | #define CH7 990 30 | 31 | int song_1[] = {CM3,CM5,CM6,CM3,CM2,CM3,CM5,CM6,CH1,CM6,CM5,CM1,CM3,CM2, 32 | CM2,CM3,CM5,CM2,CM3,CM3,CL6,CL6,CL6,CM1,CM2,CM3,CM2,CL7, 33 | CL6,CM1,CL5}; 34 | 35 | int beat_1[] = {1,1,3,1,1,3,1,1,1,1,1,1,1,1,3,1,1,3,1,1,1,1,1,1,1,2,1,1, 36 | 1,1,1,1,1,1,3}; 37 | 38 | int song_2[] = {CM1,CM1,CM1,CL5,CM3,CM3,CM3,CM1,CM1,CM3,CM5,CM5,CM4,CM3,CM2, 39 | CM2,CM3,CM4,CM4,CM3,CM2,CM3,CM1,CM1,CM3,CM2,CL5,CL7,CM2,CM1 40 | }; 41 | 42 | int beat_2[] = {1,1,1,3,1,1,1,3,1,1,1,1,1,1,3,1,1,1,2,1,1,1,3,1,1,1,3,3,2,3}; 43 | 44 | int main(void) 45 | { 46 | int i, j; 47 | 48 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 49 | printf("setup wiringPi failed !"); 50 | return 1; 51 | } 52 | 53 | if(softToneCreate(BuzPin) == -1){ 54 | printf("setup softTone failed !"); 55 | return 1; 56 | } 57 | 58 | while(1){ 59 | printf("music is being played...\n"); 60 | 61 | for(i=0;i 2 | #include 3 | 4 | #define ReedPin 0 5 | #define Gpin 2 6 | #define Rpin 1 7 | 8 | void LED(char* color) 9 | { 10 | pinMode(Gpin, OUTPUT); 11 | pinMode(Rpin, OUTPUT); 12 | if (color == "RED") 13 | { 14 | digitalWrite(Rpin, HIGH); 15 | digitalWrite(Gpin, LOW); 16 | } 17 | else if (color == "GREEN") 18 | { 19 | digitalWrite(Rpin, LOW); 20 | digitalWrite(Gpin, HIGH); 21 | } 22 | else 23 | printf("LED Error"); 24 | } 25 | 26 | int main(void) 27 | { 28 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 29 | printf("setup wiringPi failed !"); 30 | return 1; 31 | } 32 | 33 | pinMode(ReedPin, INPUT); 34 | LED("GREEN"); 35 | 36 | while(1){ 37 | if(0 == digitalRead(ReedPin)){ 38 | delay(10); 39 | if(0 == digitalRead(ReedPin)){ 40 | LED("RED"); 41 | printf("Detected Magnetic Material!\n"); 42 | } 43 | } 44 | else if(1 == digitalRead(ReedPin)){ 45 | delay(10); 46 | if(1 == digitalRead(ReedPin)){ 47 | while(!digitalRead(ReedPin)); 48 | LED("GREEN"); 49 | } 50 | } 51 | } 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /C/12_photo_interrupter/photo_interrupter.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define LBPin 0 // light break pin set to GPIO0 5 | #define Gpin 2 6 | #define Rpin 1 7 | 8 | void LED(int color) 9 | { 10 | pinMode(Gpin, OUTPUT); 11 | pinMode(Rpin, OUTPUT); 12 | if (color == 0){ 13 | digitalWrite(Rpin, HIGH); 14 | digitalWrite(Gpin, LOW); 15 | } 16 | else if (color == 1){ 17 | digitalWrite(Rpin, LOW); 18 | digitalWrite(Gpin, HIGH); 19 | } 20 | } 21 | 22 | void Print(int x){ 23 | if ( x == 0 ){ 24 | printf("Light was blocked\n"); 25 | } 26 | } 27 | 28 | int main(void){ 29 | 30 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 31 | printf("setup wiringPi failed !"); 32 | return 1; 33 | } 34 | 35 | pinMode(LBPin, INPUT); 36 | int temp; 37 | while(1){ 38 | //Reverse the input of LBPin 39 | if ( digitalRead(LBPin) == 0 ){ 40 | temp = 1; 41 | } 42 | if ( digitalRead(LBPin) == 1 ){ 43 | temp = 0; 44 | } 45 | 46 | LED(temp); 47 | Print(temp); 48 | delay(100); 49 | } 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /C/13_pcf8591/pcf8591.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define PCF 120 6 | 7 | int main (void) 8 | { 9 | int value ; 10 | wiringPiSetup () ; 11 | // Setup pcf8591 on base pin 120, and address 0x48 12 | pcf8591Setup (PCF, 0x48) ; 13 | while(1) // loop forever 14 | { 15 | value = analogRead (PCF + 0) ; 16 | printf("%d\n", value); 17 | analogWrite (PCF + 0, value) ; 18 | delay (10) ; 19 | } 20 | return 0 ; 21 | } 22 | -------------------------------------------------------------------------------- /C/14_rain_detector/rain_detector.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define PCF 120 7 | #define DOpin 0 8 | 9 | void Print(int x) 10 | { 11 | switch(x) 12 | { 13 | case 1: 14 | printf("\n***************\n" ); 15 | printf( "* Not Raining *\n" ); 16 | printf( "***************\n\n"); 17 | break; 18 | case 0: 19 | printf("\n*************\n" ); 20 | printf( "* Raining!! *\n" ); 21 | printf( "*************\n\n"); 22 | break; 23 | default: 24 | printf("\n**********************\n" ); 25 | printf( "* Print value error. *\n" ); 26 | printf( "**********************\n\n"); 27 | break; 28 | } 29 | } 30 | 31 | int main() 32 | { 33 | int analogVal; 34 | int tmp, status; 35 | 36 | if(wiringPiSetup() == -1){ 37 | printf("setup wiringPi failed !"); 38 | return 1; 39 | } 40 | // Setup pcf8591 on base pin 120, and address 0x48 41 | pcf8591Setup(PCF, 0x48); 42 | 43 | pinMode(DOpin, INPUT); 44 | 45 | status = 0; 46 | while(1) // loop forever 47 | { 48 | analogVal = analogRead(PCF + 0); 49 | printf("%d\n", analogVal); 50 | 51 | tmp = digitalRead(DOpin); 52 | 53 | if (tmp != status) 54 | { 55 | Print(tmp); 56 | status = tmp; 57 | } 58 | 59 | delay (200); 60 | } 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /C/15_joystick_PS2/joystick_PS2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define PCF 120 6 | #define uchar unsigned char 7 | 8 | int AIN0 = PCF + 0; 9 | int AIN1 = PCF + 1; 10 | int AIN2 = PCF + 2; 11 | 12 | char *state[7] = {"home", "up", "down", "left", "right", "pressed"}; 13 | 14 | int direction(){ 15 | int x, y, b; 16 | int tmp=0; 17 | x = analogRead(AIN1); 18 | y = analogRead(AIN0); 19 | b = analogRead(AIN2); 20 | if (y <= 30) 21 | tmp = 1; // up 22 | if (y >= 225) 23 | tmp = 2; // down 24 | 25 | if (x >= 225) 26 | tmp = 3; // left 27 | if (x <= 30) 28 | tmp = 4; // right 29 | 30 | if (b <= 30) 31 | tmp = 5; // button preesd 32 | if (x-125<15 && x-125>-15 && y-125<15 && y-125>-15 && b >= 60) 33 | tmp = 0; // home position 34 | 35 | return tmp; 36 | } 37 | 38 | int main (void) 39 | { 40 | int tmp=0; 41 | int status = 0; 42 | wiringPiSetup (); 43 | // Setup pcf8591 on base pin 120, and address 0x48 44 | pcf8591Setup (PCF, 0x48); 45 | while(1) // loop forever 46 | { 47 | tmp = direction(); 48 | if (tmp != status) 49 | { 50 | printf("%s\n", state[tmp]); 51 | status = tmp; 52 | } 53 | } 54 | return 0 ; 55 | } 56 | -------------------------------------------------------------------------------- /C/16_potentiometer/potentiometer.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define PCF 120 6 | 7 | int main (void) 8 | { 9 | int value ; 10 | wiringPiSetup () ; 11 | // Setup pcf8591 on base pin 120, and address 0x48 12 | pcf8591Setup (PCF, 0x48) ; 13 | while(1) // loop forever 14 | { 15 | value = analogRead (PCF + 0) ; 16 | printf("Value: %d\n", value); 17 | analogWrite (PCF + 0, value) ; 18 | delay (200) ; 19 | } 20 | return 0 ; 21 | } 22 | -------------------------------------------------------------------------------- /C/17_analog_hall_switch/analog_hall_switch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define PCF 120 6 | 7 | int main (void) 8 | { 9 | int res, tmp, status; 10 | wiringPiSetup (); 11 | // Setup pcf8591 on base pin 120, and address 0x48 12 | pcf8591Setup (PCF, 0x48); 13 | status = 0; 14 | while(1) // loop forever 15 | { 16 | res = analogRead(PCF + 0); 17 | printf("Current intensity of magnetic field : %d\n", res); 18 | if (res - 133 < 5 || res - 133 > -5) 19 | tmp = 0; 20 | if (res < 128) tmp = -1; 21 | if (res > 138) tmp = 1; 22 | if (tmp != status) 23 | { 24 | switch(tmp) 25 | { 26 | case 0: 27 | printf("\n*****************\n" ); 28 | printf( "* Magnet: None. *\n" ); 29 | printf( "*****************\n\n"); 30 | break; 31 | case -1: 32 | printf("\n******************\n" ); 33 | printf( "* Magnet: North. *\n" ); 34 | printf( "******************\n\n"); 35 | break; 36 | case 1: 37 | printf("\n******************\n" ); 38 | printf( "* Magnet: South. *\n" ); 39 | printf( "******************\n\n"); 40 | break; 41 | } 42 | status = tmp; 43 | } 44 | delay (200); 45 | } 46 | return 0 ; 47 | } 48 | -------------------------------------------------------------------------------- /C/17_switch_hall/switch_hall.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define HallPin 0 5 | #define Gpin 2 6 | #define Rpin 1 7 | 8 | void LED(char* color) 9 | { 10 | pinMode(Gpin, OUTPUT); 11 | pinMode(Rpin, OUTPUT); 12 | if (color == "RED") 13 | { 14 | digitalWrite(Rpin, HIGH); 15 | digitalWrite(Gpin, LOW); 16 | } 17 | else if (color == "GREEN") 18 | { 19 | digitalWrite(Rpin, LOW); 20 | digitalWrite(Gpin, HIGH); 21 | } 22 | else 23 | printf("LED Error"); 24 | } 25 | 26 | int main(void) 27 | { 28 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 29 | printf("setup wiringPi failed !"); 30 | return 1; 31 | } 32 | 33 | pinMode(HallPin, INPUT); 34 | LED("GREEN"); 35 | 36 | while(1){ 37 | if(0 == digitalRead(HallPin)){ 38 | delay(10); 39 | if(0 == digitalRead(HallPin)){ 40 | LED("RED"); 41 | printf("Detected magnetic materials \n"); 42 | } 43 | } 44 | else if(1 == digitalRead(HallPin)){ 45 | delay(10); 46 | if(1 == digitalRead(HallPin)){ 47 | while(!digitalRead(HallPin)); 48 | LED("GREEN"); 49 | } 50 | } 51 | } 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /C/18_thermistor/thermistor.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define PCF 120 7 | #define DOpin 0 8 | 9 | void Print(int x) 10 | { 11 | switch(x) 12 | { 13 | case 0: 14 | printf("\n************\n" ); 15 | printf( "* Too Hot! *\n" ); 16 | printf( "************\n\n"); 17 | break; 18 | case 1: 19 | printf("\n***********\n" ); 20 | printf( "* Better~ *\n" ); 21 | printf( "***********\n\n"); 22 | break; 23 | default: 24 | printf("\n**********************\n" ); 25 | printf( "* Print value error. *\n" ); 26 | printf( "**********************\n\n"); 27 | break; 28 | } 29 | } 30 | 31 | int main() 32 | { 33 | unsigned char analogVal; 34 | double Vr, Rt, temp; 35 | int tmp, status; 36 | 37 | if(wiringPiSetup() == -1){ 38 | printf("setup wiringPi failed !"); 39 | return 1; 40 | } 41 | // Setup pcf8591 on base pin 120, and address 0x48 42 | pcf8591Setup(PCF, 0x48); 43 | 44 | pinMode(DOpin, INPUT); 45 | 46 | status = 0; 47 | while(1) // loop forever 48 | { 49 | printf("loop"); 50 | analogVal = analogRead(PCF + 0); 51 | Vr = 5 * (double)(analogVal) / 255; 52 | Rt = 10000 * (double)(Vr) / (5 - (double)(Vr)); 53 | temp = 1 / (((log(Rt/10000)) / 3950)+(1 / (273.15 + 25))); 54 | temp = temp - 273.15; 55 | printf("Current temperature : %lf\n", temp); 56 | 57 | // For a threshold, uncomment one of the code for 58 | // which module you use. DONOT UNCOMMENT BOTH! 59 | //--------------------------------------------- 60 | // 1. For Analog Temperature module(with DO) 61 | tmp = digitalRead(DOpin); 62 | 63 | // 2. For Thermister module(with sig pin) 64 | // if (temp > 33) tmp = 0; 65 | // else if (temp < 31) tmp = 1; 66 | //--------------------------------------------- 67 | 68 | if (tmp != status) 69 | { 70 | Print(tmp); 71 | status = tmp; 72 | } 73 | 74 | delay (200); 75 | } 76 | return 0; 77 | } 78 | -------------------------------------------------------------------------------- /C/19_sound_sensor/sound_sensor.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define PCF 120 6 | 7 | int main (void) 8 | { 9 | int value; 10 | int count = 0; 11 | wiringPiSetup (); 12 | // Setup pcf8591 on base pin 120, and address 0x48 13 | pcf8591Setup (PCF, 0x48); 14 | while(1) // loop forever 15 | { 16 | value = analogRead (PCF + 0); 17 | printf("value: %d\n", value); 18 | if (value < 80){ 19 | printf("Voice In!! \n"); 20 | } 21 | delay(100); 22 | } 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /C/20_photoresistor/photoresistor.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define PCF 120 7 | #define DOpin 0 8 | 9 | int main() 10 | { 11 | int analogVal; 12 | 13 | if(wiringPiSetup() == -1){ 14 | printf("setup wiringPi failed !"); 15 | return 1; 16 | } 17 | // Setup pcf8591 on base pin 120, and address 0x48 18 | pcf8591Setup(PCF, 0x48); 19 | 20 | while(1) // loop forever 21 | { 22 | analogVal = analogRead(PCF + 0); 23 | printf("Value: %d\n", analogVal); 24 | 25 | delay (200); 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /C/21_flame_sensor/flame_sensor.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define PCF 120 7 | #define DOpin 0 8 | 9 | void Print(int x) 10 | { 11 | switch(x) 12 | { 13 | case 1: 14 | printf("\n*********\n" ); 15 | printf( "* Saft~ *\n" ); 16 | printf( "*********\n\n"); 17 | break; 18 | case 0: 19 | printf("\n*********\n" ); 20 | printf( "* Fire! *\n" ); 21 | printf( "*********\n\n"); 22 | break; 23 | default: 24 | printf("\n**********************\n" ); 25 | printf( "* Print value error. *\n" ); 26 | printf( "**********************\n\n"); 27 | break; 28 | } 29 | } 30 | 31 | int main() 32 | { 33 | int analogVal; 34 | int tmp, status; 35 | 36 | if(wiringPiSetup() == -1){ 37 | printf("setup wiringPi failed !"); 38 | return 1; 39 | } 40 | // Setup pcf8591 on base pin 120, and address 0x48 41 | pcf8591Setup(PCF, 0x48); 42 | 43 | pinMode(DOpin, INPUT); 44 | 45 | status = 0; 46 | while(1) // loop forever 47 | { 48 | analogVal = analogRead(PCF + 0); 49 | printf("%d\n", analogVal); 50 | 51 | tmp = digitalRead(DOpin); 52 | 53 | if (tmp != status) 54 | { 55 | Print(tmp); 56 | status = tmp; 57 | } 58 | 59 | delay (200); 60 | } 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /C/22_gas_sensor/gas_sensor.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define PCF 120 7 | #define DOpin 0 8 | #define Buzz 1 9 | 10 | void Print(int x) 11 | { 12 | switch(x) 13 | { 14 | case 1: 15 | printf("\n*********\n" ); 16 | printf( "* Saft~ *\n" ); 17 | printf( "*********\n\n"); 18 | break; 19 | case 0: 20 | printf("\n***************\n" ); 21 | printf( "* Danger Gas! *\n" ); 22 | printf( "***************\n\n"); 23 | break; 24 | default: 25 | printf("\n**********************\n" ); 26 | printf( "* Print value error. *\n" ); 27 | printf( "**********************\n\n"); 28 | break; 29 | } 30 | } 31 | 32 | int main() 33 | { 34 | int analogVal; 35 | int tmp, status, count; 36 | 37 | if(wiringPiSetup() == -1){ 38 | printf("setup wiringPi failed !"); 39 | return 1; 40 | } 41 | // Setup pcf8591 on base pin 120, and address 0x48 42 | pcf8591Setup(PCF, 0x48); 43 | 44 | pinMode (DOpin, INPUT); 45 | pinMode (Buzz, OUTPUT); 46 | digitalWrite(Buzz, HIGH); 47 | 48 | status = 0; 49 | count = 0; 50 | while(1) // loop forever 51 | { 52 | analogVal = analogRead(PCF + 0); 53 | printf("%d\n", analogVal); 54 | 55 | tmp = digitalRead(DOpin); 56 | 57 | if (tmp != status) 58 | { 59 | Print(tmp); 60 | status = tmp; 61 | } 62 | 63 | if (status == 0) 64 | { 65 | count ++; 66 | if (count % 2 == 0) 67 | {digitalWrite(Buzz, HIGH);} 68 | else 69 | {digitalWrite(Buzz, LOW);} 70 | } 71 | else 72 | { 73 | count = 0; 74 | digitalWrite(Buzz, HIGH); 75 | } 76 | delay (200); 77 | } 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /C/23_ircontrol/ircontrol.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #define uchar unsigned char 11 | 12 | #define LedPinRed 0 13 | #define LedPinGreen 1 14 | #define LedPinBlue 2 15 | 16 | uchar color[3] = {0xff, 0xff, 0xff}; 17 | uchar Lv[3] = {0xff, 0x44, 0x00}; 18 | 19 | char *keymap[21] ={ 20 | " KEY_CHANNELDOWN ", 21 | " KEY_CHANNEL ", 22 | " KEY_CHANNELUP ", 23 | " KEY_PREVIOUS ", 24 | " KEY_NEXT ", 25 | " KEY_PLAYPAUSE ", 26 | " KEY_VOLUMEDOWN ", 27 | " KEY_VOLUMEUP ", 28 | " KEY_EQUAL ", 29 | " KEY_NUMERIC_0 ", 30 | " BTN_0 ", 31 | " BTN_1 ", 32 | " KEY_NUMERIC_1 ", 33 | " KEY_NUMERIC_2 ", 34 | " KEY_NUMERIC_3 ", 35 | " KEY_NUMERIC_4 ", 36 | " KEY_NUMERIC_5 ", 37 | " KEY_NUMERIC_6 ", 38 | " KEY_NUMERIC_7 ", 39 | " KEY_NUMERIC_8 ", 40 | " KEY_NUMERIC_9 "}; 41 | 42 | void ledInit(void) 43 | { 44 | softPwmCreate(LedPinRed, 0, 100); 45 | softPwmCreate(LedPinGreen,0, 100); 46 | softPwmCreate(LedPinBlue, 0, 100); 47 | } 48 | 49 | void ledColorSet() 50 | { 51 | softPwmWrite(LedPinRed, color[0]); 52 | softPwmWrite(LedPinGreen, color[1]); 53 | softPwmWrite(LedPinBlue, color[2]); 54 | } 55 | 56 | int key(char *code){ 57 | int i; 58 | int num; 59 | for (i=0; i<21; i++){ 60 | if (strstr(code, keymap[i])){ 61 | num = i; 62 | } 63 | } 64 | return num + 1; 65 | } 66 | 67 | int RGB(int i){ 68 | switch(i){ 69 | case 1: color[0] = Lv[0]; printf("Red OFF\n"); break; 70 | case 2: color[0] = Lv[1]; printf("Dark Red\n"); break; 71 | case 3: color[0] = Lv[2]; printf("Bright Red\n"); break; 72 | case 4: color[1] = Lv[0]; printf("Green OFF\n"); break; 73 | case 5: color[1] = Lv[1]; printf("Dark Green\n"); break; 74 | case 6: color[1] = Lv[2]; printf("Bright Green\n"); break; 75 | case 7: color[2] = Lv[0]; printf("Blue OFF\n"); break; 76 | case 8: color[2] = Lv[1]; printf("Dark Blue\n"); break; 77 | case 9: color[2] = Lv[2]; printf("Bright Green\n"); break; 78 | } 79 | } 80 | 81 | int main(void) 82 | { 83 | struct lirc_config *config; 84 | int buttonTimer = millis(); 85 | char *code; 86 | char *c; 87 | if(wiringPiSetup() == -1){ 88 | printf("setup wiringPi failed !"); 89 | return 1; 90 | } 91 | 92 | if(lirc_init("lirc",1)==-1) 93 | exit(EXIT_FAILURE); 94 | 95 | ledInit(); 96 | ledColorSet(); 97 | 98 | if(lirc_readconfig(NULL,&config,NULL)==0) 99 | { 100 | while(lirc_nextcode(&code)==0) 101 | { 102 | if(code==NULL) continue;{ 103 | if (millis() - buttonTimer > 400){ 104 | RGB(key(code)); 105 | ledColorSet(color); 106 | } 107 | } 108 | free(code); 109 | } 110 | lirc_freeconfig(config); 111 | } 112 | lirc_deinit(); 113 | exit(EXIT_SUCCESS); 114 | return 0; 115 | } 116 | -------------------------------------------------------------------------------- /C/23_ircontrol/lircrc: -------------------------------------------------------------------------------- 1 | begin 2 | remote = * 3 | button = KEY_CHANNELDOWN 4 | prog = ircontrol 5 | config = KEY_CHANNELDOWN 6 | end 7 | 8 | begin 9 | remote = * 10 | button = KEY_CHANNEL 11 | prog = ircontrol 12 | config = KEY_CHANNEL 13 | end 14 | 15 | begin 16 | remote = * 17 | button = KEY_CHANNELUP 18 | prog = ircontrol 19 | config = KEY_CHANNELUP 20 | end 21 | 22 | begin 23 | remote = * 24 | button = KEY_PREVIOUS 25 | prog = ircontrol 26 | config = KEY_PREVIOUS 27 | end 28 | 29 | begin 30 | remote = * 31 | button = KEY_NEXT 32 | prog = ircontrol 33 | config = KEY_NEXT 34 | end 35 | 36 | begin 37 | remote = * 38 | button = KEY_PLAYPAUSE 39 | prog = ircontrol 40 | config = KEY_PLAYPAUSE 41 | end 42 | 43 | begin 44 | remote = * 45 | button = KEY_VOLUMEDOWN 46 | prog = ircontrol 47 | config = KEY_VOLUMEDOWN 48 | end 49 | 50 | begin 51 | remote = * 52 | button = KEY_VOLUMEUP 53 | prog = ircontrol 54 | config = KEY_VOLUMEUP 55 | end 56 | 57 | begin 58 | remote = * 59 | button = KEY_EQUAL 60 | prog = ircontrol 61 | config = KEY_EQUAL 62 | end 63 | 64 | begin 65 | remote = * 66 | button = KEY_NUMERIC_0 67 | prog = ircontrol 68 | config = KEY_NUMERIC_0 69 | end 70 | 71 | begin 72 | remote = * 73 | button = KEY_NUMERIC_1 74 | prog = ircontrol 75 | config = KEY_NUMERIC_1 76 | end 77 | 78 | begin 79 | remote = * 80 | button = KEY_NUMERIC_2 81 | prog = ircontrol 82 | config = KEY_NUMERIC_2 83 | end 84 | 85 | begin 86 | remote = * 87 | button = KEY_NUMERIC_3 88 | prog = ircontrol 89 | config = KEY_NUMERIC_3 90 | end 91 | 92 | begin 93 | remote = * 94 | button = KEY_NUMERIC_4 95 | prog = ircontrol 96 | config = KEY_NUMERIC_4 97 | end 98 | 99 | begin 100 | remote = * 101 | button = KEY_NUMERIC_5 102 | prog = ircontrol 103 | config = KEY_NUMERIC_5 104 | end 105 | 106 | begin 107 | remote = * 108 | button = KEY_NUMERIC_6 109 | prog = ircontrol 110 | config = KEY_NUMERIC_6 111 | end 112 | 113 | begin 114 | remote = * 115 | button = KEY_NUMERIC_7 116 | prog = ircontrol 117 | config = KEY_NUMERIC_7 118 | end 119 | 120 | begin 121 | remote = * 122 | button = KEY_NUMERIC_8 123 | prog = ircontrol 124 | config = KEY_NUMERIC_8 125 | end 126 | 127 | begin 128 | remote = * 129 | button = KEY_NUMERIC_9 130 | prog = ircontrol 131 | config = KEY_NUMERIC_9 132 | end 133 | 134 | begin 135 | remote = * 136 | button = BTN_0 137 | prog = ircontrol 138 | config = BTN_0 139 | end 140 | 141 | begin 142 | remote = * 143 | button = BTN_1 144 | prog = ircontrol 145 | config = BTN_1: 146 | end 147 | -------------------------------------------------------------------------------- /C/24_touch_switch/touch_switch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define TouchPin 0 5 | #define Gpin 2 6 | #define Rpin 1 7 | 8 | int tmp = 0; 9 | 10 | void LED(int color) 11 | { 12 | pinMode(Gpin, OUTPUT); 13 | pinMode(Rpin, OUTPUT); 14 | if (color == 0) 15 | { 16 | digitalWrite(Rpin, HIGH); 17 | digitalWrite(Gpin, LOW); 18 | } 19 | else if (color == 1) 20 | { 21 | digitalWrite(Rpin, LOW); 22 | digitalWrite(Gpin, HIGH); 23 | } 24 | else 25 | printf("LED Error"); 26 | } 27 | 28 | void Print(int x){ 29 | if (x != tmp){ 30 | if (x == 0) 31 | printf("...ON\n"); 32 | if (x == 1) 33 | printf("OFF..\n"); 34 | tmp = x; 35 | } 36 | } 37 | 38 | int main(void) 39 | { 40 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 41 | printf("setup wiringPi failed !"); 42 | return 1; 43 | } 44 | 45 | pinMode(TouchPin, INPUT); 46 | 47 | while(1){ 48 | LED(digitalRead(TouchPin)); 49 | Print(digitalRead(TouchPin)); 50 | } 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /C/25_ultrasonic_ranging/ultrasonic_ranging.c: -------------------------------------------------------------------------------- 1 | /******************************* 2 | * Ultra Sonic Raning module Pin VCC should 3 | * be connected to 5V power. 4 | ******************************/ 5 | #include 6 | #include 7 | #include 8 | 9 | #define Trig 0 10 | #define Echo 1 11 | 12 | void ultraInit(void) 13 | { 14 | pinMode(Echo, INPUT); 15 | pinMode(Trig, OUTPUT); 16 | } 17 | 18 | float disMeasure(void) 19 | { 20 | struct timeval tv1; 21 | struct timeval tv2; 22 | long time1, time2; 23 | float dis; 24 | 25 | digitalWrite(Trig, LOW); 26 | delayMicroseconds(2); 27 | 28 | digitalWrite(Trig, HIGH); 29 | delayMicroseconds(10); //发出超声波脉冲 30 | digitalWrite(Trig, LOW); 31 | 32 | while(!(digitalRead(Echo) == 1)); 33 | gettimeofday(&tv1, NULL); //获取当前时间 34 | 35 | while(!(digitalRead(Echo) == 0)); 36 | gettimeofday(&tv2, NULL); //获取当前时间 37 | 38 | time1 = tv1.tv_sec * 1000000 + tv1.tv_usec; //微秒级的时间 39 | time2 = tv2.tv_sec * 1000000 + tv2.tv_usec; 40 | 41 | dis = (float)(time2 - time1) / 1000000 * 34000 / 2; //求出距离 42 | 43 | return dis; 44 | } 45 | 46 | int main(void) 47 | { 48 | float dis; 49 | 50 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 51 | printf("setup wiringPi failed !"); 52 | return 1; 53 | } 54 | 55 | ultraInit(); 56 | 57 | while(1){ 58 | dis = disMeasure(); 59 | printf("%0.2f cm\n\n",dis); 60 | delay(300); 61 | } 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /C/26_ds18b20/ds18b20.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #define BUFSIZE 128 11 | 12 | typedef unsigned char uchar; 13 | typedef unsigned int uint; 14 | 15 | float tempRead(void) 16 | { 17 | float temp; 18 | int i, j; 19 | int fd; 20 | int ret; 21 | 22 | char buf[BUFSIZE]; 23 | char tempBuf[5]; 24 | 25 | fd = open("/sys/bus/w1/devices/28-031590bf4aff/w1_slave", O_RDONLY); 26 | 27 | if(-1 == fd){ 28 | perror("open device file error"); 29 | return 1; 30 | } 31 | 32 | while(1){ 33 | ret = read(fd, buf, BUFSIZE); 34 | if(0 == ret){ 35 | break; 36 | } 37 | if(-1 == ret){ 38 | if(errno == EINTR){ 39 | continue; 40 | } 41 | perror("read()"); 42 | close(fd); 43 | return 1; 44 | } 45 | } 46 | 47 | for(i=0;i 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define RoAPin 0 8 | #define RoBPin 1 9 | #define SWPin 2 10 | 11 | static volatile int globalCounter = 0 ; 12 | 13 | unsigned char flag; 14 | unsigned char Last_RoB_Status; 15 | unsigned char Current_RoB_Status; 16 | 17 | void btnISR(void) 18 | { 19 | globalCounter = 0; 20 | } 21 | 22 | void rotaryDeal(void) 23 | { 24 | Last_RoB_Status = digitalRead(RoBPin); 25 | 26 | while(!digitalRead(RoAPin)){ 27 | Current_RoB_Status = digitalRead(RoBPin); 28 | flag = 1; 29 | } 30 | 31 | if(flag == 1){ 32 | flag = 0; 33 | if((Last_RoB_Status == 0)&&(Current_RoB_Status == 1)){ 34 | globalCounter ++; 35 | } 36 | if((Last_RoB_Status == 1)&&(Current_RoB_Status == 0)){ 37 | globalCounter --; 38 | } 39 | } 40 | } 41 | 42 | int main(void) 43 | { 44 | if(wiringPiSetup() < 0){ 45 | fprintf(stderr, "Unable to setup wiringPi:%s\n",strerror(errno)); 46 | return 1; 47 | } 48 | 49 | pinMode(SWPin, INPUT); 50 | pinMode(RoAPin, INPUT); 51 | pinMode(RoBPin, INPUT); 52 | 53 | pullUpDnControl(SWPin, PUD_UP); 54 | 55 | if(wiringPiISR(SWPin, INT_EDGE_FALLING, &btnISR) < 0){ 56 | fprintf(stderr, "Unable to init ISR\n",strerror(errno)); 57 | return 1; 58 | } 59 | 60 | int tmp = 0; 61 | 62 | while(1){ 63 | rotaryDeal(); 64 | if (tmp != globalCounter){ 65 | printf("%d\n", globalCounter); 66 | tmp = globalCounter; 67 | } 68 | } 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /C/28_humiture/humiture.c: -------------------------------------------------------------------------------- 1 | /* 2 | * dht11.c: 3 | * Simple test program to test the wiringPi functions 4 | * DHT11 test 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #define MAXTIMINGS 85 13 | 14 | #define DHTPIN 0 15 | 16 | int dht11_dat[5] = {0,0,0,0,0}; 17 | 18 | void read_dht11_dat() 19 | { 20 | uint8_t laststate = HIGH; 21 | uint8_t counter = 0; 22 | uint8_t j = 0, i; 23 | float f; // fahrenheit 24 | 25 | dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0; 26 | 27 | // pull pin down for 18 milliseconds 28 | pinMode(DHTPIN, OUTPUT); 29 | digitalWrite(DHTPIN, LOW); 30 | delay(18); 31 | // then pull it up for 40 microseconds 32 | digitalWrite(DHTPIN, HIGH); 33 | delayMicroseconds(40); 34 | // prepare to read the pin 35 | pinMode(DHTPIN, INPUT); 36 | 37 | // detect change and read data 38 | for ( i=0; i< MAXTIMINGS; i++) { 39 | counter = 0; 40 | while (digitalRead(DHTPIN) == laststate) { 41 | counter++; 42 | delayMicroseconds(1); 43 | if (counter == 255) { 44 | break; 45 | } 46 | } 47 | laststate = digitalRead(DHTPIN); 48 | 49 | if (counter == 255) break; 50 | 51 | // ignore first 3 transitions 52 | if ((i >= 4) && (i%2 == 0)) { 53 | // shove each bit into the storage bytes 54 | dht11_dat[j/8] <<= 1; 55 | if (counter > 16) 56 | dht11_dat[j/8] |= 1; 57 | j++; 58 | } 59 | } 60 | 61 | // check we read 40 bits (8bit x 5 ) + verify checksum in the last byte 62 | // print it out if data is good 63 | if ((j >= 40) && 64 | (dht11_dat[4] == ((dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF)) ) { 65 | f = dht11_dat[2] * 9. / 5. + 32; 66 | printf("Humidity = %d.%d %% Temperature = %d.%d *C (%.1f *F)\n", 67 | dht11_dat[0], dht11_dat[1], dht11_dat[2], dht11_dat[3], f); 68 | } 69 | // else 70 | // { 71 | // printf("Data not good, skip\n"); 72 | // } 73 | } 74 | 75 | int main (void) 76 | { 77 | 78 | printf ("Raspberry Pi wiringPi DHT11 Temperature test program\n") ; 79 | 80 | if (wiringPiSetup () == -1) 81 | exit (1) ; 82 | 83 | while (1) 84 | { 85 | read_dht11_dat(); 86 | delay(1000); // wait 1sec to refresh 87 | } 88 | 89 | return 0 ; 90 | } 91 | -------------------------------------------------------------------------------- /C/29_ir_obstacle/ir_obstacle.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define ObstaclePin 0 5 | 6 | void myISR(void) 7 | { 8 | printf("Detected Barrier !\n"); 9 | } 10 | 11 | int main(void) 12 | { 13 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 14 | printf("setup wiringPi failed !\n"); 15 | return 1; 16 | } 17 | 18 | if(wiringPiISR(ObstaclePin, INT_EDGE_FALLING, &myISR) < 0){ 19 | printf("Unable to setup ISR !!!\n"); 20 | return 1; 21 | } 22 | 23 | while(1){ 24 | ; 25 | } 26 | 27 | return 0; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /C/30_i2c_lcd1602/i2c_lcd1602.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int LCDAddr = 0x27; 7 | int BLEN = 1; 8 | int fd; 9 | 10 | void write_word(int data){ 11 | int temp = data; 12 | if ( BLEN == 1 ) 13 | temp |= 0x08; 14 | else 15 | temp &= 0xF7; 16 | wiringPiI2CWrite(fd, temp); 17 | } 18 | 19 | void send_command(int comm){ 20 | int buf; 21 | // Send bit7-4 firstly 22 | buf = comm & 0xF0; 23 | buf |= 0x04; // RS = 0, RW = 0, EN = 1 24 | write_word(buf); 25 | delay(2); 26 | buf &= 0xFB; // Make EN = 0 27 | write_word(buf); 28 | 29 | // Send bit3-0 secondly 30 | buf = (comm & 0x0F) << 4; 31 | buf |= 0x04; // RS = 0, RW = 0, EN = 1 32 | write_word(buf); 33 | delay(2); 34 | buf &= 0xFB; // Make EN = 0 35 | write_word(buf); 36 | } 37 | 38 | void send_data(int data){ 39 | int buf; 40 | // Send bit7-4 firstly 41 | buf = data & 0xF0; 42 | buf |= 0x05; // RS = 1, RW = 0, EN = 1 43 | write_word(buf); 44 | delay(2); 45 | buf &= 0xFB; // Make EN = 0 46 | write_word(buf); 47 | 48 | // Send bit3-0 secondly 49 | buf = (data & 0x0F) << 4; 50 | buf |= 0x05; // RS = 1, RW = 0, EN = 1 51 | write_word(buf); 52 | delay(2); 53 | buf &= 0xFB; // Make EN = 0 54 | write_word(buf); 55 | } 56 | 57 | void init(){ 58 | send_command(0x33); // Must initialize to 8-line mode at first 59 | delay(5); 60 | send_command(0x32); // Then initialize to 4-line mode 61 | delay(5); 62 | send_command(0x28); // 2 Lines & 5*7 dots 63 | delay(5); 64 | send_command(0x0C); // Enable display without cursor 65 | delay(5); 66 | send_command(0x01); // Clear Screen 67 | wiringPiI2CWrite(fd, 0x08); 68 | } 69 | 70 | void clear(){ 71 | send_command(0x01); //clear Screen 72 | } 73 | 74 | void write(int x, int y, char data[]){ 75 | int addr, i; 76 | int tmp; 77 | if (x < 0) x = 0; 78 | if (x > 15) x = 15; 79 | if (y < 0) y = 0; 80 | if (y > 1) y = 1; 81 | 82 | // Move cursor 83 | addr = 0x80 + 0x40 * y + x; 84 | send_command(addr); 85 | 86 | tmp = strlen(data); 87 | for (i = 0; i < tmp; i++){ 88 | send_data(data[i]); 89 | } 90 | } 91 | 92 | void main(){ 93 | fd = wiringPiI2CSetup(LCDAddr); 94 | init(); 95 | while(1) 96 | { 97 | write(0, 0, "Greetings!"); 98 | write(1, 1, "From SunFounder"); 99 | delay(2000); 100 | clear(); 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /C/31_barometer/Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | gcc barometer.c bmp180.c -lm -lwiringPi -lwiringPiDev 3 | -------------------------------------------------------------------------------- /C/31_barometer/barometer.c: -------------------------------------------------------------------------------- 1 | #include "bmp180.h" 2 | #include 3 | #include 4 | 5 | int main(int argc, char **argv){ 6 | char *i2c_device = "/dev/i2c-1"; 7 | int address = 0x77; 8 | 9 | void *bmp = bmp180_init(address, i2c_device); 10 | 11 | if(bmp != NULL){ 12 | int i; 13 | for(i = 0; i < 100; i++) { 14 | float t = bmp180_temperature(bmp); 15 | long p = bmp180_pressure(bmp); 16 | float alt = bmp180_altitude(bmp); 17 | printf("temperature = %.2f, pressure = %lu, altitude = %.2f\n", t, p, alt); 18 | usleep(2 * 1000 * 1000); 19 | } 20 | } 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /C/31_barometer/bmp180.c: -------------------------------------------------------------------------------- 1 | /* 2 | * @author Alexander Rüedlinger 3 | * @date 26.02.2015 4 | * 5 | * A C driver for the sensor BMP180. 6 | * 7 | * update: 8 | * 2019-08-29: switch from Linux/i2c library to wiringPi i2c Library. 9 | */ 10 | 11 | #ifndef __BMP180__ 12 | #define __BMP180__ 13 | #include 14 | #include "bmp180.h" 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #endif 27 | 28 | 29 | /* 30 | * AC register 31 | */ 32 | #define BMP180_REG_AC1_H 0xAA 33 | #define BMP180_REG_AC2_H 0xAC 34 | #define BMP180_REG_AC3_H 0xAE 35 | #define BMP180_REG_AC4_H 0xB0 36 | #define BMP180_REG_AC5_H 0xB2 37 | #define BMP180_REG_AC6_H 0xB4 38 | 39 | /* 40 | * B1 register 41 | */ 42 | #define BMP180_REG_B1_H 0xB6 43 | 44 | /* 45 | * B2 register 46 | */ 47 | #define BMP180_REG_B2_H 0xB8 48 | 49 | /* 50 | * MB register 51 | */ 52 | #define BMP180_REG_MB_H 0xBA 53 | 54 | /* 55 | * MC register 56 | */ 57 | #define BMP180_REG_MC_H 0xBC 58 | 59 | /* 60 | * MD register 61 | */ 62 | #define BMP180_REG_MD_H 0xBE 63 | 64 | /* 65 | * AC register 66 | */ 67 | #define BMP180_CTRL 0xF4 68 | 69 | /* 70 | * Temperature register 71 | */ 72 | #define BMP180_REG_TMP 0xF6 73 | 74 | /* 75 | * Pressure register 76 | */ 77 | #define BMP180_REG_PRE 0xF6 78 | 79 | /* 80 | * Temperature read command 81 | */ 82 | #define BMP180_TMP_READ_CMD 0x2E 83 | 84 | /* 85 | * Waiting time in us for reading temperature values 86 | */ 87 | #define BMP180_TMP_READ_WAIT_US 5000 88 | 89 | /* 90 | * Pressure oversampling modes 91 | */ 92 | #define BMP180_PRE_OSS0 0 // ultra low power 93 | #define BMP180_PRE_OSS1 1 // standard 94 | #define BMP180_PRE_OSS2 2 // high resolution 95 | #define BMP180_PRE_OSS3 3 // ultra high resoultion 96 | 97 | /* 98 | * Pressure read commands 99 | */ 100 | #define BMP180_PRE_OSS0_CMD 0x34 101 | #define BMP180_PRE_OSS1_CMD 0x74 102 | #define BMP180_PRE_OSS2_CMD 0xB4 103 | #define BMP180_PRE_OSS3_CMD 0xF4 104 | 105 | /* 106 | * Waiting times in us for reading pressure values 107 | */ 108 | #define BMP180_PRE_OSS0_WAIT_US 5000 109 | #define BMP180_PRE_OSS1_WAIT_US 8000 110 | #define BMP180_PRE_OSS2_WAIT_US 14000 111 | #define BMP180_PRE_OSS3_WAIT_US 26000 112 | 113 | /* 114 | * Average sea-level pressure in hPa 115 | */ 116 | #define BMP180_SEA_LEVEL 1013.25 117 | 118 | 119 | /* 120 | * Define debug function. 121 | */ 122 | 123 | //#define __BMP180_DEBUG__ 124 | #ifdef __BMP180_DEBUG__ 125 | #define DEBUG(...) printf(__VA_ARGS__) 126 | #else 127 | #define DEBUG(...) 128 | #endif 129 | 130 | /* 131 | * Shortcut to cast void pointer to a bmp180_t pointer 132 | */ 133 | #define TO_BMP(x) (bmp180_t*) x 134 | 135 | 136 | 137 | /* 138 | * Basic structure for the bmp180 sensor 139 | */ 140 | typedef struct { 141 | /* file descriptor */ 142 | int file; 143 | 144 | /* i2c device address */ 145 | int address; 146 | 147 | /* BMP180 oversampling mode */ 148 | int oss; 149 | 150 | /* i2c device file path */ 151 | int i2c_device; 152 | 153 | /* Eprom values */ 154 | int ac1; 155 | int ac2; 156 | int ac3; 157 | int ac4; 158 | int ac5; 159 | int ac6; 160 | int b1; 161 | int b2; 162 | int mb; 163 | int mc; 164 | int md; 165 | } bmp180_t; 166 | 167 | 168 | /* 169 | * Lookup table for BMP180 register addresses 170 | */ 171 | int bmp180_register_table[11][2] = { 172 | {BMP180_REG_AC1_H, 1}, 173 | {BMP180_REG_AC2_H, 1}, 174 | {BMP180_REG_AC3_H, 1}, 175 | {BMP180_REG_AC4_H, 0}, 176 | {BMP180_REG_AC5_H, 0}, 177 | {BMP180_REG_AC6_H, 0}, 178 | {BMP180_REG_B1_H, 1}, 179 | {BMP180_REG_B2_H, 1}, 180 | {BMP180_REG_MB_H, 1}, 181 | {BMP180_REG_MC_H, 1}, 182 | {BMP180_REG_MD_H, 1} 183 | }; 184 | 185 | 186 | /* 187 | * Prototypes for helper functions 188 | */ 189 | int bmp180_set_addr(void *_bmp); 190 | void bmp180_read_eprom_reg(void *_bmp, int *_data, int reg, int sign); 191 | void bmp180_read_eprom(void *_bmp); 192 | int bmp180_read_raw_pressure(void *_bmp, int oss); 193 | int bmp180_read_raw_temperature(void *_bmp); 194 | void bmp180_init_error_cleanup(void *_bmp); 195 | 196 | 197 | /* 198 | * Implemetation of the helper functions 199 | */ 200 | 201 | 202 | /* 203 | * Sets the address for the i2c device file. 204 | * 205 | * @param bmp180 sensor 206 | */ 207 | int bmp180_set_addr(void *_bmp) { 208 | bmp180_t* bmp = TO_BMP(_bmp); 209 | int error; 210 | 211 | // if((error = ioctl(bmp->i2c_device, I2C_SLAVE, bmp->address)) < 0) { 212 | // DEBUG("error: ioctl() failed\n"); 213 | // } 214 | 215 | return error; 216 | } 217 | 218 | 219 | /* 220 | * Reads a single calibration coefficient from the BMP180 eprom. 221 | * 222 | * @param bmp180 sensor 223 | */ 224 | void bmp180_read_eprom_reg(void *_bmp, int *_store, int reg, int sign) { 225 | bmp180_t *bmp = TO_BMP(_bmp); 226 | int data = wiringPiI2CReadReg16(bmp->i2c_device, reg) & 0xFFFF; 227 | 228 | // i2c_smbus_read_word_data assumes little endian 229 | // but ARM uses big endian. Thus the ordering of the bytes is reversed. 230 | // data = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 bit position 231 | // | lsb | msb | 232 | 233 | // msb + lsb 234 | *_store = ((data << 8) & 0xFF00) + (data >> 8); 235 | 236 | if(sign && (*_store > 32767)) { 237 | *_store -= 65536; 238 | } 239 | } 240 | 241 | 242 | /* 243 | * Reads the eprom of this BMP180 sensor. 244 | * 245 | * @param bmp180 sensor 246 | */ 247 | void bmp180_read_eprom(void *_bmp) { 248 | bmp180_t *bmp = TO_BMP(_bmp); 249 | 250 | int *bmp180_register_addr[11] = { 251 | &bmp->ac1, &bmp->ac2, &bmp->ac3, &bmp->ac4, &bmp->ac5, &bmp->ac6, 252 | &bmp->b1, &bmp->b2, &bmp->mb, &bmp->mc, &bmp->md 253 | }; 254 | 255 | int sign, reg; 256 | int *data; 257 | int i; 258 | for(i = 0; i < 11; i++) { 259 | reg = (int) bmp180_register_table[i][0]; 260 | sign = (int) bmp180_register_table[i][1]; 261 | data = bmp180_register_addr[i]; 262 | bmp180_read_eprom_reg(_bmp, data, reg, sign); 263 | } 264 | } 265 | 266 | 267 | /* 268 | * Returns the raw measured temperature value of this BMP180 sensor. 269 | * 270 | * @param bmp180 sensor 271 | */ 272 | int bmp180_read_raw_temperature(void *_bmp) { 273 | bmp180_t* bmp = TO_BMP(_bmp); 274 | wiringPiI2CWriteReg8(bmp->i2c_device, BMP180_CTRL, BMP180_TMP_READ_CMD); 275 | 276 | usleep(BMP180_TMP_READ_WAIT_US); 277 | int data = wiringPiI2CReadReg16 (bmp->i2c_device, BMP180_REG_TMP) & 0xFFFF; 278 | 279 | data = ((data << 8) & 0xFF00) + (data >> 8); 280 | 281 | return data; 282 | } 283 | 284 | 285 | /* 286 | * Returns the raw measured pressure value of this BMP180 sensor. 287 | * 288 | * @param bmp180 sensor 289 | */ 290 | int bmp180_read_raw_pressure(void *_bmp, int oss) { 291 | bmp180_t* bmp = TO_BMP(_bmp); 292 | uint16_t wait; 293 | int cmd; 294 | 295 | switch(oss) { 296 | case BMP180_PRE_OSS1: 297 | wait = BMP180_PRE_OSS1_WAIT_US; cmd = BMP180_PRE_OSS1_CMD; 298 | break; 299 | 300 | case BMP180_PRE_OSS2: 301 | wait = BMP180_PRE_OSS2_WAIT_US; cmd = BMP180_PRE_OSS2_CMD; 302 | break; 303 | 304 | case BMP180_PRE_OSS3: 305 | wait = BMP180_PRE_OSS3_WAIT_US; cmd = BMP180_PRE_OSS3_CMD; 306 | break; 307 | 308 | case BMP180_PRE_OSS0: 309 | default: 310 | wait = BMP180_PRE_OSS0_WAIT_US; cmd = BMP180_PRE_OSS0_CMD; 311 | break; 312 | } 313 | 314 | wiringPiI2CWriteReg8 (bmp->i2c_device, BMP180_CTRL, cmd); 315 | 316 | usleep(wait); 317 | 318 | int msb, lsb, xlsb, data; 319 | msb = wiringPiI2CReadReg8 (bmp->i2c_device, BMP180_REG_PRE) & 0xFF; 320 | lsb = wiringPiI2CReadReg8 (bmp->i2c_device, BMP180_REG_PRE+1) & 0xFF; 321 | xlsb = wiringPiI2CReadReg8 (bmp->i2c_device, BMP180_REG_PRE+2) & 0xFF; 322 | 323 | data = ((msb << 16) + (lsb << 8) + xlsb) >> (8 - bmp->oss); 324 | 325 | return data; 326 | } 327 | 328 | /* 329 | * Implementation of the interface functions 330 | */ 331 | 332 | /** 333 | * Dumps the eprom values of this BMP180 sensor. 334 | * 335 | * @param bmp180 sensor 336 | * @param bmp180 eprom struct 337 | */ 338 | void bmp180_dump_eprom(void *_bmp, bmp180_eprom_t *eprom) { 339 | bmp180_t *bmp = TO_BMP(_bmp); 340 | eprom->ac1 = bmp->ac1; 341 | eprom->ac2 = bmp->ac2; 342 | eprom->ac3 = bmp->ac3; 343 | eprom->ac4 = bmp->ac4; 344 | eprom->ac5 = bmp->ac5; 345 | eprom->ac6 = bmp->ac6; 346 | eprom->b1 = bmp->b1; 347 | eprom->b2 = bmp->b2; 348 | eprom->mb = bmp->mb; 349 | eprom->mc = bmp->mc; 350 | eprom->md = bmp->md; 351 | } 352 | 353 | 354 | /** 355 | * Creates a BMP180 sensor object. 356 | * 357 | * @param i2c device address 358 | * @param i2c device file path 359 | * @return bmp180 sensor 360 | */ 361 | void *bmp180_init(int address, const char* i2c_device_filepath) { 362 | DEBUG("device: init using address %#x and i2cbus %s\n", address, i2c_device_filepath); 363 | 364 | // setup BMP180 365 | void *_bmp = malloc(sizeof(bmp180_t)); 366 | if(_bmp == NULL) { 367 | DEBUG("error: malloc returns NULL pointer\n"); 368 | return NULL; 369 | } 370 | 371 | bmp180_t *bmp = TO_BMP(_bmp); 372 | bmp->address = address; 373 | 374 | // setup i2c device path 375 | bmp->i2c_device = wiringPiI2CSetup(address); 376 | 377 | // setup i2c device 378 | bmp180_read_eprom(_bmp); 379 | bmp->oss = 0; 380 | 381 | DEBUG("device: open ok\n"); 382 | 383 | return _bmp; 384 | } 385 | 386 | 387 | /** 388 | * Returns the measured temperature in celsius. 389 | * 390 | * @param bmp180 sensor 391 | * @return temperature 392 | */ 393 | float bmp180_temperature(void *_bmp) { 394 | bmp180_t* bmp = TO_BMP(_bmp); 395 | long UT, X1, X2, B5; 396 | float T; 397 | 398 | UT = bmp180_read_raw_temperature(_bmp); 399 | 400 | DEBUG("UT=%lu\n",UT); 401 | 402 | X1 = ((UT - bmp->ac6) * bmp->ac5) >> 15; 403 | X2 = (bmp->mc << 11) / (X1 + bmp->md); 404 | B5 = X1 + X2; 405 | T = ((B5 + 8) >> 4) / 10.0; 406 | 407 | return T; 408 | } 409 | 410 | /** 411 | * Returns the measured pressure in pascal. 412 | * 413 | * @param bmp180 sensor 414 | * @return pressure 415 | */ 416 | long bmp180_pressure(void *_bmp) { 417 | bmp180_t* bmp = TO_BMP(_bmp); 418 | long UT, UP, B6, B5, X1, X2, X3, B3, p; 419 | unsigned long B4, B7; 420 | 421 | UT = bmp180_read_raw_temperature(_bmp); 422 | UP = bmp180_read_raw_pressure(_bmp, bmp->oss); 423 | 424 | X1 = ((UT - bmp->ac6) * bmp->ac5) >> 15; 425 | X2 = (bmp->mc << 11) / (X1 + bmp->md); 426 | 427 | B5 = X1 + X2; 428 | 429 | B6 = B5 - 4000; 430 | 431 | X1 = (bmp->b2 * (B6 * B6) >> 12) >> 11; 432 | X2 = (bmp->ac2 * B6) >> 11; 433 | X3 = X1 + X2; 434 | 435 | B3 = ((((bmp->ac1 * 4) + X3) << bmp->oss) + 2) / 4; 436 | X1 = (bmp->ac3 * B6) >> 13; 437 | X2 = (bmp->b1 * ((B6 * B6) >> 12)) >> 16; 438 | X3 = ((X1 + X2) + 2) >> 2; 439 | 440 | 441 | B4 = bmp->ac4 * (unsigned long)(X3 + 32768) >> 15; 442 | B7 = ((unsigned long) UP - B3) * (50000 >> bmp->oss); 443 | 444 | if(B7 < 0x80000000) { 445 | p = (B7 * 2) / B4; 446 | } else { 447 | p = (B7 / B4) * 2; 448 | } 449 | 450 | X1 = (p >> 8) * (p >> 8); 451 | X1 = (X1 * 3038) >> 16; 452 | X2 = (-7357 * p) >> 16; 453 | p = p + ((X1 + X2 + 3791) >> 4); 454 | 455 | return p; 456 | } 457 | 458 | /** 459 | * Returns altitude in meters based on the measured pressure 460 | * and temperature of this sensor. 461 | * 462 | * @param bmp180 sensor 463 | * @return altitude 464 | */ 465 | float bmp180_altitude(void *_bmp) { 466 | float p, alt; 467 | p = bmp180_pressure(_bmp); 468 | alt = 44330 * (1 - pow(( (p/100) / BMP180_SEA_LEVEL),1/5.255)); 469 | 470 | return alt; 471 | } 472 | 473 | /** 474 | * Sets the oversampling setting for this sensor. 475 | * 476 | * @param bmp180 sensor 477 | * @param oversampling mode 478 | */ 479 | void bmp180_set_oss(void *_bmp, int oss) { 480 | bmp180_t* bmp = TO_BMP(_bmp); 481 | bmp->oss = oss; 482 | } 483 | 484 | -------------------------------------------------------------------------------- /C/31_barometer/bmp180.h: -------------------------------------------------------------------------------- 1 | /* 2 | * @author Alexander Rüedlinger 3 | * @date 26.02.2015 4 | * 5 | * A c driver for the sensor BMP180. 6 | * 7 | */ 8 | 9 | /* 10 | * pressure oversampling modes 11 | */ 12 | #define BMP180_PRE_OSS0 0 // ultra low power 13 | #define BMP180_PRE_OSS1 1 // standard 14 | #define BMP180_PRE_OSS2 2 // high resolution 15 | #define BMP180_PRE_OSS3 3 // ultra high resoultion 16 | 17 | 18 | typedef struct { 19 | /* Eprom values */ 20 | int ac1; 21 | int ac2; 22 | int ac3; 23 | int ac4; 24 | int ac5; 25 | int ac6; 26 | int b1; 27 | int b2; 28 | int mb; 29 | int mc; 30 | int md; 31 | } bmp180_eprom_t; 32 | 33 | void *bmp180_init(int address, const char* i2c_device_filepath); 34 | 35 | void bmp180_close(void *_bmp); 36 | 37 | long bmp180_pressure(void *_bmp); 38 | 39 | void bmp180_set_oss(void *_bmp, int oss); 40 | 41 | float bmp180_temperature(void *_bmp); 42 | 43 | float bmp180_altitude(void *_bmp); 44 | 45 | void bmp180_dump_eprom(void *_bmp, bmp180_eprom_t *eprom); 46 | 47 | -------------------------------------------------------------------------------- /C/31_barometer/bmp280.c: -------------------------------------------------------------------------------- 1 | /********************************************************************** 2 | * Filename : bmp280.c 3 | * Description : Simple use for bmp280 through i2c bus 4 | * Author : Cavon 5 | * Brand : SunFounder 6 | * E-mail : support@sunfounder.com 7 | * Website : www.sunfounder.com 8 | * Update : Cavon 2016-10-09 New release 9 | **********************************************************************/ 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | #define QNH 1020 16 | 17 | // Power mode 18 | //#define POWER_MODE 0 // sleep mode 19 | //#define POWER_MODE 1 // forced mode 20 | //#define POWER_MODE 2 // forced mode 21 | #define POWER_MODE 3 // normal mode 22 | 23 | // Temperature resolution 24 | //#define OSRS_T 0 // skipped 25 | //#define OSRS_T 1 // 16 Bit 26 | //#define OSRS_T 2 // 17 Bit 27 | //#define OSRS_T 3 // 18 Bit 28 | //#define OSRS_T 4 // 19 Bit 29 | #define OSRS_T 5 // 20 Bit 30 | 31 | // Pressure resolution 32 | //#define OSRS_P 0 // pressure measurement skipped 33 | //#define OSRS_P 1 // 16 Bit ultra low power 34 | //#define OSRS_P 2 // 17 Bit low power 35 | //#define OSRS_P 3 // 18 Bit standard resolution 36 | //#define OSRS_P 4 // 19 Bit high resolution 37 | #define OSRS_P 5 // 20 Bit ultra high resolution 38 | 39 | // Filter settings 40 | //#define FILTER 0 // 41 | //#define FILTER 1 // 42 | //#define FILTER 2 // 43 | //#define FILTER 3 // 44 | #define FILTER 4 // 45 | //#define FILTER 5 // 46 | //#define FILTER 6 // 47 | //#define FILTER 7 // 48 | 49 | // Standby settings 50 | //#define T_SB 0 // 000 0,5ms 51 | //#define T_SB 1 // 001 62.5 ms 52 | //#define T_SB 2 // 010 125 ms 53 | //#define T_SB 3 // 011 250ms 54 | #define T_SB 4 // 100 500ms 55 | //#define T_SB 5 // 101 1000ms 56 | //#define T_SB 6 // 110 2000ms 57 | //#define T_SB 7 // 111 4000ms 58 | 59 | #define BMP280_REGISTER_DIG_T1 0x88 60 | #define BMP280_REGISTER_DIG_T2 0x8A 61 | #define BMP280_REGISTER_DIG_T3 0x8C 62 | #define BMP280_REGISTER_DIG_P1 0x8E 63 | #define BMP280_REGISTER_DIG_P2 0x90 64 | #define BMP280_REGISTER_DIG_P3 0x92 65 | #define BMP280_REGISTER_DIG_P4 0x94 66 | #define BMP280_REGISTER_DIG_P5 0x96 67 | #define BMP280_REGISTER_DIG_P6 0x98 68 | #define BMP280_REGISTER_DIG_P7 0x9A 69 | #define BMP280_REGISTER_DIG_P8 0x9C 70 | #define BMP280_REGISTER_DIG_P9 0x9E 71 | #define BMP280_REGISTER_CHIPID 0xD0 72 | #define BMP280_REGISTER_VERSION 0xD1 73 | #define BMP280_REGISTER_SOFTRESET 0xE0 74 | #define BMP280_REGISTER_CONTROL 0xF4 75 | #define BMP280_REGISTER_CONFIG 0xF5 76 | #define BMP280_REGISTER_STATUS 0xF3 77 | #define BMP280_REGISTER_TEMPDATA_MSB 0xFA 78 | #define BMP280_REGISTER_TEMPDATA_LSB 0xFB 79 | #define BMP280_REGISTER_TEMPDATA_XLSB 0xFC 80 | #define BMP280_REGISTER_PRESSDATA_MSB 0xF7 81 | #define BMP280_REGISTER_PRESSDATA_LSB 0xF8 82 | #define BMP280_REGISTER_PRESSDATA_XLSB 0xF9 83 | 84 | int CONFIG = (T_SB <<5) + (FILTER <<2); // combine bits for config 85 | int CTRL_MEAS = (OSRS_T <<5) + (OSRS_P <<2) + POWER_MODE; // combine bits for ctrl_meas 86 | 87 | int bmp280 = 0; 88 | struct { 89 | int chip_id; 90 | int chip_version; 91 | double temperature; 92 | double pressure; 93 | double altitude; 94 | } bmp; 95 | 96 | int dig_T1 = 0; 97 | int dig_T2 = 0; 98 | int dig_T3 = 0; 99 | int dig_P1 = 0; 100 | int dig_P2 = 0; 101 | int dig_P3 = 0; 102 | int dig_P4 = 0; 103 | int dig_P5 = 0; 104 | int dig_P6 = 0; 105 | int dig_P7 = 0; 106 | int dig_P8 = 0; 107 | int dig_P9 = 0; 108 | 109 | void write_byte_data(int reg, int value){ 110 | wiringPiI2CWriteReg8(bmp280, reg, value); 111 | } 112 | 113 | int read_byte_data(int reg){ 114 | int result; 115 | result = wiringPiI2CReadReg8(bmp280, reg); 116 | return result; 117 | } 118 | 119 | int read_word_data_unsigned(int reg){ 120 | int result; 121 | result = wiringPiI2CReadReg16(bmp280, reg); 122 | return result; 123 | } 124 | 125 | int read_word_data_signed(int reg){ 126 | int result; 127 | result = read_word_data_unsigned(reg); 128 | if (result > 32767){ 129 | result -= 65536; 130 | } 131 | return result; 132 | } 133 | 134 | void read_id(self){ 135 | int REG_ID = 0xD0; 136 | int result; 137 | result = read_word_data_unsigned(REG_ID); 138 | bmp.chip_id = result & 0x00FF; 139 | bmp.chip_version = result >> 8; 140 | } 141 | 142 | void reg_check(self){ 143 | write_byte_data(BMP280_REGISTER_SOFTRESET, 0xB6); 144 | delay(200); 145 | write_byte_data(BMP280_REGISTER_CONTROL, CTRL_MEAS); 146 | delay(200); 147 | write_byte_data(BMP280_REGISTER_CONFIG, CONFIG); 148 | delay(200); 149 | 150 | dig_T1 = read_word_data_unsigned(BMP280_REGISTER_DIG_T1); // read correction settings 151 | dig_T2 = read_word_data_signed(BMP280_REGISTER_DIG_T2); 152 | dig_T3 = read_word_data_signed(BMP280_REGISTER_DIG_T3); 153 | dig_P1 = read_word_data_unsigned(BMP280_REGISTER_DIG_P1); 154 | dig_P2 = read_word_data_signed(BMP280_REGISTER_DIG_P2); 155 | dig_P3 = read_word_data_signed(BMP280_REGISTER_DIG_P3); 156 | dig_P4 = read_word_data_signed(BMP280_REGISTER_DIG_P4); 157 | dig_P5 = read_word_data_signed(BMP280_REGISTER_DIG_P5); 158 | dig_P6 = read_word_data_signed(BMP280_REGISTER_DIG_P6); 159 | dig_P7 = read_word_data_signed(BMP280_REGISTER_DIG_P7); 160 | dig_P8 = read_word_data_signed(BMP280_REGISTER_DIG_P8); 161 | dig_P9 = read_word_data_signed(BMP280_REGISTER_DIG_P9); 162 | } 163 | 164 | void read(){ 165 | int raw_temperature_msb, raw_temperature_lsb, raw_temperature_xlsb; 166 | int raw_pressure_msb, raw_pressure_lsb, raw_pressure_xlsb; 167 | int raw_temperature; 168 | int raw_pressure; 169 | double var1, var2, temperature, t_fine, pressure, altitude; 170 | 171 | raw_temperature_msb = read_byte_data(BMP280_REGISTER_TEMPDATA_MSB); // read raw temperature msb 172 | raw_temperature_lsb = read_byte_data(BMP280_REGISTER_TEMPDATA_LSB); // read raw temperature lsb 173 | raw_temperature_xlsb = read_byte_data(BMP280_REGISTER_TEMPDATA_XLSB); // read raw temperature xlsb 174 | raw_pressure_msb = read_byte_data(BMP280_REGISTER_PRESSDATA_MSB); // read raw pressure msb 175 | raw_pressure_lsb = read_byte_data(BMP280_REGISTER_PRESSDATA_LSB); // read raw pressure lsb 176 | raw_pressure_xlsb = read_byte_data(BMP280_REGISTER_PRESSDATA_XLSB); // read raw pressure xlsb 177 | 178 | raw_temperature=(raw_temperature_msb <<12)+(raw_temperature_lsb<<4)+(raw_temperature_xlsb>>4); // combine 3 bytes msb 12 bits left, lsb 4 bits left, xlsb 4 bits right 179 | raw_pressure=(raw_pressure_msb <<12)+(raw_pressure_lsb <<4)+(raw_pressure_xlsb >>4); // combine 3 bytes msb 12 bits left, lsb 4 bits left, xlsb 4 bits right 180 | 181 | var1=(raw_temperature/16384.0-dig_T1/1024.0)*dig_T2; // formula for temperature from datasheet 182 | var2=(raw_temperature/131072.0-dig_T1/8192.0)*(raw_temperature/131072.0-dig_T1/8192.0)*dig_T3; // formula for temperature from datasheet 183 | temperature=(var1+var2)/5120.0; // formula for temperature from datasheet 184 | t_fine=(var1+var2); // need for pressure calculation 185 | 186 | var1=t_fine/2.0-64000.0; // formula for pressure from datasheet 187 | var2=var1*var1*dig_P6/32768.0; // formula for pressure from datasheet 188 | var2=var2+var1*dig_P5*2; // formula for pressure from datasheet 189 | var2=var2/4.0+dig_P4*65536.0; // formula for pressure from datasheet 190 | var1=(dig_P3*var1*var1/524288.0+dig_P2*var1)/524288.0; // formula for pressure from datasheet 191 | var1=(1.0+var1/32768.0)*dig_P1; // formula for pressure from datasheet 192 | pressure=1048576.0-raw_pressure; // formula for pressure from datasheet 193 | pressure=(pressure-var2/4096.0)*6250.0/var1; // formula for pressure from datasheet 194 | var1=dig_P9*pressure*pressure/2147483648.0; // formula for pressure from datasheet 195 | var2=pressure*dig_P8/32768.0; // formula for pressure from datasheet 196 | pressure=pressure+(var1+var2+dig_P7)/16.0; // formula for pressure from datasheet 197 | 198 | //altitude= 44330.0 * (1.0 - pow(pressure / (QNH*100), (1.0/5.255))); // formula for altitude from airpressure 199 | 200 | bmp.temperature = temperature; 201 | bmp.pressure = pressure / 100.0; 202 | } 203 | 204 | void main(){ 205 | int address = 0x77; 206 | bmp280 = wiringPiI2CSetup(address); 207 | while (1){ 208 | read_id(); 209 | 210 | if(bmp.chip_id == 88){ 211 | reg_check(); 212 | read(); 213 | printf("Temperature : %2.2f `C\n", bmp.temperature); 214 | printf("Pressure : %5.4f mbar\n\n", bmp.pressure); 215 | } 216 | else{ 217 | printf("Error\n"); 218 | // Chip ID should be 88 219 | printf("Chip ID : %d\n", bmp.chip_id); 220 | printf("Version : %d\n", bmp.chip_version); 221 | delay(1000); 222 | } 223 | } 224 | } 225 | -------------------------------------------------------------------------------- /C/32_mpu6050/32_mpu6050.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int fd; 7 | int acclX, acclY, acclZ; 8 | int gyroX, gyroY, gyroZ; 9 | double acclX_scaled, acclY_scaled, acclZ_scaled; 10 | double gyroX_scaled, gyroY_scaled, gyroZ_scaled; 11 | 12 | int read_word_2c(int addr) 13 | { 14 | int val; 15 | val = wiringPiI2CReadReg8(fd, addr); 16 | val = val << 8; 17 | val += wiringPiI2CReadReg8(fd, addr+1); 18 | if (val >= 0x8000) 19 | val = -(65536 - val); 20 | 21 | return val; 22 | } 23 | 24 | double dist(double a, double b) 25 | { 26 | return sqrt((a*a) + (b*b)); 27 | } 28 | 29 | double get_y_rotation(double x, double y, double z) 30 | { 31 | double radians; 32 | radians = atan2(x, dist(y, z)); 33 | return -(radians * (180.0 / M_PI)); 34 | } 35 | 36 | double get_x_rotation(double x, double y, double z) 37 | { 38 | double radians; 39 | radians = atan2(y, dist(x, z)); 40 | return (radians * (180.0 / M_PI)); 41 | } 42 | 43 | int main() 44 | { 45 | fd = wiringPiI2CSetup (0x68); 46 | wiringPiI2CWriteReg8 (fd,0x6B,0x00);//disable sleep mode 47 | printf("set 0x6B=%X\n",wiringPiI2CReadReg8 (fd,0x6B)); 48 | 49 | while(1) { 50 | 51 | gyroX = read_word_2c(0x43); 52 | gyroY = read_word_2c(0x45); 53 | gyroZ = read_word_2c(0x47); 54 | 55 | gyroX_scaled = gyroX / 131.0; 56 | gyroY_scaled = gyroY / 131.0; 57 | gyroZ_scaled = gyroZ / 131.0; 58 | 59 | //Print values for the X, Y, and Z axes of the gyroscope sensor. 60 | printf("My gyroX_scaled: %f\n", gyroX_scaled); 61 | printf("My gyroY_scaled: %f\n", gyroY_scaled); 62 | printf("My gyroZ_scaled: %f\n", gyroZ_scaled); 63 | 64 | acclX = read_word_2c(0x3B); 65 | acclY = read_word_2c(0x3D); 66 | acclZ = read_word_2c(0x3F); 67 | 68 | acclX_scaled = acclX / 16384.0; 69 | acclY_scaled = acclY / 16384.0; 70 | acclZ_scaled = acclZ / 16384.0; 71 | 72 | //Print the X, Y, and Z values of the acceleration sensor. 73 | printf("My acclX_scaled: %f\n", acclX_scaled); 74 | printf("My acclY_scaled: %f\n", acclY_scaled); 75 | printf("My acclZ_scaled: %f\n", acclZ_scaled); 76 | 77 | printf("My X rotation: %f\n", get_x_rotation(acclX_scaled, acclY_scaled, acclZ_scaled)); 78 | printf("My Y rotation: %f\n", get_y_rotation(acclX_scaled, acclY_scaled, acclZ_scaled)); 79 | 80 | 81 | delay(100); 82 | } 83 | return 0; 84 | } 85 | -------------------------------------------------------------------------------- /C/33_ds1302/rtc_ds1302.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | #include 9 | 10 | // Register defines 11 | 12 | #define RTC_SECS 0 13 | #define RTC_MINS 1 14 | #define RTC_HOURS 2 15 | #define RTC_DATE 3 16 | #define RTC_MONTH 4 17 | #define RTC_DAY 5 18 | #define RTC_YEAR 6 19 | #define RTC_WP 7 20 | #define RTC_TC 8 21 | #define RTC_BM 31 22 | 23 | 24 | static unsigned int masks [] = { 0x7F, 0x7F, 0x3F, 0x3F, 0x1F, 0x07, 0xFF } ; 25 | 26 | 27 | // bcdToD: dToBCD: 28 | static int bcdToD (unsigned int byte, unsigned int mask) 29 | { 30 | unsigned int b1, b2 ; 31 | byte &= mask ; 32 | b1 = byte & 0x0F ; 33 | b2 = ((byte >> 4) & 0x0F) * 10 ; 34 | return b1 + b2 ; 35 | } 36 | 37 | static unsigned int dToBcd (unsigned int byte) 38 | { 39 | byte = byte % 100; 40 | return ((byte / 10) << 4) + (byte % 10) ; 41 | } 42 | 43 | // ramTest: 44 | static int ramTestValues [] = 45 | { 0x00, 0xFF, 0xAA, 0x55, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x00, 0xF0, 0x0F, -1 } ; 46 | 47 | static int ramTest (void) 48 | { 49 | int addr ; 50 | int got ; 51 | int i = 0 ; 52 | int errors = 0 ; 53 | int testVal ; 54 | 55 | printf ("DS1302 RAM TEST\n") ; 56 | 57 | testVal = ramTestValues [i] ; 58 | 59 | while (testVal != -1) 60 | { 61 | for (addr = 0 ; addr < 31 ; ++addr) 62 | ds1302ramWrite (addr, testVal) ; 63 | 64 | for (addr = 0 ; addr < 31 ; ++addr) 65 | if ((got = ds1302ramRead (addr)) != testVal) 66 | { 67 | printf ("DS1302 RAM Failure: Address: %2d, Expected: 0x%02X, Got: 0x%02X\n", 68 | addr, testVal, got) ; 69 | ++errors ; 70 | } 71 | testVal = ramTestValues [++i] ; 72 | } 73 | 74 | for (addr = 0 ; addr < 31 ; ++addr) 75 | ds1302ramWrite (addr, addr) ; 76 | 77 | for (addr = 0 ; addr < 31 ; ++addr) 78 | if ((got = ds1302ramRead (addr)) != addr) 79 | { 80 | printf ("DS1302 RAM Failure: Address: %2d, Expected: 0x%02X, Got: 0x%02X\n", 81 | addr, addr, got) ; 82 | ++errors ; 83 | } 84 | 85 | if (errors == 0) 86 | printf ("-- DS1302 RAM TEST: OK\n") ; 87 | else 88 | printf ("-- DS1302 RAM TEST FAILURE. %d errors.\n", errors) ; 89 | 90 | return 0 ; 91 | } 92 | 93 | // setLinuxClock: 94 | static int setLinuxClock (void) 95 | { 96 | char dateTime [20] ; 97 | char command [64] ; 98 | int clock [8] ; 99 | 100 | 101 | printf ("Setting the Linux Clock from the DS1302... ") ; fflush (stdout) ; 102 | 103 | ds1302clockRead (clock) ; 104 | 105 | // [MMDDhhmm[[CC]YY][.ss]] 106 | 107 | sprintf (dateTime, "%02d%02d%02d%02d%02d%02d.%02d", 108 | bcdToD (clock [RTC_MONTH], masks [RTC_MONTH]), 109 | bcdToD (clock [RTC_DATE], masks [RTC_DATE]), 110 | bcdToD (clock [RTC_HOURS], masks [RTC_HOURS]), 111 | bcdToD (clock [RTC_MINS], masks [RTC_MINS]), 112 | 20, 113 | bcdToD (clock [RTC_YEAR], masks [RTC_YEAR]), 114 | bcdToD (clock [RTC_SECS], masks [RTC_SECS])) ; 115 | 116 | sprintf (command, "/bin/date %s", dateTime) ; 117 | system (command) ; 118 | 119 | return 0 ; 120 | } 121 | 122 | 123 | 124 | // setDSclock: 125 | static int setDSclock (void) 126 | { 127 | struct tm t ; 128 | time_t now ; 129 | int clock [8] ; 130 | int time = 0 ; 131 | int date = 0 ; 132 | int weekday = 0 ; 133 | 134 | printf ("Setting the clock in the DS1302 from type in... ") ; 135 | 136 | printf ("\n\nEnter Date(YYYYMMDD): ") ; 137 | scanf ("%d", &date) ; 138 | printf ("Enter time(HHMMSS, 24-hour clock): ") ; 139 | scanf ("%d", &time) ; 140 | printf ("Enter Weekday(0 as sunday): ") ; 141 | scanf ("%d", &weekday) ; 142 | // printf("\ndate: %d, time: %d\n\n", date, time) ; 143 | 144 | clock [ 0] = dToBcd (time % 100) ; // seconds 145 | clock [ 1] = dToBcd (time / 100 % 100) ; // mins 146 | clock [ 2] = dToBcd (time / 100 / 100) ; // hours 147 | clock [ 3] = dToBcd (date % 100) ; // date 148 | clock [ 4] = dToBcd (date / 100 % 100) ; // months 0-11 --> 1-12 149 | clock [ 5] = dToBcd (weekday) ; // weekdays (sun 0) 150 | clock [ 6] = dToBcd (date / 100 / 100) ; // years 151 | clock [ 7] = 0 ; // W-Protect off 152 | 153 | ds1302clockWrite (clock) ; 154 | 155 | printf ("OK\n") ; 156 | 157 | return 0 ; 158 | } 159 | 160 | 161 | 162 | 163 | int main (int argc, char *argv []) 164 | { 165 | int i ; 166 | int clock [8] ; 167 | int year ; 168 | int month ; 169 | int date ; 170 | int hour ; 171 | int minute ; 172 | int second ; 173 | int weekday ; 174 | 175 | wiringPiSetup () ; 176 | ds1302setup (4, 5, 6) ; 177 | 178 | if (argc == 2) 179 | { 180 | /**/ if (strcmp (argv [1], "-slc") == 0) 181 | return setLinuxClock () ; 182 | else if (strcmp (argv [1], "-sdsc") == 0) 183 | return setDSclock () ; 184 | else if (strcmp (argv [1], "-rtest") == 0) 185 | return ramTest () ; 186 | else 187 | { 188 | printf ("Usage: ds1302 [-slc | -sdsc | -rtest]\n") ; 189 | return EXIT_FAILURE ; 190 | } 191 | } 192 | 193 | for (i = 0 ;; ++i) 194 | { 195 | printf ("%5d: ", i) ; 196 | 197 | ds1302clockRead (clock) ; 198 | 199 | hour = bcdToD (clock [2], masks [2]) ; 200 | minute = bcdToD (clock [1], masks [1]) ; 201 | second = bcdToD (clock [0], masks [0]) ; 202 | 203 | date = bcdToD (clock [3], masks [3]) ; 204 | month = bcdToD (clock [4], masks [4]) ; 205 | year = bcdToD (clock [6], masks [6]) + 2000 ; 206 | weekday = bcdToD (clock [5], masks [5]) ; 207 | 208 | printf (" %04d-%02d-%02d", year, month, date) ; 209 | printf (" %02d:%02d:%02d", hour, minute, second) ; 210 | 211 | switch (weekday){ 212 | case 0: printf (" SUN") ; break; 213 | case 1: printf (" MON") ; break; 214 | case 2: printf (" TUE") ; break; 215 | case 3: printf (" WED") ; break; 216 | case 4: printf (" THU") ; break; 217 | case 5: printf (" FRI") ; break; 218 | case 6: printf (" SAT") ; break; 219 | } 220 | 221 | printf ("\n") ; 222 | 223 | delay (200) ; 224 | } 225 | 226 | return 0 ; 227 | } 228 | -------------------------------------------------------------------------------- /C/34_tracking/tracking.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define TrackSensorPin 0 5 | #define LedPin 1 6 | 7 | int main(void) 8 | { 9 | if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen 10 | printf("setup wiringPi failed !"); 11 | return 1; 12 | } 13 | 14 | pinMode(TrackSensorPin, INPUT); 15 | pinMode(LedPin, OUTPUT); 16 | 17 | while(1){ 18 | if(digitalRead(TrackSensorPin) == LOW){ 19 | printf("White line is detected\n"); 20 | digitalWrite(LedPin, LOW); //led on 21 | delay(100); 22 | digitalWrite(LedPin, HIGH); //led off 23 | } 24 | else{ 25 | printf("...Black line is detected\n"); 26 | delay(100); 27 | } 28 | } 29 | 30 | return 0; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /C/35_expand02/temp_monitor.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #define LedRed 0 12 | #define LedGreen 1 13 | #define LedBlue 2 14 | 15 | #define PCF 120 16 | 17 | #define Beep 3 18 | 19 | #define BUFSIZE 128 20 | 21 | typedef unsigned char uchar; 22 | typedef unsigned int uint; 23 | 24 | static int sys_state = 1; 25 | 26 | static int AIN0 = PCF + 0; 27 | static int AIN1 = PCF + 1; 28 | static int AIN2 = PCF + 2; 29 | 30 | void beepInit(void) 31 | { 32 | pinMode(Beep, OUTPUT); 33 | } 34 | 35 | void beep_on(void) 36 | { 37 | digitalWrite(Beep, LOW); 38 | } 39 | 40 | void beep_off(void) 41 | { 42 | digitalWrite(Beep, HIGH); 43 | } 44 | 45 | void beepCtrl(int t) 46 | { 47 | beep_on(); 48 | delay(t); 49 | beep_off(); 50 | delay(t); 51 | } 52 | 53 | float tempRead(void) 54 | { 55 | float temp; 56 | int i, j; 57 | int fd; 58 | int ret; 59 | 60 | char buf[BUFSIZE]; 61 | char tempBuf[5]; 62 | 63 | fd = open("/sys/bus/w1/devices/28-031590bf4aff/w1_slave", O_RDONLY); 64 | 65 | if(-1 == fd){ 66 | perror("open device file error"); 67 | return 1; 68 | } 69 | 70 | while(1){ 71 | ret = read(fd, buf, BUFSIZE); 72 | if(0 == ret){ 73 | break; 74 | } 75 | if(-1 == ret){ 76 | if(errno == EINTR){ 77 | continue; 78 | } 79 | perror("read()"); 80 | close(fd); 81 | return 1; 82 | } 83 | } 84 | 85 | for(i=0;i= 250){ 126 | tmp = 1; 127 | } 128 | if(xVal <= 5){ 129 | tmp = 2; 130 | } 131 | 132 | yVal = analogRead(AIN0); 133 | if(yVal >= 250){ 134 | tmp = 4; 135 | } 136 | if(yVal <= 5){ 137 | tmp = 3; 138 | } 139 | 140 | zVal = analogRead(AIN2); 141 | if(zVal <= 5){ 142 | tmp = 5; 143 | } 144 | 145 | if(xVal-127<30 && xVal-127>-30 && yVal-127<30 && yVal-127>-30 && zVal>127){ 146 | tmp = 0; 147 | } 148 | // Uncomment this line to see the value of joystick. 149 | // printf("x = %d, y = %d, z = %d",xVal,yVal,zVal); 150 | return tmp; 151 | } 152 | 153 | int main(void) 154 | { 155 | int i; 156 | uchar joyStick = 0; 157 | float temp; 158 | uchar low = 26, high = 30; 159 | 160 | if(wiringPiSetup() == -1){ 161 | printf("setup wiringPi failed !"); 162 | return 1; 163 | } 164 | 165 | pcf8591Setup(PCF, 0x48); 166 | ledInit(); 167 | beepInit(); 168 | 169 | printf("System is running...\n"); 170 | 171 | while(1){ 172 | flag: 173 | joyStick = get_joyStick_state(); 174 | 175 | switch(joyStick){ 176 | case 1 : --low; break; 177 | case 2 : ++low; break; 178 | case 3 : ++high; break; 179 | case 4 : --high; break; 180 | case 5 : joystickquit(); break; 181 | default: break; 182 | } 183 | 184 | if(low >= high){ 185 | printf("Error, lower limit should be less than upper limit\n"); 186 | goto flag; 187 | } 188 | 189 | printf("The lower limit of temperature : %d\n", low); 190 | printf("The upper limit of temperature : %d\n", high); 191 | 192 | temp = tempRead(); 193 | 194 | printf("Current temperature : %0.3f\n", temp); 195 | 196 | if(temp < low){ 197 | ledCtrl(LedBlue, LOW); 198 | ledCtrl(LedRed, HIGH); 199 | ledCtrl(LedGreen, LOW); 200 | for(i = 0;i < 3; i++){ 201 | beepCtrl(400); 202 | } 203 | } 204 | if(temp >= low && temp < high){ 205 | ledCtrl(LedBlue, HIGH); 206 | ledCtrl(LedRed, HIGH); 207 | ledCtrl(LedGreen, LOW); 208 | } 209 | if(temp >= high){ 210 | ledCtrl(LedBlue, HIGH); 211 | ledCtrl(LedRed, LOW); 212 | ledCtrl(LedGreen, HIGH); 213 | for(i = 0;i < 3; i++){ 214 | beepCtrl(80); 215 | } 216 | } 217 | 218 | if(sys_state == 0){ 219 | ledCtrl(LedRed, LOW); 220 | ledCtrl(LedGreen, LOW); 221 | ledCtrl(LedBlue, LOW); 222 | beep_off(); 223 | printf("SyStem will be off...\n"); 224 | break; 225 | } 226 | } 227 | return 0; 228 | } 229 | -------------------------------------------------------------------------------- /C/README.md: -------------------------------------------------------------------------------- 1 | # Sunfounder Sensor Kit C code for Raspberry Pi 2 | 3 | website: 4 | www.sunfounder.com 5 | 6 | E-mail: 7 | support@sunfounder.com 8 | 9 | -------------------------------------------------------------------------------- /C/cleanout.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/bash 2 | # Discription: 3 | # This program is to clean all the a.out file 4 | # 5 | # Virsion: 1.0 6 | # Cavon 2015/05/20 First Realease 7 | 8 | for i in * 9 | do 10 | git rm -f ./$i/a.out 11 | done 12 | rm log 13 | -------------------------------------------------------------------------------- /Fritzing/01_dual_color_led.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/01_dual_color_led.fzz -------------------------------------------------------------------------------- /Fritzing/02_RGB_LED.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/02_RGB_LED.fzz -------------------------------------------------------------------------------- /Fritzing/03_AutoFlashLED.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/03_AutoFlashLED.fzz -------------------------------------------------------------------------------- /Fritzing/04_Relay module.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/04_Relay module.fzz -------------------------------------------------------------------------------- /Fritzing/05_Laser.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/05_Laser.fzz -------------------------------------------------------------------------------- /Fritzing/06_Button.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/06_Button.fzz -------------------------------------------------------------------------------- /Fritzing/07_Tilt-Switch.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/07_Tilt-Switch.fzz -------------------------------------------------------------------------------- /Fritzing/08_Vibration Switch.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/08_Vibration Switch.fzz -------------------------------------------------------------------------------- /Fritzing/09_IR Receiver.svg.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/09_IR Receiver.svg.fzz -------------------------------------------------------------------------------- /Fritzing/10_Active Buzzer.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/10_Active Buzzer.fzz -------------------------------------------------------------------------------- /Fritzing/10_Passive Buzzer.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/10_Passive Buzzer.fzz -------------------------------------------------------------------------------- /Fritzing/11_Reed switch.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/11_Reed switch.fzz -------------------------------------------------------------------------------- /Fritzing/12_Photo interrupter.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/12_Photo interrupter.fzz -------------------------------------------------------------------------------- /Fritzing/13_PCF8591.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/13_PCF8591.fzz -------------------------------------------------------------------------------- /Fritzing/14_Rain Detection.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/14_Rain Detection.fzz -------------------------------------------------------------------------------- /Fritzing/15_JoyStick_PS2.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/15_JoyStick_PS2.fzz -------------------------------------------------------------------------------- /Fritzing/16_Potentiometer.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/16_Potentiometer.fzz -------------------------------------------------------------------------------- /Fritzing/17_Analog_Hall_Switch.svg.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/17_Analog_Hall_Switch.svg.fzz -------------------------------------------------------------------------------- /Fritzing/17_Switch_Hall.svg.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/17_Switch_Hall.svg.fzz -------------------------------------------------------------------------------- /Fritzing/18_Analog_Temperature.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/18_Analog_Temperature.fzz -------------------------------------------------------------------------------- /Fritzing/18_Thermistor.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/18_Thermistor.fzz -------------------------------------------------------------------------------- /Fritzing/19_Sound Sensor.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/19_Sound Sensor.fzz -------------------------------------------------------------------------------- /Fritzing/20_Photoresistor.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/20_Photoresistor.fzz -------------------------------------------------------------------------------- /Fritzing/21_Flame_Sensor.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/21_Flame_Sensor.fzz -------------------------------------------------------------------------------- /Fritzing/22_Gas Sensor.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/22_Gas Sensor.fzz -------------------------------------------------------------------------------- /Fritzing/23_IR remote control.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/23_IR remote control.fzz -------------------------------------------------------------------------------- /Fritzing/24_Touch_Switch.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/24_Touch_Switch.fzz -------------------------------------------------------------------------------- /Fritzing/25_Ultrasonic_Ranging.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/25_Ultrasonic_Ranging.fzz -------------------------------------------------------------------------------- /Fritzing/26_DS18B20.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/26_DS18B20.fzz -------------------------------------------------------------------------------- /Fritzing/27_Rotary Encode.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/27_Rotary Encode.fzz -------------------------------------------------------------------------------- /Fritzing/28_Humiture.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/28_Humiture.fzz -------------------------------------------------------------------------------- /Fritzing/29_IR Obstacle.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/29_IR Obstacle.fzz -------------------------------------------------------------------------------- /Fritzing/30_I2C LCD1602.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/30_I2C LCD1602.fzz -------------------------------------------------------------------------------- /Fritzing/31_Barometer.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/31_Barometer.fzz -------------------------------------------------------------------------------- /Fritzing/32_MPU6050.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/32_MPU6050.fzz -------------------------------------------------------------------------------- /Fritzing/33_DS1302.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/33_DS1302.fzz -------------------------------------------------------------------------------- /Fritzing/34_Tracking.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/34_Tracking.fzz -------------------------------------------------------------------------------- /Fritzing/35_Expand02.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Fritzing/35_Expand02.fzz -------------------------------------------------------------------------------- /Python/01_dule_color_led.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | colors = [0xFF00, 0x00FF, 0x0FF0, 0xF00F] 6 | pins = (11, 12) # pins is a dict 7 | 8 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 9 | GPIO.setup(pins, GPIO.OUT) # Set pins' mode is output 10 | GPIO.output(pins, GPIO.LOW) # Set pins to LOW(0V) to off led 11 | 12 | p_R = GPIO.PWM(pins[0], 2000) # set Frequece to 2KHz 13 | p_G = GPIO.PWM(pins[1], 2000) 14 | 15 | p_R.start(0) # Initial duty Cycle = 0(leds off) 16 | p_G.start(0) 17 | 18 | def map(x, in_min, in_max, out_min, out_max): 19 | return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min 20 | 21 | def setColor(col): # For example : col = 0x1122 22 | R_val = col >> 8 23 | G_val = col & 0x00FF 24 | 25 | R_val = map(R_val, 0, 255, 0, 100) 26 | G_val = map(G_val, 0, 255, 0, 100) 27 | 28 | p_R.ChangeDutyCycle(R_val) # Change duty cycle 29 | p_G.ChangeDutyCycle(G_val) 30 | 31 | def loop(): 32 | while True: 33 | for col in colors: 34 | setColor(col) 35 | time.sleep(0.5) 36 | 37 | def destroy(): 38 | p_R.stop() 39 | p_G.stop() 40 | GPIO.output(pins, GPIO.LOW) # Turn off all leds 41 | GPIO.cleanup() 42 | 43 | if __name__ == "__main__": 44 | try: 45 | loop() 46 | except KeyboardInterrupt: 47 | destroy() 48 | -------------------------------------------------------------------------------- /Python/02_rgb_led.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | colors = [0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0x00FFFF] 6 | R = 11 7 | G = 12 8 | B = 13 9 | 10 | def setup(Rpin, Gpin, Bpin): 11 | global pins 12 | global p_R, p_G, p_B 13 | pins = {'pin_R': Rpin, 'pin_G': Gpin, 'pin_B': Bpin} 14 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 15 | for i in pins: 16 | GPIO.setup(pins[i], GPIO.OUT) # Set pins' mode is output 17 | GPIO.output(pins[i], GPIO.HIGH) # Set pins to high(+3.3V) to off led 18 | 19 | p_R = GPIO.PWM(pins['pin_R'], 2000) # set Frequece to 2KHz 20 | p_G = GPIO.PWM(pins['pin_G'], 1999) 21 | p_B = GPIO.PWM(pins['pin_B'], 5000) 22 | 23 | p_R.start(100) # Initial duty Cycle = 0(leds off) 24 | p_G.start(100) 25 | p_B.start(100) 26 | 27 | def map(x, in_min, in_max, out_min, out_max): 28 | return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min 29 | 30 | def off(): 31 | GPIO.setmode(GPIO.BOARD) 32 | for i in pins: 33 | GPIO.setup(pins[i], GPIO.OUT) # Set pins' mode is output 34 | GPIO.output(pins[i], GPIO.HIGH) # Turn off all leds 35 | 36 | def setColor(col): # For example : col = 0x112233 37 | R_val = (col & 0xff0000) >> 16 38 | G_val = (col & 0x00ff00) >> 8 39 | B_val = (col & 0x0000ff) >> 0 40 | 41 | R_val = map(R_val, 0, 255, 0, 100) 42 | G_val = map(G_val, 0, 255, 0, 100) 43 | B_val = map(B_val, 0, 255, 0, 100) 44 | 45 | p_R.ChangeDutyCycle(100-R_val) # Change duty cycle 46 | p_G.ChangeDutyCycle(100-G_val) 47 | p_B.ChangeDutyCycle(100-B_val) 48 | 49 | def loop(): 50 | while True: 51 | for col in colors: 52 | setColor(col) 53 | time.sleep(1) 54 | 55 | def destroy(): 56 | p_R.stop() 57 | p_G.stop() 58 | p_B.stop() 59 | off() 60 | GPIO.cleanup() 61 | 62 | if __name__ == "__main__": 63 | try: 64 | setup(R, G, B) 65 | loop() 66 | except KeyboardInterrupt: 67 | destroy() 68 | -------------------------------------------------------------------------------- /Python/04_relay.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | RelayPin = 11 # pin11 6 | 7 | def setup(): 8 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 9 | GPIO.setup(RelayPin, GPIO.OUT) 10 | GPIO.output(RelayPin, GPIO.HIGH) 11 | 12 | def loop(): 13 | while True: 14 | #'...relayd on' 15 | GPIO.output(RelayPin, GPIO.LOW) 16 | time.sleep(0.5) 17 | #'relay off...' 18 | GPIO.output(RelayPin, GPIO.HIGH) 19 | time.sleep(0.5) 20 | 21 | def destroy(): 22 | GPIO.output(RelayPin, GPIO.HIGH) 23 | GPIO.cleanup() # Release resource 24 | 25 | if __name__ == '__main__': # Program start from here 26 | setup() 27 | try: 28 | loop() 29 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 30 | destroy() 31 | 32 | -------------------------------------------------------------------------------- /Python/05_laser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | ##################################################### 3 | # 4 | # DO NOT WATCH THE LASER DERECTELY IN THE EYE! 5 | # 6 | ##################################################### 7 | import RPi.GPIO as GPIO 8 | import time 9 | 10 | LedPin = 11 # pin11 11 | 12 | def setup(): 13 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 14 | GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output 15 | GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led 16 | 17 | def loop(): 18 | while True: 19 | #'...Laser on' 20 | GPIO.output(LedPin, GPIO.LOW) # led on 21 | time.sleep(0.5) 22 | #'Laser off...' 23 | GPIO.output(LedPin, GPIO.HIGH) # led off 24 | time.sleep(0.5) 25 | 26 | def destroy(): 27 | GPIO.output(LedPin, GPIO.HIGH) # led off 28 | GPIO.cleanup() # Release resource 29 | 30 | if __name__ == '__main__': # Program start from here 31 | setup() 32 | try: 33 | loop() 34 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 35 | destroy() 36 | 37 | -------------------------------------------------------------------------------- /Python/06_button.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | 4 | BtnPin = 11 5 | Gpin = 12 6 | Rpin = 13 7 | 8 | def setup(): 9 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 10 | GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output 11 | GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output 12 | GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode is input, and pull up to high level(3.3V) 13 | GPIO.add_event_detect(BtnPin, GPIO.BOTH, callback=detect, bouncetime=200) 14 | 15 | def Led(x): 16 | if x == 0: 17 | GPIO.output(Rpin, 1) 18 | GPIO.output(Gpin, 0) 19 | if x == 1: 20 | GPIO.output(Rpin, 0) 21 | GPIO.output(Gpin, 1) 22 | 23 | def detect(chn): 24 | Led(GPIO.input(BtnPin)) 25 | 26 | def loop(): 27 | while True: 28 | pass 29 | 30 | def destroy(): 31 | GPIO.output(Gpin, GPIO.HIGH) # Green led off 32 | GPIO.output(Rpin, GPIO.HIGH) # Red led off 33 | GPIO.cleanup() # Release resource 34 | 35 | if __name__ == '__main__': # Program start from here 36 | setup() 37 | try: 38 | loop() 39 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 40 | destroy() 41 | 42 | -------------------------------------------------------------------------------- /Python/07_tilt_switch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | 4 | TiltPin = 11 5 | Gpin = 13 6 | Rpin = 12 7 | 8 | def setup(): 9 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 10 | GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output 11 | GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output 12 | GPIO.setup(TiltPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode is input, and pull up to high level(3.3V) 13 | GPIO.add_event_detect(TiltPin, GPIO.BOTH, callback=detect, bouncetime=200) 14 | 15 | def Led(x): 16 | if x == 0: 17 | GPIO.output(Rpin, 1) 18 | GPIO.output(Gpin, 0) 19 | if x == 1: 20 | GPIO.output(Rpin, 0) 21 | GPIO.output(Gpin, 1) 22 | 23 | def detect(chn): 24 | Led(GPIO.input(TiltPin)) 25 | 26 | def loop(): 27 | while True: 28 | pass 29 | 30 | def destroy(): 31 | GPIO.output(Gpin, GPIO.HIGH) # Green led off 32 | GPIO.output(Rpin, GPIO.HIGH) # Red led off 33 | GPIO.cleanup() # Release resource 34 | 35 | if __name__ == '__main__': # Program start from here 36 | setup() 37 | try: 38 | loop() 39 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 40 | destroy() 41 | 42 | -------------------------------------------------------------------------------- /Python/08_mecury_switch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | 4 | MPin = 11 5 | Gpin = 12 6 | Rpin = 13 7 | 8 | def setup(): 9 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 10 | GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output 11 | GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output 12 | GPIO.setup(MPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode is input, and pull up to high level(3.3V) 13 | GPIO.add_event_detect(MPin, GPIO.BOTH, callback=detect, bouncetime=200) 14 | 15 | def Led(x): 16 | if x == 0: 17 | GPIO.output(Rpin, 1) 18 | GPIO.output(Gpin, 0) 19 | if x == 1: 20 | GPIO.output(Rpin, 0) 21 | GPIO.output(Gpin, 1) 22 | 23 | def Print(x): 24 | if x == 0: 25 | print ' ********************' 26 | print ' * Mecury Tilt! *' 27 | print ' ********************' 28 | 29 | def detect(chn): 30 | Led(GPIO.input(MPin)) 31 | Print(GPIO.input(MPin)) 32 | 33 | def loop(): 34 | while True: 35 | pass 36 | 37 | def destroy(): 38 | GPIO.output(Gpin, GPIO.HIGH) # Green led off 39 | GPIO.output(Rpin, GPIO.HIGH) # Red led off 40 | GPIO.cleanup() # Release resource 41 | 42 | if __name__ == '__main__': # Program start from here 43 | setup() 44 | try: 45 | loop() 46 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 47 | destroy() 48 | 49 | -------------------------------------------------------------------------------- /Python/08_vibration_switch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | VibratePin = 11 6 | Gpin = 13 7 | Rpin = 12 8 | 9 | tmp = 0 10 | 11 | def setup(): 12 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 13 | GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output 14 | GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output 15 | GPIO.setup(VibratePin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode is input, and pull up to high level(3.3V) 16 | 17 | def Led(x): 18 | if x == 0: 19 | GPIO.output(Rpin, 1) 20 | GPIO.output(Gpin, 0) 21 | if x == 1: 22 | GPIO.output(Rpin, 0) 23 | GPIO.output(Gpin, 1) 24 | 25 | def loop(): 26 | state = 0 27 | while True: 28 | if GPIO.input(VibratePin)==0: 29 | state = state + 1 30 | if state > 1: 31 | state = 0 32 | Led(state) 33 | time.sleep(1) 34 | 35 | def destroy(): 36 | GPIO.output(Gpin, GPIO.HIGH) # Green led off 37 | GPIO.output(Rpin, GPIO.HIGH) # Red led off 38 | GPIO.cleanup() # Release resource 39 | 40 | if __name__ == '__main__': # Program start from here 41 | setup() 42 | try: 43 | loop() 44 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 45 | destroy() 46 | 47 | -------------------------------------------------------------------------------- /Python/09_ir_receiver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | 4 | IrPin = 11 5 | count = 0 6 | 7 | def setup(): 8 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 9 | GPIO.setup(IrPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) 10 | 11 | def cnt(ev=None): 12 | global count 13 | count += 1 14 | print ('Received infrared. cnt = ', count) 15 | 16 | def loop(): 17 | GPIO.add_event_detect(IrPin, GPIO.FALLING, callback=cnt) # wait for falling 18 | while True: 19 | pass # Don't do anything 20 | 21 | def destroy(): 22 | GPIO.cleanup() # Release resource 23 | 24 | if __name__ == '__main__': # Program start from here 25 | setup() 26 | try: 27 | loop() 28 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 29 | destroy() 30 | 31 | -------------------------------------------------------------------------------- /Python/10_active_buzzer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | Buzzer = 11 # pin11 6 | 7 | def setup(pin): 8 | global BuzzerPin 9 | BuzzerPin = pin 10 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 11 | GPIO.setup(BuzzerPin, GPIO.OUT) 12 | GPIO.output(BuzzerPin, GPIO.HIGH) 13 | 14 | def on(): 15 | GPIO.output(BuzzerPin, GPIO.LOW) 16 | 17 | def off(): 18 | GPIO.output(BuzzerPin, GPIO.HIGH) 19 | 20 | def beep(x): 21 | on() 22 | time.sleep(x) 23 | off() 24 | time.sleep(x) 25 | 26 | def loop(): 27 | while True: 28 | beep(0.5) 29 | 30 | def destroy(): 31 | GPIO.output(BuzzerPin, GPIO.HIGH) 32 | GPIO.cleanup() # Release resource 33 | 34 | if __name__ == '__main__': # Program start from here 35 | setup(Buzzer) 36 | try: 37 | loop() 38 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 39 | destroy() 40 | 41 | -------------------------------------------------------------------------------- /Python/10_passive_buzzer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #--------------------------------------------------- 3 | # 4 | # This is a program for Passive Buzzer Module 5 | # It will play simple songs. 6 | # You could try to make songs by youselves! 7 | # 8 | # Passive buzzer Pi 9 | # VCC ----------------- 3.3V 10 | # GND ------------------ GND 11 | # SIG ---------------- Pin 11 12 | # 13 | #--------------------------------------------------- 14 | 15 | import RPi.GPIO as GPIO 16 | import time 17 | 18 | Buzzer = 11 19 | 20 | CL = [0, 131, 147, 165, 175, 196, 211, 248] # Frequency of Low C notes 21 | 22 | CM = [0, 262, 294, 330, 350, 393, 441, 495] # Frequency of Middle C notes 23 | 24 | CH = [0, 525, 589, 661, 700, 786, 882, 990] # Frequency of High C notes 25 | 26 | song_1 = [ CM[3], CM[5], CM[6], CM[3], CM[2], CM[3], CM[5], CM[6], # Notes of song1 27 | CH[1], CM[6], CM[5], CM[1], CM[3], CM[2], CM[2], CM[3], 28 | CM[5], CM[2], CM[3], CM[3], CL[6], CL[6], CL[6], CM[1], 29 | CM[2], CM[3], CM[2], CL[7], CL[6], CM[1], CL[5] ] 30 | 31 | beat_1 = [ 1, 1, 3, 1, 1, 3, 1, 1, # Beats of song 1, 1 means 1/8 beats 32 | 1, 1, 1, 1, 1, 1, 3, 1, 33 | 1, 3, 1, 1, 1, 1, 1, 1, 34 | 1, 2, 1, 1, 1, 1, 1, 1, 35 | 1, 1, 3 ] 36 | 37 | song_2 = [ CM[1], CM[1], CM[1], CL[5], CM[3], CM[3], CM[3], CM[1], # Notes of song2 38 | CM[1], CM[3], CM[5], CM[5], CM[4], CM[3], CM[2], CM[2], 39 | CM[3], CM[4], CM[4], CM[3], CM[2], CM[3], CM[1], CM[1], 40 | CM[3], CM[2], CL[5], CL[7], CM[2], CM[1] ] 41 | 42 | beat_2 = [ 1, 1, 2, 2, 1, 1, 2, 2, # Beats of song 2, 1 means 1/8 beats 43 | 1, 1, 2, 2, 1, 1, 3, 1, 44 | 1, 2, 2, 1, 1, 2, 2, 1, 45 | 1, 2, 2, 1, 1, 3 ] 46 | 47 | def setup(): 48 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 49 | GPIO.setup(Buzzer, GPIO.OUT) # Set pins' mode is output 50 | global Buzz # Assign a global variable to replace GPIO.PWM 51 | Buzz = GPIO.PWM(Buzzer, 440) # 440 is initial frequency. 52 | Buzz.start(50) # Start Buzzer pin with 50% duty ration 53 | 54 | def loop(): 55 | while True: 56 | # Playing song 1... 57 | for i in range(1, len(song_1)): # Play song 1 58 | Buzz.ChangeFrequency(song_1[i]) # Change the frequency along the song note 59 | time.sleep(beat_1[i] * 0.5) # delay a note for beat * 0.5s 60 | time.sleep(1) # Wait a second for next song. 61 | 62 | # Playing song 2... 63 | for i in range(1, len(song_2)): # Play song 1 64 | Buzz.ChangeFrequency(song_2[i]) # Change the frequency along the song note 65 | time.sleep(beat_2[i] * 0.5) # delay a note for beat * 0.5s 66 | 67 | def destory(): 68 | Buzz.stop() # Stop the buzzer 69 | GPIO.output(Buzzer, 1) # Set Buzzer pin to High 70 | GPIO.cleanup() # Release resource 71 | 72 | if __name__ == '__main__': # Program start from here 73 | setup() 74 | try: 75 | loop() 76 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 77 | destory() 78 | -------------------------------------------------------------------------------- /Python/11_reed_switch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | 4 | ReedPin = 11 5 | Gpin = 13 6 | Rpin = 12 7 | 8 | def setup(): 9 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 10 | GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output 11 | GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output 12 | GPIO.setup(ReedPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode is input, and pull up to high level(3.3V) 13 | GPIO.add_event_detect(ReedPin, GPIO.BOTH, callback=detect, bouncetime=200) 14 | 15 | def Led(x): 16 | if x == 0: 17 | GPIO.output(Rpin, 1) 18 | GPIO.output(Gpin, 0) 19 | if x == 1: 20 | GPIO.output(Rpin, 0) 21 | GPIO.output(Gpin, 1) 22 | 23 | def detect(chn): 24 | Led(GPIO.input(ReedPin)) 25 | 26 | def loop(): 27 | while True: 28 | pass 29 | 30 | def destroy(): 31 | GPIO.output(Gpin, GPIO.HIGH) # Green led off 32 | GPIO.output(Rpin, GPIO.HIGH) # Red led off 33 | GPIO.cleanup() # Release resource 34 | 35 | if __name__ == '__main__': # Program start from here 36 | setup() 37 | try: 38 | loop() 39 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 40 | destroy() 41 | 42 | -------------------------------------------------------------------------------- /Python/12_photo_interrupter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | 4 | PIPin = 11 5 | Gpin = 13 6 | Rpin = 12 7 | 8 | def setup(): 9 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 10 | GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output 11 | GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output 12 | GPIO.setup(PIPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode is input, and pull up to high level(3.3V) 13 | GPIO.add_event_detect(PIPin, GPIO.BOTH, callback=detect, bouncetime=200) 14 | 15 | def Led(x): 16 | if x == 0: 17 | GPIO.output(Rpin, 1) 18 | GPIO.output(Gpin, 0) 19 | if x == 1: 20 | GPIO.output(Rpin, 0) 21 | GPIO.output(Gpin, 1) 22 | print ('Light was blocked') 23 | 24 | def detect(chn): 25 | Led(GPIO.input(PIPin)) 26 | 27 | def loop(): 28 | while True: 29 | pass 30 | 31 | def destroy(): 32 | GPIO.output(Gpin, GPIO.HIGH) # Green led off 33 | GPIO.output(Rpin, GPIO.HIGH) # Red led off 34 | GPIO.cleanup() # Release resource 35 | 36 | if __name__ == '__main__': # Program start from here 37 | setup() 38 | try: 39 | loop() 40 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 41 | destroy() 42 | 43 | -------------------------------------------------------------------------------- /Python/13_pcf8591.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import PCF8591 as ADC 3 | 4 | def setup(): 5 | ADC.setup(0x48) 6 | 7 | def loop(): 8 | while True: 9 | print (ADC.read(0)) 10 | ADC.write(ADC.read(0)) 11 | 12 | def destroy(): 13 | ADC.write(0) 14 | 15 | if __name__ == "__main__": 16 | try: 17 | setup() 18 | loop() 19 | except KeyboardInterrupt: 20 | destroy() 21 | -------------------------------------------------------------------------------- /Python/14_rain_detector.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import PCF8591 as ADC 3 | import RPi.GPIO as GPIO 4 | import time 5 | import math 6 | 7 | DO = 17 8 | GPIO.setmode(GPIO.BCM) 9 | 10 | def setup(): 11 | ADC.setup(0x48) 12 | GPIO.setup(DO, GPIO.IN) 13 | 14 | def Print(x): 15 | if x == 1: 16 | print ('') 17 | print (' ***************') 18 | print (' * Not raining *') 19 | print (' ***************') 20 | print ('') 21 | if x == 0: 22 | print ('') 23 | print (' *************') 24 | print (' * Raining!! *') 25 | print (' *************') 26 | print ('') 27 | 28 | def loop(): 29 | status = 1 30 | while True: 31 | print (ADC.read(0)) 32 | 33 | tmp = GPIO.input(DO); 34 | if tmp != status: 35 | Print(tmp) 36 | status = tmp 37 | 38 | time.sleep(0.2) 39 | 40 | if __name__ == '__main__': 41 | try: 42 | setup() 43 | loop() 44 | except KeyboardInterrupt: 45 | pass 46 | -------------------------------------------------------------------------------- /Python/15_joystick_PS2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #------------------------------------------------------ 3 | # 4 | # This is a program for JoystickPS2 Module. 5 | # 6 | # This program depend on PCF8591 ADC chip. Follow 7 | # the instruction book to connect the module and 8 | # ADC0832 to your Raspberry Pi. 9 | # 10 | #------------------------------------------------------ 11 | import PCF8591 as ADC 12 | import time 13 | 14 | def setup(): 15 | ADC.setup(0x48) # Setup PCF8591 16 | global state 17 | 18 | def direction(): #get joystick result 19 | state = ['home', 'up', 'down', 'left', 'right', 'pressed'] 20 | i = 0 21 | if ADC.read(0) <= 30: 22 | i = 1 #up 23 | if ADC.read(0) >= 225: 24 | i = 2 #down 25 | 26 | if ADC.read(1) >= 225: 27 | i = 3 #left 28 | if ADC.read(1) <= 30: 29 | i = 4 #right 30 | 31 | if ADC.read(2) <= 30: 32 | i = 5 # Button pressed 33 | 34 | if ADC.read(0) - 125 < 15 and ADC.read(0) - 125 > -15 and ADC.read(1) - 125 < 15 and ADC.read(1) - 125 > -15 and ADC.read(2) == 255: 35 | i = 0 36 | 37 | return state[i] 38 | 39 | def loop(): 40 | status = '' 41 | while True: 42 | tmp = direction() 43 | if tmp != None and tmp != status: 44 | print (tmp) 45 | status = tmp 46 | 47 | def destroy(): 48 | pass 49 | 50 | if __name__ == '__main__': # Program start from here 51 | setup() 52 | try: 53 | loop() 54 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 55 | destroy() 56 | -------------------------------------------------------------------------------- /Python/16_potentiometer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import PCF8591 as ADC 3 | import time 4 | 5 | def setup(): 6 | ADC.setup(0x48) 7 | 8 | def loop(): 9 | status = 1 10 | while True: 11 | print ('Value:', ADC.read(0)) 12 | Value = ADC.read(0) 13 | outvalue = map(Value,0,255,120,255) 14 | ADC.write(outvalue) 15 | time.sleep(0.2) 16 | def destroy(): 17 | ADC.write(0) 18 | 19 | def map(x, in_min, in_max, out_min, out_max): 20 | '''To map the value from arange to another''' 21 | return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min 22 | 23 | if __name__ == '__main__': 24 | try: 25 | setup() 26 | loop() 27 | except KeyboardInterrupt: 28 | destroy() 29 | -------------------------------------------------------------------------------- /Python/17_analog_hall_switch.py: -------------------------------------------------------------------------------- 1 | #/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | import PCF8591 as ADC 4 | import time 5 | 6 | def setup(): 7 | ADC.setup(0x48) 8 | 9 | def Print(x): 10 | if x == 0: 11 | print ('') 12 | print ('*************') 13 | print ('* No Magnet *') 14 | print ('*************') 15 | print ('') 16 | if x == 1: 17 | print ('') 18 | print ('****************') 19 | print ('* Magnet North *') 20 | print ('****************') 21 | print ('') 22 | if x == -1: 23 | print ('') 24 | print ('****************') 25 | print ('* Magnet South *') 26 | print ('****************') 27 | print ('') 28 | 29 | def loop(): 30 | status = 0 31 | while True: 32 | res = ADC.read(0) 33 | print ('Current intensity of magnetic field : ', res) 34 | if res - 133 < 5 and res - 133 > -5: 35 | tmp = 0 36 | if res < 128: 37 | tmp = -1 38 | if res > 138: 39 | tmp = 1 40 | if tmp != status: 41 | Print(tmp) 42 | status = tmp 43 | time.sleep(0.2) 44 | 45 | if __name__ == '__main__': 46 | setup() 47 | loop() 48 | 49 | -------------------------------------------------------------------------------- /Python/17_switch_hall.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | 4 | HallPin = 11 5 | Gpin = 13 6 | Rpin = 12 7 | 8 | def setup(): 9 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 10 | GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output 11 | GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output 12 | GPIO.setup(HallPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode is input, and pull up to high level(3.3V) 13 | GPIO.add_event_detect(HallPin, GPIO.BOTH, callback=detect, bouncetime=200) 14 | 15 | def Led(x): 16 | if x == 0: 17 | GPIO.output(Rpin, 1) 18 | GPIO.output(Gpin, 0) 19 | if x == 1: 20 | GPIO.output(Rpin, 0) 21 | GPIO.output(Gpin, 1) 22 | 23 | def Print(x): 24 | if x == 0: 25 | print (' ***********************************') 26 | print (' * Detected magnetic materials *') 27 | print (' ***********************************') 28 | 29 | def detect(chn): 30 | Led(GPIO.input(HallPin)) 31 | Print(GPIO.input(HallPin)) 32 | 33 | def loop(): 34 | while True: 35 | pass 36 | 37 | def destroy(): 38 | GPIO.output(Gpin, GPIO.HIGH) # Green led off 39 | GPIO.output(Rpin, GPIO.HIGH) # Red led off 40 | GPIO.cleanup() # Release resource 41 | 42 | if __name__ == '__main__': # Program start from here 43 | setup() 44 | try: 45 | loop() 46 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 47 | destroy() 48 | 49 | -------------------------------------------------------------------------------- /Python/18_thermistor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import PCF8591 as ADC 3 | import RPi.GPIO as GPIO 4 | import time 5 | import math 6 | 7 | DO = 17 8 | GPIO.setmode(GPIO.BCM) 9 | 10 | def setup(): 11 | ADC.setup(0x48) 12 | GPIO.setup(DO, GPIO.IN) 13 | 14 | def Print(x): 15 | if x == 1: 16 | print ('') 17 | print ('***********') 18 | print ('* Better~ *') 19 | print ('***********') 20 | print ('') 21 | if x == 0: 22 | print ('') 23 | print ('************') 24 | print ('* Too Hot! *') 25 | print ('************') 26 | print ('') 27 | 28 | def loop(): 29 | status = 1 30 | tmp = 1 31 | while True: 32 | analogVal = ADC.read(0) 33 | Vr = 5 * float(analogVal) / 255 34 | Rt = 10000 * Vr / (5 - Vr) 35 | temp = 1/(((math.log(Rt / 10000)) / 3950) + (1 / (273.15+25))) 36 | temp = temp - 273.15 37 | print ('temperature = ', temp, 'C') 38 | 39 | # For a threshold, uncomment one of the code for 40 | # which module you use. DONOT UNCOMMENT BOTH! 41 | ################################################# 42 | # 1. For Analog Temperature module(with DO) 43 | tmp = GPIO.input(DO) 44 | # 45 | # 2. For Thermister module(with sig pin) 46 | #if temp > 33: 47 | # tmp = 0 48 | #elif temp < 31: 49 | # tmp = 1 50 | ################################################# 51 | 52 | if tmp != status: 53 | Print(tmp) 54 | status = tmp 55 | 56 | time.sleep(0.2) 57 | 58 | if __name__ == '__main__': 59 | try: 60 | setup() 61 | loop() 62 | except KeyboardInterrupt: 63 | pass 64 | -------------------------------------------------------------------------------- /Python/19_sound_sensor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import PCF8591 as ADC 3 | import RPi.GPIO as GPIO 4 | import time 5 | 6 | GPIO.setmode(GPIO.BCM) 7 | 8 | def setup(): 9 | ADC.setup(0x48) 10 | 11 | def loop(): 12 | count = 0 13 | while True: 14 | voiceValue = ADC.read(0) 15 | if voiceValue: 16 | print ("Value:", voiceValue) 17 | if voiceValue < 50: 18 | print ("Voice In!! ", count) 19 | count += 1 20 | time.sleep(0.2) 21 | 22 | if __name__ == '__main__': 23 | try: 24 | setup() 25 | loop() 26 | except KeyboardInterrupt: 27 | pass 28 | -------------------------------------------------------------------------------- /Python/20_photoresistor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import PCF8591 as ADC 3 | import RPi.GPIO as GPIO 4 | import time 5 | 6 | DO = 17 7 | GPIO.setmode(GPIO.BCM) 8 | 9 | def setup(): 10 | ADC.setup(0x48) 11 | GPIO.setup(DO, GPIO.IN) 12 | 13 | 14 | def loop(): 15 | status = 1 16 | while True: 17 | print ('Value: ', ADC.read(0)) 18 | 19 | time.sleep(0.2) 20 | 21 | if __name__ == '__main__': 22 | try: 23 | setup() 24 | loop() 25 | except KeyboardInterrupt: 26 | pass 27 | -------------------------------------------------------------------------------- /Python/21_flame_sensor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import PCF8591 as ADC 3 | import RPi.GPIO as GPIO 4 | import time 5 | import math 6 | 7 | DO = 17 8 | GPIO.setmode(GPIO.BCM) 9 | 10 | def setup(): 11 | ADC.setup(0x48) 12 | GPIO.setup(DO, GPIO.IN) 13 | 14 | def Print(x): 15 | if x == 1: 16 | print ('') 17 | print (' *********') 18 | print (' * Safe~ *') 19 | print (' *********') 20 | print ('') 21 | if x == 0: 22 | print ('') 23 | print (' *********') 24 | print (' * Fire! *') 25 | print (' *********') 26 | print ('') 27 | 28 | def loop(): 29 | status = 1 30 | while True: 31 | print (ADC.read(0)) 32 | 33 | tmp = GPIO.input(DO); 34 | if tmp != status: 35 | Print(tmp) 36 | status = tmp 37 | 38 | time.sleep(0.2) 39 | 40 | if __name__ == '__main__': 41 | try: 42 | setup() 43 | loop() 44 | except KeyboardInterrupt: 45 | pass 46 | -------------------------------------------------------------------------------- /Python/22_gas_sensor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import PCF8591 as ADC 3 | import RPi.GPIO as GPIO 4 | import time 5 | import math 6 | 7 | DO = 17 8 | Buzz = 18 9 | GPIO.setmode(GPIO.BCM) 10 | 11 | def setup(): 12 | ADC.setup(0x48) 13 | GPIO.setup (DO, GPIO.IN) 14 | GPIO.setup (Buzz, GPIO.OUT) 15 | GPIO.output (Buzz, 1) 16 | 17 | def Print(x): 18 | if x == 1: 19 | print ('') 20 | print (' *********') 21 | print (' * Safe~ *') 22 | print (' *********') 23 | print ('') 24 | if x == 0: 25 | print ('') 26 | print (' ***************') 27 | print (' * Danger Gas! *') 28 | print (' ***************') 29 | print ('') 30 | 31 | def loop(): 32 | status = 1 33 | count = 0 34 | while True: 35 | print (ADC.read(0)) 36 | 37 | tmp = GPIO.input(DO) 38 | if tmp != status: 39 | Print(tmp) 40 | status = tmp 41 | if status == 0: 42 | count += 1 43 | if count % 2 == 0: 44 | GPIO.output(Buzz, 1) 45 | else: 46 | GPIO.output(Buzz, 0) 47 | else: 48 | GPIO.output(Buzz, 1) 49 | count = 0 50 | 51 | time.sleep(0.2) 52 | 53 | def destroy(): 54 | GPIO.output(Buzz, 1) 55 | GPIO.cleanup() 56 | 57 | if __name__ == '__main__': 58 | try: 59 | setup() 60 | loop() 61 | except KeyboardInterrupt: 62 | destroy() 63 | -------------------------------------------------------------------------------- /Python/23_ircontrol.py: -------------------------------------------------------------------------------- 1 | import lirc 2 | import time 3 | import RPi.GPIO as GPIO 4 | 5 | # client = lirc.Client() 6 | # print(client.version()) 7 | 8 | ''' RGB config''' 9 | Rpin = 17 10 | Gpin = 18 11 | Bpin = 27 12 | 13 | Lv = [0, 20, 90] # Light Level 14 | color = [0, 0, 0] 15 | 16 | p_R = None 17 | p_G = None 18 | p_B = None 19 | 20 | 21 | def setColor(color): 22 | # global p_R, p_G, p_B 23 | p_R.ChangeDutyCycle(100 - color[0]) # Change duty cycle 24 | p_G.ChangeDutyCycle(100 - color[1]) 25 | p_B.ChangeDutyCycle(100 - color[2]) 26 | 27 | def x(): 28 | setColor(color) 29 | 30 | def setup(): 31 | global p_R, p_G, p_B 32 | GPIO.setmode(GPIO.BCM) 33 | GPIO.setup(Rpin, GPIO.OUT) 34 | GPIO.setup(Gpin, GPIO.OUT) 35 | GPIO.setup(Bpin, GPIO.OUT) 36 | 37 | p_R = GPIO.PWM(Rpin, 2000) # Set Frequece to 2KHz 38 | p_G = GPIO.PWM(Gpin, 2000) 39 | p_B = GPIO.PWM(Bpin, 2000) 40 | 41 | p_R.start(100) 42 | p_G.start(100) 43 | p_B.start(100) 44 | 45 | def map(x, in_min, in_max, out_min, out_max): 46 | return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min 47 | 48 | def key_handler(key:str): 49 | global color 50 | 51 | if key == 'KEY_CHANNELDOWN': 52 | color[0] = Lv[0] 53 | print ('Red OFF') 54 | 55 | elif key == 'KEY_CHANNEL': 56 | color[0] = Lv[1] 57 | print ('Dark Red') 58 | 59 | elif key == 'KEY_CHANNELUP': 60 | color[0] = Lv[2] 61 | print ('Bright Red') 62 | 63 | elif key == 'KEY_PREVIOUS': 64 | color[1] = Lv[0] 65 | print ('Green OFF') 66 | 67 | elif key == 'KEY_NEXT': 68 | color[1] = Lv[1] 69 | print ('Dark Green') 70 | 71 | elif key == 'KEY_PLAYPAUSE': 72 | color[1] = Lv[2] 73 | print ('Bright Green') 74 | 75 | elif key == 'KEY_VOLUMEDOWN': 76 | color[2] = Lv[0] 77 | print ('Blue OFF') 78 | 79 | elif key == 'KEY_VOLUMEUP': 80 | color[2] = Lv[1] 81 | print ('Dark Blue') 82 | 83 | elif key == 'KEY_EQUAL': 84 | color[2] = Lv[2] 85 | print ('Bright BLUE') 86 | 87 | setColor(color) 88 | 89 | 90 | def loop(): 91 | with lirc.LircdConnection(timeout=5.0) as conn: 92 | conn.connect() 93 | while True: 94 | try: 95 | # print(conn.readline()) # 0000000000000001 00 KEY_CHANNELDOWN ./lircd.conf 96 | key = conn.readline().split(' ')[2] #KEY_CHANNELDOWN 97 | # print(key) 98 | key_handler(key) 99 | except TimeoutError: 100 | # print('Timeout') 101 | pass 102 | 103 | def destroy(): 104 | p_R.stop() 105 | p_G.stop() 106 | p_B.stop() 107 | GPIO.output(Rpin, GPIO.HIGH) # Turn off all leds 108 | GPIO.output(Gpin, GPIO.HIGH) 109 | GPIO.output(Bpin, GPIO.HIGH) 110 | GPIO.cleanup() 111 | 112 | 113 | if __name__ == "__main__": 114 | try: 115 | setup() 116 | loop() 117 | except KeyboardInterrupt: 118 | destroy() 119 | 120 | 121 | -------------------------------------------------------------------------------- /Python/24_touch_switch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | 4 | TouchPin = 11 5 | Gpin = 13 6 | Rpin = 12 7 | 8 | tmp = 0 9 | 10 | def setup(): 11 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 12 | GPIO.setup(Gpin, GPIO.OUT) # Set Green Led Pin mode to output 13 | GPIO.setup(Rpin, GPIO.OUT) # Set Red Led Pin mode to output 14 | GPIO.setup(TouchPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin's mode is input, and pull up to high level(3.3V) 15 | 16 | def Led(x): 17 | if x == 0: 18 | GPIO.output(Rpin, 1) 19 | GPIO.output(Gpin, 0) 20 | if x == 1: 21 | GPIO.output(Rpin, 0) 22 | GPIO.output(Gpin, 1) 23 | 24 | def Print(x): 25 | global tmp 26 | if x != tmp: 27 | if x == 0: 28 | print (' **********') 29 | print (' * ON *') 30 | print (' **********') 31 | 32 | if x == 1: 33 | print (' **********') 34 | print (' * OFF *') 35 | print (' **********') 36 | tmp = x 37 | 38 | def loop(): 39 | while True: 40 | Led(GPIO.input(TouchPin)) 41 | Print(GPIO.input(TouchPin)) 42 | 43 | def destroy(): 44 | GPIO.output(Gpin, GPIO.HIGH) # Green led off 45 | GPIO.output(Rpin, GPIO.HIGH) # Red led off 46 | GPIO.cleanup() # Release resource 47 | 48 | if __name__ == '__main__': # Program start from here 49 | setup() 50 | try: 51 | loop() 52 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 53 | destroy() 54 | 55 | -------------------------------------------------------------------------------- /Python/25_ultrasonic_ranging.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import RPi.GPIO as GPIO 4 | import time 5 | 6 | TRIG = 11 7 | ECHO = 12 8 | 9 | def setup(): 10 | GPIO.setmode(GPIO.BOARD) 11 | GPIO.setup(TRIG, GPIO.OUT) 12 | GPIO.setup(ECHO, GPIO.IN) 13 | 14 | def distance(): 15 | GPIO.output(TRIG, 0) 16 | time.sleep(0.000002) 17 | 18 | GPIO.output(TRIG, 1) 19 | time.sleep(0.00001) 20 | GPIO.output(TRIG, 0) 21 | 22 | 23 | while GPIO.input(ECHO) == 0: 24 | a = 0 25 | time1 = time.time() 26 | while GPIO.input(ECHO) == 1: 27 | a = 1 28 | time2 = time.time() 29 | 30 | during = time2 - time1 31 | return during * 340 / 2 * 100 32 | 33 | def loop(): 34 | while True: 35 | dis = distance() 36 | print (dis, 'cm') 37 | print ('') 38 | time.sleep(0.3) 39 | 40 | def destroy(): 41 | GPIO.cleanup() 42 | 43 | if __name__ == "__main__": 44 | setup() 45 | try: 46 | loop() 47 | except KeyboardInterrupt: 48 | destroy() 49 | -------------------------------------------------------------------------------- /Python/26_ds18b20.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #---------------------------------------------------------------- 3 | # Note: 4 | # ds18b20's data pin must be connected to pin7. 5 | # replace the 28-XXXXXXXXX as yours. 6 | #---------------------------------------------------------------- 7 | import os 8 | 9 | ds18b20 = '' 10 | 11 | def setup(): 12 | global ds18b20 13 | for i in os.listdir('/sys/bus/w1/devices'): 14 | if i != 'w1_bus_master1': 15 | ds18b20 = '28-031590bf4aff' 16 | 17 | def read(): 18 | # global ds18b20 19 | location = '/sys/bus/w1/devices/' + ds18b20 + '/w1_slave' 20 | tfile = open(location) 21 | text = tfile.read() 22 | tfile.close() 23 | secondline = text.split("\n")[1] 24 | temperaturedata = secondline.split(" ")[9] 25 | temperature = float(temperaturedata[2:]) 26 | temperature = temperature / 1000 27 | return temperature 28 | 29 | def loop(): 30 | while True: 31 | if read() != None: 32 | print ("Current temperature : %0.3f C" % read()) 33 | 34 | def destroy(): 35 | pass 36 | 37 | if __name__ == '__main__': 38 | try: 39 | setup() 40 | loop() 41 | except KeyboardInterrupt: 42 | destroy() 43 | 44 | -------------------------------------------------------------------------------- /Python/27_rotary_encoder.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | RoAPin = 11 # CLK Pin 6 | RoBPin = 12 # DT Pin 7 | BtnPin = 13 # Button Pin 8 | 9 | globalCounter = 0 10 | 11 | flag = 0 12 | Last_RoB_Status = 0 13 | Current_RoB_Status = 0 14 | 15 | def setup(): 16 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 17 | GPIO.setup(RoAPin, GPIO.IN) # input mode 18 | GPIO.setup(RoBPin, GPIO.IN) 19 | GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) 20 | 21 | def rotaryDeal(): 22 | global flag 23 | global Last_RoB_Status 24 | global Current_RoB_Status 25 | global globalCounter 26 | Last_RoB_Status = GPIO.input(RoBPin) 27 | while(not GPIO.input(RoAPin)): 28 | Current_RoB_Status = GPIO.input(RoBPin) 29 | flag = 1 30 | if flag == 1: 31 | flag = 0 32 | if (Last_RoB_Status == 0) and (Current_RoB_Status == 1): 33 | globalCounter = globalCounter + 1 34 | if (Last_RoB_Status == 1) and (Current_RoB_Status == 0): 35 | globalCounter = globalCounter - 1 36 | 37 | def btnISR(channel): 38 | global globalCounter 39 | globalCounter = 0 40 | 41 | def loop(): 42 | global globalCounter 43 | tmp = 0 # Rotary Temperary 44 | 45 | GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=btnISR) 46 | while True: 47 | rotaryDeal() 48 | if tmp != globalCounter: 49 | print ('globalCounter = %d' % globalCounter) 50 | tmp = globalCounter 51 | 52 | def destroy(): 53 | GPIO.cleanup() # Release resource 54 | 55 | if __name__ == '__main__': # Program start from here 56 | setup() 57 | try: 58 | loop() 59 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 60 | destroy() 61 | 62 | -------------------------------------------------------------------------------- /Python/28_humiture.py: -------------------------------------------------------------------------------- 1 | ''' 2 | ********************************************************************** 3 | * Filename : dht11.py 4 | * Description : test for SunFoudner DHT11 humiture & temperature module 5 | * Author : Dream 6 | * Brand : SunFounder 7 | * E-mail : service@sunfounder.com 8 | * Website : www.sunfounder.com 9 | * Update : Dream 2016-09-30 New release 10 | ********************************************************************** 11 | ''' 12 | #!/usr/bin/env python3 13 | import RPi.GPIO as GPIO 14 | import time 15 | 16 | DHTPIN = 17 17 | 18 | GPIO.setmode(GPIO.BCM) 19 | 20 | MAX_UNCHANGE_COUNT = 100 21 | 22 | STATE_INIT_PULL_DOWN = 1 23 | STATE_INIT_PULL_UP = 2 24 | STATE_DATA_FIRST_PULL_DOWN = 3 25 | STATE_DATA_PULL_UP = 4 26 | STATE_DATA_PULL_DOWN = 5 27 | 28 | def read_dht11_dat(): 29 | GPIO.setup(DHTPIN, GPIO.OUT) 30 | GPIO.output(DHTPIN, GPIO.HIGH) 31 | time.sleep(0.05) 32 | GPIO.output(DHTPIN, GPIO.LOW) 33 | time.sleep(0.02) 34 | GPIO.setup(DHTPIN, GPIO.IN, GPIO.PUD_UP) 35 | 36 | unchanged_count = 0 37 | last = -1 38 | data = [] 39 | while True: 40 | current = GPIO.input(DHTPIN) 41 | data.append(current) 42 | if last != current: 43 | unchanged_count = 0 44 | last = current 45 | else: 46 | unchanged_count += 1 47 | if unchanged_count > MAX_UNCHANGE_COUNT: 48 | break 49 | 50 | state = STATE_INIT_PULL_DOWN 51 | 52 | lengths = [] 53 | current_length = 0 54 | 55 | for current in data: 56 | current_length += 1 57 | 58 | if state == STATE_INIT_PULL_DOWN: 59 | if current == GPIO.LOW: 60 | state = STATE_INIT_PULL_UP 61 | else: 62 | continue 63 | if state == STATE_INIT_PULL_UP: 64 | if current == GPIO.HIGH: 65 | state = STATE_DATA_FIRST_PULL_DOWN 66 | else: 67 | continue 68 | if state == STATE_DATA_FIRST_PULL_DOWN: 69 | if current == GPIO.LOW: 70 | state = STATE_DATA_PULL_UP 71 | else: 72 | continue 73 | if state == STATE_DATA_PULL_UP: 74 | if current == GPIO.HIGH: 75 | current_length = 0 76 | state = STATE_DATA_PULL_DOWN 77 | else: 78 | continue 79 | if state == STATE_DATA_PULL_DOWN: 80 | if current == GPIO.LOW: 81 | lengths.append(current_length) 82 | state = STATE_DATA_PULL_UP 83 | else: 84 | continue 85 | if len(lengths) != 40: 86 | #print ("Data not good, skip") 87 | return False 88 | 89 | shortest_pull_up = min(lengths) 90 | longest_pull_up = max(lengths) 91 | halfway = (longest_pull_up + shortest_pull_up) / 2 92 | bits = [] 93 | the_bytes = [] 94 | byte = 0 95 | 96 | for length in lengths: 97 | bit = 0 98 | if length > halfway: 99 | bit = 1 100 | bits.append(bit) 101 | #print ("bits: %s, length: %d" % (bits, len(bits))) 102 | for i in range(0, len(bits)): 103 | byte = byte << 1 104 | if (bits[i]): 105 | byte = byte | 1 106 | else: 107 | byte = byte | 0 108 | if ((i + 1) % 8 == 0): 109 | the_bytes.append(byte) 110 | byte = 0 111 | #print (the_bytes) 112 | checksum = (the_bytes[0] + the_bytes[1] + the_bytes[2] + the_bytes[3]) & 0xFF 113 | if the_bytes[4] != checksum: 114 | #print ("Data not good, skip") 115 | return False 116 | 117 | return the_bytes[0], the_bytes[2] 118 | 119 | def main(): 120 | print ("Raspberry Pi wiringPi DHT11 Temperature test program\n") 121 | while True: 122 | result = read_dht11_dat() 123 | if result: 124 | humidity, temperature = result 125 | print ("humidity: %s %%, Temperature: %s C`" % (humidity, temperature)) 126 | time.sleep(1) 127 | 128 | def destroy(): 129 | GPIO.cleanup() 130 | 131 | if __name__ == '__main__': 132 | try: 133 | main() 134 | except KeyboardInterrupt: 135 | destroy() -------------------------------------------------------------------------------- /Python/29_ir_obstacle.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | 4 | ObstaclePin = 11 5 | 6 | def setup(): 7 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 8 | GPIO.setup(ObstaclePin, GPIO.IN, pull_up_down=GPIO.PUD_UP) 9 | 10 | def loop(): 11 | while True: 12 | if (0 == GPIO.input(ObstaclePin)): 13 | print ("Detected Barrier!") 14 | 15 | 16 | def destroy(): 17 | GPIO.cleanup() # Release resource 18 | 19 | if __name__ == '__main__': # Program start from here 20 | setup() 21 | try: 22 | loop() 23 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 24 | destroy() 25 | 26 | -------------------------------------------------------------------------------- /Python/30_i2c_lcd1602.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import LCD1602 3 | import time 4 | 5 | def setup(): 6 | LCD1602.init(0x27, 1) # init(slave address, background light) 7 | LCD1602.write(0, 0, 'Greetings!!') 8 | LCD1602.write(1, 1, 'from SunFounder') 9 | time.sleep(2) 10 | 11 | def loop(): 12 | space = ' ' 13 | greetings = 'Thank you for buying SunFounder Sensor Kit for Raspberry! ^_^' 14 | greetings = space + greetings 15 | while True: 16 | tmp = greetings 17 | for i in range(0, len(greetings)): 18 | LCD1602.write(0, 0, tmp) 19 | tmp = tmp[1:] 20 | time.sleep(0.8) 21 | LCD1602.clear() 22 | 23 | def destroy(): 24 | pass 25 | 26 | if __name__ == "__main__": 27 | try: 28 | setup() 29 | #loop() 30 | while True: 31 | pass 32 | except KeyboardInterrupt: 33 | destroy() 34 | -------------------------------------------------------------------------------- /Python/31_barometer.py: -------------------------------------------------------------------------------- 1 | #--------------------------------------------------------- 2 | # 3 | # This is a program for Barometer Pressure Sensor 4 | # Module. It could measure the pressure and temperature. 5 | # 6 | # This program depend on BMP085.py writted by 7 | # Adafruit. 8 | # 9 | # Barometer Module Pi 10 | # VCC ----------------- 3.3V 11 | # GND ------------------ GND 12 | # SCL ----------------- SCL1 13 | # SDA ----------------- SDA1 14 | # 15 | #--------------------------------------------------------- 16 | #!/usr/bin/env python3 17 | 18 | import Adafruit_BMP.BMP085 as BMP085 19 | import time 20 | 21 | def setup(): 22 | print ('\n Barometer begins...') 23 | 24 | def loop(): 25 | while True: 26 | sensor = BMP085.BMP085() 27 | temp = sensor.read_temperature() # Read temperature to veriable temp 28 | pressure = sensor.read_pressure() # Read pressure to veriable pressure 29 | 30 | print ('') 31 | print (' Temperature = {0:0.2f} C'.format(temp)) # Print temperature 32 | print (' Pressure = {0:0.2f} Pa'.format(pressure)) # Print pressure 33 | time.sleep(1) 34 | print ('') 35 | 36 | def destroy(): 37 | pass 38 | 39 | if __name__ == '__main__': # Program start from here 40 | setup() 41 | try: 42 | loop() 43 | except KeyboardInterrupt: 44 | destroy() -------------------------------------------------------------------------------- /Python/31_bmp280.py: -------------------------------------------------------------------------------- 1 | ''' 2 | ********************************************************************** 3 | * Filename : bmp280.py 4 | * Description : Simple use for bmp280 through i2c bus 5 | * Author : Cavon 6 | * Brand : SunFounder 7 | * E-mail : support@sunfounder.com 8 | * Website : www.sunfounder.com 9 | * Update : Cavon 2016-10-09 New release 10 | ********************************************************************** 11 | ''' 12 | #!/usr/bin/env python3 13 | import time 14 | import RPi.GPIO as GPIO 15 | import smbus2 as smbus 16 | class BMP280: 17 | # this value is necessary to calculate the correct height above sealevel 18 | # its also included in airport wheather information ATIS named as QNH 19 | # unit is hPa 20 | QNH=1020 21 | 22 | # power mode 23 | # POWER_MODE=0 # sleep mode 24 | # POWER_MODE=1 # forced mode 25 | # POWER_MODE=2 # forced mode 26 | POWER_MODE=3 # normal mode 27 | 28 | # temperature resolution 29 | # OSRS_T = 0 # skipped 30 | # OSRS_T = 1 # 16 Bit 31 | # OSRS_T = 2 # 17 Bit 32 | # OSRS_T = 3 # 18 Bit 33 | # OSRS_T = 4 # 19 Bit 34 | OSRS_T = 5 # 20 Bit 35 | 36 | # pressure resolution 37 | # OSRS_P = 0 # pressure measurement skipped 38 | # OSRS_P = 1 # 16 Bit ultra low power 39 | # OSRS_P = 2 # 17 Bit low power 40 | # OSRS_P = 3 # 18 Bit standard resolution 41 | # OSRS_P = 4 # 19 Bit high resolution 42 | OSRS_P = 5 # 20 Bit ultra high resolution 43 | 44 | # filter settings 45 | # FILTER = 0 # 46 | # FILTER = 1 # 47 | # FILTER = 2 # 48 | # FILTER = 3 # 49 | FILTER = 4 # 50 | # FILTER = 5 # 51 | # FILTER = 6 # 52 | # FILTER = 7 # 53 | 54 | # standby settings 55 | # T_SB = 0 # 000 0,5ms 56 | # T_SB = 1 # 001 62.5 ms 57 | # T_SB = 2 # 010 125 ms 58 | # T_SB = 3 # 011 250ms 59 | T_SB = 4 # 100 500ms 60 | # T_SB = 5 # 101 1000ms 61 | # T_SB = 6 # 110 2000ms 62 | # T_SB = 7 # 111 4000ms 63 | 64 | 65 | CONFIG = (T_SB <<5) + (FILTER <<2) # combine bits for config 66 | CTRL_MEAS = (OSRS_T <<5) + (OSRS_P <<2) + POWER_MODE # combine bits for ctrl_meas 67 | 68 | # print ("CONFIG:",CONFIG) 69 | # print ("CTRL_MEAS:",CTRL_MEAS) 70 | 71 | BMP280_REGISTER_DIG_T1 = 0x88 72 | BMP280_REGISTER_DIG_T2 = 0x8A 73 | BMP280_REGISTER_DIG_T3 = 0x8C 74 | BMP280_REGISTER_DIG_P1 = 0x8E 75 | BMP280_REGISTER_DIG_P2 = 0x90 76 | BMP280_REGISTER_DIG_P3 = 0x92 77 | BMP280_REGISTER_DIG_P4 = 0x94 78 | BMP280_REGISTER_DIG_P5 = 0x96 79 | BMP280_REGISTER_DIG_P6 = 0x98 80 | BMP280_REGISTER_DIG_P7 = 0x9A 81 | BMP280_REGISTER_DIG_P8 = 0x9C 82 | BMP280_REGISTER_DIG_P9 = 0x9E 83 | BMP280_REGISTER_CHIPID = 0xD0 84 | BMP280_REGISTER_VERSION = 0xD1 85 | BMP280_REGISTER_SOFTRESET = 0xE0 86 | BMP280_REGISTER_CONTROL = 0xF4 87 | BMP280_REGISTER_CONFIG = 0xF5 88 | BMP280_REGISTER_STATUS = 0xF3 89 | BMP280_REGISTER_TEMPDATA_MSB = 0xFA 90 | BMP280_REGISTER_TEMPDATA_LSB = 0xFB 91 | BMP280_REGISTER_TEMPDATA_XLSB = 0xFC 92 | BMP280_REGISTER_PRESSDATA_MSB = 0xF7 93 | BMP280_REGISTER_PRESSDATA_LSB = 0xF8 94 | BMP280_REGISTER_PRESSDATA_XLSB = 0xF9 95 | 96 | _BUS_0_TYPES = ['Pi 1 Model B'] 97 | _BUS_1_TYPES = ['Pi 3 Model B', 98 | 'Pi 3 Model B', 99 | 'Pi 2 Model B', 100 | 'Pi2 Model B', 101 | 'Model B+'] 102 | 103 | _DEBUG = False 104 | _DEBUG_INFO = 'DEBUG "BMP280.py":' 105 | 106 | def __init__(self, bus_number=None, address=0x77): 107 | self.address = address 108 | if bus_number == None: 109 | self.bus_number = self._get_bus_number() 110 | else: 111 | self.bus_number = bus_number 112 | self.bus = smbus.SMBus(self.bus_number) 113 | 114 | self.dig_T1 = 0.0 115 | self.dig_T2 = 0.0 116 | self.dig_T3 = 0.0 117 | self.dig_P1 = 0.0 118 | self.dig_P2 = 0.0 119 | self.dig_P3 = 0.0 120 | self.dig_P4 = 0.0 121 | self.dig_P5 = 0.0 122 | self.dig_P6 = 0.0 123 | self.dig_P7 = 0.0 124 | self.dig_P8 = 0.0 125 | self.dig_P9 = 0.0 126 | 127 | def _get_bus_number(self): 128 | pi_type = GPIO.RPI_INFO['TYPE'] 129 | if pi_type in self._BUS_0_TYPES: 130 | bus_number = 0 131 | elif pi_type in self._BUS_1_TYPES: 132 | bus_number = 1 133 | else: 134 | raise ValueError('Reading Pi type error, Your Pi "{0}"" is not in the list.\n Please post an Issus at our Github Page or contract us\n Github page: https://github.com/sunfounder/Sunfounder_Smart_Video_Car_Kit_for_RaspberryPi/issues\n Email: support@sunfounder.com\n SunFounder'.format(pi_type)) 135 | 136 | if self._DEBUG: 137 | print self._DEBUG_INFO, 'Get i2c bus number %d' % bus_number 138 | return bus_number 139 | 140 | def _write_byte_data(self, reg, value): 141 | if self._DEBUG: 142 | print self._DEBUG_INFO, 'Writing value %2X to %2X' % (value, reg) 143 | self.bus.write_byte_data(self.address, reg, value) 144 | 145 | def _read_byte_data(self, reg): 146 | if self._DEBUG: 147 | print self._DEBUG_INFO, 'Reading value from %2X' % reg 148 | results = self.bus.read_byte_data(self.address, reg) 149 | return results 150 | 151 | def _read_i2c_block_data(self, reg, length): 152 | if self._DEBUG: 153 | print self._DEBUG_INFO, 'Reading value from %2X' % reg 154 | results = self.bus.read_i2c_block_data(self.address, reg, length) 155 | return results 156 | 157 | def _read_word_data_unsigned(self, reg): 158 | if self._DEBUG: 159 | print self._DEBUG_INFO, 'Reading value from %2X' % reg 160 | results = self.bus.read_word_data(self.address, reg) 161 | return results 162 | 163 | def _read_word_data_signed(self, reg): 164 | if self._DEBUG: 165 | print self._DEBUG_INFO, 'Reading value from %2X' % reg 166 | results = self.bus.read_word_data(self.address, reg) 167 | if results > 32767: 168 | results -= 65536 169 | return results 170 | 171 | def read_id(self): 172 | REG_ID = 0xD0 173 | 174 | (chip_id, chip_version) = self._read_i2c_block_data(REG_ID, 2) 175 | return (chip_id, chip_version) 176 | 177 | #if (device.readS8(self.BMP280_REGISTER_CHIPID) == 0x58): # check sensor id 0x58=BMP280 178 | def reg_check(self): 179 | #print addr 180 | self._write_byte_data(self.BMP280_REGISTER_SOFTRESET, 0xB6) 181 | time.sleep(0.2) 182 | self._write_byte_data(self.BMP280_REGISTER_CONTROL, self.CTRL_MEAS) 183 | time.sleep(0.2) 184 | self._write_byte_data(self.BMP280_REGISTER_CONFIG, self.CONFIG) 185 | time.sleep(0.2) 186 | 187 | self.dig_T1 = self._read_word_data_unsigned(self.BMP280_REGISTER_DIG_T1) # read correction settings 188 | self.dig_T2 = self._read_word_data_signed(self.BMP280_REGISTER_DIG_T2) 189 | self.dig_T3 = self._read_word_data_signed(self.BMP280_REGISTER_DIG_T3) 190 | self.dig_P1 = self._read_word_data_unsigned(self.BMP280_REGISTER_DIG_P1) 191 | self.dig_P2 = self._read_word_data_signed(self.BMP280_REGISTER_DIG_P2) 192 | self.dig_P3 = self._read_word_data_signed(self.BMP280_REGISTER_DIG_P3) 193 | self.dig_P4 = self._read_word_data_signed(self.BMP280_REGISTER_DIG_P4) 194 | self.dig_P5 = self._read_word_data_signed(self.BMP280_REGISTER_DIG_P5) 195 | self.dig_P6 = self._read_word_data_signed(self.BMP280_REGISTER_DIG_P6) 196 | self.dig_P7 = self._read_word_data_signed(self.BMP280_REGISTER_DIG_P7) 197 | self.dig_P8 = self._read_word_data_signed(self.BMP280_REGISTER_DIG_P8) 198 | self.dig_P9 = self._read_word_data_signed(self.BMP280_REGISTER_DIG_P9) 199 | 200 | def read(self): 201 | raw_temp_msb=self._read_byte_data(self.BMP280_REGISTER_TEMPDATA_MSB) # read raw temperature msb 202 | raw_temp_lsb=self._read_byte_data(self.BMP280_REGISTER_TEMPDATA_LSB) # read raw temperature lsb 203 | raw_temp_xlsb=self._read_byte_data(self.BMP280_REGISTER_TEMPDATA_XLSB) # read raw temperature xlsb 204 | raw_press_msb=self._read_byte_data(self.BMP280_REGISTER_PRESSDATA_MSB) # read raw pressure msb 205 | raw_press_lsb=self._read_byte_data(self.BMP280_REGISTER_PRESSDATA_LSB) # read raw pressure lsb 206 | raw_press_xlsb=self._read_byte_data(self.BMP280_REGISTER_PRESSDATA_XLSB) # read raw pressure xlsb 207 | 208 | raw_temp=(raw_temp_msb <<12)+(raw_temp_lsb<<4)+(raw_temp_xlsb>>4) # combine 3 bytes msb 12 bits left, lsb 4 bits left, xlsb 4 bits right 209 | raw_press=(raw_press_msb <<12)+(raw_press_lsb <<4)+(raw_press_xlsb >>4) # combine 3 bytes msb 12 bits left, lsb 4 bits left, xlsb 4 bits right 210 | var1=(raw_temp/16384.0-self.dig_T1/1024.0)*self.dig_T2 # formula for temperature from datasheet 211 | var2=(raw_temp/131072.0-self.dig_T1/8192.0)*(raw_temp/131072.0-self.dig_T1/8192.0)*self.dig_T3 # formula for temperature from datasheet 212 | temp=(var1+var2)/5120.0 # formula for temperature from datasheet 213 | t_fine=(var1+var2) # need for pressure calculation 214 | 215 | var1=t_fine/2.0-64000.0 # formula for pressure from datasheet 216 | var2=var1*var1*self.dig_P6/32768.0 # formula for pressure from datasheet 217 | var2=var2+var1*self.dig_P5*2 # formula for pressure from datasheet 218 | var2=var2/4.0+self.dig_P4*65536.0 # formula for pressure from datasheet 219 | var1=(self.dig_P3*var1*var1/524288.0+self.dig_P2*var1)/524288.0 # formula for pressure from datasheet 220 | var1=(1.0+var1/32768.0)*self.dig_P1 # formula for pressure from datasheet 221 | press=1048576.0-raw_press # formula for pressure from datasheet 222 | press=(press-var2/4096.0)*6250.0/var1 # formula for pressure from datasheet 223 | var1=self.dig_P9*press*press/2147483648.0 # formula for pressure from datasheet 224 | var2=press*self.dig_P8/32768.0 # formula for pressure from datasheet 225 | press=press+(var1+var2+self.dig_P7)/16.0 # formula for pressure from datasheet 226 | 227 | #altitude= 44330.0 * (1.0 - pow(press / (self.QNH*100), (1.0/5.255))) # formula for altitude from airpressure 228 | 229 | return temp, press/ 100.0 230 | 231 | def main(): 232 | bmp = BMP280() 233 | chip_id, chip_version = bmp.read_id() 234 | 235 | if chip_id == 88: 236 | bmp.reg_check() 237 | 238 | temperature, pressure = bmp.read() 239 | print("Temperature : %2.2f `C" % temperature) 240 | print("Pressure : %5.4f mbar" % pressure) 241 | print "" 242 | else: 243 | print("Error") 244 | print("Chip ID : %d" % chip_id) 245 | print("Version : %d" % chip_version) 246 | time.sleep(1) 247 | 248 | 249 | if __name__=="__main__": 250 | while True: 251 | main() -------------------------------------------------------------------------------- /Python/32_mpu6050.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import smbus2 as smbus 4 | import math 5 | import time 6 | 7 | # Power management registers 8 | power_mgmt_1 = 0x6b 9 | power_mgmt_2 = 0x6c 10 | 11 | def read_byte(adr): 12 | return bus.read_byte_data(address, adr) 13 | 14 | def read_word(adr): 15 | high = bus.read_byte_data(address, adr) 16 | low = bus.read_byte_data(address, adr+1) 17 | val = (high << 8) + low 18 | return val 19 | 20 | def read_word_2c(adr): 21 | val = read_word(adr) 22 | if (val >= 0x8000): 23 | return -((65535 - val) + 1) 24 | else: 25 | return val 26 | 27 | def dist(a,b): 28 | return math.sqrt((a*a)+(b*b)) 29 | 30 | def get_y_rotation(x,y,z): 31 | radians = math.atan2(x, dist(y,z)) 32 | return -math.degrees(radians) 33 | 34 | def get_x_rotation(x,y,z): 35 | radians = math.atan2(y, dist(x,z)) 36 | return math.degrees(radians) 37 | 38 | 39 | bus = smbus.SMBus(1) # or bus = smbus.SMBus(1) for Revision 2 boards 40 | address = 0x68 # This is the address value read via the i2cdetect command 41 | 42 | # Now wake the 6050 up as it starts in sleep mode 43 | bus.write_byte_data(address, power_mgmt_1, 0) 44 | 45 | while True: 46 | time.sleep(0.1) 47 | gyro_xout = read_word_2c(0x43) 48 | gyro_yout = read_word_2c(0x45) 49 | gyro_zout = read_word_2c(0x47) 50 | 51 | print ("gyro_xout : ", gyro_xout, " scaled: ", (gyro_xout / 131)) 52 | print ("gyro_yout : ", gyro_yout, " scaled: ", (gyro_yout / 131)) 53 | print ("gyro_zout : ", gyro_zout, " scaled: ", (gyro_zout / 131)) 54 | 55 | accel_xout = read_word_2c(0x3b) 56 | accel_yout = read_word_2c(0x3d) 57 | accel_zout = read_word_2c(0x3f) 58 | 59 | accel_xout_scaled = accel_xout / 16384.0 60 | accel_yout_scaled = accel_yout / 16384.0 61 | accel_zout_scaled = accel_zout / 16384.0 62 | 63 | print ("accel_xout: ", accel_xout, " scaled: ", accel_xout_scaled) 64 | print ("accel_yout: ", accel_yout, " scaled: ", accel_yout_scaled) 65 | print ("accel_zout: ", accel_zout, " scaled: ", accel_zout_scaled) 66 | 67 | print ("x rotation: " , get_x_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled)) 68 | print ("y rotation: " , get_y_rotation(accel_xout_scaled, accel_yout_scaled, accel_zout_scaled)) 69 | 70 | time.sleep(0.5) 71 | -------------------------------------------------------------------------------- /Python/33_ds1302.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #----------------------------------------------------- 3 | # 4 | # This is a program for DS1302 RTC Module. 5 | # It provide precision timmer. 6 | # 7 | # This program depend on rpi_time.py. 8 | # 9 | # ds1302 Module Pi 10 | # VCC ------------------ 5 V (Must be 5v) 11 | # GND ------------------ GND 12 | # SCL ---------------- GPIO23 13 | # I/O ---------------- GPIO24 14 | # RST ---------------- GPIO25 15 | # 16 | #----------------------------------------------------- 17 | from datetime import datetime 18 | from ds1302 import DS1302 19 | from sys import version_info 20 | import time 21 | 22 | if version_info.major == 2: 23 | input = raw_input 24 | 25 | rtc = DS1302() 26 | 27 | def setup(): 28 | print ('') 29 | print ('') 30 | print (rtc.get_datetime()) 31 | print ('') 32 | print ('') 33 | a = input( "Do you want to setup date and time?(y/n) ") 34 | if a == 'y' or a == 'Y': 35 | date = input("Input date:(YYYY MM DD) ") 36 | time = input("Input time:(HH MM SS) ") 37 | date = list(map(lambda x: int(x), date.split())) 38 | time = list(map(lambda x: int(x), time.split())) 39 | print ('') 40 | print ('') 41 | rtc.set_datetime(datetime(date[0], date[1], date[2], time[0], time[1], time[2])) 42 | dt = rtc.get_datetime() 43 | print ("You set the date and time to:", dt) 44 | 45 | def loop(): 46 | while True: 47 | a = rtc.get_datetime() 48 | print (a) 49 | time.sleep(0.5) 50 | 51 | def destory(): 52 | pass # Release resource 53 | 54 | if __name__ == '__main__': # Program start from here 55 | setup() 56 | try: 57 | loop() 58 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 59 | destory() -------------------------------------------------------------------------------- /Python/34_tracking.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | TrackPin = 11 6 | LedPin = 12 7 | 8 | def setup(): 9 | GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location 10 | GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output 11 | GPIO.setup(TrackPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) 12 | GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led 13 | 14 | def loop(): 15 | while True: 16 | if GPIO.input(TrackPin) == GPIO.LOW: 17 | print ('White line is detected') 18 | time.sleep(0.5) 19 | GPIO.output(LedPin, GPIO.LOW) # led on 20 | else: 21 | print ('...Black line is detected') 22 | time.sleep(0.5) 23 | GPIO.output(LedPin, GPIO.HIGH) # led off 24 | 25 | def destroy(): 26 | GPIO.output(LedPin, GPIO.HIGH) # led off 27 | GPIO.cleanup() # Release resource 28 | 29 | if __name__ == '__main__': # Program start from here 30 | setup() 31 | try: 32 | loop() 33 | except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. 34 | destroy() 35 | 36 | -------------------------------------------------------------------------------- /Python/35_temp_monitor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import RPi.GPIO as GPIO 3 | import importlib 4 | import time 5 | import sys 6 | 7 | # BOARD pin numbering 8 | LedR = 11 9 | LedG = 12 10 | LedB = 13 11 | Buzz = 15 12 | 13 | #ds18b20 = '28-031590bf4aff' 14 | #location = '/sys/bus/w1/devices/' + ds18b20 + '/w1_slave' 15 | 16 | joystick = importlib.import_module('15_joystick_PS2') 17 | ds18b20 = importlib.import_module('26_ds18b20') 18 | beep = importlib.import_module('10_active_buzzer') 19 | rgb = importlib.import_module('02_rgb_led') 20 | 21 | joystick.setup() 22 | ds18b20.setup() 23 | beep.setup(Buzz) 24 | rgb.setup(LedR, LedG, LedB) 25 | 26 | color = {'Red':0xFF0000, 'Green':0x00FF00, 'Blue':0x0000FF} 27 | 28 | def setup(): 29 | global lowl, highl 30 | lowl = 29 31 | highl = 31 32 | 33 | def edge(): 34 | global lowl, highl 35 | temp = joystick.direction() 36 | if temp == 'Pressed': 37 | destroy() 38 | quit() 39 | if temp == 'up' and lowl < highl-1: 40 | highl += 1 41 | if temp == 'down' and lowl >= -5: 42 | highl -= 1 43 | if temp == 'right' and highl <= 125: 44 | lowl += 1 45 | if temp == 'left' and lowl < highl-1: 46 | lowl -= 1 47 | 48 | def loop(): 49 | while True: 50 | edge() 51 | temp = ds18b20.read() 52 | print ('The lower limit of temperature : ', lowl) 53 | print ('The upper limit of temperature : ', highl) 54 | print ('Current temperature : ', temp) 55 | if float(temp) < float(lowl): 56 | rgb.setColor(color['Blue']) 57 | for i in range(0, 3): 58 | beep.beep(0.5) 59 | if temp >= float(lowl) and temp < float(highl): 60 | rgb.setColor(color['Green']) 61 | if temp >= float(highl): 62 | rgb.setColor(color['Red']) 63 | for i in range(0, 3): 64 | beep.beep(0.1) 65 | 66 | def destroy(): 67 | beep.destroy() 68 | joystick.destroy() 69 | ds18b20.destroy() 70 | rgb.destroy() 71 | 72 | if __name__ == "__main__": 73 | try: 74 | setup() 75 | loop() 76 | except KeyboardInterrupt: 77 | destroy() 78 | -------------------------------------------------------------------------------- /Python/Adafruit_Python_BMP/.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | dist/ 3 | *.egg-info 4 | *.pyc 5 | -------------------------------------------------------------------------------- /Python/Adafruit_Python_BMP/Adafruit_BMP/BMP085.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 | import logging 22 | import time 23 | 24 | 25 | # BMP085 default address. 26 | BMP085_I2CADDR = 0x77 27 | 28 | # Operating Modes 29 | BMP085_ULTRALOWPOWER = 0 30 | BMP085_STANDARD = 1 31 | BMP085_HIGHRES = 2 32 | BMP085_ULTRAHIGHRES = 3 33 | 34 | # BMP085 Registers 35 | BMP085_CAL_AC1 = 0xAA # R Calibration data (16 bits) 36 | BMP085_CAL_AC2 = 0xAC # R Calibration data (16 bits) 37 | BMP085_CAL_AC3 = 0xAE # R Calibration data (16 bits) 38 | BMP085_CAL_AC4 = 0xB0 # R Calibration data (16 bits) 39 | BMP085_CAL_AC5 = 0xB2 # R Calibration data (16 bits) 40 | BMP085_CAL_AC6 = 0xB4 # R Calibration data (16 bits) 41 | BMP085_CAL_B1 = 0xB6 # R Calibration data (16 bits) 42 | BMP085_CAL_B2 = 0xB8 # R Calibration data (16 bits) 43 | BMP085_CAL_MB = 0xBA # R Calibration data (16 bits) 44 | BMP085_CAL_MC = 0xBC # R Calibration data (16 bits) 45 | BMP085_CAL_MD = 0xBE # R Calibration data (16 bits) 46 | BMP085_CONTROL = 0xF4 47 | BMP085_TEMPDATA = 0xF6 48 | BMP085_PRESSUREDATA = 0xF6 49 | 50 | # Commands 51 | BMP085_READTEMPCMD = 0x2E 52 | BMP085_READPRESSURECMD = 0x34 53 | 54 | 55 | class BMP085(object): 56 | def __init__(self, mode=BMP085_STANDARD, address=BMP085_I2CADDR, i2c=None, **kwargs): 57 | self._logger = logging.getLogger('Adafruit_BMP.BMP085') 58 | # Check that mode is valid. 59 | if mode not in [BMP085_ULTRALOWPOWER, BMP085_STANDARD, BMP085_HIGHRES, BMP085_ULTRAHIGHRES]: 60 | raise ValueError('Unexpected mode value {0}. Set mode to one of BMP085_ULTRALOWPOWER, BMP085_STANDARD, BMP085_HIGHRES, or BMP085_ULTRAHIGHRES'.format(mode)) 61 | self._mode = mode 62 | # Create I2C device. 63 | if i2c is None: 64 | import Adafruit_GPIO.I2C as I2C 65 | i2c = I2C 66 | self._device = i2c.get_i2c_device(address, **kwargs) 67 | # Load calibration values. 68 | self._load_calibration() 69 | 70 | def _load_calibration(self): 71 | self.cal_AC1 = self._device.readS16BE(BMP085_CAL_AC1) # INT16 72 | self.cal_AC2 = self._device.readS16BE(BMP085_CAL_AC2) # INT16 73 | self.cal_AC3 = self._device.readS16BE(BMP085_CAL_AC3) # INT16 74 | self.cal_AC4 = self._device.readU16BE(BMP085_CAL_AC4) # UINT16 75 | self.cal_AC5 = self._device.readU16BE(BMP085_CAL_AC5) # UINT16 76 | self.cal_AC6 = self._device.readU16BE(BMP085_CAL_AC6) # UINT16 77 | self.cal_B1 = self._device.readS16BE(BMP085_CAL_B1) # INT16 78 | self.cal_B2 = self._device.readS16BE(BMP085_CAL_B2) # INT16 79 | self.cal_MB = self._device.readS16BE(BMP085_CAL_MB) # INT16 80 | self.cal_MC = self._device.readS16BE(BMP085_CAL_MC) # INT16 81 | self.cal_MD = self._device.readS16BE(BMP085_CAL_MD) # INT16 82 | self._logger.debug('AC1 = {0:6d}'.format(self.cal_AC1)) 83 | self._logger.debug('AC2 = {0:6d}'.format(self.cal_AC2)) 84 | self._logger.debug('AC3 = {0:6d}'.format(self.cal_AC3)) 85 | self._logger.debug('AC4 = {0:6d}'.format(self.cal_AC4)) 86 | self._logger.debug('AC5 = {0:6d}'.format(self.cal_AC5)) 87 | self._logger.debug('AC6 = {0:6d}'.format(self.cal_AC6)) 88 | self._logger.debug('B1 = {0:6d}'.format(self.cal_B1)) 89 | self._logger.debug('B2 = {0:6d}'.format(self.cal_B2)) 90 | self._logger.debug('MB = {0:6d}'.format(self.cal_MB)) 91 | self._logger.debug('MC = {0:6d}'.format(self.cal_MC)) 92 | self._logger.debug('MD = {0:6d}'.format(self.cal_MD)) 93 | 94 | def _load_datasheet_calibration(self): 95 | # Set calibration from values in the datasheet example. Useful for debugging the 96 | # temp and pressure calculation accuracy. 97 | self.cal_AC1 = 408 98 | self.cal_AC2 = -72 99 | self.cal_AC3 = -14383 100 | self.cal_AC4 = 32741 101 | self.cal_AC5 = 32757 102 | self.cal_AC6 = 23153 103 | self.cal_B1 = 6190 104 | self.cal_B2 = 4 105 | self.cal_MB = -32767 106 | self.cal_MC = -8711 107 | self.cal_MD = 2868 108 | 109 | def read_raw_temp(self): 110 | """Reads the raw (uncompensated) temperature from the sensor.""" 111 | self._device.write8(BMP085_CONTROL, BMP085_READTEMPCMD) 112 | time.sleep(0.005) # Wait 5ms 113 | raw = self._device.readU16BE(BMP085_TEMPDATA) 114 | self._logger.debug('Raw temp 0x{0:X} ({1})'.format(raw & 0xFFFF, raw)) 115 | return raw 116 | 117 | def read_raw_pressure(self): 118 | """Reads the raw (uncompensated) pressure level from the sensor.""" 119 | self._device.write8(BMP085_CONTROL, BMP085_READPRESSURECMD + (self._mode << 6)) 120 | if self._mode == BMP085_ULTRALOWPOWER: 121 | time.sleep(0.005) 122 | elif self._mode == BMP085_HIGHRES: 123 | time.sleep(0.014) 124 | elif self._mode == BMP085_ULTRAHIGHRES: 125 | time.sleep(0.026) 126 | else: 127 | time.sleep(0.008) 128 | msb = self._device.readU8(BMP085_PRESSUREDATA) 129 | lsb = self._device.readU8(BMP085_PRESSUREDATA+1) 130 | xlsb = self._device.readU8(BMP085_PRESSUREDATA+2) 131 | raw = ((msb << 16) + (lsb << 8) + xlsb) >> (8 - self._mode) 132 | self._logger.debug('Raw pressure 0x{0:04X} ({1})'.format(raw & 0xFFFF, raw)) 133 | return raw 134 | 135 | def read_temperature(self): 136 | """Gets the compensated temperature in degrees celsius.""" 137 | UT = self.read_raw_temp() 138 | # Datasheet value for debugging: 139 | #UT = 27898 140 | # Calculations below are taken straight from section 3.5 of the datasheet. 141 | X1 = ((UT - self.cal_AC6) * self.cal_AC5) >> 15 142 | X2 = (self.cal_MC << 11) / (X1 + self.cal_MD) 143 | B5 = X1 + X2 144 | temp = ((B5 + 8) >> 4) / 10.0 145 | self._logger.debug('Calibrated temperature {0} C'.format(temp)) 146 | return temp 147 | 148 | def read_pressure(self): 149 | """Gets the compensated pressure in Pascals.""" 150 | UT = self.read_raw_temp() 151 | UP = self.read_raw_pressure() 152 | # Datasheet values for debugging: 153 | #UT = 27898 154 | #UP = 23843 155 | # Calculations below are taken straight from section 3.5 of the datasheet. 156 | # Calculate true temperature coefficient B5. 157 | X1 = ((UT - self.cal_AC6) * self.cal_AC5) >> 15 158 | X2 = (self.cal_MC << 11) / (X1 + self.cal_MD) 159 | B5 = X1 + X2 160 | self._logger.debug('B5 = {0}'.format(B5)) 161 | # Pressure Calculations 162 | B6 = B5 - 4000 163 | self._logger.debug('B6 = {0}'.format(B6)) 164 | X1 = (self.cal_B2 * (B6 * B6) >> 12) >> 11 165 | X2 = (self.cal_AC2 * B6) >> 11 166 | X3 = X1 + X2 167 | B3 = (((self.cal_AC1 * 4 + X3) << self._mode) + 2) / 4 168 | self._logger.debug('B3 = {0}'.format(B3)) 169 | X1 = (self.cal_AC3 * B6) >> 13 170 | X2 = (self.cal_B1 * ((B6 * B6) >> 12)) >> 16 171 | X3 = ((X1 + X2) + 2) >> 2 172 | B4 = (self.cal_AC4 * (X3 + 32768)) >> 15 173 | self._logger.debug('B4 = {0}'.format(B4)) 174 | B7 = (UP - B3) * (50000 >> self._mode) 175 | self._logger.debug('B7 = {0}'.format(B7)) 176 | if B7 < 0x80000000: 177 | p = (B7 * 2) / B4 178 | else: 179 | p = (B7 / B4) * 2 180 | X1 = (p >> 8) * (p >> 8) 181 | X1 = (X1 * 3038) >> 16 182 | X2 = (-7357 * p) >> 16 183 | p = p + ((X1 + X2 + 3791) >> 4) 184 | self._logger.debug('Pressure {0} Pa'.format(p)) 185 | return p 186 | 187 | def read_altitude(self, sealevel_pa=101325.0): 188 | """Calculates the altitude in meters.""" 189 | # Calculation taken straight from section 3.6 of the datasheet. 190 | pressure = float(self.read_pressure()) 191 | altitude = 44330.0 * (1.0 - pow(pressure / sealevel_pa, (1.0/5.255))) 192 | self._logger.debug('Altitude {0} m'.format(altitude)) 193 | return altitude 194 | 195 | def read_sealevel_pressure(self, altitude_m=0.0): 196 | """Calculates the pressure at sealevel when given a known altitude in 197 | meters. Returns a value in Pascals.""" 198 | pressure = float(self.read_pressure()) 199 | p0 = pressure / pow(1.0 - altitude_m/44330.0, 5.255) 200 | self._logger.debug('Sealevel pressure {0} Pa'.format(p0)) 201 | return p0 202 | -------------------------------------------------------------------------------- /Python/Adafruit_Python_BMP/Adafruit_BMP/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sunfounder/SunFounder_SensorKit_for_RPi2/ed88539bddcc0f77e0e75436cb8a3f40d7c5f66c/Python/Adafruit_Python_BMP/Adafruit_BMP/__init__.py -------------------------------------------------------------------------------- /Python/Adafruit_Python_BMP/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Adafruit Industries 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Python/Adafruit_Python_BMP/README.md: -------------------------------------------------------------------------------- 1 | Adafruit Python BMP 2 | =================== 3 | 4 | Python library for accessing the BMP series pressure and temperature sensors like the BMP085/BMP180 on a Raspberry Pi or Beaglebone Black. 5 | 6 | Designed specifically to work with the Adafruit BMP085/BMP180 pressure sensors ----> https://www.adafruit.com/products/1603 7 | 8 | To install, download the library by clicking the download zip link to the right and unzip the archive somewhere on your Raspberry Pi or Beaglebone Black. Then execute the following command in the directory of the library: 9 | 10 | ```` 11 | sudo python setup.py install 12 | ```` 13 | 14 | Make sure you have internet access on the device so it can download the required dependencies. 15 | 16 | See examples of usage in the examples folder. 17 | 18 | Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! 19 | 20 | Written by Tony DiCola for Adafruit Industries. 21 | MIT license, all text above must be included in any redistribution 22 | -------------------------------------------------------------------------------- /Python/Adafruit_Python_BMP/examples/google_spreadsheet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | # Google Spreadsheet BMP Sensor Data-logging Example 4 | 5 | # Depends on the 'gspread' package being installed. If you have pip installed 6 | # execute: 7 | # sudo pip install gspread 8 | 9 | # Copyright (c) 2014 Adafruit Industries 10 | # Author: Tony DiCola 11 | 12 | # Permission is hereby granted, free of charge, to any person obtaining a copy 13 | # of this software and associated documentation files (the "Software"), to deal 14 | # in the Software without restriction, including without limitation the rights 15 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 16 | # copies of the Software, and to permit persons to whom the Software is 17 | # furnished to do so, subject to the following conditions: 18 | 19 | # The above copyright notice and this permission notice shall be included in all 20 | # copies or substantial portions of the Software. 21 | 22 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 23 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 24 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 25 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 26 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 27 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 28 | # SOFTWARE. 29 | import sys 30 | import time 31 | import datetime 32 | 33 | import Adafruit_BMP.BMP085 as BMP085 34 | import gspread 35 | 36 | # Google Docs account email, password, and spreadsheet name. 37 | GDOCS_EMAIL = 'your google docs account email address' 38 | GDOCS_PASSWORD = 'your google docs account password' 39 | GDOCS_SPREADSHEET_NAME = 'your google docs spreadsheet name' 40 | 41 | # How long to wait (in seconds) between measurements. 42 | FREQUENCY_SECONDS = 30 43 | 44 | 45 | def login_open_sheet(email, password, spreadsheet): 46 | """Connect to Google Docs spreadsheet and return the first worksheet.""" 47 | try: 48 | gc = gspread.login(email, password) 49 | worksheet = gc.open(spreadsheet).sheet1 50 | return worksheet 51 | except: 52 | print 'Unable to login and get spreadsheet. Check email, password, spreadsheet name.' 53 | sys.exit(1) 54 | 55 | 56 | # Create sensor instance with default I2C bus (On Raspberry Pi either 0 or 57 | # 1 based on the revision, on Beaglebone Black default to 1). 58 | bmp = BMP085.BMP085() 59 | 60 | print 'Logging sensor measurements to {0} every {1} seconds.'.format(GDOCS_SPREADSHEET_NAME, FREQUENCY_SECONDS) 61 | print 'Press Ctrl-C to quit.' 62 | worksheet = None 63 | while True: 64 | # Login if necessary. 65 | if worksheet is None: 66 | worksheet = login_open_sheet(GDOCS_EMAIL, GDOCS_PASSWORD, GDOCS_SPREADSHEET_NAME) 67 | 68 | # Attempt to get sensor readings. 69 | temp = bmp.read_temperature() 70 | pressure = bmp.read_pressure() 71 | altitude = bmp.read_altitude() 72 | 73 | print 'Temperature: {0:0.1f} C'.format(temp) 74 | print 'Pressure: {0:0.1f} Pa'.format(pressure) 75 | print 'Altitude: {0:0.1f} m'.format(altitude) 76 | 77 | # Append the data in the spreadsheet, including a timestamp 78 | try: 79 | worksheet.append_row((datetime.datetime.now(), temp, pressure, altitude)) 80 | except: 81 | # Error appending data, most likely because credentials are stale. 82 | # Null out the worksheet so a login is performed at the top of the loop. 83 | print 'Append error, logging in again' 84 | worksheet = None 85 | time.sleep(FREQUENCY_SECONDS) 86 | continue 87 | 88 | # Wait 30 seconds before continuing 89 | print 'Wrote a row to {0}'.format(GDOCS_SPREADSHEET_NAME) 90 | time.sleep(FREQUENCY_SECONDS) 91 | -------------------------------------------------------------------------------- /Python/Adafruit_Python_BMP/examples/simpletest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Copyright (c) 2014 Adafruit Industries 3 | # Author: Tony DiCola 4 | # 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | # 12 | # The above copyright notice and this permission notice shall be included in 13 | # all copies or substantial portions of the Software. 14 | # 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | # THE SOFTWARE. 22 | 23 | # Can enable debug output by uncommenting: 24 | #import logging 25 | #logging.basicConfig(level=logging.DEBUG) 26 | 27 | import Adafruit_BMP.BMP085 as BMP085 28 | 29 | # Default constructor will pick a default I2C bus. 30 | # 31 | # For the Raspberry Pi this means you should hook up to the only exposed I2C bus 32 | # from the main GPIO header and the library will figure out the bus number based 33 | # on the Pi's revision. 34 | # 35 | # For the Beaglebone Black the library will assume bus 1 by default, which is 36 | # exposed with SCL = P9_19 and SDA = P9_20. 37 | sensor = BMP085.BMP085() 38 | 39 | # Optionally you can override the bus number: 40 | #sensor = BMP085.BMP085(busnum=2) 41 | 42 | # You can also optionally change the BMP085 mode to one of BMP085_ULTRALOWPOWER, 43 | # BMP085_STANDARD, BMP085_HIGHRES, or BMP085_ULTRAHIGHRES. See the BMP085 44 | # datasheet for more details on the meanings of each mode (accuracy and power 45 | # consumption are primarily the differences). The default mode is STANDARD. 46 | #sensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES) 47 | 48 | print 'Temp = {0:0.2f} *C'.format(sensor.read_temperature()) 49 | print 'Pressure = {0:0.2f} Pa'.format(sensor.read_pressure()) 50 | print 'Altitude = {0:0.2f} m'.format(sensor.read_altitude()) 51 | print 'Sealevel Pressure = {0:0.2f} Pa'.format(sensor.read_sealevel_pressure()) 52 | -------------------------------------------------------------------------------- /Python/Adafruit_Python_BMP/ez_setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Bootstrap setuptools installation 3 | 4 | To use setuptools in your package's setup.py, include this 5 | file in the same directory and add this to the top of your setup.py:: 6 | 7 | from ez_setup import use_setuptools 8 | use_setuptools() 9 | 10 | To require a specific version of setuptools, set a download 11 | mirror, or use an alternate download directory, simply supply 12 | the appropriate options to ``use_setuptools()``. 13 | 14 | This file can also be run as a script to install or upgrade setuptools. 15 | """ 16 | import os 17 | import shutil 18 | import sys 19 | import tempfile 20 | import zipfile 21 | import optparse 22 | import subprocess 23 | import platform 24 | import textwrap 25 | import contextlib 26 | 27 | from distutils import log 28 | 29 | try: 30 | from site import USER_SITE 31 | except ImportError: 32 | USER_SITE = None 33 | 34 | DEFAULT_VERSION = "3.5.1" 35 | DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/" 36 | 37 | def _python_cmd(*args): 38 | """ 39 | Return True if the command succeeded. 40 | """ 41 | args = (sys.executable,) + args 42 | return subprocess.call(args) == 0 43 | 44 | 45 | def _install(archive_filename, install_args=()): 46 | with archive_context(archive_filename): 47 | # installing 48 | log.warn('Installing Setuptools') 49 | if not _python_cmd('setup.py', 'install', *install_args): 50 | log.warn('Something went wrong during the installation.') 51 | log.warn('See the error message above.') 52 | # exitcode will be 2 53 | return 2 54 | 55 | 56 | def _build_egg(egg, archive_filename, to_dir): 57 | with archive_context(archive_filename): 58 | # building an egg 59 | log.warn('Building a Setuptools egg in %s', to_dir) 60 | _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) 61 | # returning the result 62 | log.warn(egg) 63 | if not os.path.exists(egg): 64 | raise IOError('Could not build the egg.') 65 | 66 | 67 | def get_zip_class(): 68 | """ 69 | Supplement ZipFile class to support context manager for Python 2.6 70 | """ 71 | class ContextualZipFile(zipfile.ZipFile): 72 | def __enter__(self): 73 | return self 74 | def __exit__(self, type, value, traceback): 75 | self.close 76 | return zipfile.ZipFile if hasattr(zipfile.ZipFile, '__exit__') else \ 77 | ContextualZipFile 78 | 79 | 80 | @contextlib.contextmanager 81 | def archive_context(filename): 82 | # extracting the archive 83 | tmpdir = tempfile.mkdtemp() 84 | log.warn('Extracting in %s', tmpdir) 85 | old_wd = os.getcwd() 86 | try: 87 | os.chdir(tmpdir) 88 | with get_zip_class()(filename) as archive: 89 | archive.extractall() 90 | 91 | # going in the directory 92 | subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) 93 | os.chdir(subdir) 94 | log.warn('Now working in %s', subdir) 95 | yield 96 | 97 | finally: 98 | os.chdir(old_wd) 99 | shutil.rmtree(tmpdir) 100 | 101 | 102 | def _do_download(version, download_base, to_dir, download_delay): 103 | egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg' 104 | % (version, sys.version_info[0], sys.version_info[1])) 105 | if not os.path.exists(egg): 106 | archive = download_setuptools(version, download_base, 107 | to_dir, download_delay) 108 | _build_egg(egg, archive, to_dir) 109 | sys.path.insert(0, egg) 110 | 111 | # Remove previously-imported pkg_resources if present (see 112 | # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details). 113 | if 'pkg_resources' in sys.modules: 114 | del sys.modules['pkg_resources'] 115 | 116 | import setuptools 117 | setuptools.bootstrap_install_from = egg 118 | 119 | 120 | def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, 121 | to_dir=os.curdir, download_delay=15): 122 | to_dir = os.path.abspath(to_dir) 123 | rep_modules = 'pkg_resources', 'setuptools' 124 | imported = set(sys.modules).intersection(rep_modules) 125 | try: 126 | import pkg_resources 127 | except ImportError: 128 | return _do_download(version, download_base, to_dir, download_delay) 129 | try: 130 | pkg_resources.require("setuptools>=" + version) 131 | return 132 | except pkg_resources.DistributionNotFound: 133 | return _do_download(version, download_base, to_dir, download_delay) 134 | except pkg_resources.VersionConflict as VC_err: 135 | if imported: 136 | msg = textwrap.dedent(""" 137 | The required version of setuptools (>={version}) is not available, 138 | and can't be installed while this script is running. Please 139 | install a more recent version first, using 140 | 'easy_install -U setuptools'. 141 | 142 | (Currently using {VC_err.args[0]!r}) 143 | """).format(VC_err=VC_err, version=version) 144 | sys.stderr.write(msg) 145 | sys.exit(2) 146 | 147 | # otherwise, reload ok 148 | del pkg_resources, sys.modules['pkg_resources'] 149 | return _do_download(version, download_base, to_dir, download_delay) 150 | 151 | def _clean_check(cmd, target): 152 | """ 153 | Run the command to download target. If the command fails, clean up before 154 | re-raising the error. 155 | """ 156 | try: 157 | subprocess.check_call(cmd) 158 | except subprocess.CalledProcessError: 159 | if os.access(target, os.F_OK): 160 | os.unlink(target) 161 | raise 162 | 163 | def download_file_powershell(url, target): 164 | """ 165 | Download the file at url to target using Powershell (which will validate 166 | trust). Raise an exception if the command cannot complete. 167 | """ 168 | target = os.path.abspath(target) 169 | cmd = [ 170 | 'powershell', 171 | '-Command', 172 | "(new-object System.Net.WebClient).DownloadFile(%(url)r, %(target)r)" % vars(), 173 | ] 174 | _clean_check(cmd, target) 175 | 176 | def has_powershell(): 177 | if platform.system() != 'Windows': 178 | return False 179 | cmd = ['powershell', '-Command', 'echo test'] 180 | devnull = open(os.path.devnull, 'wb') 181 | try: 182 | try: 183 | subprocess.check_call(cmd, stdout=devnull, stderr=devnull) 184 | except Exception: 185 | return False 186 | finally: 187 | devnull.close() 188 | return True 189 | 190 | download_file_powershell.viable = has_powershell 191 | 192 | def download_file_curl(url, target): 193 | cmd = ['curl', url, '--silent', '--output', target] 194 | _clean_check(cmd, target) 195 | 196 | def has_curl(): 197 | cmd = ['curl', '--version'] 198 | devnull = open(os.path.devnull, 'wb') 199 | try: 200 | try: 201 | subprocess.check_call(cmd, stdout=devnull, stderr=devnull) 202 | except Exception: 203 | return False 204 | finally: 205 | devnull.close() 206 | return True 207 | 208 | download_file_curl.viable = has_curl 209 | 210 | def download_file_wget(url, target): 211 | cmd = ['wget', url, '--quiet', '--output-document', target] 212 | _clean_check(cmd, target) 213 | 214 | def has_wget(): 215 | cmd = ['wget', '--version'] 216 | devnull = open(os.path.devnull, 'wb') 217 | try: 218 | try: 219 | subprocess.check_call(cmd, stdout=devnull, stderr=devnull) 220 | except Exception: 221 | return False 222 | finally: 223 | devnull.close() 224 | return True 225 | 226 | download_file_wget.viable = has_wget 227 | 228 | def download_file_insecure(url, target): 229 | """ 230 | Use Python to download the file, even though it cannot authenticate the 231 | connection. 232 | """ 233 | try: 234 | from urllib.request import urlopen 235 | except ImportError: 236 | from urllib2 import urlopen 237 | src = dst = None 238 | try: 239 | src = urlopen(url) 240 | # Read/write all in one block, so we don't create a corrupt file 241 | # if the download is interrupted. 242 | data = src.read() 243 | dst = open(target, "wb") 244 | dst.write(data) 245 | finally: 246 | if src: 247 | src.close() 248 | if dst: 249 | dst.close() 250 | 251 | download_file_insecure.viable = lambda: True 252 | 253 | def get_best_downloader(): 254 | downloaders = [ 255 | download_file_powershell, 256 | download_file_curl, 257 | download_file_wget, 258 | download_file_insecure, 259 | ] 260 | 261 | for dl in downloaders: 262 | if dl.viable(): 263 | return dl 264 | 265 | def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, 266 | to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): 267 | """ 268 | Download setuptools from a specified location and return its filename 269 | 270 | `version` should be a valid setuptools version number that is available 271 | as an egg for download under the `download_base` URL (which should end 272 | with a '/'). `to_dir` is the directory where the egg will be downloaded. 273 | `delay` is the number of seconds to pause before an actual download 274 | attempt. 275 | 276 | ``downloader_factory`` should be a function taking no arguments and 277 | returning a function for downloading a URL to a target. 278 | """ 279 | # making sure we use the absolute path 280 | to_dir = os.path.abspath(to_dir) 281 | zip_name = "setuptools-%s.zip" % version 282 | url = download_base + zip_name 283 | saveto = os.path.join(to_dir, zip_name) 284 | if not os.path.exists(saveto): # Avoid repeated downloads 285 | log.warn("Downloading %s", url) 286 | downloader = downloader_factory() 287 | downloader(url, saveto) 288 | return os.path.realpath(saveto) 289 | 290 | def _build_install_args(options): 291 | """ 292 | Build the arguments to 'python setup.py install' on the setuptools package 293 | """ 294 | return ['--user'] if options.user_install else [] 295 | 296 | def _parse_args(): 297 | """ 298 | Parse the command line for options 299 | """ 300 | parser = optparse.OptionParser() 301 | parser.add_option( 302 | '--user', dest='user_install', action='store_true', default=False, 303 | help='install in user site package (requires Python 2.6 or later)') 304 | parser.add_option( 305 | '--download-base', dest='download_base', metavar="URL", 306 | default=DEFAULT_URL, 307 | help='alternative URL from where to download the setuptools package') 308 | parser.add_option( 309 | '--insecure', dest='downloader_factory', action='store_const', 310 | const=lambda: download_file_insecure, default=get_best_downloader, 311 | help='Use internal, non-validating downloader' 312 | ) 313 | parser.add_option( 314 | '--version', help="Specify which version to download", 315 | default=DEFAULT_VERSION, 316 | ) 317 | options, args = parser.parse_args() 318 | # positional arguments are ignored 319 | return options 320 | 321 | def main(): 322 | """Install or upgrade setuptools and EasyInstall""" 323 | options = _parse_args() 324 | archive = download_setuptools( 325 | version=options.version, 326 | download_base=options.download_base, 327 | downloader_factory=options.downloader_factory, 328 | ) 329 | return _install(archive, _build_install_args(options)) 330 | 331 | if __name__ == '__main__': 332 | sys.exit(main()) 333 | -------------------------------------------------------------------------------- /Python/Adafruit_Python_BMP/munin/i2c_pressure: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # coding: utf-8 3 | 4 | from Adafruit_BMP085 import BMP085 5 | import sys 6 | 7 | # =========================================================================== 8 | # Munin Plugin - Pressure 9 | # =========================================================================== 10 | 11 | # Initialise the BMP085 and use STANDARD mode (default value) 12 | # bmp = BMP085(0x77, debug=True) 13 | bmp = BMP085(0x77) 14 | 15 | # To specify a different operating mode, uncomment one of the following: 16 | # bmp = BMP085(0x77, 0) # ULTRALOWPOWER Mode 17 | # bmp = BMP085(0x77, 1) # STANDARD Mode 18 | # bmp = BMP085(0x77, 2) # HIRES Mode 19 | # bmp = BMP085(0x77, 3) # ULTRAHIRES Mode 20 | 21 | temp = bmp.readTemperature() 22 | 23 | # Read the current barometric pressure level 24 | pressure = bmp.readPressure() 25 | 26 | is_config = len(sys.argv) == 2 and sys.argv[1] == "config" 27 | 28 | if is_config: 29 | print "graph_title Pressure (I2C)" 30 | print "graph_vlabel mBar" 31 | print "graph_category sensors" 32 | print "graph_scale no" 33 | print "graph_args -A -Y" 34 | print "pressure.label Pressure (mBar)" 35 | else: 36 | print "pressure.value %.4f" % (pressure / 100.0) 37 | -------------------------------------------------------------------------------- /Python/Adafruit_Python_BMP/munin/i2c_temperature: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # coding: utf-8 3 | 4 | from Adafruit_BMP085 import BMP085 5 | import sys 6 | 7 | # =========================================================================== 8 | # Munin Plugin - Temperature 9 | # =========================================================================== 10 | 11 | # Initialise the BMP085 and use STANDARD mode (default value) 12 | # bmp = BMP085(0x77, debug=True) 13 | bmp = BMP085(0x77) 14 | 15 | # To specify a different operating mode, uncomment one of the following: 16 | # bmp = BMP085(0x77, 0) # ULTRALOWPOWER Mode 17 | # bmp = BMP085(0x77, 1) # STANDARD Mode 18 | # bmp = BMP085(0x77, 2) # HIRES Mode 19 | # bmp = BMP085(0x77, 3) # ULTRAHIRES Mode 20 | 21 | temp = bmp.readTemperature() 22 | 23 | # Read the current barometric pressure level 24 | pressure = bmp.readPressure() 25 | 26 | is_config = len(sys.argv) == 2 and sys.argv[1] == "config" 27 | 28 | if is_config: 29 | print "graph_title Temperatur (I2C)" 30 | print "graph_vlabel °C" 31 | print "graph_category sensors" 32 | #print "graph_scale no" 33 | #print "graph_args -A -Y" 34 | print "temperature.label Temperatur (°C)" 35 | else: 36 | print "temperature.value %.4f" % temp 37 | -------------------------------------------------------------------------------- /Python/Adafruit_Python_BMP/setup.py: -------------------------------------------------------------------------------- 1 | from ez_setup import use_setuptools 2 | use_setuptools() 3 | from setuptools import setup, find_packages 4 | 5 | setup(name = 'Adafruit_BMP', 6 | version = '1.5.0', 7 | author = 'Tony DiCola', 8 | author_email = 'tdicola@adafruit.com', 9 | description = 'Library for accessing the BMP series pressure and temperature sensors like the BMP085/BMP180 on a Raspberry Pi or Beaglebone Black.', 10 | license = 'MIT', 11 | url = 'https://github.com/adafruit/Adafruit_Python_BMP/', 12 | dependency_links = ['https://github.com/adafruit/Adafruit_Python_GPIO/tarball/master#egg=Adafruit-GPIO-0.6.5'], 13 | install_requires = ['Adafruit-GPIO>=0.6.5'], 14 | packages = find_packages()) 15 | -------------------------------------------------------------------------------- /Python/LCD1602.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import time 4 | import smbus2 as smbus 5 | 6 | BUS = smbus.SMBus(1) 7 | 8 | def write_word(addr, data): 9 | global BLEN 10 | temp = data 11 | if BLEN == 1: 12 | temp |= 0x08 13 | else: 14 | temp &= 0xF7 15 | BUS.write_byte(addr ,temp) 16 | 17 | def send_command(comm): 18 | # Send bit7-4 firstly 19 | buf = comm & 0xF0 20 | buf |= 0x04 # RS = 0, RW = 0, EN = 1 21 | write_word(LCD_ADDR ,buf) 22 | time.sleep(0.002) 23 | buf &= 0xFB # Make EN = 0 24 | write_word(LCD_ADDR ,buf) 25 | 26 | # Send bit3-0 secondly 27 | buf = (comm & 0x0F) << 4 28 | buf |= 0x04 # RS = 0, RW = 0, EN = 1 29 | write_word(LCD_ADDR ,buf) 30 | time.sleep(0.002) 31 | buf &= 0xFB # Make EN = 0 32 | write_word(LCD_ADDR ,buf) 33 | 34 | def send_data(data): 35 | # Send bit7-4 firstly 36 | buf = data & 0xF0 37 | buf |= 0x05 # RS = 1, RW = 0, EN = 1 38 | write_word(LCD_ADDR ,buf) 39 | time.sleep(0.002) 40 | buf &= 0xFB # Make EN = 0 41 | write_word(LCD_ADDR ,buf) 42 | 43 | # Send bit3-0 secondly 44 | buf = (data & 0x0F) << 4 45 | buf |= 0x05 # RS = 1, RW = 0, EN = 1 46 | write_word(LCD_ADDR ,buf) 47 | time.sleep(0.002) 48 | buf &= 0xFB # Make EN = 0 49 | write_word(LCD_ADDR ,buf) 50 | 51 | def init(addr, bl): 52 | # global BUS 53 | # BUS = smbus.SMBus(1) 54 | global LCD_ADDR 55 | global BLEN 56 | LCD_ADDR = addr 57 | BLEN = bl 58 | try: 59 | send_command(0x33) # Must initialize to 8-line mode at first 60 | time.sleep(0.005) 61 | send_command(0x32) # Then initialize to 4-line mode 62 | time.sleep(0.005) 63 | send_command(0x28) # 2 Lines & 5*7 dots 64 | time.sleep(0.005) 65 | send_command(0x0C) # Enable display without cursor 66 | time.sleep(0.005) 67 | send_command(0x01) # Clear Screen 68 | BUS.write_byte(LCD_ADDR, 0x08) 69 | except: 70 | return False 71 | else: 72 | return True 73 | 74 | def clear(): 75 | send_command(0x01) # Clear Screen 76 | 77 | def openlight(): # Enable the backlight 78 | BUS.write_byte(0x27,0x08) 79 | BUS.close() 80 | 81 | def write(x, y, str): 82 | if x < 0: 83 | x = 0 84 | if x > 15: 85 | x = 15 86 | if y <0: 87 | y = 0 88 | if y > 1: 89 | y = 1 90 | 91 | # Move cursor 92 | addr = 0x80 + 0x40 * y + x 93 | send_command(addr) 94 | 95 | for chr in str: 96 | send_data(ord(chr)) 97 | 98 | if __name__ == '__main__': 99 | init(0x27, 1) 100 | write(4, 0, 'Hello') 101 | write(7, 1, 'world!') 102 | 103 | -------------------------------------------------------------------------------- /Python/PCF8591.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | #------------------------------------------------------ 3 | # 4 | # This is a program for PCF8591 Module. 5 | # 6 | # Warnng! The Analog input MUST NOT be over 3.3V! 7 | # 8 | # In this script, we use a poteniometer for analog 9 | # input, and a LED on AO for analog output. 10 | # 11 | # you can import this script to another by: 12 | # import PCF8591 as ADC 13 | # 14 | # ADC.Setup(Address) # Check it by sudo i2cdetect -y -1 15 | # ADC.read(channal) # Channal range from 0 to 3 16 | # ADC.write(Value) # Value range from 0 to 255 17 | # 18 | #------------------------------------------------------ 19 | import smbus2 as smbus 20 | import time 21 | 22 | # for RPI version 1, use "bus = smbus.SMBus(0)" 23 | bus = smbus.SMBus(1) 24 | 25 | #check your PCF8591 address by type in 'sudo i2cdetect -y -1' in terminal. 26 | def setup(Addr): 27 | global address 28 | address = Addr 29 | 30 | def read(chn): #channel 31 | try: 32 | if chn == 0: 33 | bus.write_byte(address,0x40) 34 | if chn == 1: 35 | bus.write_byte(address,0x41) 36 | if chn == 2: 37 | bus.write_byte(address,0x42) 38 | if chn == 3: 39 | bus.write_byte(address,0x43) 40 | bus.read_byte(address) # dummy read to start conversion 41 | except Exception as e: 42 | print ("Address: %s" % address) 43 | print (e) 44 | return bus.read_byte(address) 45 | 46 | def write(val): 47 | try: 48 | temp = val # move string value to temp 49 | temp = int(temp) # change string to integer 50 | # print temp to see on terminal else comment out 51 | bus.write_byte_data(address, 0x40, temp) 52 | except Exception as e: 53 | print ("Error: Device address: 0x%2X" % address) 54 | print (e) 55 | 56 | if __name__ == "__main__": 57 | setup(0x48) 58 | while True: 59 | print ('AIN0 = ', read(0)) 60 | print ('AIN1 = ', read(1)) 61 | tmp = read(0) 62 | tmp = tmp*(255-125)/255+125 # LED won't light up below 125, so convert '0-255' to '125-255' 63 | write(tmp) 64 | # time.sleep(0.3) 65 | -------------------------------------------------------------------------------- /Python/README.md: -------------------------------------------------------------------------------- 1 | ## Sunfounder SensorKit Python code for Raspberry Pi 2 | 3 | This is Sunfounder sensor kit python code for Raspberry Pi Model B/B+ and Raspberry Pi 2 Model B,Raspberry Pi 3 Model B/B+. 4 | If you have any questions about this kit, please contact with us. Our website is www.sunfounder.com, and our support E-mail is support@sunfounder.com 5 | 6 | -------------------------------------------------------------------------------- /Python/ds1302.py: -------------------------------------------------------------------------------- 1 | # RTC_DS1302 - Python Hardware Programming Education Project For Raspberry Pi 2 | # Copyright (C) 2015 Jason Birch 3 | # 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | 17 | ''' 18 | RTC_DS1302 19 | ''' 20 | ''' 21 | ------------------------------------------------------------------------ 22 | ''' 23 | ''' 24 | V1.00 - 2015-08-26 - Jason Birch 25 | ''' 26 | ''' 27 | ------------------------------------------------------------------------ 28 | ''' 29 | ''' 30 | Class to handle controlling a Real Time Clock IC DS1302. 31 | ''' 32 | 33 | import time 34 | import RPi.GPIO 35 | from datetime import datetime 36 | 37 | 38 | class DS1302: 39 | 40 | CLK_PERIOD = 0.00001 41 | 42 | DOW = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] 43 | 44 | 45 | def __init__(self, scl=23, rst=25, io=24): 46 | self.scl = scl 47 | self.rst = rst 48 | self.io = io 49 | # Turn off GPIO warnings. 50 | RPi.GPIO.setwarnings(False) 51 | # Configure Raspberry Pi GPIO interfaces. 52 | RPi.GPIO.setmode(RPi.GPIO.BCM) 53 | # Initiate DS1302 communication. 54 | self.init_ds1302() 55 | # Make sure write protect is turned off. 56 | self.write_byte(int("10001110", 2)) 57 | self.write_byte(int("00000000", 2)) 58 | # Make sure trickle charge mode is turned off. 59 | self.write_byte(int("10010000", 2)) 60 | self.write_byte(int("00000000", 2)) 61 | # End DS1302 communication. 62 | self.end_ds1302() 63 | self.datetime = {} 64 | 65 | def CloseGPIO(self): 66 | ''' 67 | Close Raspberry Pi GPIO use before finishing. 68 | ''' 69 | RPi.GPIO.cleanup() 70 | 71 | 72 | def init_ds1302(self): 73 | ''' 74 | Start a transaction with the DS1302 RTC. 75 | ''' 76 | RPi.GPIO.setup(self.scl, RPi.GPIO.OUT, initial=0) 77 | RPi.GPIO.setup(self.rst, RPi.GPIO.OUT, initial=0) 78 | RPi.GPIO.setup(self.io, RPi.GPIO.OUT, initial=0) 79 | RPi.GPIO.output(self.scl, 0) 80 | RPi.GPIO.output(self.io, 0) 81 | time.sleep(self.CLK_PERIOD) 82 | RPi.GPIO.output(self.rst, 1) 83 | 84 | 85 | def end_ds1302(self): 86 | ''' 87 | Complete a transaction with the DS1302 RTC. 88 | ''' 89 | RPi.GPIO.setup(self.scl, RPi.GPIO.OUT, initial=0) 90 | RPi.GPIO.setup(self.rst, RPi.GPIO.OUT, initial=0) 91 | RPi.GPIO.setup(self.io, RPi.GPIO.OUT, initial=0) 92 | RPi.GPIO.output(self.scl, 0) 93 | RPi.GPIO.output(self.io, 0) 94 | time.sleep(self.CLK_PERIOD) 95 | RPi.GPIO.output(self.rst, 0) 96 | 97 | 98 | def write_byte(self, Byte): 99 | ''' 100 | Write a byte of data to the DS1302 RTC. 101 | ''' 102 | for Count in range(8): 103 | time.sleep(self.CLK_PERIOD) 104 | RPi.GPIO.output(self.scl, 0) 105 | 106 | Bit = Byte % 2 107 | Byte = int(Byte / 2) 108 | time.sleep(self.CLK_PERIOD) 109 | RPi.GPIO.output(self.io, Bit) 110 | 111 | time.sleep(self.CLK_PERIOD) 112 | RPi.GPIO.output(self.scl, 1) 113 | 114 | def read_byte(self): 115 | ''' 116 | Read a byte of data to the DS1302 RTC. 117 | ''' 118 | RPi.GPIO.setup(self.io, RPi.GPIO.IN, pull_up_down=RPi.GPIO.PUD_DOWN) 119 | 120 | Byte = 0 121 | for Count in range(8): 122 | time.sleep(self.CLK_PERIOD) 123 | RPi.GPIO.output(self.scl, 1) 124 | 125 | time.sleep(self.CLK_PERIOD) 126 | RPi.GPIO.output(self.scl, 0) 127 | 128 | time.sleep(self.CLK_PERIOD) 129 | Bit = RPi.GPIO.input(self.io) 130 | Byte |= ((2 ** Count) * Bit) 131 | 132 | return Byte 133 | 134 | 135 | def write_ram(self, Data): 136 | ''' 137 | Write a message to the RTC RAM. 138 | ''' 139 | # Initiate DS1302 communication. 140 | self.init_ds1302() 141 | # Write address byte. 142 | self.write_byte(int("11111110", 2)) 143 | # Write data bytes. 144 | for Count in range(len(Data)): 145 | self.write_byte(ord(Data[Count:Count + 1])) 146 | for Count in range(31 - len(Data)): 147 | self.write_byte(ord(" ")) 148 | # End DS1302 communication. 149 | self.end_ds1302() 150 | 151 | def read_ram(self): 152 | ''' 153 | Read message from the RTC RAM. 154 | ''' 155 | # Initiate DS1302 communication. 156 | self.init_ds1302() 157 | # Write address byte. 158 | self.write_byte(int("11111111", 2)) 159 | # Read data bytes. 160 | Data = "" 161 | for Count in range(31): 162 | Byte = self.read_byte() 163 | Data += chr(Byte) 164 | # End DS1302 communication. 165 | self.end_ds1302() 166 | return Data 167 | 168 | 169 | def set_datetime(self, dt): 170 | ''' 171 | Write date and time to the RTC. 172 | ''' 173 | if not self.check_sanity(): 174 | return False 175 | # Initiate DS1302 communication. 176 | self.init_ds1302() 177 | # Write address byte. 178 | self.write_byte(int("10111110", 2)) 179 | # Write seconds data. 180 | self.write_byte((dt.second % 10) | int(dt.second / 10) * 16) 181 | # Write minute data. 182 | self.write_byte((dt.minute % 10) | int(dt.minute / 10) * 16) 183 | # Write hour data. 184 | self.write_byte((dt.hour % 10) | int(dt.hour / 10) * 16) 185 | # Write day data. 186 | self.write_byte((dt.day % 10) | int(dt.day / 10) * 16) 187 | # Write month data. 188 | self.write_byte((dt.month % 10) | int(dt.month / 10) * 16) 189 | # Write day of week data. 190 | self.write_byte((dt.isoweekday() % 10) | int(dt.isoweekday() / 10) * 16) 191 | # Write year data. 192 | self.write_byte((dt.year % 100 % 10) | int(dt.year % 100 / 10) * 16) 193 | # Make sure write protect is turned off. 194 | self.write_byte(int("00000000", 2)) 195 | # Make sure trickle charge mode is turned off. 196 | self.write_byte(int("00000000", 2)) 197 | # End DS1302 communication. 198 | self.end_ds1302() 199 | 200 | 201 | def get_datetime(self): 202 | ''' 203 | Read date and time from the RTC. 204 | ''' 205 | # Initiate DS1302 communication. 206 | self.init_ds1302() 207 | # Write address byte. 208 | self.write_byte(int("10111111", 2)) 209 | # Read date and time data. 210 | Data = "" 211 | 212 | Byte = self.read_byte() 213 | second = (Byte % 16) + int(Byte / 16) * 10 214 | Byte = self.read_byte() 215 | minute = (Byte % 16) + int(Byte / 16) * 10 216 | Byte = self.read_byte() 217 | hour = (Byte % 16) + int(Byte / 16) * 10 218 | Byte = self.read_byte() 219 | day = (Byte % 16) + int(Byte / 16) * 10 220 | Byte = self.read_byte() 221 | month = (Byte % 16) + int(Byte / 16) * 10 222 | Byte = self.read_byte() 223 | day_of_week = ((Byte % 16) + int(Byte / 16) * 10) - 1 224 | Byte = self.read_byte() 225 | year = (Byte % 16) + int(Byte / 16) * 10 + 2000 226 | 227 | # End DS1302 communication. 228 | self.end_ds1302() 229 | return datetime(year, month, day, hour, minute, second) 230 | 231 | def check_sanity(self): 232 | "check sanity of a clock. returns True if clock is sane and False otherwise" 233 | dt = self.get_datetime() 234 | if dt.year == 2000 or dt.month == 0 or dt.day == 0: 235 | return False 236 | if dt.second == 80: 237 | return False 238 | return True 239 | 240 | def format_time(dt): 241 | if dt is None: 242 | return "" 243 | fmt = "%m/%d/%Y %H:%M" 244 | return dt.strftime(fmt) 245 | 246 | def parse_time(s): 247 | fmt = "%m/%d/%Y %H:%M" 248 | return datetime.strptime(s, fmt) 249 | 250 | -------------------------------------------------------------------------------- /Python/lircrc: -------------------------------------------------------------------------------- 1 | begin 2 | remote = * 3 | button = KEY_CHANNELDOWN 4 | prog = ircontrol 5 | config = KEY_CHANNELDOWN 6 | end 7 | 8 | begin 9 | remote = * 10 | button = KEY_CHANNEL 11 | prog = ircontrol 12 | config = KEY_CHANNEL 13 | end 14 | 15 | begin 16 | remote = * 17 | button = KEY_CHANNELUP 18 | prog = ircontrol 19 | config = KEY_CHANNELUP 20 | end 21 | 22 | begin 23 | remote = * 24 | button = KEY_PREVIOUS 25 | prog = ircontrol 26 | config = KEY_PREVIOUS 27 | end 28 | 29 | begin 30 | remote = * 31 | button = KEY_NEXT 32 | prog = ircontrol 33 | config = KEY_NEXT 34 | end 35 | 36 | begin 37 | remote = * 38 | button = KEY_PLAYPAUSE 39 | prog = ircontrol 40 | config = KEY_PLAYPAUSE 41 | end 42 | 43 | begin 44 | remote = * 45 | button = KEY_VOLUMEDOWN 46 | prog = ircontrol 47 | config = KEY_VOLUMEDOWN 48 | end 49 | 50 | begin 51 | remote = * 52 | button = KEY_VOLUMEUP 53 | prog = ircontrol 54 | config = KEY_VOLUMEUP 55 | end 56 | 57 | begin 58 | remote = * 59 | button = KEY_EQUAL 60 | prog = ircontrol 61 | config = KEY_EQUAL 62 | end 63 | 64 | begin 65 | remote = * 66 | button = KEY_NUMERIC_0 67 | prog = ircontrol 68 | config = KEY_NUMERIC_0 69 | end 70 | 71 | begin 72 | remote = * 73 | button = KEY_NUMERIC_1 74 | prog = ircontrol 75 | config = KEY_NUMERIC_1 76 | end 77 | 78 | begin 79 | remote = * 80 | button = KEY_NUMERIC_2 81 | prog = ircontrol 82 | config = KEY_NUMERIC_2 83 | end 84 | 85 | begin 86 | remote = * 87 | button = KEY_NUMERIC_3 88 | prog = ircontrol 89 | config = KEY_NUMERIC_3 90 | end 91 | 92 | begin 93 | remote = * 94 | button = KEY_NUMERIC_4 95 | prog = ircontrol 96 | config = KEY_NUMERIC_4 97 | end 98 | 99 | begin 100 | remote = * 101 | button = KEY_NUMERIC_5 102 | prog = ircontrol 103 | config = KEY_NUMERIC_5 104 | end 105 | 106 | begin 107 | remote = * 108 | button = KEY_NUMERIC_6 109 | prog = ircontrol 110 | config = KEY_NUMERIC_6 111 | end 112 | 113 | begin 114 | remote = * 115 | button = KEY_NUMERIC_7 116 | prog = ircontrol 117 | config = KEY_NUMERIC_7 118 | end 119 | 120 | begin 121 | remote = * 122 | button = KEY_NUMERIC_8 123 | prog = ircontrol 124 | config = KEY_NUMERIC_8 125 | end 126 | 127 | begin 128 | remote = * 129 | button = KEY_NUMERIC_9 130 | prog = ircontrol 131 | config = KEY_NUMERIC_9 132 | end 133 | 134 | begin 135 | remote = * 136 | button = BTN_0 137 | prog = ircontrol 138 | config = BTN_0 139 | end 140 | 141 | begin 142 | remote = * 143 | button = BTN_1 144 | prog = ircontrol 145 | config = BTN_1: 146 | end 147 | -------------------------------------------------------------------------------- /Python/rpi_time_bak2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from datetime import datetime 3 | import ds1302 4 | 5 | 6 | class DS1302: 7 | def __init__(self, rangechecks=True): 8 | self.rangechecks = rangechecks 9 | ds1302.init_clock() 10 | 11 | def get_datetime(self): 12 | if not self.check_sanity(): 13 | # if clock are insane: try to reset it 14 | self.reset_clock() 15 | # if clock are still insane: return None 16 | if not self.check_sanity(): 17 | return None 18 | year, month, date = ds1302.get_date() 19 | hour, minute, second = ds1302.get_time() 20 | ''' 21 | if self.rangechecks: 22 | if year < 2000 or year > 3000: 23 | ds1302.set_date(2000, month, date) 24 | return self.get_datetime() 25 | if month not in range(1, 13): 26 | ds1302.set_date(year, 1, date) 27 | return self.get_datetime() 28 | if date not in range(1, 32): 29 | ds1302.set_date(year, month, 1) 30 | return self.get_datetime() 31 | if hour not in range(0, 24): 32 | ds1302.set_time(0, minute, second) 33 | return self.get_datetime() 34 | if minute not in range(0, 60): 35 | ds1302.set_time(hour, 0, second) 36 | return self.get_datetime() 37 | if second not in range(0, 60): 38 | ds1302.set_time(hour, minute, 0) 39 | return self.get_datetime() 40 | ''' 41 | return datetime(year, month, date, 42 | hour, minute, second) 43 | 44 | 45 | def set_datetime(self, dt): 46 | if not self.check_sanity(): 47 | # if clock are insane: try to reset it 48 | self.reset_clock() 49 | # if clock are still insane: return False 50 | if not self.check_sanity(): 51 | return False 52 | ds1302.set_date(dt.year, dt.month, dt.day) 53 | ds1302.set_time(dt.hour, dt.minute, dt.second) 54 | return True 55 | 56 | def check_sanity(self): 57 | "check sanity of a clock. returns True if clock is sane and False otherwise" 58 | year, month, date = ds1302.get_date() 59 | hours, mins, secs = ds1302.get_time() 60 | if year == 2000 or month == 0 or date == 0: 61 | return False 62 | if secs == 80: 63 | return False 64 | return True 65 | 66 | def reset_clock(self): 67 | ds1302.reset_clock() 68 | 69 | def format_time(dt): 70 | if dt is None: 71 | return "" 72 | fmt = "%m/%d/%Y %H:%M" 73 | return dt.strftime(fmt) 74 | 75 | def parse_time(s): 76 | fmt = "%m/%d/%Y %H:%M" 77 | return datetime.strptime(s, fmt) 78 | 79 | 80 | 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## SunFounder Sensor Kit V2.0 for RPi 2 2 | SunFounder Sensor Kit V2.0 for **RaspberryPi 2B**, compatible for **Rev.1 Module B/B+**, **Rev 3 Module B** 3 | 4 | Quick Links: 5 | 6 | * [About SunFounder Sensor Kit V2.0](#about_this_kit) 7 | * [Update](#update) 8 | * [About SunFounder](#about_sunfounder) 9 | * [License](#license) 10 | * [Contact us](#contact_us) 11 | 12 | 13 | ### About SunFounder Sensor Kit V2.0: 14 | This is a kit with whole bunch of sensors and activaters, provided by SunFounder. The code here contains C and Python and are both for Raspberry Pi. If any error or BUGs, wellcom to post issus in Github, or [Email](#contact_us) us. 15 | 16 | 17 | ### Update: 18 | 2020.8.13: 19 | - add a new method of install system 20 | - Replace the Raspbian to Raspberry Pi OS 21 | - Add a way to manually update the wiringPi to 2.52 22 | 23 | 2020-1-3: 24 | - Replace the 5v to 3.3V in the user manual. 25 | - update the English user manual for Raspberry Pi 4. 26 | 27 | 2019-10-12: 28 | - add in the German version of user manual. 29 | - update the English user manual for Raspberry Pi 4. 30 | 31 | 2019-09-06: 32 | 33 | - fix the bugs of print function for python3 34 | - fix the bus of ds1302, Barometer,ds18b20. 35 | 36 | 2016-10-09: 37 | 38 | - Add BMP280 both C and Python 39 | + Add BMP280 for the Newest kit. 40 | 41 | ---------------------------------------------- 42 | 43 | ### About SunFounder 44 | SunFounder is a technology company focused on Raspberry Pi and Arduino open source community development. Committed to the promotion of open source culture, we strives to bring the fun of electronics making to people all around the world and enable everyone to be a maker. Our products include learning kits, development boards, robots, sensor modules and development tools. In addition to high quality products, SunFounder also offers video tutorials to help you make your own project. If you have interest in open source or making something cool, welcome to join us! 45 | 46 | ---------------------------------------------- 47 | 48 | ### License 49 | This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 50 | 51 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied wa rranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 52 | 53 | You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 54 | 55 | {Repository Name} comes with ABSOLUTELY NO WARRANTY; for details run ./show w. This is free software, and you are welcome to redistribute it under certain conditions; run ./show c for details. 56 | 57 | SunFounder, Inc., hereby disclaims all copyright interest in the program '{Repository Name}' (which makes passes at compilers). 58 | 59 | Mike Huang, 21 August 2015 60 | 61 | Mike Huang, Chief Executive Officer 62 | 63 | Email: service@sunfounder.com, support@sunfounder.com 64 | 65 | ---------------------------------------------- 66 | 67 | ### Contact us: 68 | website: 69 | www.sunfounder.com 70 | 71 | E-mail: 72 | service@sunfounder.com, support@sunfounder.com 73 | -------------------------------------------------------------------------------- /show: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import sys 3 | 4 | license = open('LICENSE') 5 | flag = False 6 | 7 | def notice(): 8 | print 'Command Error.\nUsage:\n show c Show Conditions\n show w Show No Warranty' 9 | quit() 10 | 11 | def showc(): 12 | global flag 13 | for i in license: 14 | if i[0:4] == ' 2.': 15 | flag = True 16 | print '\n' 17 | print ' Conditions:' 18 | if flag == True and i[0:4] == ' ': 19 | if i[4:7] in ['a) ', 'b) ', 'c) ']: 20 | print '\n' 21 | print i[4:-1], 22 | if i[0:4] == ' 3.': 23 | flag = False 24 | 25 | def showw(): 26 | global flag 27 | for i in license: 28 | if i[-14:-1] == ' NO WARRANTY': 29 | flag = True 30 | print '\n' 31 | if i[-28:-1] == 'END OF TERMS AND CONDITIONS': 32 | flag = False 33 | if flag == True: 34 | if i[0:6] == ' 11. ': 35 | i = i[0:2] + i[3:] 36 | print '\n' 37 | if i[0:6] == ' 12. ': 38 | i = i[0:2] + i[3:] 39 | print '\n' 40 | print i[:-1], 41 | 42 | def main(): 43 | if len(sys.argv) != 2: 44 | notice() 45 | elif sys.argv[1] == 'c' or sys.argv[1] == 'C': 46 | showc() 47 | elif sys.argv[1] == 'w' or sys.argv[1] == 'W': 48 | showw() 49 | else: 50 | notice() 51 | 52 | if __name__ == "__main__": 53 | try: 54 | main() 55 | finally: 56 | pass 57 | 58 | --------------------------------------------------------------------------------