New Release.

Extensive updates.
Optimize code and comments.
This commit is contained in:
Suhayl
2019-12-28 15:21:48 +08:00
parent 9c283ca5ef
commit c9cfe0fcd3
101 changed files with 933 additions and 2630 deletions
+15 -20
View File
@@ -1,34 +1,29 @@
/**********************************************************************
* Filename : Blink.c
* Description : Make an led blinking.
* Description : Basic usage of GPIO. Let led blink.
* auther : www.freenove.com
* modification: 2016/06/07
* modification: 2019/12/26
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
#define ledPin 0
#define ledPin 0 //define the led pin number
int main(void)
{
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
//when initialize wiring successfully,print message to screen
printf("wiringPi initialize successfully, GPIO %d(wiringPi pin)\n",ledPin);
void main(void)
{
printf("Program is starting ... \n");
wiringPiSetup(); //Initialize wiringPi.
pinMode(ledPin, OUTPUT);//Set the pin mode
printf("Using pin%d\n",%ledPin); //Output information on terminal
while(1){
digitalWrite(ledPin, HIGH); //led on
printf("led on...\n");
delay(1000);
digitalWrite(ledPin, LOW); //led off
printf("...led off\n");
delay(1000);
digitalWrite(ledPin, HIGH); //Make GPIO output HIGH level
printf("led turned on >>>\n"); //Output information on terminal
delay(1000); //Wait for 1 second
digitalWrite(ledPin, LOW); //Make GPIO output LOW level
printf("led turned off <<<\n"); //Output information on terminal
delay(1000); //Wait for 1 second
}
return 0;
}
+16 -20
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : ButtonLED.c
* Description : Controlling an led by button.
* Author : freenove
* modification: 2016/06/12
* Description : Control led by button.
* Author : www.freenove.com
* modification: 2019/12/26
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
@@ -10,29 +10,25 @@
#define ledPin 0 //define the ledPin
#define buttonPin 1 //define the buttonPin
int main(void)
void main(void)
{
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ... \n");
pinMode(ledPin, OUTPUT); //Set ledPin output
pinMode(buttonPin, INPUT);//Set buttonPin input
wiringPiSetup(); //Initialize wiringPi.
pinMode(ledPin, OUTPUT); //Set ledPin to output
pinMode(buttonPin, INPUT);//Set buttonPin to input
pullUpDnControl(buttonPin, PUD_UP); //pull up to high level
pullUpDnControl(buttonPin, PUD_UP); //pull up to HIGH level
while(1){
if(digitalRead(buttonPin) == LOW){ //button has pressed down
digitalWrite(ledPin, HIGH); //led on
printf("led on...\n");
if(digitalRead(buttonPin) == LOW){ //button is pressed
digitalWrite(ledPin, HIGH); //Make GPIO output HIGH level
printf("Button is pressed, led turned on >>>\n"); //Output information on terminal
}
else { //button has released
digitalWrite(ledPin, LOW); //led off
printf("...led off\n");
else { //button is released
digitalWrite(ledPin, LOW); //Make GPIO output LOW level
printf("Button is released, led turned off <<<\n"); //Output information on terminal
}
}
return 0;
}
+15 -16
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : Tablelamp.c
* Description : a DIY MINI table lamp
* Author : freenove
* modification: 2016/06/13
* Description : DIY MINI table lamp
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
@@ -13,34 +13,33 @@ int ledState=LOW; //store the State of led
int buttonState=HIGH; //store the State of button
int lastbuttonState=HIGH;//store the lastState of button
long lastChangeTime; //store the change time of button state
long captureTime=50; //set the button state stable time
long captureTime=50; //set the stable time for button state
int reading;
int main(void)
{
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting...\n");
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
wiringPiSetup(); //Initialize wiringPi.
pinMode(ledPin, OUTPUT); Set ledPin to output
pinMode(buttonPin, INPUT); Set buttonPin to input
pullUpDnControl(buttonPin, PUD_UP); //pull up to high level
while(1){
reading = digitalRead(buttonPin); //read the current state of button
if( reading != lastbuttonState){ //if the button state has changed ,record the time point
if( reading != lastbuttonState){ //if the button state has changed, record the time point
lastChangeTime = millis();
}
//if changing-state of the button last beyond the time we set,we considered that
//if changing-state of the button last beyond the time we set, we consider that
//the current button state is an effective change rather than a buffeting
if(millis() - lastChangeTime > captureTime){
//if button state is changed ,update the data.
//if button state is changed, update the data.
if(reading != buttonState){
buttonState = reading;
//if the state is low ,the action is pressing
//if the state is low, it means the action is pressing
if(buttonState == LOW){
printf("Button is pressed!\n");
ledState = !ledState; //Turn the LED state .
ledState = !ledState; //Reverse the LED state
if(ledState){
printf("turn on LED ...\n");
}
@@ -48,7 +47,7 @@ int main(void)
printf("turn off LED ...\n");
}
}
//if the state is high ,the action is releasing
//if the state is high, it means the action is releasing
else {
printf("Button is released!\n");
}
+16 -26
View File
@@ -1,46 +1,36 @@
/**********************************************************************
* Filename : LightWater.c
* Description : Display 10 LEDBar Graph
* Author : freenove
* modification: 2016/06/13
* Description : Use LEDBar Graph(10 LED)
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
#define leds 10
int pins[leds] = {0,1,2,3,4,5,6,8,9,10};
void led_on(int n)//make led_n on
{
digitalWrite(n, LOW);
}
void led_off(int n)//make led_n off
{
digitalWrite(n, HIGH);
}
#define ledCounts 10
int pins[ledCounts] = {0,1,2,3,4,5,6,8,9,10};
int main(void)
void main(void)
{
int i;
printf("Program is starting ... \n");
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
for(i=0;i<leds;i++){ //make leds pins' mode is output
wiringPiSetup(); //Initialize wiringPi.
for(i=0;i<ledCounts;i++){ //Set pinMode for all led pins to output
pinMode(pins[i], OUTPUT);
}
while(1){
for(i=0;i<leds;i++){ //make led on from left to right
led_on(pins[i]);
for(i=0;i<ledCounts;i++){ // move led(on) from left to right
digitalWrite(pins[i],LOW);
delay(100);
led_off(pins[i]);
digitalWrite(pins[i],HIGH);
}
for(i=leds-1;i>-1;i--){ //make led on from right to left
led_on(pins[i]);
for(i=ledCounts-1;i>-1;i--){ // move led(on) from right to left
digitalWrite(pins[i],LOW);
delay(100);
led_off(pins[i]);
digitalWrite(pins[i],HIGH);
}
}
return 0;
}
+13 -16
View File
@@ -1,39 +1,36 @@
/**********************************************************************
* Filename : BreathingLED.c
* Description : A breathing LED
* Author : freenove
* modification: 2019/07/05
* Description : Make breathing LED with PWM
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
#include <softPwm.h>
#define ledPin 1 //Only GPIO18 can output PWM
#define ledPin 1
int main(void)
void main(void)
{
int i;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ... \n");
wiringPiSetup(); //Initialize wiringPi.
softPwmCreate(ledPin, 0, 100);//Creat SoftPWM pin
while(1){
for(i=0;i<100;i++){
softPwmWrite(ledPin, i);
for(i=0;i<100;i++){ //make the led brighter
softPwmWrite(ledPin, i);
delay(20);
}
delay(300);
for(i=100;i>=0;i--){
for(i=100;i>=0;i--){ //make the led darker
softPwmWrite(ledPin, i);
delay(20);
}
delay(300);
}
return 0;
}
+20 -21
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : ColorfulLED.c
* Description : A auto flash ColorfulLED
* Author : freenove
* modification: 2019/07/05
* Description : Random color change ColorfulLED
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <softPwm.h>
@@ -13,35 +13,34 @@
#define ledPinGreen 1
#define ledPinBlue 2
void ledInit(void)
void setupLedPin(void)
{
softPwmCreate(ledPinRed, 0, 100);//Creat SoftPWM pin
softPwmCreate(ledPinGreen,0, 100);
softPwmCreate(ledPinBlue, 0, 100);
softPwmCreate(ledPinRed, 0, 100); //Creat SoftPWM pin for red
softPwmCreate(ledPinGreen,0, 100); //Creat SoftPWM pin for green
softPwmCreate(ledPinBlue, 0, 100); //Creat SoftPWM pin for blue
}
void ledColorSet(int r_val, int g_val, int b_val)
void setLedColor(int r, int g, int b)
{
softPwmWrite(ledPinRed, r_val);//Set the duty cycle
softPwmWrite(ledPinGreen, g_val);
softPwmWrite(ledPinBlue, b_val);
softPwmWrite(ledPinRed, r); //Set the duty cycle
softPwmWrite(ledPinGreen, g); //Set the duty cycle
softPwmWrite(ledPinBlue, b); //Set the duty cycle
}
int main(void)
{
int r,g,b;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ...\n");
ledInit();
wiringPiSetup(); //Initialize wiringPi.
setupLedPin();
while(1){
r=random()%100;//get a random in (0,100)
g=random()%100;
b=random()%100;
ledColorSet(r,g,b);//set random as a duty cycle value
r=random()%100; //get a random in (0,100)
g=random()%100; //get a random in (0,100)
b=random()%100; //get a random in (0,100)
setLedColor(r,g,b);//set random as the duty cycle value
printf("r=%d, g=%d, b=%d \n",r,g,b);
delay(300);
}
+15 -18
View File
@@ -1,38 +1,35 @@
/**********************************************************************
* Filename : Doorbell.c
* Description : Controlling an buzzer by button.
* Author : freenove
* modification: 2016/06/12
* Description : Make doorbell with buzzer and button.
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
#define buzzerPin 0 //define the buzzerPin
#define buzzerPin 0 //define the buzzerPin
#define buttonPin 1 //define the buttonPin
int main(void)
void main(void)
{
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ... \n");
wiringPiSetup();
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT);
pullUpDnControl(buttonPin, PUD_UP); //pull up to high level
pullUpDnControl(buttonPin, PUD_UP); //pull up to HIGH level
while(1){
if(digitalRead(buttonPin) == LOW){ //button has pressed down
digitalWrite(buzzerPin, HIGH); //buzzer on
printf("buzzer on...\n");
if(digitalRead(buttonPin) == LOW){ //button is pressed
digitalWrite(buzzerPin, HIGH); //Turn on buzzer
printf("buzzer turned on >>> \n");
}
else { //button has released
digitalWrite(buzzerPin, LOW); //buzzer off
printf("...buzzer off\n");
else { //button is released
digitalWrite(buzzerPin, LOW); //Turn off buzzer
printf("buzzer turned off <<< \n");
}
}
return 0;
}
+19 -19
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : Alertor.c
* Description : Alarm by button.
* Author : freenove
* modification: 2016/06/14
* Description : Make Alertor with buzzer and button.
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
@@ -15,10 +15,10 @@
void alertor(int pin){
int x;
double sinVal, toneVal;
for(x=0;x<360;x++){ //frequency of the alarm along the sine wave change
sinVal = sin(x * (M_PI / 180)); //calculate the sine value
toneVal = 2000 + sinVal * 500; //Add to the resonant frequency with a Weighted
softToneWrite(pin,toneVal); //output PWM
for(x=0;x<360;x++){ // frequency of the alertor is consistent with the sine wave
sinVal = sin(x * (M_PI / 180)); //Calculate the sine value
toneVal = 2000 + sinVal * 500; //Add the resonant frequency and weighted sine value
softToneWrite(pin,toneVal); //output corresponding PWM
delay(1);
}
}
@@ -27,22 +27,22 @@ void stopAlertor(int pin){
}
int main(void)
{
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ... \n");
wiringPiSetup();
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT);
softToneCreate(buzzerPin);
pullUpDnControl(buttonPin, PUD_UP); //pull up to high level
softToneCreate(buzzerPin); //set buzzerPin
pullUpDnControl(buttonPin, PUD_UP); //pull up to HIGH level
while(1){
if(digitalRead(buttonPin) == LOW){ //button has pressed down
alertor(buzzerPin); //buzzer on
printf("alertor on...\n");
if(digitalRead(buttonPin) == LOW){ //button is pressed
alertor(buzzerPin); // turn on buzzer
printf("alertor turned on >>> \n");
}
else { //button has released
stopAlertor(buzzerPin); //buzzer off
printf("...buzzer off\n");
else { //button is released
stopAlertor(buzzerPin); // turn off buzzer
printf("alertor turned off <<< \n");
}
}
return 0;
+10 -7
View File
@@ -1,16 +1,15 @@
/**********************************************************************
* Filename : ADC.c
* Description : ADC and DAC
* Author : freenove
* modification: 2018/09/15
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <pcf8591.h>
#include <stdio.h>
#define address 0x48 //pcf8591 default address
#define pinbase 64 //any number above 64
#define pinbase 64 //any number above 64 (according to the wiringPi library)
#define A0 pinbase + 0
#define A1 pinbase + 1
#define A2 pinbase + 2
@@ -19,13 +18,17 @@
int main(void){
int value;
float voltage;
wiringPiSetup();
printf("Program is starting ... \n");
wiringPiSetup(); //Initialize wiringPi.
pcf8591Setup(pinbase,address);
while(1){
value = analogRead(A0); //read A0 pin
value = analogRead(A0); //read analog value of A0 pin
analogWrite(pinbase+0,value);
voltage = (float)value / 255.0 * 3.3; // calculate voltage
voltage = (float)value / 255.0 * 3.3; // Calculate voltage
printf("ADC value : %d ,\tVoltage : %.2fV\n",value,voltage);
delay(100);
}
+8 -7
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : Softlight.c
* Description : Potentiometer control LED
* Author : freenove
* modification: 2016/06/18
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <pcf8591.h>
@@ -20,15 +20,16 @@
int main(void){
int value;
float voltage;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ... \n");
wiringPiSetup();
softPwmCreate(ledPin,0,100);
pcf8591Setup(pinbase,address);
while(1){
value = analogRead(A0); //read A0 pin
value = analogRead(A0); //read analog value of A0 pin
softPwmWrite(ledPin,value*100/255);
voltage = (float)value / 255.0 * 3.3; // calculate voltage
printf("ADC value : %d ,\tVoltage : %.2fV\n",value,voltage);
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : ColorfulSoftlight.c
* Description : Potentiometer control RGBLED
* Author : freenove
* modification: 2016/07/03
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <pcf8591.h>
@@ -16,22 +16,23 @@
#define A2 pinbase + 2
#define A3 pinbase + 3
#define ledRedPin 3 //define 3 pins of RGBLED
#define ledRedPin 3 //define 3 pins for RGBLED
#define ledGreenPin 2
#define ledBluePin 0
int main(void){
int val_Red,val_Green,val_Blue;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ... \n");
wiringPiSetup();
softPwmCreate(ledRedPin,0,100); //creat 3 PMW output pins for RGBLED
softPwmCreate(ledGreenPin,0,100);
softPwmCreate(ledBluePin,0,100);
pcf8591Setup(pinbase,address); //initialize PCF8591
while(1){
val_Red = analogRead(A0); //read 3 potentiometers
val_Red = analogRead(A0); //read analog value of 3 potentiometers
val_Green = analogRead(A1);
val_Blue = analogRead(A2);
softPwmWrite(ledRedPin,val_Red*100/255); //map the read value of potentiometers into PWM value and output it
+8 -7
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : Nightlamp.c
* Description : Photoresistor control LED
* Author : freenove
* modification: 2016/06/18
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <pcf8591.h>
@@ -20,15 +20,16 @@
int main(void){
int value;
float voltage;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ... \n");
wiringPiSetup();
softPwmCreate(ledPin,0,100);
pcf8591Setup(pinbase,address);
while(1){
value = analogRead(A0); //read A0 pin
value = analogRead(A0); //read analog value of A0 pin
softPwmWrite(ledPin,value*100/255);
voltage = (float)value / 255.0 * 3.3; // calculate voltage
printf("ADC value : %d ,\tVoltage : %.2fV\n",value,voltage);
Binary file not shown.
+9 -8
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : Thermometer.c
* Description : A DIY Thermometer
* Author : freenove
* modification: 2016/06/20
* Description : DIY Thermometer
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <pcf8591.h>
@@ -20,13 +20,14 @@ int main(void){
int adcValue;
float tempK,tempC;
float voltage,Rt;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ... \n");
wiringPiSetup();
pcf8591Setup(pinbase,address);
while(1){
adcValue = analogRead(A0); //read A0 pin
adcValue = analogRead(A0); //read analog value A0 pin
voltage = (float)adcValue / 255.0 * 3.3; // calculate voltage
Rt = 10 * voltage / (3.3 - voltage); //calculate resistance value of thermistor
tempK = 1/(1/(273.15 + 25) + log(Rt/10)/3950.0); //calculate temperature (Kelvin)
Binary file not shown.
+9 -8
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : Joystick.c
* Description : Read Joystick
* Author : freenove
* modification: 2016/07/04
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <pcf8591.h>
@@ -20,17 +20,18 @@
int main(void){
int val_X,val_Y,val_Z;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ... \n");
wiringPiSetup();
pinMode(Z_Pin,INPUT); //set Z_Pin as input pin and pull-up mode
pullUpDnControl(Z_Pin,PUD_UP);
pcf8591Setup(pinbase,address); //initialize PCF8591
while(1){
val_Z = digitalRead(Z_Pin); //read digital quality of axis Z
val_Y = analogRead(A0); //read analog quality of axis X and Y
val_Z = digitalRead(Z_Pin); //read digital value of axis Z
val_Y = analogRead(A0); //read analog value of axis X and Y
val_X = analogRead(A1);
printf("val_X: %d ,\tval_Y: %d ,\tval_Z: %d \n",val_X,val_Y,val_Z);
delay(100);
Binary file not shown.
+10 -9
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : Motor.c
* Description : Control Motor by L293D
* Author : freenove
* modification: 2016/06/18
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <pcf8591.h>
@@ -21,7 +21,7 @@
#define motorPin1 2 //define the pin connected to L293D
#define motorPin2 0
#define enablePin 3
//Map function: map the value from a range of mapping to another range.
//Map function: map the value from a range to another range.
long map(long value,long fromLow,long fromHigh,long toLow,long toHigh){
return (toHigh-toLow)*(value-fromLow) / (fromHigh-fromLow) + toLow;
}
@@ -48,10 +48,11 @@ void motor(int ADC){
}
int main(void){
int value;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ... \n");
wiringPiSetup();
pinMode(enablePin,OUTPUT);//set mode for the pin
pinMode(motorPin1,OUTPUT);
pinMode(motorPin2,OUTPUT);
@@ -59,9 +60,9 @@ int main(void){
pcf8591Setup(pinbase,address);//initialize PCF8591
while(1){
value = analogRead(A0); //read A0 pin
value = analogRead(A0); //read analog value of A0 pin
printf("ADC value : %d \n",value);
motor(value); //start the motor
motor(value); //make the motor rotate with speed(analog value of A0 pin)
delay(100);
}
return 0;
Binary file not shown.
+10 -11
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : Relay.c
* Description : Button control Relay and Motor
* Author : freenove
* modification: 2016/07/05
* Description : Control Motor with Button and Relay
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
@@ -17,26 +17,25 @@ long captureTime=50; //set the button state stable time
int reading;
int main(void)
{
if(wiringPiSetup() == -1){ //when initialize wiring fairelay,print messageto screen
printf("setup wiringPi fairelay !");
return 1;
}
printf("Program is starting...\n");
wiringPiSetup();
pinMode(relayPin, OUTPUT);
pinMode(buttonPin, INPUT);
pullUpDnControl(buttonPin, PUD_UP); //pull up to high level
while(1){
reading = digitalRead(buttonPin); //read the current state of button
if( reading != lastbuttonState){ //if the button state has changed ,record the time point
if( reading != lastbuttonState){ //if the button state changed ,record the time point
lastChangeTime = millis();
}
//if changing-state of the button last beyond the time we set,we considered that
//the current button state is an effective change rather than a buffeting
if(millis() - lastChangeTime > captureTime){
//if button state is changed ,update the data.
//if button state is changed, update the data.
if(reading != buttonState){
buttonState = reading;
//if the state is low ,the action is pressing
//if the state is low, the action is pressing.
if(buttonState == LOW){
printf("Button is pressed!\n");
relayState = !relayState;
@@ -47,7 +46,7 @@ int main(void)
printf("turn off relay ...\n");
}
}
//if the state is high ,the action is releasing
//if the state is high, the action is releasing.
else {
printf("Button is released!\n");
}
Binary file not shown.
+6 -7
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : Sweep.c
* Description : Servo sweep
* Author : freenove
* modification: 2016/07/05
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <softPwm.h>
@@ -18,7 +18,7 @@ long map(long value,long fromLow,long fromHigh,long toLow,long toHigh){
void servoInit(int pin){ //initialization function for servo PMW pin
softPwmCreate(pin, 0, 200);
}
void servoWrite(int pin, int angle){ //Specif a certain rotation angle (0-180) for the servo
void servoWrite(int pin, int angle){ //Specific a certain rotation angle (0-180) for the servo
if(angle > 180)
angle = 180;
if(angle < 0)
@@ -36,11 +36,10 @@ void servoWriteMS(int pin, int ms){ //specific the unit for pulse(5-25ms) wi
int main(void)
{
int i;
if(wiringPiSetup() == -1){ //when initialize wiring faiservo,print messageto screen
printf("setup wiringPi faiservo !");
return 1;
}
printf("Program is starting ...\n");
wiringPiSetup();
servoInit(servoPin); //initialize PMW pin of servo
while(1){
for(i=SERVO_MIN_MS;i<SERVO_MAX_MS;i++){ //make servo rotate from minimum angle to maximum angle
Binary file not shown.
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : SteppingMotor.c
* Description :
* Author : freenove
* modification: 2016/07/07
* Description : Drive stepping Motor
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <stdio.h>
#include <wiringPi.h>
@@ -43,16 +43,16 @@ void motorStop(){ //function used to stop rotating
int main(void){
int i;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ...\n");
wiringPiSetup();
for(i=0;i<4;i++){
pinMode(motorPins[i],OUTPUT);
}
while(1){
moveSteps(1,3,512); //rotating 360° clockwise, a total of 2048 steps in a circle, namely, 512 cycles.
moveSteps(1,3,512); //rotating 360° clockwise, a total of 2048 steps in a circle, namely, 512 cycles.
delay(500);
moveSteps(0,3,512); //rotating 360° anticlockwise
delay(500);
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : LightWater02.c
* Description : Control LED by 74HC595
* Author : freenove
* modification: 2018/08/04
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
@@ -33,10 +33,11 @@ int main(void)
{
int i;
unsigned char x;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ...\n");
wiringPiSetup();
pinMode(dataPin,OUTPUT);
pinMode(latchPin,OUTPUT);
pinMode(clockPin,OUTPUT);
@@ -45,8 +46,8 @@ int main(void)
for(i=0;i<8;i++){
digitalWrite(latchPin,LOW); // Output low level to latchPin
_shiftOut(dataPin,clockPin,LSBFIRST,x);// Send serial data to 74HC595
digitalWrite(latchPin,HIGH); // Output high level to latchPin, and 74HC595 will update the data to the parallel output port.
x<<=1; // make the variable move one bit to left once, then the bright LED move one step to the left once.
digitalWrite(latchPin,HIGH); //Output high level to latchPin, and 74HC595 will update the data to the parallel output port.
x<<=1; //make the variable move one bit to left once, then the bright LED move one step to the left once.
delay(100);
}
x=0x80;
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : SevenSegmentDisplay.c
* Description : Control SevenSegmentDisplay by 74HC595
* Author : freenove
* modification: 2018/08/04
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
@@ -34,10 +34,11 @@ void _shiftOut(int dPin,int cPin,int order,int val){
int main(void)
{
int i;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ...\n");
wiringPiSetup();
pinMode(dataPin,OUTPUT);
pinMode(latchPin,OUTPUT);
pinMode(clockPin,OUTPUT);
+8 -7
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : StopWatch.c
* Description : Control 4_Digit_7_Segment_Display by 74HC595
* Author : freenove
* modification: 2018/07/16
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
@@ -49,7 +49,7 @@ void display(int dec){ //display function for 7-segment display
outData(0xff);
selectDigit(0x01); //select the first, and display the single digit
outData(num[dec%10]);
delay(delays); //display duration
delay(delays); //display duration
outData(0xff);
selectDigit(0x02); //select the second, and display the tens digit
@@ -76,10 +76,11 @@ void timer(int sig){ //Timer function
int main(void)
{
int i;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ...\n");
wiringPiSetup();
pinMode(dataPin,OUTPUT); //set the pin connected to74HC595 for output mode
pinMode(latchPin,OUTPUT);
pinMode(clockPin,OUTPUT);
+12 -11
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : LEDMatrix.c
* Description : Control LEDMatrix by 74HC595
* Author : freenove
* modification: 2018/08/03
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
@@ -11,7 +11,7 @@
#define dataPin 0 //DS Pin of 74HC595(Pin14)
#define latchPin 2 //ST_CP Pin of 74HC595(Pin12)
#define clockPin 3 //SH_CP Pin of 74HC595(Pin11)
// data of smiling face
// data of smile face
unsigned char pic[]={0x1c,0x22,0x51,0x45,0x45,0x51,0x22,0x1c};
unsigned char data[]={ // data of "0-F"
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // " "
@@ -53,15 +53,16 @@ int main(void)
{
int i,j,k;
unsigned char x;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ...\n");
wiringPiSetup();
pinMode(dataPin,OUTPUT);
pinMode(latchPin,OUTPUT);
pinMode(clockPin,OUTPUT);
while(1){
for(j=0;j<500;j++){// Repeat enough times to display the smiling face a period of time
for(j=0;j<500;j++){ //Repeat enough times to display the smiling face a period of time
x=0x80;
for(i=0;i<8;i++){
digitalWrite(latchPin,LOW);
@@ -69,13 +70,13 @@ int main(void)
_shiftOut(dataPin,clockPin,MSBFIRST,~x);//then shift data of column information to the second stage 74HC959
digitalWrite(latchPin,HIGH);//Output data of two stage 74HC595 at the same time
x>>=1;// display the next column
x>>=1; //display the next column
delay(1);
}
}
for(k=0;k<sizeof(data)-8;k++){ //sizeof(data) total number of "0-F" columns
for(j=0;j<20;j++){// times of repeated displaying LEDMatrix in every frame, the bigger the “j”, the longer the display time
x=0x80; // Set the column information to start from the first column
for(j=0;j<20;j++){ //times of repeated displaying LEDMatrix in every frame, the bigger the “j”, the longer the display time
x=0x80; //Set the column information to start from the first column
for(i=k;i<8+k;i++){
digitalWrite(latchPin,LOW);
_shiftOut(dataPin,clockPin,MSBFIRST,data[i]);
+16 -17
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : I2CLCD1602.c
* Description : Use the LCD display data
* Author : freenove
* modification: 2017/04/18
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <stdlib.h>
#include <stdio.h>
@@ -13,8 +13,8 @@
//#define pcf8574_address 0x27 // default I2C address of Pcf8574
#define pcf8574_address 0x3F // default I2C address of Pcf8574A
#define BASE 64 // BASE is not less than 64
//////// Define the output pins of the PCF8574, which are directly connected to the LCD1602 pin.
#define BASE 64 // BASE any number above 64
//Define the output pins of the PCF8574, which are directly connected to the LCD1602 pin.
#define RS BASE+0
#define RW BASE+1
#define EN BASE+2
@@ -42,32 +42,31 @@ void printDataTime(){//used to print system time
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);// get system time
timeinfo = localtime(&rawtime);// convert to local time
timeinfo = localtime(&rawtime);//convert to local time
printf("%s \n",asctime(timeinfo));
lcdPosition(lcdhd,0,1);// set the LCD cursor position to (0,1)
lcdPrintf(lcdhd,"Time:%d:%d:%d",timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
//Display system time on LCD
lcdPrintf(lcdhd,"Time:%d:%d:%d",timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec); //Display system time on LCD
}
int main(void){
int i;
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
pcf8574Setup(BASE,pcf8574_address);// initialize PCF8574
printf("Program is starting ...\n");
wiringPiSetup();
pcf8574Setup(BASE,pcf8574_address);//initialize PCF8574
for(i=0;i<8;i++){
pinMode(BASE+i,OUTPUT); // set PCF8574 port to output mode
pinMode(BASE+i,OUTPUT); //set PCF8574 port to output mode
}
digitalWrite(LED,HIGH); // turn on LCD backlight
digitalWrite(RW,LOW); // allow writing to LCD
lcdhd = lcdInit(2,16,4,RS,EN,D4,D5,D6,D7,0,0,0,0);// initialize LCD and return “handle” used to handle LCD
digitalWrite(LED,HIGH); //turn on LCD backlight
digitalWrite(RW,LOW); //allow writing to LCD
lcdhd = lcdInit(2,16,4,RS,EN,D4,D5,D6,D7,0,0,0,0);// initialize LCD and return “handle” used to handle LCD
if(lcdhd == -1){
printf("lcdInit failed !");
return 1;
}
while(1){
printCPUTemperature();// print CPU temperature
printCPUTemperature();//print CPU temperature
printDataTime(); // print system time
delay(1000);
}
Binary file not shown.
+6 -3
View File
@@ -1,8 +1,11 @@
/**********************************************************************
* Filename : DHT.cpp
* Description : DHT Temperature & Humidity Sensor library for Raspberry
* Filename : DHT.hpp
* Description : DHT Temperature & Humidity Sensor library for Raspberry.
Used for Raspberry Pi.
* Program transplantation by Freenove.
* Author : freenove
* modification: 2018/03/07
* modification: 2019/12/28
* Reference : https://github.com/RobTillaart/Arduino/tree/master/libraries/DHTlib
**********************************************************************/
#include "DHT.hpp"
//Function: Read DHT sensor, store the original data in bits[]
+5 -2
View File
@@ -1,8 +1,11 @@
/**********************************************************************
* Filename : DHT.hpp
* Description : DHT Temperature & Humidity Sensor library for Raspberry
* Description : DHT Temperature & Humidity Sensor library for Raspberry.
Used for Raspberry Pi.
* Program transplantation by Freenove.
* Author : freenove
* modification: 2018/03/07
* modification: 2019/12/28
* Reference : https://github.com/RobTillaart/Arduino/tree/master/libraries/DHTlib
**********************************************************************/
#ifndef _DHT_H_
#define _DHT_H_
+8 -7
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : DHT11.cpp
* Description : read the temperature and humidity data of DHT11
* Author : freenove
* modification: 2018/03/07
* Description : Read the temperature and humidity data of DHT11
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
@@ -14,10 +14,11 @@
int main(){
DHT dht; //create a DHT class object
int chk,sumCnt;//chk:read the return value of sensor; sumCnt:times of reading sensor
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
printf("Program is starting ...\n");
wiringPiSetup();
while(1){
chk = dht.readDHT11(DHT11_Pin); //read DHT11 and get a return value. Then determine whether data read is normal according to the return value.
sumCnt++; //counting number of reading times
@@ -29,6 +29,15 @@
|| #
||
*/
/**********************************************************************
* Filename : Keypad.hpp
* Description : This library provides a simple interface for using matrix keypads.
* Used for Raspberry Pi.
* Program transplantation by Freenove.
* Author : freenove
* modification: 2019/12/28
* Reference : https://github.com/Chris--A/Keypad
**********************************************************************/
#include "Keypad.hpp"
// <<constructor>> Allows custom keymap, pin configuration, and keypad sizes.
+9 -1
View File
@@ -29,7 +29,15 @@
|| #
||
*/
/**********************************************************************
* Filename : Keypad.hpp
* Description : This library provides a simple interface for using matrix keypads.
* Used for Raspberry Pi.
* Program transplantation by Freenove.
* Author : freenove
* modification: 2019/12/28
* Reference : https://github.com/Chris--A/Keypad
**********************************************************************/
#ifndef KEYPAD_H
#define KEYPAD_H
@@ -1,293 +0,0 @@
/*
||
|| @file Keypad.cpp
|| @version 3.1
|| @author Mark Stanley, Alexander Brevig
|| @contact mstanley@technologist.com, alexanderbrevig@gmail.com
||
|| @description
|| | This library provides a simple interface for using matrix
|| | keypads. It supports multiple keypresses while maintaining
|| | backwards compatibility with the old single key library.
|| | It also supports user selectable pins and definable keymaps.
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|| #
||
*/
#include "Keypad.hpp"
// <<constructor>> Allows custom keymap, pin configuration, and keypad sizes.
Keypad::Keypad(char *userKeymap, byte *row, byte *col, byte numRows, byte numCols) {
rowPins = row;
columnPins = col;
sizeKpd.rows = numRows;
sizeKpd.columns = numCols;
begin(userKeymap);
setDebounceTime(10);
setHoldTime(500);
keypadEventListener = 0;
startTime = 0;
single_key = false;
}
// Let the user define a keymap - assume the same row/column count as defined in constructor
void Keypad::begin(char *userKeymap) {
keymap = userKeymap;
}
// Returns a single key only. Retained for backwards compatibility.
char Keypad::getKey() {
single_key = true;
if (getKeys() && key[0].stateChanged && (key[0].kstate==PRESSED))
return key[0].kchar;
single_key = false;
return NO_KEY;
}
// Populate the key list.
bool Keypad::getKeys() {
bool keyActivity = false;
// Limit how often the keypad is scanned. This makes the loop() run 10 times as fast.
if ( (millis()-startTime)>debounceTime ) {
scanKeys();
keyActivity = updateList();
startTime = millis();
}
return keyActivity;
}
// Private : Hardware scan
void Keypad::scanKeys() {
// Re-intialize the row pins. Allows sharing these pins with other hardware.
for (byte r=0; r<sizeKpd.rows; r++) {
pin_mode(rowPins[r],INPUT_PULLUP);
}
// bitMap stores ALL the keys that are being pressed.
for (byte c=0; c<sizeKpd.columns; c++) {
pin_mode(columnPins[c],OUTPUT);
pin_write(columnPins[c], LOW); // Begin column pulse output.
for (byte r=0; r<sizeKpd.rows; r++) {
bitWrite(bitMap[r], c, !pin_read(rowPins[r])); // keypress is active low so invert to high.
}
// Set pin to high impedance input. Effectively ends column pulse.
pin_write(columnPins[c],HIGH);
pin_mode(columnPins[c],INPUT);
}
}
// Manage the list without rearranging the keys. Returns true if any keys on the list changed state.
bool Keypad::updateList() {
bool anyActivity = false;
// Delete any IDLE keys
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].kstate==IDLE) {
key[i].kchar = NO_KEY;
key[i].kcode = -1;
key[i].stateChanged = false;
}
}
// Add new keys to empty slots in the key list.
for (byte r=0; r<sizeKpd.rows; r++) {
for (byte c=0; c<sizeKpd.columns; c++) {
boolean button = bitRead(bitMap[r],c);
char keyChar = keymap[r * sizeKpd.columns + c];
int keyCode = r * sizeKpd.columns + c;
int idx = findInList (keyCode);
// Key is already on the list so set its next state.
if (idx > -1) {
nextKeyState(idx, button);
}
// Key is NOT on the list so add it.
if ((idx == -1) && button) {
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].kchar==NO_KEY) { // Find an empty slot or don't add key to list.
key[i].kchar = keyChar;
key[i].kcode = keyCode;
key[i].kstate = IDLE; // Keys NOT on the list have an initial state of IDLE.
nextKeyState (i, button);
break; // Don't fill all the empty slots with the same key.
}
}
}
}
}
// Report if the user changed the state of any key.
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].stateChanged) anyActivity = true;
}
return anyActivity;
}
// Private
// This function is a state machine but is also used for debouncing the keys.
void Keypad::nextKeyState(byte idx, boolean button) {
key[idx].stateChanged = false;
switch (key[idx].kstate) {
case IDLE:
if (button==CLOSED) {
transitionTo (idx, PRESSED);
holdTimer = millis(); } // Get ready for next HOLD state.
break;
case PRESSED:
if ((millis()-holdTimer)>holdTime) // Waiting for a key HOLD...
transitionTo (idx, HOLD);
else if (button==OPEN) // or for a key to be RELEASED.
transitionTo (idx, RELEASED);
break;
case HOLD:
if (button==OPEN)
transitionTo (idx, RELEASED);
break;
case RELEASED:
transitionTo (idx, IDLE);
break;
}
}
// New in 2.1
bool Keypad::isPressed(char keyChar) {
for (byte i=0; i<LIST_MAX; i++) {
if ( key[i].kchar == keyChar ) {
if ( (key[i].kstate == PRESSED) && key[i].stateChanged )
return true;
}
}
return false; // Not pressed.
}
// Search by character for a key in the list of active keys.
// Returns -1 if not found or the index into the list of active keys.
int Keypad::findInList (char keyChar) {
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].kchar == keyChar) {
return i;
}
}
return -1;
}
// Search by code for a key in the list of active keys.
// Returns -1 if not found or the index into the list of active keys.
int Keypad::findInList (int keyCode) {
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].kcode == keyCode) {
return i;
}
}
return -1;
}
// New in 2.0
char Keypad::waitForKey() {
char waitKey = NO_KEY;
while( (waitKey = getKey()) == NO_KEY ); // Block everything while waiting for a keypress.
return waitKey;
}
// Backwards compatibility function.
KeyState Keypad::getState() {
return key[0].kstate;
}
// The end user can test for any changes in state before deciding
// if any variables, etc. needs to be updated in their code.
bool Keypad::keyStateChanged() {
return key[0].stateChanged;
}
// The number of keys on the key list, key[LIST_MAX], equals the number
// of bytes in the key list divided by the number of bytes in a Key object.
byte Keypad::numKeys() {
return sizeof(key)/sizeof(Key);
}
// Minimum debounceTime is 1 mS. Any lower *will* slow down the loop().
void Keypad::setDebounceTime(uint debounce) {
debounce<1 ? debounceTime=1 : debounceTime=debounce;
}
void Keypad::setHoldTime(uint hold) {
holdTime = hold;
}
void Keypad::addEventListener(void (*listener)(char)){
keypadEventListener = listener;
}
void Keypad::transitionTo(byte idx, KeyState nextState) {
key[idx].kstate = nextState;
key[idx].stateChanged = true;
// Sketch used the getKey() function.
// Calls keypadEventListener only when the first key in slot 0 changes state.
if (single_key) {
if ( (keypadEventListener!=NULL) && (idx==0) ) {
keypadEventListener(key[0].kchar);
}
}
// Sketch used the getKeys() function.
// Calls keypadEventListener on any key that changes state.
else {
if (keypadEventListener!=NULL) {
keypadEventListener(key[idx].kchar);
}
}
}
/*
|| @changelog
|| | 3.1 2013-01-15 - Mark Stanley : Fixed missing RELEASED & IDLE status when using a single key.
|| | 3.0 2012-07-12 - Mark Stanley : Made library multi-keypress by default. (Backwards compatible)
|| | 3.0 2012-07-12 - Mark Stanley : Modified pin functions to support Keypad_I2C
|| | 3.0 2012-07-12 - Stanley & Young : Removed static variables. Fix for multiple keypad objects.
|| | 3.0 2012-07-12 - Mark Stanley : Fixed bug that caused shorted pins when pressing multiple keys.
|| | 2.0 2011-12-29 - Mark Stanley : Added waitForKey().
|| | 2.0 2011-12-23 - Mark Stanley : Added the public function keyStateChanged().
|| | 2.0 2011-12-23 - Mark Stanley : Added the private function scanKeys().
|| | 2.0 2011-12-23 - Mark Stanley : Moved the Finite State Machine into the function getKeyState().
|| | 2.0 2011-12-23 - Mark Stanley : Removed the member variable lastUdate. Not needed after rewrite.
|| | 1.8 2011-11-21 - Mark Stanley : Added decision logic to compile WProgram.h or Arduino.h
|| | 1.8 2009-07-08 - Alexander Brevig : No longer uses arrays
|| | 1.7 2009-06-18 - Alexander Brevig : Every time a state changes the keypadEventListener will trigger, if set.
|| | 1.7 2009-06-18 - Alexander Brevig : Added setDebounceTime. setHoldTime specifies the amount of
|| | microseconds before a HOLD state triggers
|| | 1.7 2009-06-18 - Alexander Brevig : Added transitionTo
|| | 1.6 2009-06-15 - Alexander Brevig : Added getState() and state variable
|| | 1.5 2009-05-19 - Alexander Brevig : Added setHoldTime()
|| | 1.4 2009-05-15 - Alexander Brevig : Added addEventListener
|| | 1.3 2009-05-12 - Alexander Brevig : Added lastUdate, in order to do simple debouncing
|| | 1.2 2009-05-09 - Alexander Brevig : Changed getKey()
|| | 1.1 2009-04-28 - Alexander Brevig : Modified API, and made variables private
|| | 1.0 2007-XX-XX - Mark Stanley : Initial Release
|| #
*/
@@ -1,149 +0,0 @@
/*
||
|| @file Keypad.h
|| @version 3.1
|| @author Mark Stanley, Alexander Brevig
|| @contact mstanley@technologist.com, alexanderbrevig@gmail.com
||
|| @description
|| | This library provides a simple interface for using matrix
|| | keypads. It supports multiple keypresses while maintaining
|| | backwards compatibility with the old single key library.
|| | It also supports user selectable pins and definable keymaps.
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|| #
||
*/
#ifndef KEYPAD_H
#define KEYPAD_H
#include "utility/Key.hpp"
#include <wiringPi.h>
#define NULL 0
#define INPUT_PULLUP 0x02
#define bitWrite(x,n,b) (b ? (x |= b<<n) : (x &= ~(b<<n)))
#define bitRead(x,n) ((((x>>n)&1) == 1) ? 1 : 0)
#define OPEN LOW
#define CLOSED HIGH
typedef char KeypadEvent;
typedef unsigned int uint;
typedef unsigned long ulong;
// Made changes according to this post http://arduino.cc/forum/index.php?topic=58337.0
// by Nick Gammon. Thanks for the input Nick. It actually saved 78 bytes for me. :)
typedef struct {
byte rows;
byte columns;
} KeypadSize;
#define LIST_MAX 10 // Max number of keys on the active list.
#define MAPSIZE 10 // MAPSIZE is the number of rows (times 16 columns)
#define makeKeymap(x) ((char*)x)
//class Keypad : public Key, public HAL_obj {
class Keypad : public Key {
public:
Keypad(char *userKeymap, byte *row, byte *col, byte numRows, byte numCols);
virtual void pin_mode(byte pinNum, byte mode) {
if(mode == INPUT_PULLUP) {
pinMode(pinNum, INPUT);
pullUpDnControl(pinNum,PUD_UP);
}
else{
pinMode(pinNum, mode);
}
}
virtual void pin_write(byte pinNum, boolean level) { digitalWrite(pinNum, level); }
virtual int pin_read(byte pinNum) { return digitalRead(pinNum); }
uint bitMap[MAPSIZE]; // 10 row x 16 column array of bits. Except Due which has 32 columns.
Key key[LIST_MAX];
unsigned long holdTimer;
char getKey();
bool getKeys();
KeyState getState();
void begin(char *userKeymap);
bool isPressed(char keyChar);
void setDebounceTime(uint);
void setHoldTime(uint);
void addEventListener(void (*listener)(char));
int findInList(char keyChar);
int findInList(int keyCode);
char waitForKey();
bool keyStateChanged();
byte numKeys();
private:
unsigned long startTime;
char *keymap;
byte *rowPins;
byte *columnPins;
KeypadSize sizeKpd;
uint debounceTime;
uint holdTime;
bool single_key;
void scanKeys();
bool updateList();
void nextKeyState(byte n, boolean button);
void transitionTo(byte n, KeyState nextState);
void (*keypadEventListener)(char);
};
#endif
/*
|| @changelog
|| | 3.1 2013-01-15 - Mark Stanley : Fixed missing RELEASED & IDLE status when using a single key.
|| | 3.0 2012-07-12 - Mark Stanley : Made library multi-keypress by default. (Backwards compatible)
|| | 3.0 2012-07-12 - Mark Stanley : Modified pin functions to support Keypad_I2C
|| | 3.0 2012-07-12 - Stanley & Young : Removed static variables. Fix for multiple keypad objects.
|| | 3.0 2012-07-12 - Mark Stanley : Fixed bug that caused shorted pins when pressing multiple keys.
|| | 2.0 2011-12-29 - Mark Stanley : Added waitForKey().
|| | 2.0 2011-12-23 - Mark Stanley : Added the public function keyStateChanged().
|| | 2.0 2011-12-23 - Mark Stanley : Added the private function scanKeys().
|| | 2.0 2011-12-23 - Mark Stanley : Moved the Finite State Machine into the function getKeyState().
|| | 2.0 2011-12-23 - Mark Stanley : Removed the member variable lastUdate. Not needed after rewrite.
|| | 1.8 2011-11-21 - Mark Stanley : Added test to determine which header file to compile,
|| | WProgram.h or Arduino.h.
|| | 1.8 2009-07-08 - Alexander Brevig : No longer uses arrays
|| | 1.7 2009-06-18 - Alexander Brevig : This library is a Finite State Machine every time a state changes
|| | the keypadEventListener will trigger, if set
|| | 1.7 2009-06-18 - Alexander Brevig : Added setDebounceTime setHoldTime specifies the amount of
|| | microseconds before a HOLD state triggers
|| | 1.7 2009-06-18 - Alexander Brevig : Added transitionTo
|| | 1.6 2009-06-15 - Alexander Brevig : Added getState() and state variable
|| | 1.5 2009-05-19 - Alexander Brevig : Added setHoldTime()
|| | 1.4 2009-05-15 - Alexander Brevig : Added addEventListener
|| | 1.3 2009-05-12 - Alexander Brevig : Added lastUdate, in order to do simple debouncing
|| | 1.2 2009-05-09 - Alexander Brevig : Changed getKey()
|| | 1.1 2009-04-28 - Alexander Brevig : Modified API, and made variables private
|| | 1.0 2007-XX-XX - Mark Stanley : Initial Release
|| #
*/
@@ -1,38 +0,0 @@
# Keypad Library data types
KeyState KEYWORD1
Keypad KEYWORD1
KeypadEvent KEYWORD1
# Keypad Library constants
NO_KEY LITERAL1
IDLE LITERAL1
PRESSED LITERAL1
HOLD LITERAL1
RELEASED LITERAL1
# Keypad Library methods & functions
addEventListener KEYWORD2
bitMap KEYWORD2
findKeyInList KEYWORD2
getKey KEYWORD2
getKeys KEYWORD2
getState KEYWORD2
holdTimer KEYWORD2
isPressed KEYWORD2
keyStateChanged KEYWORD2
numKeys KEYWORD2
pin_mode KEYWORD2
pin_write KEYWORD2
pin_read KEYWORD2
setDebounceTime KEYWORD2
setHoldTime KEYWORD2
waitForKey KEYWORD2
# this is a macro that converts 2d arrays to pointers
makeKeymap KEYWORD2
# List of objects created in the example sketches.
kpd KEYWORD3
keypad KEYWORD3
kbrd KEYWORD3
keyboard KEYWORD3
@@ -1,61 +0,0 @@
/*
|| @file Key.cpp
|| @version 1.0
|| @author Mark Stanley
|| @contact mstanley@technologist.com
||
|| @description
|| | Key class provides an abstract definition of a key or button
|| | and was initially designed to be used in conjunction with a
|| | state-machine.
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|| #
||
*/
#include "Key.hpp"
// default constructor
Key::Key() {
kchar = NO_KEY;
kstate = IDLE;
stateChanged = false;
}
// constructor
Key::Key(char userKeyChar) {
kchar = userKeyChar;
kcode = -1;
kstate = IDLE;
stateChanged = false;
}
void Key::key_update (char userKeyChar, KeyState userState, boolean userStatus) {
kchar = userKeyChar;
kstate = userState;
stateChanged = userStatus;
}
/*
|| @changelog
|| | 1.0 2012-06-04 - Mark Stanley : Initial Release
|| #
*/
@@ -1,70 +0,0 @@
/*
||
|| @file Key.h
|| @version 1.0
|| @author Mark Stanley
|| @contact mstanley@technologist.com
||
|| @description
|| | Key class provides an abstract definition of a key or button
|| | and was initially designed to be used in conjunction with a
|| | state-machine.
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|| #
||
*/
#ifndef KEY_H
#define KEY_H
#include <wiringPi.h>
#define boolean bool
#define byte unsigned char
#define OPEN LOW
#define CLOSED HIGH
typedef unsigned int uint;
typedef enum{ IDLE, PRESSED, HOLD, RELEASED } KeyState;
const char NO_KEY = '\0';
class Key {
public:
// members
char kchar;
int kcode;
KeyState kstate;
boolean stateChanged;
// methods
Key();
Key(char userKeyChar);
void key_update(char userKeyChar, KeyState userState, boolean userStatus);
private:
};
#endif
/*
|| @changelog
|| | 1.0 2012-06-04 - Mark Stanley : Initial Release
|| #
*/
@@ -1,37 +0,0 @@
/* @file HelloKeypad.pde
|| @version 1.0
|| @author Alexander Brevig
|| @contact alexanderbrevig@gmail.com
||
|| @description
|| | Demonstrates the simplest use of the matrix Keypad library.
|| #
*/
#include "Keypad.hpp"
#include <stdio.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup(){
//Serial.begin(9600);
}
int main(){
while(1){
char key = keypad.getKey();
if (key){
printf("%s \n",key);
}
}
}
@@ -1,308 +0,0 @@
/*
||
|| @file Keypad.cpp
|| @version 3.1
|| @author Mark Stanley, Alexander Brevig
|| @contact mstanley@technologist.com, alexanderbrevig@gmail.com
||
|| @description
|| | This library provides a simple interface for using matrix
|| | keypads. It supports multiple keypresses while maintaining
|| | backwards compatibility with the old single key library.
|| | It also supports user selectable pins and definable keymaps.
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|| #
||
*/
#include "Keypad.hpp"
// <<constructor>> Allows custom keymap, pin configuration, and keypad sizes.
Keypad::Keypad(char *userKeymap, byte *row, byte *col, byte numRows, byte numCols) {
rowPins = row;
columnPins = col;
sizeKpd.rows = numRows;
sizeKpd.columns = numCols;
begin(userKeymap);
setDebounceTime(10);
setHoldTime(500);
keypadEventListener = 0;
startTime = 0;
single_key = false;
}
// Let the user define a keymap - assume the same row/column count as defined in constructor
void Keypad::begin(char *userKeymap) {
keymap = userKeymap;
}
// Returns a single key only. Retained for backwards compatibility.
char Keypad::getKey() {
single_key = true;
if (getKeys() && key[0].stateChanged && (key[0].kstate==PRESSED))
return key[0].kchar;
single_key = false;
return NO_KEY;
}
// Populate the key list.
bool Keypad::getKeys() {
bool keyActivity = false;
// Limit how often the keypad is scanned. This makes the loop() run 10 times as fast.
if ( (millis()-startTime)>debounceTime ) {
scanKeys();
keyActivity = updateList();
startTime = millis();
}
return keyActivity;
}
// Private : Hardware scan
void Keypad::scanKeys() {
// Re-intialize the row pins. Allows sharing these pins with other hardware.
for (byte r=0; r<sizeKpd.rows; r++) {
pin_mode(rowPins[r],INPUT_PULLUP);
}
// bitMap stores ALL the keys that are being pressed.
for (byte c=0; c<sizeKpd.columns; c++) {
pin_mode(columnPins[c],OUTPUT);
pin_write(columnPins[c], LOW); // Begin column pulse output.
for (byte r=0; r<sizeKpd.rows; r++) {
bitWrite(bitMap[r], c, !pin_read(rowPins[r])); // keypress is active low so invert to high.
}
// Set pin to high impedance input. Effectively ends column pulse.
pin_write(columnPins[c],HIGH);
pin_mode(columnPins[c],INPUT);
}
}
// Manage the list without rearranging the keys. Returns true if any keys on the list changed state.
bool Keypad::updateList() {
bool anyActivity = false;
// Delete any IDLE keys
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].kstate==IDLE) {
key[i].kchar = NO_KEY;
key[i].kcode = -1;
key[i].stateChanged = false;
}
}
// Add new keys to empty slots in the key list.
for (byte r=0; r<sizeKpd.rows; r++) {
for (byte c=0; c<sizeKpd.columns; c++) {
boolean button = bitRead(bitMap[r],c);
char keyChar = keymap[r * sizeKpd.columns + c];
int keyCode = r * sizeKpd.columns + c;
int idx = findInList (keyCode);
// Key is already on the list so set its next state.
if (idx > -1) {
nextKeyState(idx, button);
}
// Key is NOT on the list so add it.
if ((idx == -1) && button) {
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].kchar==NO_KEY) { // Find an empty slot or don't add key to list.
key[i].kchar = keyChar;
key[i].kcode = keyCode;
key[i].kstate = IDLE; // Keys NOT on the list have an initial state of IDLE.
nextKeyState (i, button);
break; // Don't fill all the empty slots with the same key.
}
}
}
}
}
// Report if the user changed the state of any key.
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].stateChanged) anyActivity = true;
}
return anyActivity;
}
// Private
// This function is a state machine but is also used for debouncing the keys.
void Keypad::nextKeyState(byte idx, boolean button) {
key[idx].stateChanged = false;
switch (key[idx].kstate) {
case IDLE:
if (button==CLOSED) {
transitionTo (idx, PRESSED);
holdTimer = millis(); } // Get ready for next HOLD state.
break;
case PRESSED:
if ((millis()-holdTimer)>holdTime) // Waiting for a key HOLD...
transitionTo (idx, HOLD);
else if (button==OPEN) // or for a key to be RELEASED.
transitionTo (idx, RELEASED);
break;
case HOLD:
if (button==OPEN)
transitionTo (idx, RELEASED);
break;
case RELEASED:
transitionTo (idx, IDLE);
break;
}
}
// New in 2.1
bool Keypad::isPressed(char keyChar) {
for (byte i=0; i<LIST_MAX; i++) {
if ( key[i].kchar == keyChar ) {
if ( (key[i].kstate == PRESSED) && key[i].stateChanged )
return true;
}
}
return false; // Not pressed.
}
// Search by character for a key in the list of active keys.
// Returns -1 if not found or the index into the list of active keys.
int Keypad::findInList (char keyChar) {
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].kchar == keyChar) {
return i;
}
}
return -1;
}
// Search by code for a key in the list of active keys.
// Returns -1 if not found or the index into the list of active keys.
int Keypad::findInList (int keyCode) {
for (byte i=0; i<LIST_MAX; i++) {
if (key[i].kcode == keyCode) {
return i;
}
}
return -1;
}
// New in 2.0
char Keypad::waitForKey() {
char waitKey = NO_KEY;
while( (waitKey = getKey()) == NO_KEY ); // Block everything while waiting for a keypress.
return waitKey;
}
// Backwards compatibility function.
KeyState Keypad::getState() {
return key[0].kstate;
}
// The end user can test for any changes in state before deciding
// if any variables, etc. needs to be updated in their code.
bool Keypad::keyStateChanged() {
return key[0].stateChanged;
}
// The number of keys on the key list, key[LIST_MAX], equals the number
// of bytes in the key list divided by the number of bytes in a Key object.
byte Keypad::numKeys() {
return sizeof(key)/sizeof(Key);
}
// Minimum debounceTime is 1 mS. Any lower *will* slow down the loop().
void Keypad::setDebounceTime(uint debounce) {
debounce<1 ? debounceTime=1 : debounceTime=debounce;
}
void Keypad::setHoldTime(uint hold) {
holdTime = hold;
}
void Keypad::addEventListener(void (*listener)(char)){
keypadEventListener = listener;
}
void Keypad::transitionTo(byte idx, KeyState nextState) {
key[idx].kstate = nextState;
key[idx].stateChanged = true;
// Sketch used the getKey() function.
// Calls keypadEventListener only when the first key in slot 0 changes state.
if (single_key) {
if ( (keypadEventListener!=NULL) && (idx==0) ) {
keypadEventListener(key[0].kchar);
}
}
// Sketch used the getKeys() function.
// Calls keypadEventListener on any key that changes state.
else {
if (keypadEventListener!=NULL) {
keypadEventListener(key[idx].kchar);
}
}
}
void pin_mode(byte pinNum, byte mode) {
if(mode == INPUT_PULLUP) {
pinMode(pinNum, INPUT);
pullUpDnControl(pinNum,PUD_UP);
}
else{
pinMode(pinNum, mode);
}
}
void pin_write(byte pinNum, boolean level) {
digitalWrite(pinNum, level);
}
int pin_read(byte pinNum) {
return digitalRead(pinNum);
}
/*
|| @changelog
|| | 3.1 2013-01-15 - Mark Stanley : Fixed missing RELEASED & IDLE status when using a single key.
|| | 3.0 2012-07-12 - Mark Stanley : Made library multi-keypress by default. (Backwards compatible)
|| | 3.0 2012-07-12 - Mark Stanley : Modified pin functions to support Keypad_I2C
|| | 3.0 2012-07-12 - Stanley & Young : Removed static variables. Fix for multiple keypad objects.
|| | 3.0 2012-07-12 - Mark Stanley : Fixed bug that caused shorted pins when pressing multiple keys.
|| | 2.0 2011-12-29 - Mark Stanley : Added waitForKey().
|| | 2.0 2011-12-23 - Mark Stanley : Added the public function keyStateChanged().
|| | 2.0 2011-12-23 - Mark Stanley : Added the private function scanKeys().
|| | 2.0 2011-12-23 - Mark Stanley : Moved the Finite State Machine into the function getKeyState().
|| | 2.0 2011-12-23 - Mark Stanley : Removed the member variable lastUdate. Not needed after rewrite.
|| | 1.8 2011-11-21 - Mark Stanley : Added decision logic to compile WProgram.h or Arduino.h
|| | 1.8 2009-07-08 - Alexander Brevig : No longer uses arrays
|| | 1.7 2009-06-18 - Alexander Brevig : Every time a state changes the keypadEventListener will trigger, if set.
|| | 1.7 2009-06-18 - Alexander Brevig : Added setDebounceTime. setHoldTime specifies the amount of
|| | microseconds before a HOLD state triggers
|| | 1.7 2009-06-18 - Alexander Brevig : Added transitionTo
|| | 1.6 2009-06-15 - Alexander Brevig : Added getState() and state variable
|| | 1.5 2009-05-19 - Alexander Brevig : Added setHoldTime()
|| | 1.4 2009-05-15 - Alexander Brevig : Added addEventListener
|| | 1.3 2009-05-12 - Alexander Brevig : Added lastUdate, in order to do simple debouncing
|| | 1.2 2009-05-09 - Alexander Brevig : Changed getKey()
|| | 1.1 2009-04-28 - Alexander Brevig : Modified API, and made variables private
|| | 1.0 2007-XX-XX - Mark Stanley : Initial Release
|| #
*/
@@ -1,140 +0,0 @@
/*
||
|| @file Keypad.h
|| @version 3.1
|| @author Mark Stanley, Alexander Brevig
|| @contact mstanley@technologist.com, alexanderbrevig@gmail.com
||
|| @description
|| | This library provides a simple interface for using matrix
|| | keypads. It supports multiple keypresses while maintaining
|| | backwards compatibility with the old single key library.
|| | It also supports user selectable pins and definable keymaps.
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|| #
||
*/
#ifndef KEYPAD_H
#define KEYPAD_H
#include "utility/Key.hpp"
#include <wiringPi.h>
#define NULL 0
#define INPUT_PULLUP 0x02
#define bitWrite(x,n,b) (b ? (x |= b<<n) : (x &= ~(b<<n)))
#define bitRead(x,n) ((((x>>n)&1) == 1) ? 1 : 0)
#define OPEN LOW
#define CLOSED HIGH
typedef char KeypadEvent;
typedef unsigned int uint;
typedef unsigned long ulong;
// Made changes according to this post http://arduino.cc/forum/index.php?topic=58337.0
// by Nick Gammon. Thanks for the input Nick. It actually saved 78 bytes for me. :)
typedef struct {
byte rows;
byte columns;
} KeypadSize;
#define LIST_MAX 10 // Max number of keys on the active list.
#define MAPSIZE 10 // MAPSIZE is the number of rows (times 16 columns)
#define makeKeymap(x) ((char*)x)
//class Keypad : public Key, public HAL_obj {
class Keypad : public Key {
public:
Keypad(char *userKeymap, byte *row, byte *col, byte numRows, byte numCols);
uint bitMap[MAPSIZE]; // 10 row x 16 column array of bits. Except Due which has 32 columns.
Key key[LIST_MAX];
unsigned long holdTimer;
char getKey();
bool getKeys();
KeyState getState();
void begin(char *userKeymap);
bool isPressed(char keyChar);
void setDebounceTime(uint);
void setHoldTime(uint);
void addEventListener(void (*listener)(char));
int findInList(char keyChar);
int findInList(int keyCode);
char waitForKey();
bool keyStateChanged();
byte numKeys();
private:
unsigned long startTime;
char *keymap;
byte *rowPins;
byte *columnPins;
KeypadSize sizeKpd;
uint debounceTime;
uint holdTime;
bool single_key;
void scanKeys();
bool updateList();
void nextKeyState(byte n, boolean button);
void transitionTo(byte n, KeyState nextState);
void (*keypadEventListener)(char);
};
void pin_mode(byte pinNum, byte mode) ;
void pin_write(byte pinNum, boolean level) ;
int pin_read(byte pinNum) ;
#endif
/*
|| @changelog
|| | 3.1 2013-01-15 - Mark Stanley : Fixed missing RELEASED & IDLE status when using a single key.
|| | 3.0 2012-07-12 - Mark Stanley : Made library multi-keypress by default. (Backwards compatible)
|| | 3.0 2012-07-12 - Mark Stanley : Modified pin functions to support Keypad_I2C
|| | 3.0 2012-07-12 - Stanley & Young : Removed static variables. Fix for multiple keypad objects.
|| | 3.0 2012-07-12 - Mark Stanley : Fixed bug that caused shorted pins when pressing multiple keys.
|| | 2.0 2011-12-29 - Mark Stanley : Added waitForKey().
|| | 2.0 2011-12-23 - Mark Stanley : Added the public function keyStateChanged().
|| | 2.0 2011-12-23 - Mark Stanley : Added the private function scanKeys().
|| | 2.0 2011-12-23 - Mark Stanley : Moved the Finite State Machine into the function getKeyState().
|| | 2.0 2011-12-23 - Mark Stanley : Removed the member variable lastUdate. Not needed after rewrite.
|| | 1.8 2011-11-21 - Mark Stanley : Added test to determine which header file to compile,
|| | WProgram.h or Arduino.h.
|| | 1.8 2009-07-08 - Alexander Brevig : No longer uses arrays
|| | 1.7 2009-06-18 - Alexander Brevig : This library is a Finite State Machine every time a state changes
|| | the keypadEventListener will trigger, if set
|| | 1.7 2009-06-18 - Alexander Brevig : Added setDebounceTime setHoldTime specifies the amount of
|| | microseconds before a HOLD state triggers
|| | 1.7 2009-06-18 - Alexander Brevig : Added transitionTo
|| | 1.6 2009-06-15 - Alexander Brevig : Added getState() and state variable
|| | 1.5 2009-05-19 - Alexander Brevig : Added setHoldTime()
|| | 1.4 2009-05-15 - Alexander Brevig : Added addEventListener
|| | 1.3 2009-05-12 - Alexander Brevig : Added lastUdate, in order to do simple debouncing
|| | 1.2 2009-05-09 - Alexander Brevig : Changed getKey()
|| | 1.1 2009-04-28 - Alexander Brevig : Modified API, and made variables private
|| | 1.0 2007-XX-XX - Mark Stanley : Initial Release
|| #
*/
@@ -1,37 +0,0 @@
/* @file CustomKeypad.pde
|| @version 1.0
|| @author Alexander Brevig
|| @contact alexanderbrevig@gmail.com
||
|| @description
|| | Demonstrates changing the keypad size and key values.
|| #
*/
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
{'0','1','2','3'},
{'4','5','6','7'},
{'8','9','A','B'},
{'C','D','E','F'}
};
byte rowPins[ROWS] = {3, 2, 1, 0}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {7, 6, 5, 4}; //connect to the column pinouts of the keypad
//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
void setup(){
Serial.begin(9600);
}
void loop(){
char customKey = customKeypad.getKey();
if (customKey){
Serial.println(customKey);
}
}
@@ -1,213 +0,0 @@
/* @file DynamicKeypad.pde
|| @version 1.2
|| @author Mark Stanley
|| @contact mstanley@technologist.com
||
|| 07/11/12 - Re-modified (from DynamicKeypadJoe2) to use direct-connect kpds
|| 02/28/12 - Modified to use I2C i/o G. D. (Joe) Young
||
||
|| @dificulty: Intermediate
||
|| @description
|| | This is a demonstration of keypadEvents. It's used to switch between keymaps
|| | while using only one keypad. The main concepts being demonstrated are:
|| |
|| | Using the keypad events, PRESSED, HOLD and RELEASED to simplify coding.
|| | How to use setHoldTime() and why.
|| | Making more than one thing happen with the same key.
|| | Assigning and changing keymaps on the fly.
|| |
|| | Another useful feature is also included with this demonstration although
|| | it's not really one of the concepts that I wanted to show you. If you look
|| | at the code in the PRESSED event you will see that the first section of that
|| | code is used to scroll through three different letters on each key. For
|| | example, pressing the '2' key will step through the letters 'd', 'e' and 'f'.
|| |
|| |
|| | Using the keypad events, PRESSED, HOLD and RELEASED to simplify coding
|| | Very simply, the PRESSED event occurs imediately upon detecting a pressed
|| | key and will not happen again until after a RELEASED event. When the HOLD
|| | event fires it always falls between PRESSED and RELEASED. However, it will
|| | only occur if a key has been pressed for longer than the setHoldTime() interval.
|| |
|| | How to use setHoldTime() and why
|| | Take a look at keypad.setHoldTime(500) in the code. It is used to set the
|| | time delay between a PRESSED event and the start of a HOLD event. The value
|| | 500 is in milliseconds (mS) and is equivalent to half a second. After pressing
|| | a key for 500mS the HOLD event will fire and any code contained therein will be
|| | executed. This event will stay active for as long as you hold the key except
|| | in the case of bug #1 listed above.
|| |
|| | Making more than one thing happen with the same key.
|| | If you look under the PRESSED event (case PRESSED:) you will see that the '#'
|| | is used to print a new line, Serial.println(). But take a look at the first
|| | half of the HOLD event and you will see the same key being used to switch back
|| | and forth between the letter and number keymaps that were created with alphaKeys[4][5]
|| | and numberKeys[4][5] respectively.
|| |
|| | Assigning and changing keymaps on the fly
|| | You will see that the '#' key has been designated to perform two different functions
|| | depending on how long you hold it down. If you press the '#' key for less than the
|| | setHoldTime() then it will print a new line. However, if you hold if for longer
|| | than that it will switch back and forth between numbers and letters. You can see the
|| | keymap changes in the HOLD event.
|| |
|| |
|| | In addition...
|| | You might notice a couple of things that you won't find in the Arduino language
|| | reference. The first would be #include <ctype.h>. This is a standard library from
|| | the C programming language and though I don't normally demonstrate these types of
|| | things from outside the Arduino language reference I felt that its use here was
|| | justified by the simplicity that it brings to this sketch.
|| | That simplicity is provided by the two calls to isalpha(key) and isdigit(key).
|| | The first one is used to decide if the key that was pressed is any letter from a-z
|| | or A-Z and the second one decides if the key is any number from 0-9. The return
|| | value from these two functions is either a zero or some positive number greater
|| | than zero. This makes it very simple to test a key and see if it is a number or
|| | a letter. So when you see the following:
|| |
|| | if (isalpha(key)) // this tests to see if your key was a letter
|| |
|| | And the following may be more familiar to some but it is equivalent:
|| |
|| | if (isalpha(key) != 0) // this tests to see if your key was a letter
|| |
|| | And Finally...
|| | To better understand how the event handler affects your code you will need to remember
|| | that it gets called only when you press, hold or release a key. However, once a key
|| | is pressed or held then the event handler gets called at the full speed of the loop().
|| |
|| #
*/
#include <Keypad.h>
#include <ctype.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
// Define the keymaps. The blank spot (lower left) is the space character.
char alphaKeys[ROWS][COLS] = {
{ 'a','d','g' },
{ 'j','m','p' },
{ 's','v','y' },
{ ' ','.','#' }
};
char numberKeys[ROWS][COLS] = {
{ '1','2','3' },
{ '4','5','6' },
{ '7','8','9' },
{ ' ','0','#' }
};
boolean alpha = false; // Start with the numeric keypad.
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad
// Create two new keypads, one is a number pad and the other is a letter pad.
Keypad numpad( makeKeymap(numberKeys), rowPins, colPins, sizeof(rowPins), sizeof(colPins) );
Keypad ltrpad( makeKeymap(alphaKeys), rowPins, colPins, sizeof(rowPins), sizeof(colPins) );
unsigned long startTime;
const byte ledPin = 13; // Use the LED on pin 13.
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW); // Turns the LED on.
ltrpad.begin( makeKeymap(alphaKeys) );
numpad.begin( makeKeymap(numberKeys) );
ltrpad.addEventListener(keypadEvent_ltr); // Add an event listener.
ltrpad.setHoldTime(500); // Default is 1000mS
numpad.addEventListener(keypadEvent_num); // Add an event listener.
numpad.setHoldTime(500); // Default is 1000mS
}
char key;
void loop() {
if( alpha )
key = ltrpad.getKey( );
else
key = numpad.getKey( );
if (alpha && millis()-startTime>100) { // Flash the LED if we are using the letter keymap.
digitalWrite(ledPin,!digitalRead(ledPin));
startTime = millis();
}
}
static char virtKey = NO_KEY; // Stores the last virtual key press. (Alpha keys only)
static char physKey = NO_KEY; // Stores the last physical key press. (Alpha keys only)
static char buildStr[12];
static byte buildCount;
static byte pressCount;
static byte kpadState;
// Take care of some special events.
void keypadEvent_ltr(KeypadEvent key) {
// in here when in alpha mode.
kpadState = ltrpad.getState( );
swOnState( key );
} // end ltrs keypad events
void keypadEvent_num( KeypadEvent key ) {
// in here when using number keypad
kpadState = numpad.getState( );
swOnState( key );
} // end numbers keypad events
void swOnState( char key ) {
switch( kpadState ) {
case PRESSED:
if (isalpha(key)) { // This is a letter key so we're using the letter keymap.
if (physKey != key) { // New key so start with the first of 3 characters.
pressCount = 0;
virtKey = key;
physKey = key;
}
else { // Pressed the same key again...
virtKey++; // so select the next character on that key.
pressCount++; // Tracks how many times we press the same key.
}
if (pressCount > 2) { // Last character reached so cycle back to start.
pressCount = 0;
virtKey = key;
}
Serial.print(virtKey); // Used for testing.
}
if (isdigit(key) || key == ' ' || key == '.')
Serial.print(key);
if (key == '#')
Serial.println();
break;
case HOLD:
if (key == '#') { // Toggle between keymaps.
if (alpha == true) { // We are currently using a keymap with letters
alpha = false; // Now we want a keymap with numbers.
digitalWrite(ledPin, LOW);
}
else { // We are currently using a keymap with numbers
alpha = true; // Now we want a keymap with letters.
}
}
else { // Some key other than '#' was pressed.
buildStr[buildCount++] = (isalpha(key)) ? virtKey : key;
buildStr[buildCount] = '\0';
Serial.println();
Serial.println(buildStr);
}
break;
case RELEASED:
if (buildCount >= sizeof(buildStr)) buildCount = 0; // Our string is full. Start fresh.
break;
} // end switch-case
}// end switch on state function
@@ -1,73 +0,0 @@
/* @file EventSerialKeypad.pde
|| @version 1.0
|| @author Alexander Brevig
|| @contact alexanderbrevig@gmail.com
||
|| @description
|| | Demonstrates using the KeypadEvent.
|| #
*/
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
byte ledPin = 13;
boolean blink = false;
boolean ledPin_state;
void setup(){
Serial.begin(9600);
pinMode(ledPin, OUTPUT); // Sets the digital pin as output.
digitalWrite(ledPin, HIGH); // Turn the LED on.
ledPin_state = digitalRead(ledPin); // Store initial LED state. HIGH when LED is on.
keypad.addEventListener(keypadEvent); // Add an event listener for this keypad
}
void loop(){
char key = keypad.getKey();
if (key) {
Serial.println(key);
}
if (blink){
digitalWrite(ledPin,!digitalRead(ledPin)); // Change the ledPin from Hi2Lo or Lo2Hi.
delay(100);
}
}
// Taking care of some special events.
void keypadEvent(KeypadEvent key){
switch (keypad.getState()){
case PRESSED:
if (key == '#') {
digitalWrite(ledPin,!digitalRead(ledPin));
ledPin_state = digitalRead(ledPin); // Remember LED state, lit or unlit.
}
break;
case RELEASED:
if (key == '*') {
digitalWrite(ledPin,ledPin_state); // Restore LED state from before it started blinking.
blink = false;
}
break;
case HOLD:
if (key == '*') {
blink = true; // Blink the LED when holding the * key.
}
break;
}
}
@@ -1,35 +0,0 @@
/* @file HelloKeypad.pde
|| @version 1.0
|| @author Alexander Brevig
|| @contact alexanderbrevig@gmail.com
||
|| @description
|| | Demonstrates the simplest use of the matrix Keypad library.
|| #
*/
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup(){
Serial.begin(9600);
}
void loop(){
char key = keypad.getKey();
if (key){
Serial.println(key);
}
}
@@ -1,68 +0,0 @@
#include <Keypad.h>
const byte ROWS = 2; // use 4X4 keypad for both instances
const byte COLS = 2;
char keys[ROWS][COLS] = {
{'1','2'},
{'3','4'}
};
byte rowPins[ROWS] = {5, 4}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {7, 6}; //connect to the column pinouts of the keypad
Keypad kpd( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const byte ROWSR = 2;
const byte COLSR = 2;
char keysR[ROWSR][COLSR] = {
{'a','b'},
{'c','d'}
};
byte rowPinsR[ROWSR] = {3, 2}; //connect to the row pinouts of the keypad
byte colPinsR[COLSR] = {7, 6}; //connect to the column pinouts of the keypad
Keypad kpdR( makeKeymap(keysR), rowPinsR, colPinsR, ROWSR, COLSR );
const byte ROWSUR = 4;
const byte COLSUR = 1;
char keysUR[ROWSUR][COLSUR] = {
{'M'},
{'A'},
{'R'},
{'K'}
};
// Digitran keypad, bit numbers of PCF8574 i/o port
byte rowPinsUR[ROWSUR] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPinsUR[COLSUR] = {8}; //connect to the column pinouts of the keypad
Keypad kpdUR( makeKeymap(keysUR), rowPinsUR, colPinsUR, ROWSUR, COLSUR );
void setup(){
// Wire.begin( );
kpdUR.begin( makeKeymap(keysUR) );
kpdR.begin( makeKeymap(keysR) );
kpd.begin( makeKeymap(keys) );
Serial.begin(9600);
Serial.println( "start" );
}
//byte alternate = false;
char key, keyR, keyUR;
void loop(){
// alternate = !alternate;
key = kpd.getKey( );
keyUR = kpdUR.getKey( );
keyR = kpdR.getKey( );
if (key){
Serial.println(key);
}
if( keyR ) {
Serial.println( keyR );
}
if( keyUR ) {
Serial.println( keyUR );
}
}
@@ -1,78 +0,0 @@
/* @file MultiKey.ino
|| @version 1.0
|| @author Mark Stanley
|| @contact mstanley@technologist.com
||
|| @description
|| | The latest version, 3.0, of the keypad library supports up to 10
|| | active keys all being pressed at the same time. This sketch is an
|| | example of how you can get multiple key presses from a keypad or
|| | keyboard.
|| #
*/
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the kpd
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the kpd
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
unsigned long loopCount;
unsigned long startTime;
String msg;
void setup() {
Serial.begin(9600);
loopCount = 0;
startTime = millis();
msg = "";
}
void loop() {
loopCount++;
if ( (millis()-startTime)>5000 ) {
Serial.print("Average loops per second = ");
Serial.println(loopCount/5);
startTime = millis();
loopCount = 0;
}
// Fills kpd.key[ ] array with up-to 10 active keys.
// Returns true if there are ANY active keys.
if (kpd.getKeys())
{
for (int i=0; i<LIST_MAX; i++) // Scan the whole key list.
{
if ( kpd.key[i].stateChanged ) // Only find keys that have changed state.
{
switch (kpd.key[i].kstate) { // Report active key state : IDLE, PRESSED, HOLD, or RELEASED
case PRESSED:
msg = " PRESSED.";
break;
case HOLD:
msg = " HOLD.";
break;
case RELEASED:
msg = " RELEASED.";
break;
case IDLE:
msg = " IDLE.";
}
Serial.print("Key ");
Serial.print(kpd.key[i].kchar);
Serial.println(msg);
}
}
}
} // End loop
@@ -1,46 +0,0 @@
#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6}; //connect to the column pinouts of the keypad
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
unsigned long loopCount = 0;
unsigned long timer_t = 0;
void setup(){
Serial.begin(9600);
// Try playing with different debounceTime settings to see how it affects
// the number of times per second your loop will run. The library prevents
// setting it to anything below 1 millisecond.
kpd.setDebounceTime(10); // setDebounceTime(mS)
}
void loop(){
char key = kpd.getKey();
// Report the number of times through the loop in 1 second. This will give
// you a relative idea of just how much the debounceTime has changed the
// speed of your code. If you set a high debounceTime your loopCount will
// look good but your keypresses will start to feel sluggish.
if ((millis() - timer_t) > 1000) {
Serial.print("Your loop code ran ");
Serial.print(loopCount);
Serial.println(" times over the last second");
loopCount = 0;
timer_t = millis();
}
loopCount++;
if(key)
Serial.println(key);
}
@@ -1,38 +0,0 @@
# Keypad Library data types
KeyState KEYWORD1
Keypad KEYWORD1
KeypadEvent KEYWORD1
# Keypad Library constants
NO_KEY LITERAL1
IDLE LITERAL1
PRESSED LITERAL1
HOLD LITERAL1
RELEASED LITERAL1
# Keypad Library methods & functions
addEventListener KEYWORD2
bitMap KEYWORD2
findKeyInList KEYWORD2
getKey KEYWORD2
getKeys KEYWORD2
getState KEYWORD2
holdTimer KEYWORD2
isPressed KEYWORD2
keyStateChanged KEYWORD2
numKeys KEYWORD2
pin_mode KEYWORD2
pin_write KEYWORD2
pin_read KEYWORD2
setDebounceTime KEYWORD2
setHoldTime KEYWORD2
waitForKey KEYWORD2
# this is a macro that converts 2d arrays to pointers
makeKeymap KEYWORD2
# List of objects created in the example sketches.
kpd KEYWORD3
keypad KEYWORD3
kbrd KEYWORD3
keyboard KEYWORD3
@@ -1,61 +0,0 @@
/*
|| @file Key.cpp
|| @version 1.0
|| @author Mark Stanley
|| @contact mstanley@technologist.com
||
|| @description
|| | Key class provides an abstract definition of a key or button
|| | and was initially designed to be used in conjunction with a
|| | state-machine.
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|| #
||
*/
#include "Key.hpp"
// default constructor
Key::Key() {
kchar = NO_KEY;
kstate = IDLE;
stateChanged = false;
}
// constructor
Key::Key(char userKeyChar) {
kchar = userKeyChar;
kcode = -1;
kstate = IDLE;
stateChanged = false;
}
void Key::key_update (char userKeyChar, KeyState userState, boolean userStatus) {
kchar = userKeyChar;
kstate = userState;
stateChanged = userStatus;
}
/*
|| @changelog
|| | 1.0 2012-06-04 - Mark Stanley : Initial Release
|| #
*/
@@ -1,70 +0,0 @@
/*
||
|| @file Key.h
|| @version 1.0
|| @author Mark Stanley
|| @contact mstanley@technologist.com
||
|| @description
|| | Key class provides an abstract definition of a key or button
|| | and was initially designed to be used in conjunction with a
|| | state-machine.
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|| #
||
*/
#ifndef KEY_H
#define KEY_H
#include <wiringPi.h>
#define boolean bool
#define byte unsigned char
#define OPEN LOW
#define CLOSED HIGH
typedef unsigned int uint;
typedef enum{ IDLE, PRESSED, HOLD, RELEASED } KeyState;
const char NO_KEY = '\0';
class Key {
public:
// members
char kchar;
int kcode;
KeyState kstate;
boolean stateChanged;
// methods
Key();
Key(char userKeyChar);
void key_update(char userKeyChar, KeyState userState, boolean userStatus);
private:
};
#endif
/*
|| @changelog
|| | 1.0 2012-06-04 - Mark Stanley : Initial Release
|| #
*/
@@ -1,21 +0,0 @@
#include <wiringPi.h>
#include <stdint.h>
#include <stdio.h>
//#include "Keypad.hpp"
#define bitWrite(x,n,b) (b ? (x |= 1<<n) : (x &= ~(1<<n)))
#define bitRead(x,n) ((((x>>n)&1) == 1) ? 1 : 0)
int main(){
unsigned char a=0x85,b=4,c=1;
char ch = 'A';
printf("a : %x\n",a);
printf("%d,%d \n",bitRead(a,7),bitRead(a,4));
bitWrite(a,b,c);
bitWrite(a,2,0);
printf("a : %x\n",a);
printf("%d,%d \n",bitRead(a,7),bitRead(a,4));
printf("char is %c ... \n",ch);
return 1;
}
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : MatrixKeypad.cpp
* Description : obtain the key code of 4x4 Matrix Keypad
* Author : freenove
* modification: 2016/07/10
* Description : Obtain the key code of 4x4 Matrix Keypad
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include "Keypad.hpp"
#include <stdio.h>
@@ -14,17 +14,16 @@ char keys[ROWS][COLS] = { //key code
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {1, 4, 5, 6 }; //connect to the row pinouts of the keypad
byte colPins[COLS] = {12,3, 2, 0 }; //connect to the column pinouts of the keypad
byte rowPins[ROWS] = {1, 4, 5, 6 }; //define the row pins for the keypad
byte colPins[COLS] = {12,3, 2, 0 }; //define the column pins for the keypad
//create Keypad object
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
int main(){
printf("Program is starting ... \n");
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
wiringPiSetup();
char key = 0;
keypad.setDebounceTime(50);
while(1){
Binary file not shown.
+12 -13
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : SenseLED.c
* Description : Controlling an led by infrared Motion sensor.
* Author : freenove
* modification: 2016/06/12
* Description : Control led with infrared Motion sensor
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
@@ -11,24 +11,23 @@
#define sensorPin 0 //define the sensorPin
int main(void)
{
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
{
printf("Program is starting ... \n");
wiringPiSetup();
pinMode(ledPin, OUTPUT);
pinMode(sensorPin, INPUT);
while(1){
if(digitalRead(sensorPin) == HIGH){ //if read sensor for high level
digitalWrite(ledPin, HIGH); //led on
printf("led on...\n");
if(digitalRead(sensorPin) == HIGH){ //if read value of sensor is HIGH level
digitalWrite(ledPin, HIGH); //make led on
printf("led turned on >>> \n");
}
else {
digitalWrite(ledPin, LOW); //led off
printf("...led off\n");
digitalWrite(ledPin, LOW); //make led off
printf("led turned off <<< \n");
}
}
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : UltrasonicRanging.c
* Description : Get distance from UltrasonicRanging
* Author : freenove
* modification: 2016/07/14
* Description : Get distance via UltrasonicRanging sensor
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
@@ -14,23 +14,22 @@
#define timeOut MAX_DISTANCE*60 // calculate timeout according to the maximum measured distance
//function pulseIn: obtain pulse time of a pin
int pulseIn(int pin, int level, int timeout);
float getSonar(){ // get the measurement results of ultrasonic module,with unit: cm
float getSonar(){ //get the measurement result of ultrasonic module with unit: cm
long pingTime;
float distance;
digitalWrite(trigPin,HIGH); //trigPin send 10us high level
digitalWrite(trigPin,HIGH); //send 10us high level to trigPin
delayMicroseconds(10);
digitalWrite(trigPin,LOW);
pingTime = pulseIn(echoPin,HIGH,timeOut); //read plus time of echoPin
distance = (float)pingTime * 340.0 / 2.0 / 10000.0; // the sound speed is 340m/s,and calculate distance
distance = (float)pingTime * 340.0 / 2.0 / 10000.0; //calculate distance with sound speed 340m/s
return distance;
}
int main(){
printf("Program is starting ... \n");
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
wiringPiSetup();
float distance = 0;
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
+5 -5
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : MPU6050RAW.c
* Description : Read the Raw data of MPU6050
* Author : freenove
* modification: 2016/07/18
* Description : Read data of MPU6050
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <stdio.h>
#include <stdint.h>
@@ -10,7 +10,7 @@
#include "I2Cdev.h"
#include "MPU6050.h"
MPU6050 accelgyro; //instantiate a MPU6050 class object
MPU6050 accelgyro; //creat MPU6050 class object
int16_t ax, ay, az; //store acceleration data
int16_t gx, gy, gz; //store gyroscope data
@@ -26,7 +26,7 @@ void setup() {
}
void loop() {
// read raw accel/gyro measurements from device
// read accel/gyro values of MPU6050
accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
// display accel/gyro x/y/z values
printf("a/g: %6hd %6hd %6hd %6hd %6hd %6hd\n",ax,ay,az,gx,gy,gz);
Binary file not shown.
Binary file not shown.
+14 -13
View File
@@ -1,8 +1,8 @@
/**********************************************************************
* Filename : LightWater03.c
* Description : Control LED by 74HC595 on the DIY circuit board
* Author : freenove
* modification: 2016/08/16
* Description : Control LED by 74HC595 on DIY circuit board
* Author : www.freenove.com
* modification: 2019/12/27
**********************************************************************/
#include <wiringPi.h>
#include <stdio.h>
@@ -12,7 +12,7 @@
#define dataPin 0 //DS Pin of 74HC595(Pin14)
#define latchPin 2 //ST_CP Pin of 74HC595(Pin12)
#define clockPin 3 //SH_CP Pin of 74HC595(Pin11)
//Define an array to save the pulse width of LED. Output the signal to the 8 adjacent LEDs in order.
//Define an array to store the pulse width of LED, which will be output to the 8 LEDs in order.
const int pluseWidth[]={0,0,0,0,0,0,0,0,64,32,16,8,4,2,1,0,0,0,0,0,0,0,0};
void outData(int8_t data){
digitalWrite(latchPin,LOW);
@@ -22,17 +22,18 @@ void outData(int8_t data){
int main(void)
{
int i,j,index; //index:current position in array pluseWidth
int moveSpeed = 100; //move speed delay, the larger, the slower
long lastMove; //Record the last time point of the move
if(wiringPiSetup() == -1){ //when initialize wiring failed,print messageto screen
printf("setup wiringPi failed !");
return 1;
}
int moveSpeed = 100; //It works as a delay. The larger, the slower
long lastMove; //Record the last time point of the led move
printf("Program is starting ...\n");
wiringPiSetup();
pinMode(dataPin,OUTPUT);
pinMode(latchPin,OUTPUT);
pinMode(clockPin,OUTPUT);
index = 0; //Starting from the array index 0
lastMove = millis(); //the start time
lastMove = millis(); // record the start time
while(1){
if(millis() - lastMove > moveSpeed) { //speed control
lastMove = millis(); //Record the time point of the move
@@ -40,8 +41,8 @@ int main(void)
if(index > 15) index = 0; //index to 0
}
for(i=0;i<64;i++){ //The cycle of PWM is 64 cycles
int8_t data = 0; //This loop of output data
for(j=0;j<8;j++){ //Calculate the output state of this loop
int8_t data = 0;
for(j=0;j<8;j++){ //Calculate the output state
if(i < pluseWidth[index+j]){ //Calculate the LED state according to the pulse width
data |= 0x01<<j ; //Calculate the data
}
+1 -1
View File
@@ -3,7 +3,7 @@
# Filename : Hello.py
# Description : Print "Hello World!".
# auther : www.freenove.com
# modification: 2018/08/04
# modification: 2019/12/27
########################################################################
def Hello():
+16 -16
View File
@@ -1,38 +1,38 @@
#!/usr/bin/env python3
########################################################################
# Filename : Blink.py
# Description : Make an led blinking.
# Description : Basic usage of GPIO. Let led blink.
# auther : www.freenove.com
# modification: 2018/08/02
# modification: 2019/12/28
########################################################################
import RPi.GPIO as GPIO
import time
ledPin = 11 # RPI Board pin11
ledPin = 11 # define ledPin
def setup():
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(ledPin, GPIO.OUT) # Set ledPin's mode is output
GPIO.output(ledPin, GPIO.LOW) # Set ledPin low to off led
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(ledPin, GPIO.OUT) # set the ledPin to OUTPUT mode
GPIO.output(ledPin, GPIO.LOW) # make ledPin output LOW level
print ('using pin%d'%ledPin)
def loop():
while True:
GPIO.output(ledPin, GPIO.HIGH) # led on
print ('...led on')
time.sleep(1)
GPIO.output(ledPin, GPIO.LOW) # led off
print ('led off...')
time.sleep(1)
GPIO.output(ledPin, GPIO.HIGH) # make ledPin output HIGH level to turn on led
print ('led turned on >>>') # print information on terminal
time.sleep(1) # Wait for 1 second
GPIO.output(ledPin, GPIO.LOW) # make ledPin output LOW level to turn off led
print ('led turned off <<<')
time.sleep(1) # Wait for 1 second
def destroy():
GPIO.output(ledPin, GPIO.LOW) # led off
GPIO.cleanup() # Release resource
GPIO.cleanup() # Release all GPIO
if __name__ == '__main__': # Program start from here
if __name__ == '__main__': # Program entrance
print ('Program is starting ... \n')
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
########################################################################
# Filename : Blink.py
# Description : Basic usage of GPIO. Let led blink.
# auther : www.freenove.com
# modification: 2019/12/26
########################################################################
from gpiozero import LED
from time import sleep
print ('Program is starting ... ')
led = LED(17) # define LED pin according to BCM Numbering
# led = LED("J8:11") # BOARD Numbering
'''
# pins numbering, the following lines are all equivalent
led = LED("GPIO17") # BCM
led = LED("BCM17") # BCM
led = LED("BOARD11") # BOARD
led = LED("WPI0") # WiringPi
led = LED("J8:11") # BOARD
'''
while True:
led.on() # turn on LED
print ('led turned on >>>') # print message on terminal
sleep(1) # wait 1 second
led.off() # turn off LED
print ('led turned off <<<')
sleep(1) # wait 1 second
+20 -19
View File
@@ -1,38 +1,39 @@
#!/usr/bin/env python3
########################################################################
# Filename : ButtonLED.py
# Description : Controlling an led by button.
# Author : freenove
# modification: 2018/08/02
# Description : Control led with button
# auther : www.freenove.com
# modification: 2019/12/28
########################################################################
import RPi.GPIO as GPIO
ledPin = 11 # define the ledPin
buttonPin = 12 # define the buttonPin
ledPin = 11 # define ledPin
buttonPin = 12 # define buttonPin
def setup():
print ('Program is starting...')
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(ledPin, GPIO.OUT) # Set ledPin's mode is output
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set buttonPin's mode is input, and pull up to high level(3.3V)
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(ledPin, GPIO.OUT) # set ledPin to OUTPUT mode
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # set buttonPin to PULL UP INPUT mode
def loop():
while True:
if GPIO.input(buttonPin)==GPIO.LOW:
GPIO.output(ledPin,GPIO.HIGH)
print ('led on ...')
else :
GPIO.output(ledPin,GPIO.LOW)
print ('led off ...')
if GPIO.input(buttonPin)==GPIO.LOW: # if button is pressed
GPIO.output(ledPin,GPIO.HIGH) # turn on led
print ('led turned on >>>') # print information on terminal
else : # if button is relessed
GPIO.output(ledPin,GPIO.LOW) # turn off led
print ('led turned off <<<')
def destroy():
GPIO.output(ledPin, GPIO.LOW) # led off
GPIO.cleanup() # Release resource
GPIO.output(ledPin, GPIO.LOW) # turn off led
GPIO.cleanup() # Release GPIO resource
if __name__ == '__main__': # Program start from here
if __name__ == '__main__': # Program entrance
print ('Program is starting...')
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
########################################################################
# Filename : ButtonLED.py
# Description : Control led with button.
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
from gpiozero import LED, Button
from signal import pause
print ('Program is starting ... ')
led = LED(17) # define LED pin according to BCM Numbering
button = Button(18) # define Button pin according to BCM Numbering
def onButtonPressed():
led.on()
print("Button is pressed, led turned on >>>")
def onButtonReleased():
led.off()
print("Button is released, led turned on <<<")
button.when_pressed = onButtonPressed
button.when_released = onButtonReleased
pause()
+31 -32
View File
@@ -2,45 +2,44 @@
########################################################################
# Filename : Tablelamp.py
# Description : a DIY MINI table lamp
# Author : freenove
# modification: 2018/08/02
# auther : www.freenove.com
# modification: 2019/12/28
########################################################################
import RPi.GPIO as GPIO
ledPin = 11 # define the ledPin
buttonPin = 12 # define the buttonPin
ledPin = 11 # define ledPin
buttonPin = 12 # define buttonPin
ledState = False
def setup():
print ('Program is starting...')
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(ledPin, GPIO.OUT) # Set ledPin's mode is output
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set buttonPin's mode is input, and pull up to high
def setup():
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(ledPin, GPIO.OUT) # set ledPin to OUTPUT mode
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # set buttonPin to PULL UP INPUT mode
def buttonEvent(channel):#When the button is pressed, this function will be executed
global ledState
print ('buttonEvent GPIO%d' %channel)
ledState = not ledState
if ledState :
print ('Turn on LED ... ')
else :
print ('Turn off LED ... ')
GPIO.output(ledPin,ledState)
def buttonEvent(channel): # When button is pressed, this function will be executed
global ledState
print ('buttonEvent GPIO%d' %channel)
ledState = not ledState
if ledState :
print ('Led turned on >>>')
else :
print ('Led turned off <<<')
GPIO.output(ledPin,ledState)
def loop():
#Button detect
GPIO.add_event_detect(buttonPin,GPIO.FALLING,callback = buttonEvent,bouncetime=300)
while True:
pass
#Button detect
GPIO.add_event_detect(buttonPin,GPIO.FALLING,callback = buttonEvent,bouncetime=300)
while True:
pass
def destroy():
GPIO.output(ledPin, GPIO.LOW) # led off
GPIO.cleanup() # Release resource
GPIO.cleanup() # Release GPIO resource
if __name__ == '__main__': # Program start from here
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
destroy()
if __name__ == '__main__': # Program entrance
print ('Program is starting...')
setup()
try:
loop()
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
@@ -0,0 +1,25 @@
#!/usr/bin/env python3
########################################################################
# Filename : Tablelamp.py
# Description : DIY MINI table lamp
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
from gpiozero import LED, Button
from signal import pause
print ('Program is starting ... ')
led = LED(17) # define LED pin according to BCM Numbering
button = Button(18) # define Button pin according to BCM Numbering
def onButtonPressed():
led.toggle()
if led.is_lit :
print("Led turned on >>>")
else :
print("Led turned off <<<")
button.when_pressed = onButtonPressed
pause()
@@ -1,42 +1,39 @@
#!/usr/bin/env python3
########################################################################
# Filename : LightWater.py
# Description : Display 10 LEDBar Graph
# Author : freenove
# modification: 2018/08/02
# Description : Use LEDBar Graph(10 LED)
# auther : www.freenove.com
# modification: 2019/12/28
########################################################################
import RPi.GPIO as GPIO
import time
ledPins = [11, 12, 13, 15, 16, 18, 22, 3, 5, 24]
def setup():
print ('Program is starting...')
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
for pin in ledPins:
GPIO.setup(pin, GPIO.OUT) # Set all ledPins' mode is output
GPIO.output(pin, GPIO.HIGH) # Set all ledPins to high(+3.3V) to off led
def setup():
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(ledPins, GPIO.OUT) # set all ledPins to OUTPUT mode
GPIO.output(ledPins, GPIO.HIGH) # make all ledPins output HIGH level, turn off all led
def loop():
while True:
for pin in ledPins: #make led on from left to right
for pin in ledPins: # make led(on) move from left to right
GPIO.output(pin, GPIO.LOW)
time.sleep(0.1)
GPIO.output(pin, GPIO.HIGH)
for pin in ledPins[::-1]: #make led on from right to left
for pin in ledPins[::-1]: # make led(on) move from right to left
GPIO.output(pin, GPIO.LOW)
time.sleep(0.1)
GPIO.output(pin, GPIO.HIGH)
def destroy():
for pin in ledPins:
GPIO.output(pin, GPIO.HIGH) # turn off all leds
GPIO.cleanup() # Release resource
GPIO.cleanup() # Release all GPIO
if __name__ == '__main__': # Program start from here
if __name__ == '__main__': # Program entrance
print ('Program is starting...')
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
########################################################################
# Filename : LightWater.py
# Description : Use LEDBar Graph(10 LED)
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
from gpiozero import LEDBoard
from time import sleep
from signal import pause
print ('Program is starting ... ')
ledPins = ["J8:11", "J8:12","J8:13","J8:15","J8:16","J8:18","J8:22","J8:3","J8:5","J8:24"]
leds = LEDBoard(*ledPins, active_high=False)
while True:
for index in range(0,len(ledPins),1): #move led(on) from left to right
leds.on(index)
sleep(0.1)
leds.off(index)
for index in range(len(ledPins)-1,-1,-1): #move led(on) from right to left
leds.on(index)
sleep(0.1)
leds.off(index)
@@ -1,43 +1,43 @@
#!/usr/bin/env python3
########################################################################
# Filename : BreathingLED.py
# Description : A breathing LED
# Author : freenove
# modification: 2018/08/02
# Description : Breathing LED
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import time
LedPin = 12
LedPin = 12 # define the LedPin
def setup():
global p
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output
GPIO.output(LedPin, GPIO.LOW) # Set LedPin to low
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(LedPin, GPIO.OUT) # set LedPin to OUTPUT mode
GPIO.output(LedPin, GPIO.LOW) # make ledPin output LOW level to turn off LED
p = GPIO.PWM(LedPin, 1000) # set Frequece to 1KHz
p.start(0) # Duty Cycle = 0
p = GPIO.PWM(LedPin, 500) # set PWM Frequence to 500Hz
p.start(0) # set initial Duty Cycle to 0
def loop():
while True:
for dc in range(0, 101, 1): # Increase duty cycle: 0~100
p.ChangeDutyCycle(dc) # Change duty cycle
for dc in range(0, 101, 1): # make the led brighter
p.ChangeDutyCycle(dc) # set dc value as the duty cycle
time.sleep(0.01)
time.sleep(1)
for dc in range(100, -1, -1): # Decrease duty cycle: 100~0
p.ChangeDutyCycle(dc)
for dc in range(100, -1, -1): # make the led darker
p.ChangeDutyCycle(dc) # set dc value as the duty cycle
time.sleep(0.01)
time.sleep(1)
def destroy():
p.stop()
GPIO.output(LedPin, GPIO.LOW) # turn off led
GPIO.cleanup()
p.stop() # stop PWM
GPIO.cleanup() # Release all GPIO
if __name__ == '__main__': # Program start from here
if __name__ == '__main__': # Program entrance
print ('Program is starting ... ')
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
@@ -1,53 +1,52 @@
#!/usr/bin/env python3
########################################################################
# Filename : ColorfulLED.py
# Description : A auto flash ColorfulLED
# Author : freenove
# modification: 2018/08/02
# Description : Random color change ColorfulLED
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import time
import random
pins = {'pin_R':11, 'pin_G':12, 'pin_B':13} # pins is a dict
pins = {'pinRed':11, 'pinGreen':12, 'pinBlue':13} # define the pins for RGBLED
def setup():
global p_R,p_G,p_B
print ('Program is starting ... ')
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
for i in pins:
GPIO.setup(pins[i], GPIO.OUT) # Set pins' mode is output
GPIO.output(pins[i], GPIO.HIGH) # Set pins to high(+3.3V) to off led
p_R = GPIO.PWM(pins['pin_R'], 2000) # set Frequece to 2KHz
p_G = GPIO.PWM(pins['pin_G'], 2000)
p_B = GPIO.PWM(pins['pin_B'], 2000)
p_R.start(0) # Initial duty Cycle = 0
p_G.start(0)
p_B.start(0)
global pwmRed,pwmGreen,pwmBlue
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(pins, GPIO.OUT) # set RGBLED pins to OUTPUT mode
GPIO.output(pins, GPIO.HIGH) # make RGBLED pins output HIGH level
pwmRed = GPIO.PWM(pins['pinRed'], 2000) # set PWM Frequence to 2kHz
pwmGreen = GPIO.PWM(pins['pinGreen'], 2000) # set PWM Frequence to 2kHz
pwmBlue = GPIO.PWM(pins['pinBlue'], 2000) # set PWM Frequence to 2kHz
pwmRed.start(0) # set initial Duty Cycle to 0
pwmGreen.start(0)
pwmBlue.start(0)
def setColor(r_val,g_val,b_val):
p_R.ChangeDutyCycle(r_val) # Change duty cycle
p_G.ChangeDutyCycle(g_val)
p_B.ChangeDutyCycle(b_val)
def setColor(r_val,g_val,b_val): # change duty cycle for three pins to r_val,g_val,b_val
pwmRed.ChangeDutyCycle(r_val) # change pwmRed duty cycle to r_val
pwmGreen.ChangeDutyCycle(g_val)
pwmBlue.ChangeDutyCycle(b_val)
def loop():
while True :
r=random.randint(0,100)#get a random in (0,100)
r=random.randint(0,100) #get a random in (0,100)
g=random.randint(0,100)
b=random.randint(0,100)
setColor(r,g,b)#set random as a duty cycle value
setColor(r,g,b) #set random as a duty cycle value
print ('r=%d, g=%d, b=%d ' %(r ,g, b))
time.sleep(0.3)
def destroy():
p_R.stop()
p_G.stop()
p_B.stop()
pwmRed.stop()
pwmGreen.stop()
pwmBlue.stop()
GPIO.cleanup()
if __name__ == '__main__': # Program start from here
if __name__ == '__main__': # Program entrance
print ('Program is starting ... ')
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
+18 -19
View File
@@ -1,38 +1,37 @@
#!/usr/bin/env python3
########################################################################
# Filename : Doorbell.py
# Description : Controlling an buzzer by button.
# Author : freenove
# modification: 2018/08/02
# Description : Make doorbell with buzzer and button
# auther : www.freenove.com
# modification: 2019/12/28
########################################################################
import RPi.GPIO as GPIO
buzzerPin = 11 # define the buzzerPin
buttonPin = 12 # define the buttonPin
buzzerPin = 11 # define buzzerPin
buttonPin = 12 # define buttonPin
def setup():
print ('Program is starting...')
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(buzzerPin, GPIO.OUT) # Set buzzerPin's mode is output
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set buttonPin's mode is input, and pull up to high level(3.3V)
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(buzzerPin, GPIO.OUT) # set buzzerPin to OUTPUT mode
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # set buttonPin to PULL UP INPUT mode
def loop():
while True:
if GPIO.input(buttonPin)==GPIO.LOW:
GPIO.output(buzzerPin,GPIO.HIGH)
print ('buzzer on ...')
else :
GPIO.output(buzzerPin,GPIO.LOW)
print ('buzzer off ...')
if GPIO.input(buttonPin)==GPIO.LOW: # if button is pressed
GPIO.output(buzzerPin,GPIO.HIGH) # turn on buzzer
print ('buzzer turned on >>>')
else : # if button is relessed
GPIO.output(buzzerPin,GPIO.LOW) # turn off buzzer
print ('buzzer turned off <<<')
def destroy():
GPIO.output(buzzerPin, GPIO.LOW) # buzzer off
GPIO.cleanup() # Release resource
GPIO.cleanup() # Release all GPIO
if __name__ == '__main__': # Program start from here
if __name__ == '__main__': # Program entrance
print ('Program is starting...')
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
########################################################################
# Filename : Doorbell.py
# Description : Make doorbell with buzzer and button
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
from gpiozero import LED, Button
from signal import pause
print ('Program is starting...')
led = LED(17)
button = Button(18)
def onButtonPressed():
led.on()
print("Button is pressed, led turned on >>>")
def onButtonReleased():
led.off()
print("Button is released, led turned on <<<")
button.when_pressed = onButtonPressed
button.when_released = onButtonReleased
pause()
+19 -19
View File
@@ -1,9 +1,9 @@
#!/usr/bin/env python3
########################################################################
# Filename : Alertor.py
# Description : Alarm by button.
# Author : freenove
# modification: 2018/08/02
# Description : Make Alertor with buzzer and button
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import time
@@ -13,41 +13,41 @@ buzzerPin = 11 # define the buzzerPin
buttonPin = 12 # define the buttonPin
def setup():
global p
print ('Program is starting...')
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(buzzerPin, GPIO.OUT) # Set buzzerPin's mode is output
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set buttonPin's mode is input, and pull up to high level(3.3V)
p = GPIO.PWM(buzzerPin, 1)
global p
GPIO.setmode(GPIO.BOARD) # Use PHYSICAL GPIO Numbering
GPIO.setup(buzzerPin, GPIO.OUT) # set RGBLED pins to OUTPUT mode
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set buttonPin to INPUT mode, and pull up to HIGH level, 3.3V
p = GPIO.PWM(buzzerPin, 1)
p.start(0);
def loop():
while True:
if GPIO.input(buttonPin)==GPIO.LOW:
alertor()
print ('buzzer on ...')
print ('alertor turned on >>> ')
else :
stopAlertor()
print ('buzzer off ...')
print ('alertor turned off <<<')
def alertor():
p.start(50)
for x in range(0,361): #frequency of the alarm along the sine wave change
sinVal = math.sin(x * (math.pi / 180.0)) #calculate the sine value
toneVal = 2000 + sinVal * 500 #Add to the resonant frequency with a Weighted
p.ChangeFrequency(toneVal) #output PWM
for x in range(0,361): # Make frequency of the alertor consistent with the sine wave
sinVal = math.sin(x * (math.pi / 180.0)) # calculate the sine value
toneVal = 2000 + sinVal * 500 # Add to the resonant frequency with a Weighted
p.ChangeFrequency(toneVal) # Change Frequency of PWM to toneVal
time.sleep(0.001)
def stopAlertor():
p.stop()
def destroy():
GPIO.output(buzzerPin, GPIO.LOW) # buzzer off
GPIO.cleanup() # Release resource
GPIO.output(buzzerPin, GPIO.LOW) # Turn off buzzer
GPIO.cleanup() # Release GPIO resource
if __name__ == '__main__': # Program start from here
if __name__ == '__main__': # Program entrance
print ('Program is starting...')
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
+12 -12
View File
@@ -1,40 +1,40 @@
#!/usr/bin/env python3
#############################################################################
# Filename : ADC.py
# Description : ADC and DAC
# Author : freenove
# modification: 2018/09/15
# Description : Analog and Digital Conversion, ADC and DAC
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import smbus
import time
address = 0x48 #default address of PCF8591
address = 0x48 # default address of PCF8591
bus=smbus.SMBus(1)
cmd=0x40 #command
cmd=0x40 # command, 0100 0000
def analogRead(chn):#read ADC value,chn:0,1,2,3
def analogRead(chn): # read ADC value,chn:0,1,2,3
value = bus.read_byte_data(address,cmd+chn)
return value
def analogWrite(value):#write DAC value
def analogWrite(value): # write DAC value
bus.write_byte_data(address,cmd,value)
def loop():
while True:
value = analogRead(0) #read the ADC value of channel 0
analogWrite(value) #write the DAC value
voltage = value / 255.0 * 3.3 #calculate the voltage value
value = analogRead(0) # read the ADC value of channel 0
analogWrite(value) # write the DAC value to control led
voltage = value / 255.0 * 3.3 # calculate the voltage value
print ('ADC Value : %d, Voltage : %.2f'%(value,voltage))
time.sleep(0.01)
def destroy():
bus.close()
if __name__ == '__main__':
if __name__ == '__main__': # Program entrance
print ('Program is starting ... ')
try:
loop()
except KeyboardInterrupt:
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
@@ -1,17 +1,17 @@
#!/usr/bin/env python3
#############################################################################
# Filename : Softlight.py
# Description : Potentiometer control LED
# Author : freenove
# modification: 2018/08/02
# Description : Control LED with Potentiometer
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import smbus
import time
address = 0x48
address = 0x48 # default address of PCF8591
bus=smbus.SMBus(1)
cmd=0x40
cmd=0x40 # command, 0100 0000
ledPin = 11
def analogRead(chn):
@@ -32,7 +32,7 @@ def setup():
def loop():
while True:
value = analogRead(0) #read A0 pin
value = analogRead(0) #read ADC value of A0 pin
p.ChangeDutyCycle(value*100/255) #Convert ADC value to duty cycle of PWM
voltage = value / 255.0 * 3.3 #calculate voltage
print ('ADC Value : %d, Voltage : %.2f'%(value,voltage))
@@ -42,12 +42,12 @@ def destroy():
bus.close()
GPIO.cleanup()
if __name__ == '__main__':
if __name__ == '__main__': # Program entrance
print ('Program is starting ... ')
setup()
try:
loop()
except KeyboardInterrupt:
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
@@ -1,9 +1,9 @@
#!/usr/bin/env python3
#############################################################################
# Filename : Softlight.py
# Description : Potentiometer control LED
# Author : freenove
# modification: 2018/08/02
# Description : Control RGBLED with Potentiometer
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import smbus
@@ -13,11 +13,11 @@ address = 0x48
bus=smbus.SMBus(1)
cmd=0x40
ledRedPin = 15 #define 3 pins of RGBLED
ledRedPin = 15 # define 3 pins for RGBLED
ledGreenPin = 13
ledBluePin = 11
def analogRead(chn): #read ADC value
def analogRead(chn): # read ADC value
bus.write_byte(address,cmd+chn)
value = bus.read_byte(address)
value = bus.read_byte(address)
@@ -29,11 +29,11 @@ def analogWrite(value):
def setup():
global p_Red,p_Green,p_Blue
GPIO.setmode(GPIO.BOARD)
GPIO.setup(ledRedPin,GPIO.OUT) #set 3 pins of RGBLED to output mode
GPIO.setup(ledRedPin,GPIO.OUT) # set RGBLED pins to OUTPUT mode
GPIO.setup(ledGreenPin,GPIO.OUT)
GPIO.setup(ledBluePin,GPIO.OUT)
p_Red = GPIO.PWM(ledRedPin,1000) #configure PMW to 3 pins of RGBLED
p_Red = GPIO.PWM(ledRedPin,1000) # configure PMW for RGBLED pins, set PWM Frequence to 1kHz
p_Red.start(0)
p_Green = GPIO.PWM(ledGreenPin,1000)
p_Green.start(0)
@@ -42,13 +42,13 @@ def setup():
def loop():
while True:
value_Red = analogRead(0) #read ADC value of 3 potentiometers
value_Red = analogRead(0) # read ADC value of 3 potentiometers
value_Green = analogRead(1)
value_Blue = analogRead(2)
p_Red.ChangeDutyCycle(value_Red*100/255) #map the read value of potentiometers into PWM value and output it
p_Red.ChangeDutyCycle(value_Red*100/255) # map the read value of potentiometers into PWM value and output it
p_Green.ChangeDutyCycle(value_Green*100/255)
p_Blue.ChangeDutyCycle(value_Blue*100/255)
#print read ADC value
# print read ADC value
print ('ADC Value value_Red: %d ,\tvlue_Green: %d ,\tvalue_Blue: %d'%(value_Red,value_Green,value_Blue))
time.sleep(0.01)
@@ -56,13 +56,10 @@ def destroy():
bus.close()
GPIO.cleanup()
if __name__ == '__main__':
if __name__ == '__main__': # Program entrance
print ('Program is starting ... ')
setup()
try:
loop()
except KeyboardInterrupt:
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
@@ -1,9 +1,9 @@
#!/usr/bin/env python3
#############################################################################
# Filename : Nightlamp.py
# Description : Photoresistor control LED
# Author : freenove
# modification: 2018/08/02
# Description : Control LED with Photoresistor
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import smbus
@@ -12,7 +12,7 @@ import time
address = 0x48
bus=smbus.SMBus(1)
cmd=0x40
ledPin = 11
ledPin = 11 # define ledPin
def analogRead(chn):
value = bus.read_byte_data(address,cmd+chn)
@@ -24,15 +24,15 @@ def analogWrite(value):
def setup():
global p
GPIO.setmode(GPIO.BOARD)
GPIO.setup(ledPin,GPIO.OUT)
GPIO.setup(ledPin,GPIO.OUT) # set ledPin to OUTPUT mode
GPIO.output(ledPin,GPIO.LOW)
p = GPIO.PWM(ledPin,1000)
p = GPIO.PWM(ledPin,1000) # set PWM Frequence to 1kHz
p.start(0)
def loop():
while True:
value = analogRead(0)
value = analogRead(0) # read the ADC value of channel 0
p.ChangeDutyCycle(value*100/255)
voltage = value / 255.0 * 3.3
print ('ADC Value : %d, Voltage : %.2f'%(value,voltage))
@@ -42,12 +42,12 @@ def destroy():
bus.close()
GPIO.cleanup()
if __name__ == '__main__':
if __name__ == '__main__': # Program entrance
print ('Program is starting ... ')
setup()
try:
loop()
except KeyboardInterrupt:
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
@@ -1,9 +1,9 @@
#!/usr/bin/env python3
#############################################################################
# Filename : Thermometer.py
# Description : A DIY Thermometer
# Author : freenove
# modification: 2018/08/02
# Description : DIY Thermometer
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import smbus
@@ -26,23 +26,23 @@ def setup():
def loop():
while True:
value = analogRead(0) #read A0 pin
voltage = value / 255.0 * 3.3 #calculate voltage
Rt = 10 * voltage / (3.3 - voltage) #calculate resistance value of thermistor
tempK = 1/(1/(273.15 + 25) + math.log(Rt/10)/3950.0) #calculate temperature (Kelvin)
tempC = tempK -273.15 #calculate temperature (Celsius)
value = analogRead(0) # read ADC value A0 pin
voltage = value / 255.0 * 3.3 # calculate voltage
Rt = 10 * voltage / (3.3 - voltage) # calculate resistance value of thermistor
tempK = 1/(1/(273.15 + 25) + math.log(Rt/10)/3950.0) # calculate temperature (Kelvin)
tempC = tempK -273.15 # calculate temperature (Celsius)
print ('ADC Value : %d, Voltage : %.2f, Temperature : %.2f'%(value,voltage,tempC))
time.sleep(0.01)
def destroy():
GPIO.cleanup()
if __name__ == '__main__':
if __name__ == '__main__': # Program entrance
print ('Program is starting ... ')
setup()
try:
loop()
except KeyboardInterrupt:
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
+11 -14
View File
@@ -1,9 +1,9 @@
#!/usr/bin/env python3
#############################################################################
# Filename : Joystick.py
# Description : Read Joystick
# Author : freenove
# modification: 2018/08/02
# Description : Read Joystick state
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import smbus
@@ -12,12 +12,12 @@ import time
address = 0x48
bus=smbus.SMBus(1)
cmd=0x40
Z_Pin = 12 #define pin for Z_Pin
def analogRead(chn): #read ADC value
Z_Pin = 12 # define Z_Pin
def analogRead(chn): # read ADC value
bus.write_byte(address,cmd+chn)
value = bus.read_byte(address)
value = bus.read_byte(address)
#value = bus.read_byte_data(address,cmd+chn)
# value = bus.read_byte_data(address,cmd+chn)
return value
def analogWrite(value):
@@ -25,11 +25,11 @@ def analogWrite(value):
def setup():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(Z_Pin,GPIO.IN,GPIO.PUD_UP) #set Z_Pin to pull-up mode
GPIO.setup(Z_Pin,GPIO.IN,GPIO.PUD_UP) # set Z_Pin to pull-up mode
def loop():
while True:
val_Z = GPIO.input(Z_Pin) #read digital quality of axis Z
val_Y = analogRead(0) #read analog quality of axis X and Y
val_Z = GPIO.input(Z_Pin) # read digital value of axis Z
val_Y = analogRead(0) # read analog value of axis X and Y
val_X = analogRead(1)
print ('value_X: %d ,\tvlue_Y: %d ,\tvalue_Z: %d'%(val_X,val_Y,val_Z))
time.sleep(0.01)
@@ -39,12 +39,9 @@ def destroy():
GPIO.cleanup()
if __name__ == '__main__':
print ('Program is starting ... ')
print ('Program is starting ... ') # Program entrance
setup()
try:
loop()
except KeyboardInterrupt:
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
+18 -17
View File
@@ -1,9 +1,9 @@
#!/usr/bin/env python3
#############################################################################
# Filename : Motor.py
# Description : Control Motor by L293D
# Author : freenove
# modification: 2018/08/02
# Description : Control Motor with L293D
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import smbus
@@ -12,7 +12,7 @@ import time
address = 0x48
bus=smbus.SMBus(1)
cmd=0x40
# define the pin connected to L293D
# define the pins connected to L293D
motoRPin1 = 13
motoRPin2 = 11
enablePin = 15
@@ -26,25 +26,26 @@ def analogWrite(value):
def setup():
global p
GPIO.setmode(GPIO.BOARD) # set mode for pin
GPIO.setup(motoRPin1,GPIO.OUT)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(motoRPin1,GPIO.OUT) # set pins to OUTPUT mode
GPIO.setup(motoRPin2,GPIO.OUT)
GPIO.setup(enablePin,GPIO.OUT)
p = GPIO.PWM(enablePin,1000)# creat PWM
p = GPIO.PWM(enablePin,1000) # creat PWM and set Frequence to 1KHz
p.start(0)
#mapNUM function: map the value from a range of mapping to another range.
# mapNUM function: map the value from a range of mapping to another range.
def mapNUM(value,fromLow,fromHigh,toLow,toHigh):
return (toHigh-toLow)*(value-fromLow) / (fromHigh-fromLow) + toLow
#motor function: determine the direction and speed of the motor according to the ADC value to be input.
# motor function: determine the direction and speed of the motor according to the input ADC value input
def motor(ADC):
value = ADC -128
if (value > 0):
GPIO.output(motoRPin1,GPIO.HIGH)
GPIO.output(motoRPin2,GPIO.LOW)
if (value > 0): # make motor turn forward
GPIO.output(motoRPin1,GPIO.HIGH) motoRPin1 output HIHG level
GPIO.output(motoRPin2,GPIO.LOW) motoRPin2 output LOW level
print ('Turn Forward...')
elif (value < 0):
elif (value < 0): # make motor turn backward
GPIO.output(motoRPin1,GPIO.LOW)
GPIO.output(motoRPin2,GPIO.HIGH)
print ('Turn Backward...')
@@ -53,11 +54,11 @@ def motor(ADC):
GPIO.output(motoRPin2,GPIO.LOW)
print ('Motor Stop...')
p.start(mapNUM(abs(value),0,128,0,100))
print ('The PWM duty cycle is %d%%\n'%(abs(value)*100/127)) #print PMW duty cycle.
print ('The PWM duty cycle is %d%%\n'%(abs(value)*100/127)) # print PMW duty cycle.
def loop():
while True:
value = analogRead(0)
value = analogRead(0) # read ADC value of channel 0
print ('ADC Value : %d'%(value))
motor(value)
time.sleep(0.01)
@@ -66,11 +67,11 @@ def destroy():
bus.close()
GPIO.cleanup()
if __name__ == '__main__':
if __name__ == '__main__': # Program entrance
print ('Program is starting ... ')
setup()
try:
loop()
except KeyboardInterrupt:
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
+13 -14
View File
@@ -1,22 +1,21 @@
#!/usr/bin/env python3
########################################################################
# Filename : Relay.py
# Description : Button control Relay and Motor
# Author : freenove
# modification: 2018/09/27
# Description : Control Relay and Motor via Button
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import time
relayPin = 11 # define the relayPin
relayPin = 11 # define the relayPin
buttonPin = 12 # define the buttonPin
debounceTime = 50
def setup():
print ('Program is starting...')
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(relayPin, GPIO.OUT) # Set relayPin's mode is output
GPIO.setup(buttonPin, GPIO.IN)
def setup():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(relayPin, GPIO.OUT) # set relayPin to OUTPUT mode
GPIO.setup(buttonPin, GPIO.IN) # set buttonPin to INTPUT mode
def loop():
relayState = False
@@ -41,16 +40,16 @@ def loop():
else :
print("Button is released!")
GPIO.output(relayPin,relayState)
lastButtonState = reading
lastButtonState = reading # lastButtonState store latest state
def destroy():
GPIO.output(relayPin, GPIO.LOW) # relay off
GPIO.cleanup() # Release resource
GPIO.cleanup()
if __name__ == '__main__': # Program start from here
if __name__ == '__main__': # Program entrance
print ('Program is starting...')
setup()
try:
loop()
except KeyboardInterrupt:
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
+14 -14
View File
@@ -2,8 +2,8 @@
########################################################################
# Filename : Sweep.py
# Description : Servo sweep
# Author : freenove
# modification: 2018/08/02
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import time
@@ -12,32 +12,32 @@ SERVO_MIN_DUTY = 2.5+OFFSE_DUTY #define pulse duty cycle for minimum angle o
SERVO_MAX_DUTY = 12.5+OFFSE_DUTY #define pulse duty cycle for maximum angle of servo
servoPin = 12
def map( value, fromLow, fromHigh, toLow, toHigh):
def map( value, fromLow, fromHigh, toLow, toHigh): # map a value from one range to another range
return (toHigh-toLow)*(value-fromLow) / (fromHigh-fromLow) + toLow
def setup():
global p
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(servoPin, GPIO.OUT) # Set servoPin's mode is output
GPIO.output(servoPin, GPIO.LOW) # Set servoPin to low
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(servoPin, GPIO.OUT) # Set servoPin to OUTPUT mode
GPIO.output(servoPin, GPIO.LOW) # Make servoPin output LOW level
p = GPIO.PWM(servoPin, 50) # set Frequece to 50Hz
p.start(0) # Duty Cycle = 0
p.start(0) # Set initial Duty Cycle to 0
def servoWrite(angle): # make the servo rotate to specific angle (0-180 degrees)
def servoWrite(angle): # make the servo rotate to specific angle, 0-180
if(angle<0):
angle = 0
elif(angle > 180):
angle = 180
p.ChangeDutyCycle(map(angle,0,180,SERVO_MIN_DUTY,SERVO_MAX_DUTY))#map the angle to duty cycle and output it
p.ChangeDutyCycle(map(angle,0,180,SERVO_MIN_DUTY,SERVO_MAX_DUTY)) # map the angle to duty cycle and output it
def loop():
while True:
for dc in range(0, 181, 1): #make servo rotate from 0 to 180 deg
servoWrite(dc) # Write to servo
for dc in range(0, 181, 1): # make servo rotate from 0 to 180 deg
servoWrite(dc) # Write dc value to servo
time.sleep(0.001)
time.sleep(0.5)
for dc in range(180, -1, -1): #make servo rotate from 180 to 0 deg
for dc in range(180, -1, -1): # make servo rotate from 180 to 0 deg
servoWrite(dc)
time.sleep(0.001)
time.sleep(0.5)
@@ -46,10 +46,10 @@ def destroy():
p.stop()
GPIO.cleanup()
if __name__ == '__main__': #Program start from here
if __name__ == '__main__': # Program entrance
print ('Program is starting...')
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
@@ -1,57 +1,60 @@
#!/usr/bin/env python3
########################################################################
# Filename : SteppingMotor.py
# Description :
# Author : freenove
# modification: 2018/08/02
# Description : Drive SteppingMotor
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import time
motorPins = (12, 16, 18, 22) #define pins connected to four phase ABCD of stepper motor
CCWStep = (0x01,0x02,0x04,0x08) #define power supply order for coil for rotating anticlockwise
CWStep = (0x08,0x04,0x02,0x01) #define power supply order for coil for rotating clockwise
motorPins = (12, 16, 18, 22) # define pins connected to four phase ABCD of stepper motor
CCWStep = (0x01,0x02,0x04,0x08) # define power supply order for rotating anticlockwise
CWStep = (0x08,0x04,0x02,0x01) # define power supply order for rotating clockwise
def setup():
print ('Program is starting...')
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
def setup():
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
for pin in motorPins:
GPIO.setup(pin,GPIO.OUT)
#as for four phase stepping motor, four steps is a cycle. the function is used to drive the stepping motor clockwise or anticlockwise to take four steps
# as for four phase stepping motor, four steps is a cycle. the function is used to drive the stepping motor clockwise or anticlockwise to take four steps
def moveOnePeriod(direction,ms):
for j in range(0,4,1): #cycle for power supply order
for i in range(0,4,1): #assign to each pin, a total of 4 pins
if (direction == 1):#power supply order clockwise
for j in range(0,4,1): # cycle for power supply order
for i in range(0,4,1): # assign to each pin
if (direction == 1):# power supply order clockwise
GPIO.output(motorPins[i],((CCWStep[j] == 1<<i) and GPIO.HIGH or GPIO.LOW))
else : #power supply order anticlockwise
else : # power supply order anticlockwise
GPIO.output(motorPins[i],((CWStep[j] == 1<<i) and GPIO.HIGH or GPIO.LOW))
if(ms<3): #the delay can not be less than 3ms, otherwise it will exceed speed limit of the motor
if(ms<3): # the delay can not be less than 3ms, otherwise it will exceed speed limit of the motor
ms = 3
time.sleep(ms*0.001)
#continuous rotation function, the parameter steps specifies the rotation cycles, every four steps is a cycle
# continuous rotation function, the parameter steps specifies the rotation cycles, every four steps is a cycle
def moveSteps(direction, ms, steps):
for i in range(steps):
moveOnePeriod(direction, ms)
#function used to stop rotating
# function used to stop motor
def motorStop():
for i in range(0,4,1):
GPIO.output(motorPins[i],GPIO.LOW)
def loop():
while True:
moveSteps(1,3,512) #rotating 360 deg clockwise, a total of 2048 steps in a circle, namely, 512 cycles.
moveSteps(1,3,512) # rotating 360 deg clockwise, a total of 2048 steps in a circle, 512 cycles
time.sleep(0.5)
moveSteps(0,3,512) #rotating 360 deg anticlockwise
moveSteps(0,3,512) # rotating 360 deg anticlockwise
time.sleep(0.5)
def destroy():
GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program start from here
if __name__ == '__main__': # Program entrance
print ('Program is starting...')
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
@@ -1,26 +1,27 @@
#!/usr/bin/env python3
#############################################################################
# Filename : LightWater02.py
# Description : Control LED by 74HC595
# Author : freenove
# modification: 2018/08/02
# Description : Control LED with 74HC595
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import time
#Defines the data bit that is transmitted preferentially in the shiftOut function.
# Defines the data bit that is transmitted preferentially in the shiftOut function.
LSBFIRST = 1
MSBFIRST = 2
#define the pins connect to 74HC595
dataPin = 11 #DS Pin of 74HC595(Pin14)
latchPin = 13 #ST_CP Pin of 74HC595(Pin12)
clockPin = 15 #CH_CP Pin of 74HC595(Pin11)
# define the pins for 74HC595
dataPin = 11 # DS Pin of 74HC595(Pin14)
latchPin = 13 # ST_CP Pin of 74HC595(Pin12)
clockPin = 15 # CH_CP Pin of 74HC595(Pin11)
def setup():
GPIO.setmode(GPIO.BOARD) # Number GPIOs by its physical location
GPIO.setup(dataPin, GPIO.OUT)
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(dataPin, GPIO.OUT) # set pin to OUTPUT mode
GPIO.setup(latchPin, GPIO.OUT)
GPIO.setup(clockPin, GPIO.OUT)
#shiftOut function, use bit serial transmission.
# shiftOut function, use bit serial transmission.
def shiftOut(dPin,cPin,order,val):
for i in range(0,8):
GPIO.output(cPin,GPIO.LOW);
@@ -34,10 +35,10 @@ def loop():
while True:
x=0x01
for i in range(0,8):
GPIO.output(latchPin,GPIO.LOW) #Output low level to latchPin
shiftOut(dataPin,clockPin,LSBFIRST,x)#Send serial data to 74HC595
GPIO.output(latchPin,GPIO.HIGH)#Output high level to latchPin, and 74HC595 will update the data to the parallel output port.
x<<=1# make the variable move one bit to left once, then the bright LED move one step to the left once.
GPIO.output(latchPin,GPIO.LOW) # Output low level to latchPin
shiftOut(dataPin,clockPin,LSBFIRST,x) # Send serial data to 74HC595
GPIO.output(latchPin,GPIO.HIGH) # Output high level to latchPin, and 74HC595 will update the data to the parallel output port.
x<<=1 # make the variable move one bit to left once, then the bright LED move one step to the left once.
time.sleep(0.1)
x=0x80
for i in range(0,8):
@@ -47,13 +48,13 @@ def loop():
x>>=1
time.sleep(0.1)
def destroy(): # When 'Ctrl+C' is pressed, the function is executed.
def destroy():
GPIO.cleanup()
if __name__ == '__main__': # Program starting from here
if __name__ == '__main__': # Program entrance
print ('Program is starting...' )
setup()
try:
loop()
except KeyboardInterrupt:
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
@@ -1,23 +1,23 @@
#!/usr/bin/env python3
#############################################################################
# Filename : SevenSegmentDisplay.py
# Description : Control SevenSegmentDisplay by 74HC595
# Author : freenove
# modification: 2018/08/02
# Description : Control SevenSegmentDisplay with 74HC595
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import time
LSBFIRST = 1
MSBFIRST = 2
#define the pins connect to 74HC595
dataPin = 11 #DS Pin of 74HC595(Pin14)
latchPin = 13 #ST_CP Pin of 74HC595(Pin12)
clockPin = 15 #CH_CP Pin of 74HC595(Pin11)
#SevenSegmentDisplay display the character "0"- "F"successively
# define the pins for 74HC595
dataPin = 11 # DS Pin of 74HC595(Pin14)
latchPin = 13 # ST_CP Pin of 74HC595(Pin12)
clockPin = 15 # CH_CP Pin of 74HC595(Pin11)
# SevenSegmentDisplay display the character "0"- "F" successively
num = [0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e]
def setup():
GPIO.setmode(GPIO.BOARD) # Number GPIOs by its physical location
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(dataPin, GPIO.OUT)
GPIO.setup(latchPin, GPIO.OUT)
GPIO.setup(clockPin, GPIO.OUT)
@@ -35,22 +35,22 @@ def loop():
while True:
for i in range(0,len(num)):
GPIO.output(latchPin,GPIO.LOW)
shiftOut(dataPin,clockPin,MSBFIRST,num[i])#Output the figures and the highest level is transfered preferentially.
shiftOut(dataPin,clockPin,MSBFIRST,num[i]) # Send serial data to 74HC595
GPIO.output(latchPin,GPIO.HIGH)
time.sleep(0.5)
for i in range(0,len(num)):
GPIO.output(latchPin,GPIO.LOW)
shiftOut(dataPin,clockPin,MSBFIRST,num[i]&0x7f)#Use "&0x7f"to display the decimal point.
shiftOut(dataPin,clockPin,MSBFIRST,num[i]&0x7f) # Use "&0x7f" to display the decimal point.
GPIO.output(latchPin,GPIO.HIGH)
time.sleep(0.5)
def destroy(): # When 'Ctrl+C' is pressed, the function is executed.
def destroy():
GPIO.cleanup()
if __name__ == '__main__': # Program starting from here
if __name__ == '__main__': # Program entrance
print ('Program is starting...' )
setup()
try:
loop()
except KeyboardInterrupt:
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
+22 -22
View File
@@ -1,9 +1,9 @@
#!/usr/bin/env python3
#############################################################################
# Filename : StopWatch.py
# Description : Control 4_Digit_7_Segment_Display by 74HC595
# Author : freenove
# modification: 2018/08/03
# Description : Control 4_Digit_7_Segment_Display with 74HC595
# Author : www.freenove.com
# modification: 2019/12/27
########################################################################
import RPi.GPIO as GPIO
import time
@@ -11,17 +11,17 @@ import threading
LSBFIRST = 1
MSBFIRST = 2
#define the pins connect to 74HC595
dataPin = 18 #DS Pin of 74HC595(Pin14)
latchPin = 16 #ST_CP Pin of 74HC595(Pin12)
clockPin = 12 #SH_CP Pin of 74HC595(Pin11)
# define the pins connect to 74HC595
dataPin = 18 # DS Pin of 74HC595
latchPin = 16 # ST_CP Pin of 74HC595
clockPin = 12 # SH_CP Pin of 74HC595
num = (0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90)
digitPin = (11,13,15,19) # Define the pin of 7-segment display common end
counter = 0 # Variable counter, the number will be dislayed by 7-segment display
t = 0 # define the Timer object
def setup():
GPIO.setmode(GPIO.BOARD) # Number GPIOs by its physical location
GPIO.setup(dataPin, GPIO.OUT) # Set pin mode to output
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(dataPin, GPIO.OUT) # Set pin mode to OUTPUT
GPIO.setup(latchPin, GPIO.OUT)
GPIO.setup(clockPin, GPIO.OUT)
for pin in digitPin:
@@ -36,7 +36,7 @@ def shiftOut(dPin,cPin,order,val):
GPIO.output(dPin,(0x80&(val<<i)==0x80) and GPIO.HIGH or GPIO.LOW)
GPIO.output(cPin,GPIO.HIGH)
def outData(data): #function used to output data for 74HC595
def outData(data): # function used to output data for 74HC595
GPIO.output(latchPin,GPIO.LOW)
shiftOut(dataPin,clockPin,MSBFIRST,data)
GPIO.output(latchPin,GPIO.HIGH)
@@ -47,11 +47,11 @@ def selectDigit(digit): # Open one of the 7-segment display and close the remain
GPIO.output(digitPin[2],GPIO.LOW if ((digit&0x02) == 0x02) else GPIO.HIGH)
GPIO.output(digitPin[3],GPIO.LOW if ((digit&0x01) == 0x01) else GPIO.HIGH)
def display(dec): #display function for 7-segment display
outData(0xff) #eliminate residual display
selectDigit(0x01) #Select the first, and display the single digit
def display(dec): # display function for 7-segment display
outData(0xff) # eliminate residual display
selectDigit(0x01) # Select the first, and display the single digit
outData(num[dec%10])
time.sleep(0.003) #display duration
time.sleep(0.003) # display duration
outData(0xff)
selectDigit(0x02) # Select the second, and display the tens digit
outData(num[dec%100//10])
@@ -64,32 +64,32 @@ def display(dec): #display function for 7-segment display
selectDigit(0x08) # Select the fourth, and display the thousands digit
outData(num[dec%10000//1000])
time.sleep(0.003)
def timer(): #timer function
def timer():
global counter
global t
t = threading.Timer(1.0,timer) #reset time of timer to 1s
t.start() #Start timing
t = threading.Timer(1.0,timer) # reset time of timer to 1s
t.start() # Start timing
counter+=1
print ("counter : %d"%counter)
def loop():
global t
global counter
t = threading.Timer(1.0,timer) #set the timer
t = threading.Timer(1.0,timer) # set the timer
t.start() # Start timing
while True:
display(counter) # display the number counter
def destroy(): # When "Ctrl+C" is pressed, the function is executed.
def destroy():
global t
GPIO.cleanup()
t.cancel() #cancel the timer
t.cancel()
if __name__ == '__main__': # Program starting from here
if __name__ == '__main__': # Program entrance
print ('Program is starting...' )
setup()
try:
loop()
except KeyboardInterrupt:
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
+18 -18
View File
@@ -1,21 +1,21 @@
#!/usr/bin/env python3
#############################################################################
# Filename : LEDMatrix.py
# Description : Control LEDMatrix by 74HC595
# Author : freenove
# modification: 2018/08/03
# Description : Control LEDMatrix with 74HC595
# auther : www.freenove.com
# modification: 2019/12/28
########################################################################
import RPi.GPIO as GPIO
import time
LSBFIRST = 1
MSBFIRST = 2
#define the pins connect to 74HC595
dataPin = 11 #DS Pin of 74HC595(Pin14)
latchPin = 13 #ST_CP Pin of 74HC595(Pin12)
clockPin = 15 #SH_CP Pin of 74HC595(Pin11)
pic = [0x1c,0x22,0x51,0x45,0x45,0x51,0x22,0x1c]# data of smiling face
data = [#data of "0-F"
# define the pins connect to 74HC595
dataPin = 11 # DS Pin of 74HC595(Pin14)
latchPin = 13 # ST_CP Pin of 74HC595(Pin12)
clockPin = 15 # SH_CP Pin of 74HC595(Pin11)
pic = [0x1c,0x22,0x51,0x45,0x45,0x51,0x22,0x1c] # data of smiling face
data = [ # data of "0-F"
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, # " "
0x00, 0x00, 0x3E, 0x41, 0x41, 0x3E, 0x00, 0x00, # "0"
0x00, 0x00, 0x21, 0x7F, 0x01, 0x00, 0x00, 0x00, # "1"
@@ -36,7 +36,7 @@ data = [#data of "0-F"
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, # " "
]
def setup():
GPIO.setmode(GPIO.BOARD) # Number GPIOs by its physical location
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(dataPin, GPIO.OUT)
GPIO.setup(latchPin, GPIO.OUT)
GPIO.setup(clockPin, GPIO.OUT)
@@ -52,18 +52,18 @@ def shiftOut(dPin,cPin,order,val):
def loop():
while True:
for j in range(0,500):# Repeat enough times to display the smiling face a period of time
for j in range(0,500): # Repeat enough times to display the smiling face a period of time
x=0x80
for i in range(0,8):
GPIO.output(latchPin,GPIO.LOW)
shiftOut(dataPin,clockPin,MSBFIRST,pic[i]) #first shift data of line information to first stage 74HC959
shiftOut(dataPin,clockPin,MSBFIRST,~x) #then shift data of column information to second stage 74HC959
GPIO.output(latchPin,GPIO.HIGH)# Output data of two stage 74HC595 at the same time
time.sleep(0.001)# display the next column
GPIO.output(latchPin,GPIO.HIGH) # Output data of two stage 74HC595 at the same time
time.sleep(0.001) # display the next column
x>>=1
for k in range(0,len(data)-8):#len(data) total number of "0-F" columns
for j in range(0,20):# times of repeated displaying LEDMatrix in every frame, the bigger the "j", the longer the display time.
for k in range(0,len(data)-8): #len(data) total number of "0-F" columns
for j in range(0,20): # times of repeated displaying LEDMatrix in every frame, the bigger the "j", the longer the display time.
x=0x80 # Set the column information to start from the first column
for i in range(k,k+8):
GPIO.output(latchPin,GPIO.LOW)
@@ -72,13 +72,13 @@ def loop():
GPIO.output(latchPin,GPIO.HIGH)
time.sleep(0.001)
x>>=1
def destroy(): # When 'Ctrl+C' is pressed, the function is executed.
def destroy():
GPIO.cleanup()
if __name__ == '__main__': # Program starting from here
if __name__ == '__main__': # Program entrance
print ('Program is starting...' )
setup()
try:
loop()
except KeyboardInterrupt:
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
+16 -16
View File
@@ -1,37 +1,37 @@
#!/usr/bin/env python3
########################################################################
# Filename : SenseLED.py
# Description : Controlling an led by infrared Motion sensor.
# Author : freenove
# modification: 2018/08/03
# Description : Control led with infrared Motion sensor.
# auther : www.freenove.com
# modification: 2019/12/28
########################################################################
import RPi.GPIO as GPIO
ledPin = 12 # define the ledPin
sensorPin = 11 # define the sensorPin
ledPin = 12 # define ledPin
sensorPin = 11 # define sensorPin
def setup():
print ('Program is starting...')
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(ledPin, GPIO.OUT) # Set ledPin's mode is output
GPIO.setup(sensorPin, GPIO.IN) # Set sensorPin's mode is input
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(ledPin, GPIO.OUT) # set ledPin to OUTPUT mode
GPIO.setup(sensorPin, GPIO.IN) # set sensorPin to INPUT mode
def loop():
while True:
if GPIO.input(sensorPin)==GPIO.HIGH:
GPIO.output(ledPin,GPIO.HIGH)
print ('led on ...')
GPIO.output(ledPin,GPIO.HIGH) # turn on led
print ('led turned on >>>')
else :
GPIO.output(ledPin,GPIO.LOW)
print ('led off ...')
GPIO.output(ledPin,GPIO.LOW) # turn off led
print ('led turned off <<<')
def destroy():
GPIO.cleanup() # Release resource
GPIO.cleanup() # Release GPIO resource
if __name__ == '__main__': # Program start from here
if __name__ == '__main__': # Program entrance
print ('Program is starting...')
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()
@@ -1,19 +1,19 @@
#!/usr/bin/env python3
########################################################################
# Filename : UltrasonicRanging.py
# Description : Get distance from UltrasonicRanging.
# Author : freenove
# modification: 2018/08/03
# Description : Get distance via UltrasonicRanging sensor
# auther : www.freenove.com
# modification: 2019/12/28
########################################################################
import RPi.GPIO as GPIO
import time
trigPin = 16
echoPin = 18
MAX_DISTANCE = 220 #define the maximum measured distance
timeOut = MAX_DISTANCE*60 #calculate timeout according to the maximum measured distance
MAX_DISTANCE = 220 # define the maximum measuring distance, unit: cm
timeOut = MAX_DISTANCE*60 # calculate timeout according to the maximum measuring distance
def pulseIn(pin,level,timeOut): # function pulseIn: obtain pulse time of a pin
def pulseIn(pin,level,timeOut): # obtain pulse time of a pin under timeOut
t0 = time.time()
while(GPIO.input(pin) != level):
if((time.time() - t0) > timeOut*0.000001):
@@ -25,32 +25,32 @@ def pulseIn(pin,level,timeOut): # function pulseIn: obtain pulse time of a pin
pulseTime = (time.time() - t0)*1000000
return pulseTime
def getSonar(): #get the measurement results of ultrasonic module,with unit: cm
GPIO.output(trigPin,GPIO.HIGH) #make trigPin send 10us high level
time.sleep(0.00001) #10us
GPIO.output(trigPin,GPIO.LOW)
pingTime = pulseIn(echoPin,GPIO.HIGH,timeOut) #read plus time of echoPin
distance = pingTime * 340.0 / 2.0 / 10000.0 # the sound speed is 340m/s, and calculate distance
def getSonar(): # get the measurement results of ultrasonic module,with unit: cm
GPIO.output(trigPin,GPIO.HIGH) # make trigPin output 10us HIGH level
time.sleep(0.00001) # 10us
GPIO.output(trigPin,GPIO.LOW) # make trigPin output LOW level
pingTime = pulseIn(echoPin,GPIO.HIGH,timeOut) # read plus time of echoPin
distance = pingTime * 340.0 / 2.0 / 10000.0 # calculate distance with sound speed 340m/s
return distance
def setup():
print ('Program is starting...')
GPIO.setmode(GPIO.BOARD) #numbers GPIOs by physical location
GPIO.setup(trigPin, GPIO.OUT) #
GPIO.setup(echoPin, GPIO.IN) #
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(trigPin, GPIO.OUT) # set trigPin to OUTPUT mode
GPIO.setup(echoPin, GPIO.IN) # set echoPin to INPUT mode
def loop():
while(True):
distance = getSonar()
distance = getSonar() # get distance
print ("The distance is : %.2f cm"%(distance))
time.sleep(1)
if __name__ == '__main__': #program start from here
if __name__ == '__main__': # Program entrance
print ('Program is starting...')
setup()
try:
loop()
except KeyboardInterrupt: #when 'Ctrl+C' is pressed, the program will exit
GPIO.cleanup() #release resource
except KeyboardInterrupt: # Press ctrl-c to end the program.
GPIO.cleanup() # release GPIO resource
+11 -11
View File
@@ -1,33 +1,33 @@
#!/usr/bin/env python3
########################################################################
# Filename : MPU6050RAW.py
# Description : Read the Raw data of MPU6050.
# Author : freenove
# modification: 2018/08/03
# Description : Read data of MPU6050.
# auther : www.freenove.com
# modification: 2019/12/28
########################################################################
import MPU6050
import time
mpu = MPU6050.MPU6050() #instantiate a MPU6050 class object
accel = [0]*3 #store accelerometer data
gyro = [0]*3 #store gyroscope data
mpu = MPU6050.MPU6050() # instantiate a MPU6050 class object
accel = [0]*3 # define an arry to store accelerometer data
gyro = [0]*3 # define an arry to store gyroscope data
def setup():
mpu.dmp_initialize() #initialize MPU6050
mpu.dmp_initialize() # initialize MPU6050
def loop():
while(True):
accel = mpu.get_acceleration() #get accelerometer data
gyro = mpu.get_rotation() #get gyroscope data
accel = mpu.get_acceleration() # get accelerometer data
gyro = mpu.get_rotation() # get gyroscope data
print("a/g:%d\t%d\t%d\t%d\t%d\t%d "%(accel[0],accel[1],accel[2],gyro[0],gyro[1],gyro[2]))
print("a/g:%.2f g\t%.2f g\t%.2f g\t%.2f d/s\t%.2f d/s\t%.2f d/s"%(accel[0]/16384.0,accel[1]/16384.0,
accel[2]/16384.0,gyro[0]/131.0,gyro[1]/131.0,gyro[2]/131.0))
time.sleep(0.1)
if __name__ == '__main__': # Program start from here
if __name__ == '__main__': # Program entrance
print("Program is starting ... ")
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed,the program will exit.
except KeyboardInterrupt: # Press ctrl-c to end the program.
pass
@@ -1,27 +1,29 @@
#!/usr/bin/env python3
#############################################################################
# Filename : LightWater03.py
# Description : Control LED by 74HC595 on the DIY circuit board
# Author : freenove
# modification: 2018/08/03
# Description : Control LED with 74HC595 on the DIY circuit board
# auther : www.freenove.com
# modification: 2019/12/28
########################################################################
import RPi.GPIO as GPIO
import time
LSBFIRST = 1
MSBFIRST = 2
#define the pins connect to 74HC595
dataPin = 11 #DS Pin of 74HC595(Pin14)
latchPin = 13 #ST_CP Pin of 74HC595(Pin12)
clockPin = 15 #SH_CP Pin of 74HC595(Pin11)
#Define an array to save the pulse width of LED. Output the signal to the 8 adjacent LEDs in order.
# define the pins connect to 74HC595
dataPin = 11 # DS Pin of 74HC595(Pin14)
latchPin = 13 # ST_CP Pin of 74HC595(Pin12)
clockPin = 15 # SH_CP Pin of 74HC595(Pin11)
# Define an array to store the pulse width of LED
pluseWidth = [0,0,0,0,0,0,0,0,64,32,16,8,4,2,1,0,0,0,0,0,0,0,0]
def setup():
GPIO.setmode(GPIO.BOARD) # Number GPIOs by its physical location
GPIO.setup(dataPin, GPIO.OUT)
GPIO.setup(latchPin, GPIO.OUT)
GPIO.setup(clockPin, GPIO.OUT)
GPIO.setmode(GPIO.BOARD) # use PHYSICAL GPIO Numbering
GPIO.setup(dataPin, GPIO.OUT) # set dataPin to OUTPUT mode
GPIO.setup(latchPin, GPIO.OUT) # set latchPin to OUTPUT mode
GPIO.setup(clockPin, GPIO.OUT) # set clockPin to OUTPUT mode
def shiftOut(dPin,cPin,order,val):
for i in range(0,8):
@@ -38,30 +40,30 @@ def outData(data):
GPIO.output(latchPin,GPIO.HIGH)
def loop():
moveSpeed = 0.1 #move speed delay, the larger, the slower
index = 0 #Starting from the array index 0
lastMove = time.time() #the start time
moveSpeed = 0.1 # moveSpeed works like a relay, the larger, the slower
index = 0 # array index starts from 0
lastMove = time.time() # record the start time
while True:
if(time.time() - lastMove > moveSpeed): #speed control
lastMove = time.time() #Record the time point of the move
index +=1 #move to next
if(index > 15): #index to 0
if(time.time() - lastMove > moveSpeed): # control speed
lastMove = time.time() # Record the time point of the move
index +=1 # move to next
if(index > 15): # index to 0
index = 0
for i in range(0,64): #The cycle of PWM is 64 cycles
data = 0 #This loop of output data
for i in range(0,64): # The cycle of PWM is 64 cycles
data = 0
for j in range(0,8): #Calculate the output state of this loop
if(i < pluseWidth[j+index]): #Calculate the LED state according to the pulse width
data |= 1<<j #Calculate the data
outData(data) #Send the data to 74HC595
data |= 1<<j # Calculate the data
outData(data) # Send the data to 74HC595
def destroy(): # When 'Ctrl+C' is pressed, the function is executed.
def destroy():
GPIO.cleanup()
if __name__ == '__main__': # Program starting from here
if __name__ == '__main__': # Program entrance
print ('Program is starting...')
setup()
try:
loop()
except KeyboardInterrupt:
except KeyboardInterrupt: # Press ctrl-c to end the program.
destroy()