Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Update example vhost file for Apache2
WSGIPythonPath /path/to/repo/FuzzManager/server <VirtualHost *:80> ServerName fuzzmanager.your.domain Alias /static/ /path/to/repo/FuzzManager/server/crashmanager/static/ Alias /tests/ /path/to/repo/FuzzManager/server/tests/ WSGIScriptAlias / /path/to/repo/FuzzManager/server/server/wsgi.py WSGIPassAuthorization On <Location /> AuthType Basic AuthName "LDAP Login" AuthBasicProvider file ldap AuthUserFile /path/to/.htpasswd # Your LDAP configuration here, including Require directives # This user is used by clients to download test cases and signatures Require user fuzzmanager </Location> <Location /crashmanager/rest/> Satisfy Any Allow from all </Location> <Directory /path/to/repo/FuzzManager/server> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> </VirtualHost>
WSGIDaemonProcess fuzzmanager.your.domain python-path=/path/to/repo/FuzzManager/server WSGIProcessGroup fuzzmanager.your.domain WSGIApplicationGroup %{GLOBAL} <VirtualHost *:80> ServerName fuzzmanager.your.domain Alias /static/ /path/to/repo/FuzzManager/server/crashmanager/static/ Alias /tests/ /path/to/repo/FuzzManager/server/tests/ WSGIScriptAlias / /path/to/repo/FuzzManager/server/server/wsgi.py process-group=fuzzmanager.your.domain WSGIPassAuthorization On <Location /> AuthType Basic AuthName "LDAP Login" AuthBasicProvider file ldap AuthUserFile /path/to/.htpasswd # Your LDAP configuration here, including Require directives # This user is used by clients to download test cases and signatures Require user fuzzmanager </Location> <Location /crashmanager/rest/> Satisfy Any Allow from all </Location> <Location /ec2spotmanager/rest/> Satisfy Any Allow from all </Location> <Directory /path/to/repo/FuzzManager/server> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> </VirtualHost>
Add body section to create a new session
FORMAT: 1A HOST: https://neighbor.ly/api/ # Neighbor.ly Here you will find how to integrate an application with Neighbor.ly. Check our [Dashboard source code](https://github.com/neighborly/neighborly-dashboard) for a real use case. # Sessions Your first stop when integrating with Neighborly. For a lot of endpoints, you are expected to provide an `access_token`, managed by this section. ## Sessions [/sessions] ### Create a session [POST] + Request { "email": "mr.nobody@example.com", "password": "your-really-strong-password" } + Header Accept: application/vnd.api+json;revision=1 + Response 201 (application/json) { "access_token": "Ndf6kxgLfr_KMhAg8wMpm7Yit2cvHkv9oI8qIXWiHmZdeqI1h0cmn8p4wCEhoZS-AQY", "user_id": 1 } + Response 400 (application/json) {} + Response 401 (application/json) {}
FORMAT: 1A HOST: https://neighbor.ly/api/ # Neighbor.ly Here you will find how to integrate an application with Neighbor.ly. Check our [Dashboard source code](https://github.com/neighborly/neighborly-dashboard) for a real use case. # Sessions Your first stop when integrating with Neighborly. For a lot of endpoints, you are expected to provide an `access_token`, managed by this section. ## Sessions [/sessions] ### Create a session [POST] + Request + Header Accept: application/vnd.api+json;revision=1 + Body { "email": "mr.nobody@example.com", "password": "your-really-strong-password" } + Response 201 (application/json) { "access_token": "Ndf6kxgLfr_KMhAg8wMpm7Yit2cvHkv9oI8qIXWiHmZdeqI1h0cmn8p4wCEhoZS-AQY", "user_id": 1 } + Response 400 (application/json) {} + Response 401 (application/json) {}
Make the API version optional in the request
# Lion API Lion is a basic localization service using `git` as the backend for storing translations. ## Request headers All requests to Lion must include the following headers: - `Lion-Api-Version` # Group Projects ## Project collection [/projects] ### List projects [GET] List all configured projects + Request (application/json) + Header Lion-Api-Version: v1 + Response 200 (application/json) + Header Lion-Api-Version: v1 + Body { "projects": [ "projectA": { "name" "projectA" // All project details } ] } ## Project management [/project/{name}] + Parameters + name (required, string) ... Project name ### Get project [GET] Fetch project details, given the projects' name. + Request (application/json) + Header Lion-Api-Version: v1 + Response 200 (application/json) + Header Lion-Api-Version: v1 + Body { "name": "Project name", "resources": [ "resource1", "..." ] } + Response 404 (application/json) + Header Lion-Api-Version: v1
# Lion API Lion is a basic localization service using `git` as the backend for storing translations. ## Request headers Requests should have the `Lion-Api-Version` header set. The current API version is `v1`. If the header is not set, it is assumed to be the latest version. Example header: - `Lion-Api-Version: v1` # Group Projects ## Project collection [/projects] ### List projects [GET] List all configured projects + Request (application/json) + Header Lion-Api-Version: v1 + Response 200 (application/json) + Header Lion-Api-Version: v1 + Body { "projects": [ "projectA": { "name" "projectA" // All project details } ] } ## Project management [/project/{name}] + Parameters + name (required, string) ... Project name ### Get project [GET] Fetch project details, given the projects' name. + Request (application/json) + Header Lion-Api-Version: v1 + Response 200 (application/json) + Header Lion-Api-Version: v1 + Body { "name": "Project name", "resources": [ "resource1", "..." ] } + Response 404 (application/json) + Header Lion-Api-Version: v1
Add article body to API Blueprint
FORMAT: 1A HOST: https://www.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt" }
FORMAT: 1A HOST: https://www.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt", "body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>" }
Add /user and /user/orgs api endpoints to api docs
FORMAT: 1A HOST: https://orgmanager.miguelpiedrafita.com/api # Orgmanager API The Orgmanager API allows you to integrate Orgmanager with other applications and projects. ## Questions Collection [/questions] ### List All Questions [GET] + Response 200 (application/json) [ { "question": "Favourite programming language?", "published_at": "2015-08-05T08:40:51.620Z", "choices": [ { "choice": "Swift", "votes": 2048 }, { "choice": "Python", "votes": 1024 }, { "choice": "Objective-C", "votes": 512 }, { "choice": "Ruby", "votes": 256 } ] } ] ### Create a New Question [POST] You may create your own question using this action. It takes a JSON object containing a question and a collection of answers in the form of choices. + Request (application/json) { "question": "Favourite programming language?", "choices": [ "Swift", "Python", "Objective-C", "Ruby" ] } + Response 201 (application/json) + Headers Location: /questions/2 + Body { "question": "Favourite programming language?", "published_at": "2015-08-05T08:40:51.620Z", "choices": [ { "choice": "Swift", "votes": 0 }, { "choice": "Python", "votes": 0 }, { "choice": "Objective-C", "votes": 0 }, { "choice": "Ruby", "votes": 0 } ] }
FORMAT: 1A HOST: https://orgmanager.miguelpiedrafita.com/api # Orgmanager API The Orgmanager API allows you to integrate Orgmanager with other applications and projects. ## User Data [/user] ### Get user info [GET] + Response 200 (application/json) { "id":1, "name":"Miguel Piedrafita", "email":"soy@miguelpiedrafita.com", "github_username":"m1guelpf", "created_at":"2017-01-25 18:44:32", "updated_at":"2017-02-16 19:40:50" } ## User Organizations [/user/orgs] ### Get user organizations [GET] + Response 200 (application/json) { "id":1, "name":"Test Organization", "url":"https:\/\/api.github.com\/orgs\/test-org", "description":null, "avatar":"https:\/\/miguelpiedrafita.com\/logo.png", "invitecount":100 }
Add URLs to API Blueprint
FORMAT: 1A HOST: https://api.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt" }
FORMAT: 1A HOST: https://www.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt" }
Fix locale example for API Blueprint
FORMAT: 1A HOST: https://www.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/{locale}/articles/{id}] A single Article object with all its details + Parameters + locale = `en` (optional, string, `cy`) ... Locale of the Article. + id (required, string, `where-to-go-to-get-free-debt-advice`) ... ID of the Article. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt", "body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>" }
FORMAT: 1A HOST: https://www.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/{locale}/articles/{id}] A single Article object with all its details + Parameters + locale = `en` (optional, string, `en`) ... Locale of the Article. + id (required, string, `where-to-go-to-get-free-debt-advice`) ... ID of the Article. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt", "body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>" }
Remove articles collection from API blueprint
FORMAT: 1A HOST: https://api.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service's API. # Group Articles Article related resources of the **Money Advice Service** ## Articles Collection [/articles] ### List all Articles [GET] + Response 200 (application/json) [{ "id": 1, "content": "Jogging in park" }, { "id": 2, "content": "Pick-up posters from post-office" }] ## Article [/articles/{id}] A single Article object with all its details + Parameters + slug (required, string, `the-article`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header X-My-Header: The Value + Body { "slug": "the-article", "title": "Pick-up posters from post-office", content: "<p>La de da</p>" }
FORMAT: 1A HOST: https://api.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header X-My-Header: The Value + Body { "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice" }
Add locale to API Blueprint
FORMAT: 1A HOST: https://www.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt", "body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>" }
FORMAT: 1A HOST: https://www.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/{locale}/articles/{id}] A single Article object with all its details + Parameters + locale = `en` (optional, string, `cy`) ... Locale of the Article. + id (required, string, `foo-bar`) ... ID of the Article. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt", "body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>" }
Add link header to API Blueprint
FORMAT: 1A HOST: https://api.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header X-My-Header: The Value + Body { "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice" }
FORMAT: 1A HOST: https://api.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice" }
Add article body to API Blueprint
FORMAT: 1A HOST: https://www.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt" }
FORMAT: 1A HOST: https://www.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt", "body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>" }
Substitute name with slug for fetching projects
# Lion API Lion is a basic localization service using `git` as the backend for storing translations. ## Request headers Requests should have the `Lion-Api-Version` header set. The current API version is `v1`. If the header is not set, it is assumed to be the latest version. Example header: - `Lion-Api-Version: v1` # Group Projects ## Project collection [/projects] ### List projects [GET] List all configured projects + Request (application/json) + Header Lion-Api-Version: v1 + Response 200 (application/json) + Header Lion-Api-Version: v1 + Body { "projects": [ "projectA": { "name" "projectA" // All project details } ] } ## Project management [/project/{name}] + Parameters + name (required, string) ... Project name ### Get project [GET] Fetch project details, given the projects' name. + Request (application/json) + Header Lion-Api-Version: v1 + Response 200 (application/json) + Header Lion-Api-Version: v1 + Body { "name": "Project name", "resources": [ "resource1", "..." ] } + Response 404 (application/json) + Header Lion-Api-Version: v1
# Lion API Lion is a basic localization service using `git` as the backend for storing translations. ## Request headers Requests should have the `Lion-Api-Version` header set. The current API version is `v1`. If the header is not set, it is assumed to be the latest version. Example header: - `Lion-Api-Version: v1` # Group Projects ## Project collection [/projects] ### List projects [GET] List all configured projects + Request (application/json) + Header Lion-Api-Version: v1 + Response 200 (application/json) + Header Lion-Api-Version: v1 + Body { "projects": [ "projectA": { "name" "projectA" // All project details ... } ] } ## Project management [/project/{slug}] + Parameters + slug (required, string) ... Project slug ### Get project [GET] Fetch project details, given the projects' name. + Request (application/json) + Header Lion-Api-Version: v1 + Response 200 (application/json) + Header Lion-Api-Version: v1 + Body { "name": "Project name", "slug": "project-name", "resources": [ "resource1", "..." ] } + Response 404 (application/json) + Header Lion-Api-Version: v1
Add article description to API Blueprint
FORMAT: 1A HOST: https://api.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice" }
FORMAT: 1A HOST: https://api.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt" }
Update Introduction description for Apiary
FORMAT: 1A HOST: https://awesome-bucketlist-api.herokuapp.com/ # awesome-bucketlist Polls is a simple API allowing consumers to view polls and vote in them. ## Bucketlists [/bucketlists] ### Create New Bucketlist [POST] Creates a new bucketlist under your account. + Request (application/json) + Headers Authorization: "Your Token" + Response 201 (application/json) [ { "name": "Dare Devil", "description": "Stunts I want to try out." } ] ### Get All Bucketlists [GET] You may create your own question using this action. It takes a JSON object containing a question and a collection of answers in the form of choices. + Request (application/json) + Headers Authorization: "Your Token" + Response 200 (application/json) + Body [ { "name": "Dare Devil", "description": "Stunts I want to try out." } ]
FORMAT: 1A HOST: https://awesome-bucketlist-api.herokuapp.com/ # awesome-bucketlist A Bucketlist is a list of items, activities or goals you want to achieve before you "kick the bucket" this is an API to allow you create a new user account, login into your account, create, update, view or delete bucketlists and bucketlist items.e ## Bucketlists [/bucketlists] ### Create New Bucketlist [POST] Creates a new bucketlist under your account. + Request (application/json) + Headers Authorization: "Your Token" + Response 201 (application/json) [ { "name": "Dare Devil", "description": "Stunts I want to try out." } ] ### Get All Bucketlists [GET] You may create your own question using this action. It takes a JSON object containing a question and a collection of answers in the form of choices. + Request (application/json) + Headers Authorization: "Your Token" + Response 200 (application/json) + Body [ { "name": "Dare Devil", "description": "Stunts I want to try out." } ]
Add missing rescue search documentation
<!-- include(models.apib) --> # Group Rescues <!-- include(rescues/list.apib) --> <!-- include(rescues/create.apib) --> <!-- include(rescues/retrieve.apib) --> <!-- include(rescues/update.apib) -->
# Group Rescues <!-- include(rescues/list.apib) --> <!-- include(rescues/create.apib) --> <!-- include(rescues/retrieve.apib) --> <!-- include(rescues/search.apib) --> <!-- include(rescues/update.apib) -->
Fix locale example for API Blueprint
FORMAT: 1A HOST: https://www.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/{locale}/articles/{id}] A single Article object with all its details + Parameters + locale = `en` (optional, string, `cy`) ... Locale of the Article. + id (required, string, `where-to-go-to-get-free-debt-advice`) ... ID of the Article. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt", "body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>" }
FORMAT: 1A HOST: https://www.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/{locale}/articles/{id}] A single Article object with all its details + Parameters + locale = `en` (optional, string, `en`) ... Locale of the Article. + id (required, string, `where-to-go-to-get-free-debt-advice`) ... ID of the Article. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt", "body": "<h2>Watch out for companies that aren't charities</h2><p>Look out for companies with misleading names that sound like debt charities but are actually commercial businesses.</p><p>Never ever pay for services from this type of company.</p>" }
Add link header to API Blueprint
FORMAT: 1A HOST: https://api.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header X-My-Header: The Value + Body { "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice" }
FORMAT: 1A HOST: https://api.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice" }
Add article description to API Blueprint
FORMAT: 1A HOST: https://api.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice" }
FORMAT: 1A HOST: https://api.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt" }
Add URLs to API Blueprint
FORMAT: 1A HOST: https://api.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "id": "where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt" }
FORMAT: 1A HOST: https://www.moneyadviceservice.org.uk # Money Advice Service API for the Money Advice Service. # Articles Article related resources of the **Money Advice Service**. ## Article [/articles/{id}] A single Article object with all its details + Parameters + id (required, string, `foo-bar`) ... String `id` of the Article to perform action with. Has example value. ### Retrieve a Article [GET] + Response 200 (application/json) + Header Link: <https://www.moneyadviceservice.org.uk/cy/articles/ble-i-gael-cyngor-am-ddim-ynghylch-dyled>; rel="alternate"; hreflang="cy"; title="Ble i gael cyngor am ddim ynghylch dyled" + Body { "url": "https://www.moneyadviceservice.org.uk/en/articles/where-to-go-to-get-free-debt-advice", "title": "Where to go to get free debt advice", "description": "Find out where you can get free, confidential help if you are struggling with debt" }
Use 4 spaces as indentation
FORMAT: 1A # Machines API # Group Machines # Machines collection [/machines/{id}] + Parameters - id (number, `1`) ## Get Machines [GET] - Request (application/json) + Parameters - id (number, `2`) - Response 200 (application/json; charset=utf-8) [ { "type": "bulldozer", "name": "willy" } ] - Request (application/json) + Parameters - id (number, `3`) - Response 200 (application/json; charset=utf-8) [ { "type": "bulldozer", "name": "willy" } ]
FORMAT: 1A # Machines API # Group Machines # Machines collection [/machines/{id}] + Parameters + id (number, `1`) ## Get Machines [GET] + Request (application/json) + Parameters + id (number, `2`) + Response 200 (application/json; charset=utf-8) [ { "type": "bulldozer", "name": "willy" } ] + Request (application/json) + Parameters + id (number, `3`) + Response 200 (application/json; charset=utf-8) [ { "type": "bulldozer", "name": "willy" } ]
Correct API definition semantic issues.
FORMAT: 1A # Organising, Swiftly _Organising_ is an outliner/todo list with strong search functionality. ## Node Collection [/nodes] ### Root node and all children [GET] Returns the root node, with all of its children. + Response 200 (application/json) { "ID": 0, "text": "Update repo", "completed": false, "children": [ { "ID": 1, "text": "Commit changes", "completed": true }, { "ID": 2, "text": "Push to origin", "completed": false } ] }
FORMAT: 1A # Organising, Swiftly _Organising_ is an outliner/todo list with strong search functionality. ## Node Collection [/nodes] ### Root node and all children [GET] Returns the root node, with all of its children. + Response 200 (application/json) { "ID": 0, "text": "Update repo", "completed": false, "children": [ { "ID": 1, "text": "Commit changes", "completed": true }, { "ID": 2, "text": "Push to origin", "completed": false } ] }
Add Apiary Documentation for the API
FORMAT: 1A HOST: https://awesome-bucketlist-api.herokuapp.com/ # awesome-bucketlist Polls is a simple API allowing consumers to view polls and vote in them. ## Bucketlists [/bucketlists] ### Create New Bucketlist [POST] Creates a new bucketlist under your account. + Request (application/json) + Headers Authorization: "Your Token" + Response 201 (application/json) [ { "name": "Dare Devil", "description": "Stunts I want to try out." } ] ### Get All Bucketlists [GET] You may create your own question using this action. It takes a JSON object containing a question and a collection of answers in the form of choices. + Request (application/json) + Headers Authorization: "Your Token" + Response 200 (application/json) + Body [ { "name": "Dare Devil", "description": "Stunts I want to try out." } ]
Add login and registration to blueprint
FORMAT: 1A # Admiral Admiral is a deployment management system for Fleet and CoreOS. Unlike other deployment systems, Admiral also allows for automatic deployment and scaling of Fleet units. # Admiral Root [/v1] This resource simply represents the root of the Admiral API. It provides a basic JSON response as validation that the API server is running. ## Retrieve the API Information [GET] + Response 200 (application/json) { "name": "Admiral API", "version": 1 } ## Group Authentication Resources related to authenticating users. ## Login [/v1/login] ### Login [POST] Authenticates a user and returns a token that the client should use for further interactions with the API server. Requests should be made with a JSON object containing the following items: + Request (application/json) { "username": "johndoe", "password": "password" } + Response 200 (application/json) { "token": "API token" } + Response 401 (application/json) { "error": 401, "message": "The specified user was invalid." } ## Registration [/v1/register] ### Register [POST] Registers a user with the specified information, and returns a new token if the registration was successful. Registration must be enabled on the server or this endpoint will return an error. + Request (application/json) { "username": "johndoe", "password": "password" } + Response 200 (application/json) { "token": "API token" } + Response 500 (application/json) { "error": 500, "message": "The server is not accepting registration." }
Rename of SelectByText to SelectItemText
 msg←SelectAdvanced;result;output;sel;froot;prev ⍝ Test /Examples/DC/SelectAdvanced ⍝ Ensure 'multi' (the selection list) is there: msg←'selection list not there' :If 0≢sel←Find'multi' ⍝ Grab the 2 elements already chosen: Click'PressMe' output←Find'output' {0≠⍴output.Text}Retry ⍬ ⍝ Wait to see if it gets populated msg←'Expected output was not produced.' :AndIf 'You picked: Bananas Pears'≡prev←output.Text ⍝ Make a single selection: froot←'Grapes' 'multi'SelectByText'-'froot Click'PressMe' output←Find'output' {prev≢output.Text}Retry ⍬ ⍝ Wait to see if it gets populated :AndIf (prev←output.Text)≡'You picked: ',froot ⍝ Make another selection: 'multi'SelectByText'Pears' Click'PressMe' output←Find'output' {prev≢output.Text}Retry ⍬ ⍝ Wait to see if it gets populated :AndIf (prev←output.Text)≡'You picked: ',froot,' Pears' msg←'' :EndIf
 msg←SelectAdvanced;result;output;sel;froot;prev ⍝ Test /Examples/DC/SelectAdvanced ⍝ Ensure 'multi' (the selection list) is there: msg←'selection list not there' :If 0≢sel←Find'multi' ⍝ Grab the 2 elements already chosen: Click'PressMe' output←Find'output' {0≠⍴output.Text}Retry ⍬ ⍝ Wait to see if it gets populated msg←'Expected output was not produced.' :AndIf 'You picked: Bananas Pears'≡prev←output.Text ⍝ Make a single selection: froot←'Grapes' 'multi'SelectItemText'~'froot Click'PressMe' output←Find'output' {prev≢output.Text}Retry ⍬ ⍝ Wait to see if it gets populated :AndIf (prev←output.Text)≡'You picked: ',froot ⍝ Make another selection: 'multi'SelectItemText'Pears' Click'PressMe' output←Find'output' {prev≢output.Text}Retry ⍬ ⍝ Wait to see if it gets populated :AndIf (prev←output.Text)≡'You picked: ',froot,' Pears' msg←'' :EndIf
Add missing '=' in MS3/Examples/DC/EditFieldSample
:Class EditFieldSimple : MiPageSample ⍝ Control:: _DC.EditField _DC.Button _html.label ⍝ Description:: Collect input and echo it on a button press ∇ Compose;btn;F1;label;name :Access Public F1←'myform'Add _.Form ⍝ Create a form label←('for"name"')F1.Add _.label'Please enter your name' name←'name'F1.Add _.EditField done←'done'F1.Add _.Button'Done' done.On'click' 'CallbackFn' 'result'F1.Add _.div ⍝ a div to contain output, updated by CallbackFn ∇ ∇ r←CallbackFn :Access Public r←'#result'Replace _.p('Hello, ',(Get'name'),'!') ∇ :EndClass
:Class EditFieldSimple : MiPageSample ⍝ Control:: _DC.EditField _DC.Button _html.label ⍝ Description:: Collect input and echo it on a button press ∇ Compose;btn;F1;label;name :Access Public F1←'myform'Add _.Form ⍝ Create a form label←('for="name"')F1.Add _.label'Please enter your name' name←'name'F1.Add _.EditField done←'done'F1.Add _.Button'Done' done.On'click' 'CallbackFn' 'result'F1.Add _.div ⍝ a div to contain output, updated by CallbackFn ∇ ∇ r←CallbackFn :Access Public r←'#result'Replace _.p('Hello, ',(Get'name'),'!') ∇ :EndClass
Upgrade message inculdes note of 15.0+ being free.
:Class MS3Server : MiServer ⍝ This is an example of a customized MiServer ⍝ The MiServer class exposes several overridable methods that can be customized by the user ⍝ In this case we customize the onServerLoad method ⍝ The ClassName parameter in the Server.xml configuration file is used to specify the customized class :Include #.MS3SiteUtils ⍝∇:require =/MS3SiteUtils ∇ Make config :Access Public :Implements Constructor :Base config ⍝ Version warning :If 14>{⊃(//)⎕VFI ⍵/⍨2>+\'.'=⍵}2⊃'.'⎕WG'APLVersion' ⎕←'' ⎕←'MiServer 3.0 itself will run under Dyalog APL versions 13.2 and later' ⎕←'However, the MS3 MiSite uses features found only in Dyalog APL versions beginning with 14.0' ⎕←'' ⎕←'Please restart the MS3 MiSite using Dyalog APL version 14.0 or later...' → :EndIf ∇ ∇ onServerLoad :Access Public Override ⍝ Handle any server startup processing {}C ⍝ initialize CACHE ∇ :EndClass
:Class MS3Server : MiServer ⍝ This is an example of a customized MiServer ⍝ The MiServer class exposes several overridable methods that can be customized by the user ⍝ In this case we customize the onServerLoad method ⍝ The ClassName parameter in the Server.xml configuration file is used to specify the customized class :Include #.MS3SiteUtils ⍝∇:require =/MS3SiteUtils ∇ Make config :Access Public :Implements Constructor :Base config ⍝ Version warning :If 14>{⊃(//)⎕VFI ⍵/⍨2>+\'.'=⍵}2⊃'.'⎕WG'APLVersion' ⎕←'' ⎕←'MiServer 3.0 itself will run under Dyalog APL versions 13.2 and later' ⎕←'However, the MS3 MiSite uses features found only in Dyalog APL versions beginning with 14.0' ⎕←'From version 15.0, Dyalog APL is available free of charge at http://www.dyalog.com' ⎕←'' ⎕←'Please restart the MS3 MiSite using Dyalog APL version 14.0 or later...' → :EndIf ∇ ∇ onServerLoad :Access Public Override ⍝ Handle any server startup processing {}C ⍝ initialize CACHE ∇ :EndClass
Fix to new ParseAttr syntax
:class aSimple : MiPageSample ⍝ Control:: _html.a ⍝ Description:: Insert a hyperlink ∇ Compose :Access public Add 'Click ' 'href' 'http://www.dyalog.com/meet-team-dyalog.htm'Add _.a'here' Add ' to meet us.' ∇ :endclass
:class aSimple : MiPageSample ⍝ Control:: _html.a ⍝ Description:: Insert a hyperlink ∇ Compose :Access public Add'Click ' 'href=http://www.dyalog.com/meet-team-dyalog.htm'Add _.a'here' Add' to meet us.' ∇ :endclass
Trim fat on apl nr 1
#!/usr/local/bin/apl -s 'Day 3: Perfectly Spherical Houses in a Vacuum' i ← (0 0) cmds ← ('<' '>' '^' 'v') dirs ← ((¯1 0) (1 0) (0 ¯1) (0 1)) houses ← ∪ (0 0) , i { ++\⍵ } { dirs[ti] ⊣ ti ← cmds ⍳ ⍵ } ⍞ ⍴ houses ⍝ the amount of houses to visit )OFF
#!/usr/local/bin/apl -s 'Day 3: Perfectly Spherical Houses in a Vacuum' cmds ← ('<' '>' '^' 'v') dirs ← ((¯1 0) (1 0) (0 ¯1) (0 1)) houses ← ∪ (0 0) , { ++\⍵ } { dirs[ti] ⊣ ti ← cmds ⍳ ⍵ } ⍞ ⍴ houses ⍝ the amount of houses to visit )OFF
Remove empty comment that messes up the index page
:class abbrsample: MiPage ⍝ Control:: HTML.abbr ⍝ Description:: this is an example of use of abbr which allows you to display text when hovering over an area ⍝ ⍝ This is an example of using the HTML 'abbr' element. ∇ Compose :Access public ⍝ We simply display the text 'Hover over THIS to reveal.' ⍝ First we add the text 'Hover over', then Add'Hover over ' ⍝ Then we add the element 'abbr' containing the text 'THIS', ⍝ making sure the text to display when hovering over it ⍝ (the title) displays 'True Http Internet Scripts' 'title' 'True Http Internet Scripts'Add _.abbr'THIS' ⍝ then we add the final text. Add' to reveal.' ∇ :endclass
:class abbrsample: MiPage ⍝ Control:: HTML.abbr ⍝ Description:: this is an example of use of abbr which allows you to display text when hovering over an area ⍝ This is an example of using the HTML 'abbr' element. ∇ Compose :Access public ⍝ We simply display the text 'Hover over THIS to reveal.' ⍝ First we add the text 'Hover over', then Add'Hover over ' ⍝ Then we add the element 'abbr' containing the text 'THIS', ⍝ making sure the text to display when hovering over it ⍝ (the title) displays 'True Http Internet Scripts' 'title' 'True Http Internet Scripts'Add _.abbr'THIS' ⍝ then we add the final text. Add' to reveal.' ∇ :endclass
Add boilerplate APL script to serve CGI webpages
#!/usr/local/bin/apl --script NEWLINE ← ⎕UCS 10 HEADERS ← 'Content-Type: text/plain', NEWLINE HEADERS ⍝ ⎕←HEADERS ⍝ ⍕⎕TS )OFF ⍝ testVars←'FUCKYEAH' ⍝ ≠\~(testVars ∊ 'AEIOU') ⍝ (124 × 4)≠(+/124 124 124) ⍝ testVars ∊ '<>'
Add explanation of arguments in AppleScript scripts
on run argv tell application "iTunes" set p to first item of argv set a to (p as POSIX file) add a to playlist (second item of argv) end tell end run
on run argv set posixFile to first item of argv set playlistName to second item of argv tell application "iTunes" set p to posixFile set a to (p as POSIX file) add a to playlist playlistName end tell end run
Change session name to 'rspec'
-- execute_iterm.scpt -- last change: 19 Jan 2013 --- -- this script require an argument that represent the command to execute on run argv set command to (item 1 of argv) tell application "iTerm" try set mysession to current session of current terminal on error set myterm to (make new terminal) tell myterm launch session "Default" set mysession to current session end tell end try -- execute the command tell mysession write text command end tell end tell end run
-- execute_iterm.scpt -- last change: 19 Jan 2013 --- -- this script require an argument that represent the command to execute on run argv set command to (item 1 of argv) tell application "iTerm" try set mysession to current session of current terminal on error set myterm to (make new terminal) tell myterm launch session "rspec" set mysession to current session end tell end try -- execute the command tell mysession write text command end tell end tell end run
Fix get state for locales that have commas as decimal delimiters
tell application "Spotify" set cstate to "{" set cstate to cstate & "\"track_id\": \"" & current track's id & "\"" set cstate to cstate & ",\"volume\": " & sound volume set cstate to cstate & ",\"position\": " & player position set cstate to cstate & ",\"state\": \"" & player state & "\"" set cstate to cstate & "}" return cstate end tell
on replace_chars(this_text, search_string, replacement_string) set AppleScript's text item delimiters to the search_string set the item_list to every text item of this_text set AppleScript's text item delimiters to the replacement_string set this_text to the item_list as string set AppleScript's text item delimiters to "" return this_text end replace_chars tell application "Spotify" -- force string coercion and locale format set position to "" & player position set cstate to "{" set cstate to cstate & "\"track_id\": \"" & current track's id & "\"" set cstate to cstate & ",\"volume\": " & sound volume -- replace , with . when locale has , as decimal delimiter set cstate to cstate & ",\"position\": " & my replace_chars(position, ",", ".") set cstate to cstate & ",\"state\": \"" & player state & "\"" set cstate to cstate & "}" return cstate end tell
Simplify filterer code so it actually works.
on run tell application "BibDesk" try set alertResult to display alert ("Really remove all linked files and private notes from " & name of first document as string) & "?" buttons {"Cancel", "OK"} default button "OK" cancel button "Cancel" as warning if button returned of alertResult is "OK" then save first document in "Filtered " & (name of first document as string) & ".bib" repeat with thePub in first document's publications set thePub's note to my splitNote(thePub's note) repeat with theFile in thePub's linked files remove theFile from thePub end repeat end repeat save first document end if on error -128 display dialog "User cancelled." end try end tell end run to splitNote(theNoteText) try set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to {"---"} set theParts to every text item of theNoteText if length of theParts is greater than 1 then set outText to text 2 through end of last item of theParts else set outText to "" end if set AppleScript's text item delimiters to oldDelims on error set AppleScript's text item delimiters to oldDelims end try return outText end splitNote
on run tell application "BibDesk" try set alertResult to display alert ("Really remove all linked files and private notes from " & name of first document as string) & "?" buttons {"Cancel", "OK"} default button "OK" cancel button "Cancel" as warning if button returned of alertResult is "OK" then set theDocument to first document save theDocument set theFile to (theDocument's file) as alias tell application "Finder" set theContainer to (container of theFile) as alias set newFile to make new file with properties {container:theFile, name:"Filtered " & ((name of theDocument) as string)} end tell return save first document in (newFile as file) repeat with thePub in first document's publications set thePub's note to my splitNote(thePub's note) repeat with theFile in thePub's linked files remove theFile from thePub end repeat end repeat save first document end if on error -128 display dialog "User cancelled." end try end tell end run to splitNote(theNoteText) try set oldDelims to AppleScript's text item delimiters set AppleScript's text item delimiters to {"---"} set theParts to every text item of theNoteText if length of theParts is greater than 1 then set outText to (text 2 through end) of last item of theParts else set outText to "" end if set AppleScript's text item delimiters to oldDelims on error set AppleScript's text item delimiters to oldDelims end try return outText end splitNote
Change script for rspec command only
-- execute_iterm.scpt -- last change: 19 Jan 2013 --- -- this script require an argument that represent the command to execute on run argv set command to (item 1 of argv) tell application "iTerm" try set mysession to current session of current terminal on error set myterm to (make new terminal) tell myterm launch session "rspec" set mysession to current session end tell end try -- execute the command tell mysession write text command end tell end tell end run
-- execute_iterm.scpt -- last change: 19 Jan 2013 --- -- this script require an argument that represent the command to execute on run argv set command to (item 1 of argv) tell application "iTerm" repeat with _terminal in terminals repeat with _session in (every session of _terminal whose name contains "rspec") tell the _session write text command end tell end repeat end repeat end tell end run
Delete Alfred Play Song playlist when clearing cache
-- clears workflow cache, including album artwork and compiled scripts -- on loadConfig() return (load script POSIX file (do shell script "./resources/compile-config.sh")) end loadConfig on run query set config to loadConfig() try tell application "Finder" delete folder (workflowCacheFolder of config) end tell end try end run
-- clears workflow cache, including album artwork and compiled scripts -- on loadConfig() return (load script POSIX file (do shell script "./resources/compile-config.sh")) end loadConfig on run query set config to loadConfig() try tell application "Finder" delete folder (workflowCacheFolder of config) end tell tell application "Music" delete user playlist (workflowPlaylistName of config) end tell end try end run
Set current song to empty string if nothing is playing
set theFolder to POSIX path of ((the path to me as text) & "::") set Controller to run script ("script s" & return & (read alias (POSIX file (theFolder & "/lib/controller.scpt")) as «class utf8») & return & "end script " & return & "return s") set currentTrack to Controller's getCurrentSong() set output to item 1 of currentTrack & " - " & item 2 of currentTrack do shell script "echo " & quoted form of output
set theFolder to POSIX path of ((the path to me as text) & "::") set Controller to run script ("script s" & return & (read alias (POSIX file (theFolder & "/lib/controller.scpt")) as «class utf8») & return & "end script " & return & "return s") set currentTrack to Controller's getCurrentSong() try set output to quoted form of (item 1 of currentTrack & " - " & item 2 of currentTrack) on error set output to "" end try do shell script "echo " & output
Update headphone connect script for Big Sur
activate application "SystemUIServer" tell application "System Events" tell process "SystemUIServer" set btMenu to (menu bar item 1 of menu bar 1 whose description contains "bluetooth") tell btMenu click try tell (menu item "Rosco's Headphones" of menu 1) click if exists menu item "Connect" of menu 1 then click menu item "Connect" of menu 1 return "Connecting..." else if exists menu item "Disconnect" of menu 1 then click menu item "Disconnect" of menu 1 return "Disconnecting..." end if end tell end try end tell end tell key code 53 return "Device not found or Bluetooth turned off" end tell
-- Source: https://www.reddit.com/r/MacOS/comments/i4czgu/big_sur_airpods_script/gck3gz3 -- Works on macOS 11 Big Sur use framework "IOBluetooth" use scripting additions set DeviceName to "Rosco's Headphones" on getFirstMatchingDevice(deviceName) repeat with device in (current application's IOBluetoothDevice's pairedDevices() as list) if (device's nameOrAddress as string) contains deviceName then return device end repeat end getFirstMatchingDevice on toggleDevice(device) if not (device's isConnected as boolean) then device's openConnection() return "Connecting " & (device's nameOrAddress as string) else device's closeConnection() return "Disconnecting " & (device's nameOrAddress as string) end if end toggleDevice return toggleDevice(getFirstMatchingDevice(DeviceName))
Fix bug where Apple Music playlists could not be played
-- plays selected song or playlist directly (the Play Song v1 behavior) -- for songs, this behavior continues playing music after the song finishes on loadConfig() return (load script POSIX file (do shell script "./resources/compile-config.sh")) end loadConfig on run query set config to loadConfig() set typeAndId to parseResultQuery(query as text) of config set theType to type of typeAndId set theId to id of typeAndId tell application "iTunes" if theType is "song" then set theSong to getSong(theId) of config play theSong else if theType is "playlist" then set thePlaylist to getPlaylist(theId) of config play thePlaylist else log "Unknown type: " & theType end if end tell end run
-- plays selected song or playlist directly (the Play Song v1 behavior) -- for songs, this behavior continues playing music after the song finishes on loadConfig() return (load script POSIX file (do shell script "./resources/compile-config.sh")) end loadConfig on run query set config to loadConfig() set typeAndId to parseResultQuery(query as text) of config set theType to type of typeAndId set theId to id of typeAndId tell application "iTunes" if theType is "song" then set theSong to getSong(theId) of config play theSong else if theType ends with "playlist" then set thePlaylist to getPlaylist(theId) of config play thePlaylist else log "Unknown type: " & theType end if end tell end run
Make Mac disk image packager set application icon location more reliably.
-- This Applescript changes all of the icon labels on the disk image to -- a different color. -- Usage: osascript set-labels.applescript <volume-name> -- where <volume-name> is the volume name of the disk image. on run argv tell application "Finder" set diskname to item 1 of argv set file_list to every file in disk diskname repeat with i in file_list if the name of i is "Applications" then set the position of i to {368, 135} else if the name of i ends with ".app" then set the position of i to {134, 135} end if -- The magic happens here: This will set the label color of -- the file icon. Change the 7 to change the color: 0 is no -- label, then red, orange, yellow, green, blue, purple, or gray. set the label index of i to 7 end repeat end tell end run
-- This Applescript changes all of the icon labels on the disk image to -- a different color. -- Usage: osascript set-labels.applescript <volume-name> -- where <volume-name> is the volume name of the disk image. on run argv tell application "Finder" set diskname to item 1 of argv tell disk diskname set file_list to every file repeat with i in file_list if the name of i is "Applications" then set the position of i to {368, 135} else if the name of i ends with ".app" then set the position of i to {134, 135} end if -- The magic happens here: This will set the label color of -- the file icon. Change the 7 to change the color: 0 is no -- label, then red, orange, yellow, green, blue, purple, or gray. set the label index of i to 7 end repeat update without registering applications delay 4 end tell end tell end run
Add practice text area to lookup dialog
on run {input} try do shell script "$HOME/Dropbox\\ \\(Personal\\)/projects/plover-tools/plover-dictionary-lookup/dictlook -x " & "\"" & input & "\"" display dialog result buttons {"OK"} default button 1 on error display dialog "No such luck." buttons {"OK"} default button 1 beep end try end run
on run {input} try do shell script "$HOME/Dropbox\\ \\(Personal\\)/projects/plover-tools/plover-dictionary-lookup/dictlook -x " & "\"" & input & "\"" display dialog result default answer "" buttons {"OK"} default button 1 on error display dialog "No such luck." buttons {"OK"} default button 1 beep end try end run
Remove git pull from closing Vagrant
set close_vagrant to "z puppet; git pull; vagrant halt -f;" -- close vagrant tell application "iTerm" activate set myterm to (make new terminal) tell myterm launch session "Default" set mysession to current session end tell tell mysession write text close_vagrant end tell delay 5 end tell -- quit iTerm ignoring application responses tell application "iTerm" quit end tell end ignoring delay 2 tell application "System Events" to keystroke return
set close_vagrant to "z puppet; vagrant halt -f;" -- close vagrant tell application "iTerm" activate set myterm to (make new terminal) tell myterm launch session "Default" set mysession to current session end tell tell mysession write text close_vagrant end tell delay 5 end tell -- quit iTerm ignoring application responses tell application "iTerm" quit end tell end ignoring delay 2 tell application "System Events" to keystroke return
Change tabs to open at work
set myTabs to {"http://app.getsentry.com/", "http://app.ubervu.com/", "http://github.com/uberVU/thehole/issues/assigned/palcu?direction=desc&labels=&milestone=&page=1&sort=updated&state=open/", "https://mail.google.com/mail/u/1/?shva=1#inbox", "https://drive.google.com/a/ubervu.com/#folders/0BzycGIkC5P50TXBlcTZoRXZ5VUE"} tell application "Google Chrome" activate repeat with i in myTabs open location i end repeat end tell
set myTabs to {"http://app.getsentry.com/", "http://github.com/uberVU/thehole/issues/assigned/palcu?direction=desc&labels=&milestone=&page=1&sort=updated&state=open/", "https://mail.google.com/mail/u/1/?shva=1#inbox", "https://drive.google.com/a/hootsuite.com/#folders/0BwuFsHJDxJWPYmxXQ1VQVlN6T2M"} tell application "Google Chrome" activate repeat with i in myTabs open location i end repeat end tell
Update the watch workers applescript to watch the celerybeat log file.
set broker to "h8.opera.com" set workers to {"h6.opera.com", "h8.opera.com", "h9.opera.com", "h10.opera.com"} tell application "iTerm" activate set myterm to (make new terminal) tell myterm set number of columns to 80 set number of rows to 50 repeat with workerhost in workers set worker to (make new session at the end of sessions) tell worker set name to workerhost set foreground color to "white" set background color to "black" set transparency to 0.1 exec command "/bin/sh -i" write text "ssh root@" & workerhost & " 'tail -f /var/log/celeryd.log'" end tell end repeat set rabbit to (make new session at the end of sessions) tell rabbit set name to "rabbit.log" set foreground color to "white" set background color to "black" set transparency to 0.1 exec command "/bin/sh -i" write text "ssh root@" & broker & " 'tail -f /var/log/rabbitmq/rabbit.log'" end tell tell the first session activate end tell end tell end tell
set broker to "h8.opera.com" set workers to {"h6.opera.com", "h8.opera.com", "h9.opera.com", "h10.opera.com"} set clock to "h6.opera.com" tell application "iTerm" activate set myterm to (make new terminal) tell myterm set number of columns to 80 set number of rows to 50 repeat with workerhost in workers set worker to (make new session at the end of sessions) tell worker set name to workerhost set foreground color to "white" set background color to "black" set transparency to 0.1 exec command "/bin/sh -i" write text "ssh root@" & workerhost & " 'tail -f /var/log/celeryd.log'" end tell end repeat set celerybeat to (make new session at the end of sessions) tell celerybeat set name to "celerybeat.log" set foreground color to "white" set background color to "black" set transparency to 0.1 exec command "/bin/sh -i" write text "ssh root@" & clock & " 'tail -f /var/log/celerybeat.log'" end tell set rabbit to (make new session at the end of sessions) tell rabbit set name to "rabbit.log" set foreground color to "white" set background color to "black" set transparency to 0.1 exec command "/bin/sh -i" write text "ssh root@" & broker & " 'tail -f /var/log/rabbitmq/rabbit.log'" end tell tell the first session activate end tell end tell end tell
Work around an issue with iTunes 9 that causes it to delay a connection to remote speakers
(* Script object to make calling a defined function easier while in the iTunes and System Events name space. *) script remoteSpeakerFinder -- Given a list of buttons, find the remote speakers button -- by finding the first button with a name that isn't in a -- rejection list. on findCorrectButton (in_buttons) set buttons_to_skip to {"Burn Disc"} repeat with a_button in in_buttons try -- some buttons don't have names set the_name to name of a_button if buttons_to_skip does not contain {the_name} then return the_name end if end try end repeat return 16 -- default response end findCorrectButton end script (* Tell iTunes to use the "Mobile" set of remote speakers. *) tell application "System Events" tell process "iTunes" set the_buttons to (get buttons of window 1) set the_speaker_button to (remoteSpeakerFinder's findCorrectButton(the_buttons)) -- Switch to the speakers in my bedroom set frontmost to true click button the_speaker_button of window 1 key code 115 -- Home Key (first speaker in list) key code 125 -- Down Arrow key code 125 -- Down Arrow key code 36 -- Return Key end tell end tell
(* Script object to make calling a defined function easier while in the iTunes and System Events name space. *) script remoteSpeakerFinder -- Given a list of buttons, find the remote speakers button -- by finding the first button with a name that isn't in a -- rejection list. on findCorrectButton (in_buttons) set buttons_to_skip to {"Burn Disc"} repeat with a_button in in_buttons try -- some buttons don't have names set the_name to name of a_button if buttons_to_skip does not contain {the_name} then return the_name end if end try end repeat return 16 -- default response end findCorrectButton end script (* Tell iTunes to use the "Mobile" set of remote speakers. *) tell application "System Events" tell process "iTunes" set the_buttons to (get buttons of window 1) set the_speaker_button to (remoteSpeakerFinder's findCorrectButton(the_buttons)) -- Switch to the speakers in my bedroom set frontmost to true click button the_speaker_button of window 1 key code 115 -- Home Key (first speaker in list) key code 125 -- Down Arrow key code 125 -- Down Arrow key code 36 -- Return Key -- Wait for iTunes to connect to the speakers delay 5 end tell end tell
Update URLs that open at the office
set myTabs to {"http://app.getsentry.com/", "http://github.com/uberVU/thehole/issues/assigned/palcu?direction=desc&labels=&milestone=&page=1&sort=updated&state=open/", "https://mail.google.com/mail/u/1/?shva=1#inbox", "https://drive.google.com/a/hootsuite.com/#folders/0BwuFsHJDxJWPYmxXQ1VQVlN6T2M"} tell application "Google Chrome" activate repeat with i in myTabs open location i end repeat end tell
set myTabs to {"https://github.com/search?utf8=%E2%9C%93&q=assignee%3Apalcu+state%3Aopen&type=Issues&ref=searchresults", "https://mail.google.com/mail/u/1/?shva=1#inbox", "https://drive.google.com/a/hootsuite.com/#folders/0BwuFsHJDxJWPYmxXQ1VQVlN6T2M"} tell application "Google Chrome" activate repeat with i in myTabs open location i end repeat end tell
Update script to get ALL macros instead of just hotkeyed macros.
try get application id "com.stairways.keyboardmaestro.engine" on error err_msg number err_num return "Keyboard Maestro not found. First install it and then use this workflow." end try tell application id "com.stairways.keyboardmaestro.engine" gethotkeys with asstring end tell
try get application id "com.stairways.keyboardmaestro.engine" on error err_msg number err_num return "Keyboard Maestro not found. First install it and then use this workflow." end try tell application id "com.stairways.keyboardmaestro.engine" gethotkeys with asstring and getall end tell
Add update script to open vagrant applescript
set open_vagrant to "z puppet; vagrant up;" tell application "iTerm" activate try set mysession to current session of current terminal on error set myterm to (make new terminal) tell myterm launch session "Default" set mysession to current session end tell end try tell mysession write text open_vagrant end tell end tell
set open_vagrant to "z puppet; vagrant up;" set update_master to "/Users/alex/.homesick/repos/palcu/dotfiles/scripts/update_master.sh;" tell application "iTerm" activate try set mysession to current session of current terminal on error set myterm to (make new terminal) tell myterm launch session "Default" set mysession to current session end tell end try tell mysession write text update_master write text open_vagrant end tell end tell
Update GLOB to remove the cwd from each result
(seval '(require file/glob)) (def glob (pat) (each path (seval!glob pat #:capture-dotfiles? #t) (let path (seval!path->string path) (if (dir-exists path) (out (+ path "/")) (out path)))))
(seval '(require file/glob)) (seval '(xdef cwd cwd)) (def glob (pat (o root (cwd))) (each path (seval!glob pat #:capture-dotfiles? #t) (aand (seval!path->string path) (if (dir-exists it) (+ it "/") it) (if (seval!string-prefix? it root) (cut it (len root)) it) (out it))))
Disable atstrings when generating arcfn docs.
(system "rm -rf html") (ensure-dir "html") (load "template.arc") (runall) ;; fails with "Expected tests" error ;; (run "foundation-doc.tem") (system "cp foundation-doc.html html/") (system "rm -rf output") (ensure-dir "output") (system "cp docs/* html/* output/")
(declare 'atstrings nil) (system "rm -rf html") (ensure-dir "html") (load "template.arc") (runall) ;; fails with "Expected tests" error ;; (run "foundation-doc.tem") (system "cp foundation-doc.html html/") (system "rm -rf output") (ensure-dir "output") (system "cp docs/* html/* output/")
Use interrupt for timing the sample read
const int BUFFER_SIZE = 4; int m_buffer[BUFFER_SIZE]; int m_bufIndex = 0; void setup() { // put your setup code here, to run once: Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: int val = readValue(); //Serial.print("Voltage"); //Serial.print("\t"); Serial.println(val); delay(5); //we're interested in events that happen roughly within 15-20 ms } int readValue() { m_buffer[m_bufIndex] = analogRead(A0); m_bufIndex = (m_bufIndex + 1) % BUFFER_SIZE; //test if median is better than avg int sum = 0; for (int n = 0; n < BUFFER_SIZE; ++n) { sum += m_buffer[n]; } return sum / BUFFER_SIZE; }
const int BUFFER_SIZE = 8; int m_buffer[BUFFER_SIZE]; int m_bufIndex = 0; unsigned long m_timer = 0; int m_counter = 0; void setup() { // put your setup code here, to run once: Serial.begin(9600); m_timer = millis(); // Timer0 is already used for millis() - we'll just interrupt somewhere // in the middle and call the "Compare A" function below OCR0A = 0xAF; TIMSK0 |= _BV(OCIE0A); } // Interrupt is called once a millisecond (Timer0 frequency) SIGNAL(TIMER0_COMPA_vect) { int val = readValue(); //we're interested in events that happen roughly within 15-20 ms if (m_counter++ >= 4) { Serial.println(val); m_counter = 0; } } void loop() { } int readSample() { int value = m_buffer[m_bufIndex] = analogRead(A0); m_bufIndex = (m_bufIndex + 1) % BUFFER_SIZE; return value; } int readValue() { int value = readSample(); //TODO: test if median is better than avg int sum = 0; for (int n = 0; n < BUFFER_SIZE; ++n) { sum += m_buffer[n]; } return sum / BUFFER_SIZE; }
Change logic for serial commands
// Interduino is the physical manifestation of cigtee - an arduino sketch designed to take serial commands to make stuff happen IRL void setup() { Serial.begin(9600); pinMode(13, OUTPUT); } int pinState[6]; void loop() { if(Serial.available()){ int ledState = Serial.read(); if(ledState == 65){ digitalWrite(13, HIGH); } if(ledState == 90){ digitalWrite(13, LOW); } delay(2000); } }
// Interduino is the physical manifestation of cigtee - an arduino sketch designed to take serial commands to make stuff happen IRL void setup() { Serial.begin(9600); pinMode(13, OUTPUT); } int pinState[6]; void loop() { if(Serial.available()){ int ledState = Serial.read(); if(ledState == 65){ digitalWrite(13, HIGH); } // if(ledState == 90){ // digitalWrite(13, LOW); // } delay(2000); digitalWrite(13, LOW); } }
Test out some wave files
#include <WaveHC.h> #include <WaveUtil.h> SdReader card; // This object holds the information for the card FatVolume vol; // This holds the information for the partition on the card FatReader root; // This holds the information for the volumes root directory WaveHC wave; // This is the only wave (audio) object, since we will only play one at a time void setupSdReader(SdReader &card) { if (!card.init()) Serial.println("Card init failed"); card.partialBlockRead(true); // Optimization. Disable if having issues } void setupFatVolume(FatVolume &vol) { uint8_t slot; // There are 5 slots to look at. for (slot = 0; slot < 5; slot++) if (vol.init(card, slot)) break; if (slot == 5) Serial.println("No valid FAT partition"); } void setupFatReader(FatReader &root) { if (!root.openRoot(vol)) Serial.println("Can't open root dir"); } void setup() { Serial.begin(9600); setupSdReader(card); setupFatVolume(vol); setupFatReader(root); } void loop() { }
#include <WaveHC.h> #include <WaveUtil.h> String fileNames[4] = {"BUGS2.WAV", "DAFFY1.WAV", "BUGS1.WAV", "DAFFY2.WAV"}; SdReader card; // This object holds the information for the card FatVolume vol; // This holds the information for the partition on the card FatReader root; // This holds the information for the volumes root directory WaveHC wave; // This is the only wave (audio) object, since we will only play one at a time void setupSdReader(SdReader &card) { if (!card.init()) Serial.println("Card init failed"); card.partialBlockRead(true); // Optimization. Disable if having issues } void setupFatVolume(FatVolume &vol) { uint8_t slot; // There are 5 slots to look at. for (slot = 0; slot < 5; slot++) if (vol.init(card, slot)) break; if (slot == 5) Serial.println("No valid FAT partition"); } void setupFatReader(FatReader &root) { if (!root.openRoot(vol)) Serial.println("Can't open root dir"); } void setup() { Serial.begin(9600); setupSdReader(card); setupFatVolume(vol); setupFatReader(root); } void loop() { root.rewind(); FatReader file; for (int i = 0; i < 4; i++) { char fileName[fileNames[i].length() + 1]; fileNames[i].toCharArray(fileName, fileNames[i].length() + 1); file.open(root, fileName); wave.create(file); wave.play(); while (wave.isplaying) delay(100); } }
Move begin down in example
#include "ConfigManager.h" struct Config { char name[20]; bool enabled; int8 hour; char password[20]; } config; struct Metadata { int8 version; } meta; ConfigManager configManager; void createCustomRoute(ESP8266WebServer *server) { server->on("/custom", HTTPMethod::HTTP_GET, [server](){ server->send(200, "text/plain", "Hello, World!"); }); } void setup() { meta.version = 3; // Setup config manager configManager.setAPName("Demo"); configManager.setAPFilename("/index.html"); configManager.addParameter("name", config.name, 20); configManager.addParameter("enabled", &config.enabled); configManager.addParameter("hour", &config.hour); configManager.addParameter("password", config.password, 20, set); configManager.addParameter("version", &meta.version, get); configManager.begin(config); configManager.setAPICallback(createCustomRoute); // } void loop() { configManager.loop(); // Add your loop code here }
#include "ConfigManager.h" struct Config { char name[20]; bool enabled; int8 hour; char password[20]; } config; struct Metadata { int8 version; } meta; ConfigManager configManager; void createCustomRoute(ESP8266WebServer *server) { server->on("/custom", HTTPMethod::HTTP_GET, [server](){ server->send(200, "text/plain", "Hello, World!"); }); } void setup() { meta.version = 3; // Setup config manager configManager.setAPName("Demo"); configManager.setAPFilename("/index.html"); configManager.addParameter("name", config.name, 20); configManager.addParameter("enabled", &config.enabled); configManager.addParameter("hour", &config.hour); configManager.addParameter("password", config.password, 20, set); configManager.addParameter("version", &meta.version, get); configManager.setAPICallback(createCustomRoute); configManager.begin(config); // } void loop() { configManager.loop(); // Add your loop code here }
Add main func to stop build from breaking on akira
// Interduino is the physical manifestation of cigtee - an arduino sketch designed to take serial commands to make stuff happen IRL void setup() { Serial.begin(9600); pinMode(13, OUTPUT); } int pinState[6]; void loop() { if(Serial.available()){ int ledState = Serial.read(); if(ledState == 65){ digitalWrite(13, HIGH); } if(ledState == 90){ digitalWrite(13, LOW); } } }
// Interduino is the physical manifestation of cigtee - an arduino sketch designed to take serial commands to make stuff happen IRL void setup() { Serial.begin(9600); pinMode(13, OUTPUT); } int pinState[6]; void loop() { if(Serial.available()){ int ledState = Serial.read(); if(ledState == 65){ digitalWrite(13, HIGH); } if(ledState == 90){ digitalWrite(13, LOW); } } } int main() { setup(); while(true) { loop(); } return 0; }
Read detector value to A0
const int outPinLed = 2; const int inPinTrigger = 7; const int inPinDetector = 4; int triggerPressed = 0; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(outPinLed, OUTPUT); digitalWrite(outPinLed, LOW); pinMode(inPinTrigger, INPUT); pinMode(inPinDetector, INPUT); } void loop() { int triggerPrev = triggerPressed; triggerPressed = digitalRead(inPinTrigger); if (triggerPressed != triggerPrev) { Serial.print("Trigger state changed: "); Serial.println(triggerPressed); if (triggerPressed) { int detectorValue = digitalRead(inPinDetector); Serial.print("Detector: "); Serial.println(detectorValue); } } int ledState = triggerPressed ? HIGH : LOW; digitalWrite(outPinLed, ledState); }
const int outPinLed = 2; const int inPinTrigger = 7; const int inPinDetector = A0; int triggerPressed = 0; int detectorValue = 1023; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(outPinLed, OUTPUT); digitalWrite(outPinLed, LOW); pinMode(inPinTrigger, INPUT_PULLUP); } void loop() { int triggerPrev = triggerPressed; triggerPressed = digitalRead(inPinTrigger); if (triggerPressed != triggerPrev) { Serial.print("Trigger state changed: "); Serial.println(triggerPressed); /*if (triggerPressed) { int detectorValue = analogRead(inPinDetector); Serial.print("Detector: "); Serial.println(detectorValue); }*/ } if (triggerPressed) { int detectorPrev = detectorValue; detectorValue = analogRead(inPinDetector); Serial.print(" Detector: "); Serial.print(detectorValue); Serial.print(" diff="); Serial.println(detectorValue - detectorPrev); } int ledState = triggerPressed ? HIGH : LOW; digitalWrite(outPinLed, ledState); }
Add first LDR sensor to sketch
/* Arduino based self regulating kitchen garden */ // light related setup int lightSensorPin = 3; // Set to whereever light sensor is connected int lampRelay = 4; // Set to whereever relay for lamp is connected // activity led setup int ledPin = 13; // this is just for checking activity // Initialize settings void setup() { // Initialize output pins. pinMode(ledPin, OUTPUT); // Initialize input pins. pinMode(lightSensorPin, INPUT); } // Main loop void loop() { // Read sensor values analogRead(lightSensorPin); }
Update the authentication example using an MQTT::Connect object directly
/* Basic MQTT example with Authentication - connects to an MQTT server, providing username and password - publishes "hello world" to the topic "outTopic" - subscribes to the topic "inTopic" */ #include <ESP8266WiFi.h> #include <PubSubClient.h> const char *ssid = "xxxxxxxx"; // cannot be longer than 32 characters! const char *pass = "yyyyyyyy"; // // Update these with values suitable for your network. IPAddress server(172, 16, 0, 2); void callback(String topic, byte* payload, unsigned int length) { // handle message arrived } PubSubClient client(server); void setup() { // Setup console Serial.begin(115200); delay(10); Serial.println(); Serial.println(); client.set_callback(callback); WiFi.begin(ssid, pass); int retries = 0; while ((WiFi.status() != WL_CONNECTED) && (retries < 10)) { retries++; delay(500); Serial.print("."); } if (WiFi.status() == WL_CONNECTED) { Serial.println(""); Serial.println("WiFi connected"); } client.set_auth("testeruser", "testpass"); if (client.connect("arduinoClient")) { client.publish("outTopic","hello world"); client.subscribe("inTopic"); } } void loop() { client.loop(); }
/* Basic MQTT example with Authentication - connects to an MQTT server, providing username and password - publishes "hello world" to the topic "outTopic" - subscribes to the topic "inTopic" */ #include <ESP8266WiFi.h> #include <PubSubClient.h> const char *ssid = "xxxxxxxx"; // cannot be longer than 32 characters! const char *pass = "yyyyyyyy"; // // Update these with values suitable for your network. IPAddress server(172, 16, 0, 2); void callback(String topic, byte* payload, unsigned int length) { // handle message arrived } PubSubClient client(server); void setup() { // Setup console Serial.begin(115200); delay(10); Serial.println(); Serial.println(); client.set_callback(callback); WiFi.begin(ssid, pass); int retries = 0; while ((WiFi.status() != WL_CONNECTED) && (retries < 10)) { retries++; delay(500); Serial.print("."); } if (WiFi.status() == WL_CONNECTED) { Serial.println(""); Serial.println("WiFi connected"); } if (client.connect(MQTT::Connect("arduinoClient") .set_auth("testeruser", "testpass"))) { client.publish("outTopic","hello world"); client.subscribe("inTopic"); } } void loop() { client.loop(); }
Use assert macro for print out system info
# 2 "TestSystemInfo.ino" #include <Arduino.h> #include <Arduino_FreeRTOS.h> #include <StandardCplusplus.h> #include <RabirdToolkit.h> #include <RTest.h> #include <RRawPointer.h> #include <RSharedPointer.h> #include <RFormatter.h> RTEST(TestSystemInfo) { RFormatter formatter(manager()->printer()); formatter("Size of int : %s").arg(sizeof(int)); formatter("Size of uintptr_t : %s").arg(sizeof(uintptr_t)); formatter("Size of rsize : %s").arg(sizeof(rsize)); formatter("Size of rnumber : %s").arg(sizeof(rnumber)); formatter("Size of ruint : %s").arg(sizeof(ruint)); }; void setup() { Serial.begin(9600); while(!Serial) // for the Arduino Leonardo/Micro only { } RTestApplication testApp; testApp.addTest(&RTEST_INSTANCE(TestSystemInfo)); testApp.run(); } void loop() { }
# 2 "TestSystemInfo.ino" #include <Arduino.h> #include <Arduino_FreeRTOS.h> #include <StandardCplusplus.h> #include <RabirdToolkit.h> #include <RTest.h> RTEST(TestSystemInfo) { RASSERT_MORE(sizeof(int), 0); RASSERT_MORE(sizeof(uintptr_t), 0); RASSERT_MORE(sizeof(rsize), 0); RASSERT_MORE(sizeof(rnumber), 0); RASSERT_MORE(sizeof(ruint), 0); }; void setup() { Serial.begin(9600); while(!Serial) // for the Arduino Leonardo/Micro only { } RTestApplication testApp; testApp.addTest(&RTEST_INSTANCE(TestSystemInfo)); testApp.run(); } void loop() { }
Modify samples to use Arduboy2 library
#include <Arduboy.h> #include <ArdVoice.h> #include "voices.h" Arduboy arduboy; ArdVoice ardvoice; void setup() { arduboy.begin(); arduboy.setFrameRate(30); ardvoice.playVoice(merry_q6); } void loop() { if (!(arduboy.nextFrame())) return; if (arduboy.pressed(B_BUTTON)){ ardvoice.playVoice(merry_q6); } if (arduboy.pressed(A_BUTTON)){ ardvoice.stopVoice(); } }
#include <Arduboy2.h> #include <ArdVoice.h> #include "voices.h" Arduboy2 arduboy; ArdVoice ardvoice; void setup() { arduboy.begin(); arduboy.setFrameRate(30); ardvoice.playVoice(merry_q6); } void loop() { if (!(arduboy.nextFrame())) return; if (arduboy.pressed(B_BUTTON)){ ardvoice.playVoice(merry_q6); } if (arduboy.pressed(A_BUTTON)){ ardvoice.stopVoice(); } }
Comment out power pins in ADXL example code.
int vinpin = A0; int voutpin = A1; int gndpin = A2; int zpin = A3; int ypin = A4; int xpin = A5; void setup() { Serial.begin(9600); pinMode(vinpin, OUTPUT); digitalWrite(vinpin, HIGH); pinMode(gndpin, OUTPUT); digitalWrite(gndpin, LOW); pinMode(voutpin, INPUT); pinMode(xpin, INPUT); pinMode(ypin, INPUT); pinMode(zpin, INPUT); } void loop() { Serial.print(analogRead(xpin)); Serial.print("\t"); Serial.print(analogRead(ypin)); Serial.print("\t"); Serial.print(analogRead(zpin)); Serial.println(); }
int zpin = A3; int ypin = A4; int xpin = A5; // Uncomment the following lines if you're using an ADXL335 on an // Adafruit breakout board (https://www.adafruit.com/products/163) // and want to plug it directly into (and power it from) the analog // input pins of your Arduino board. //int vinpin = A0; //int voutpin = A1; //int gndpin = A2; void setup() { Serial.begin(9600); pinMode(vinpin, OUTPUT); digitalWrite(vinpin, HIGH); pinMode(gndpin, OUTPUT); digitalWrite(gndpin, LOW); pinMode(voutpin, INPUT); pinMode(xpin, INPUT); pinMode(ypin, INPUT); pinMode(zpin, INPUT); } void loop() { Serial.print(analogRead(xpin)); Serial.print("\t"); Serial.print(analogRead(ypin)); Serial.print("\t"); Serial.print(analogRead(zpin)); Serial.println(); }
Update lcd to display and add loop functionality
#include "display.h" #include "sensor.h" #include <LiquidCrystal.h> // Arduino LCD library #include <Arduino.h> // enables use of byte pics void setup() { LCD::setup(); Sensor::setup(); } void loop() { int temp = Sensor::readTemp(); LCD::displayTemp(temp); delay(5000); LCD::clearScreen(); }
#include "display.h" #include "sensor.h" #include <LiquidCrystal.h> // Arduino LCD library #include <Arduino.h> // enables use of byte pics void setup() { Display::setup(); Sensor::setup(); } void loop() { int temp = Sensor::readTemp(); int hum = Sensor::readHum(); Display::displayTemp(temp); Display::displayHum(hum); delay(3000); }
Remove pre-filled DevAddr and Keys
#define DEBUG #include "TheThingsUno.h" const byte devAddr[4] = { 0x02, 0xDE, 0xAE, 0x00 }; const byte appSKey[16] = { 0x0D, 0x0E, 0x0A, 0x0D, 0x0B, 0x0E, 0x0E, 0x0F, 0x0C, 0x0A, 0x0F, 0x0E, 0x0B, 0x0A, 0x0B, 0x0E }; const byte nwkSKey[16] = { 0x0D, 0x0E, 0x0A, 0x0D, 0x0B, 0x0E, 0x0E, 0x0F, 0x0C, 0x0A, 0x0F, 0x0E, 0x0B, 0x0A, 0x0B, 0x0E }; #define debugSerial Serial #define loraSerial Serial1 // These are the input pins of your sensors #define TEMPSENSOR 0 #define SOILSENSOR 1 TheThingsUno ttu; void setup() { debugSerial.begin(115200); loraSerial.begin(57600); ttu.init(loraSerial, debugSerial); ttu.reset(); ttu.personalize(devAddr, nwkSKey, appSKey); #ifdef DEBUG ttu.debugStatus(); #endif Serial.println("Setup for The Things Network."); } void loop() { while (debugSerial.available()) loraSerial.write((char)debugSerial.read()); while (loraSerial.available()) debugSerial.write((char)loraSerial.read()); delay(1); }
#define DEBUG #include "TheThingsUno.h" const byte devAddr[4] = { /* copy DevAddr here */ }; const byte appSKey[16] = { /* copy AppSKey here */ }; const byte nwkSKey[16] = { /* copy NwkSKey here */ }; #define debugSerial Serial #define loraSerial Serial1 // These are the input pins of your sensors #define TEMPSENSOR 0 #define SOILSENSOR 1 TheThingsUno ttu; void setup() { debugSerial.begin(115200); loraSerial.begin(57600); ttu.init(loraSerial, debugSerial); ttu.reset(); ttu.personalize(devAddr, nwkSKey, appSKey); #ifdef DEBUG ttu.debugStatus(); #endif Serial.println("Setup for The Things Network."); } void loop() { while (debugSerial.available()) loraSerial.write((char)debugSerial.read()); while (loraSerial.available()) debugSerial.write((char)loraSerial.read()); delay(1); }
Fix bug in sram size
/* TestSuite sketch Use this sketch when running the Liberty Arduino Feature test suite. */ #include <EEPROM.h> #include <Liberty.h> Liberty liberty("TestNode"); boolean ns = false; int nc = 0; unsigned long ln; byte bs[20]; void setup() { liberty.sram(sramBytes, 20); liberty.invocable("foo", &foo); liberty.invocable("bar", &bar); liberty.invocable("qaz", &qaz); liberty.invocable("times", &times); liberty.invocable("start", &nstart); liberty.invocable("stop", &nstop); liberty.begin(); } void loop() { liberty.update(); if (ns) { unsigned long x = millis(); if (x - ln > 200) { ln = x; nc++; liberty.notify("testN1", nc); } } } int foo() { return bs[0]; } int bar() { return 42; } int qaz(int x) { return x * 4; } int times(int x, int y) { return x * y; } int nstart() { ns = true; nc = 0; ln = millis(); } int nstop() { ns = false; return nc; }
/* TestSuite sketch Use this sketch when running the Liberty Arduino Feature test suite. */ #include <EEPROM.h> #include <Liberty.h> Liberty liberty("TestNode"); boolean ns = false; int nc = 0; unsigned long ln; byte bs[50]; void setup() { liberty.sram(bs, 50); liberty.invocable("foo", &foo); liberty.invocable("bar", &bar); liberty.invocable("qaz", &qaz); liberty.invocable("times", &times); liberty.invocable("start", &nstart); liberty.invocable("stop", &nstop); liberty.begin(); } void loop() { liberty.update(); if (ns) { unsigned long x = millis(); if (x - ln > 200) { ln = x; nc++; liberty.notify("testN1", nc); } } } int foo() { return bs[0]; } int bar() { return 42; } int qaz(int x) { return x * 4; } int times(int x, int y) { return x * y; } int nstart() { ns = true; nc = 0; ln = millis(); } int nstop() { ns = false; return nc; }
Use TimerThree library to blink motor
// https://github.com/thomasfredericks/Metro-Arduino-Wiring #include <Metro.h> const int MOTORPIN = 2; Metro blink = Metro(400); bool isVibrationOn = false; bool isMotorOn = false; uint32_t now; void onMotor(void) { digitalWrite(MOTORPIN, HIGH); isMotorOn = true; } void offMotor(void) { digitalWrite(MOTORPIN, LOW); isMotorOn = false; } void beginVibration(void) { blink.reset(); isVibrationOn = true; } void endVibration(void) { offMotor(); isVibrationOn = false; } void vibrationLoop(void) { if (!isVibrationOn) { return; } if (blink.check()) { if (isMotorOn) { offMotor(); } else { onMotor(); } } } void parseMessage(char letter) { switch (letter) { case 'v': beginVibration(); break; case 'V': endVibration(); break; default: break; } } void setup() { Serial.begin(115200); Mouse.begin(); pinMode(MOTORPIN, OUTPUT); } static void mouseLoop() { // move mouse to avoid screen saver static uint32_t mprevms = 0; const uint32_t PCLOCKMS = 540000; // 9 [min] if (now - mprevms > PCLOCKMS) { mprevms = now; Mouse.move(1, 0, 0); //Serial.write("M"); } } void loop() { now = millis(); vibrationLoop(); mouseLoop(); while (Serial.available()) { char letter = Serial.read(); parseMessage(letter); } }
// https://www.pjrc.com/teensy/td_libs_TimerOne.html #include <TimerThree.h> const int MOTORPIN = 5; void parseMessage(int letter) { switch (letter) { case 'v': Timer3.pwm(MOTORPIN, 512); break; case 'V': Timer3.pwm(MOTORPIN, 0); break; default: break; } } void setup() { Serial.begin(115200); Mouse.begin(); Timer3.initialize(400000); } void loop() { while (Serial.available()) { char letter = Serial.read(); parseMessage(letter); } }
Fix variable name bug in Arduino code
int incomingByte = 0; // for incoming serial data int relay1 = 4; int relay2 = 5; boolean state1 = false; boolean state2 = false; void setup() { Serial.begin(9600); pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); } void loop() { if (Serial.available() > 0) { incomingByte = Serial.read(); if (incomingByte == '1') { Serial.println("Toggling light 1"); if (state1 == false) { state1 = true; } else { state1 = false; } digitalWrite(led1, state1); } else if (incomingByte == '2') { Serial.println("Toggling light 2"); if (state2 == false){ state2 = true; } else { state2 = false; } digitalWrite(led2, state2); } } }
int incomingByte = 0; // for incoming serial data int relay1 = 4; int relay2 = 5; boolean state1 = false; boolean state2 = false; void setup() { Serial.begin(9600); pinMode(relay1, OUTPUT); pinMode(relay2, OUTPUT); } void loop() { if (Serial.available() > 0) { incomingByte = Serial.read(); if (incomingByte == '1') { Serial.println("Toggling light 1"); if (state1 == false) { state1 = true; } else { state1 = false; } digitalWrite(relay1, state1); } else if (incomingByte == '2') { Serial.println("Toggling light 2"); if (state2 == false){ state2 = true; } else { state2 = false; } digitalWrite(relay2, state2); } } }
Switch to Adafruit's BPM085 library.
/** * Wrapper for a thermometer. * * In this case it's a BMP085 barometric sensor, because that's what I had laying around. */ #include <Wire.h> #include <I2Cdev.h> #include <BMP085.h> BMP085 barometer; boolean hasThermometer; boolean initThermometer () { Serial.print(F("Setting up BMP085 for temperature...")); Wire.begin(); barometer.initialize(); if (barometer.testConnection()) { // request temperature barometer.setControl(BMP085_MODE_TEMPERATURE); // wait appropriate time for conversion (4.5ms delay) int32_t lastMicros = micros(); while (micros() - lastMicros < barometer.getMeasureDelayMicroseconds()); Serial.println(F(" done.")); hasThermometer = true; } else { Serial.println(F(" error.")); hasThermometer = false; } return hasThermometer; } float getTemperature () { return (hasThermometer) ? barometer.getTemperatureF() : 0.0; }
/** * Wrapper for a thermometer. * * In this case it's a BMP085 barometric sensor, because that's what I had laying around. */ #include <Wire.h> #include <Adafruit_BMP085.h> Adafruit_BMP085 barometer; boolean hasThermometer; boolean initThermometer () { Serial.print(F("Setting up BMP085 for temperature...")); if (barometer.begin()) { Serial.println(F(" done.")); hasThermometer = true; } else { Serial.println(F(" error.")); hasThermometer = false; } return hasThermometer; } float getTemperature () { return (hasThermometer) ? barometer.readTemperature() * 9 / 5 + 32 : 0.0; }
Implement initial setup for Wave Shield
void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: }
#include <WaveHC.h> #include <WaveUtil.h> SdReader card; // This object holds the information for the card FatVolume vol; // This holds the information for the partition on the card FatReader root; // This holds the information for the volumes root directory WaveHC wave; // This is the only wave (audio) object, since we will only play one at a time void setupSdReader(SdReader &card) { if (!card.init()) Serial.println("Card init failed"); card.partialBlockRead(true); // Optimization. Disable if having issues } void setupFatVolume(FatVolume &vol) { uint8_t slot; // There are 5 slots to look at. for (slot = 0; slot < 5; slot++) if (vol.init(card, slot)) break; if (slot == 5) Serial.println("No valid FAT partition"); } void setupFatReader(FatReader &root) { if (!root.openRoot(vol)) Serial.println("Can't open root dir"); } void setup() { Serial.begin(9600); setupSdReader(card); setupFatVolume(vol); setupFatReader(root); } void loop() { }
Add setDeviceName for ESP32 BLE
/************************************************************* Download latest Blynk library here: https://github.com/blynkkk/blynk-library/releases/latest Blynk is a platform with iOS and Android apps to control Arduino, Raspberry Pi and the likes over the Internet. You can easily build graphic interfaces for all your projects by simply dragging and dropping widgets. Downloads, docs, tutorials: http://www.blynk.cc Sketch generator: http://examples.blynk.cc Blynk community: http://community.blynk.cc Social networks: http://www.fb.com/blynkapp http://twitter.com/blynk_app Blynk library is licensed under MIT license This example code is in public domain. ************************************************************* This example shows how to use ESP32 BLE to connect your project to Blynk. Warning: Bluetooth support is in beta! *************************************************************/ /* Comment this out to disable prints and save space */ #define BLYNK_PRINT Serial #define BLYNK_USE_DIRECT_CONNECT #include <BlynkSimpleEsp32_BLE.h> #include <BLEDevice.h> #include <BLEServer.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; void setup() { // Debug console Serial.begin(9600); Serial.println("Waiting for connections..."); Blynk.begin(auth); } void loop() { Blynk.run(); }
/************************************************************* Download latest Blynk library here: https://github.com/blynkkk/blynk-library/releases/latest Blynk is a platform with iOS and Android apps to control Arduino, Raspberry Pi and the likes over the Internet. You can easily build graphic interfaces for all your projects by simply dragging and dropping widgets. Downloads, docs, tutorials: http://www.blynk.cc Sketch generator: http://examples.blynk.cc Blynk community: http://community.blynk.cc Social networks: http://www.fb.com/blynkapp http://twitter.com/blynk_app Blynk library is licensed under MIT license This example code is in public domain. ************************************************************* This example shows how to use ESP32 BLE to connect your project to Blynk. Warning: Bluetooth support is in beta! *************************************************************/ /* Comment this out to disable prints and save space */ #define BLYNK_PRINT Serial #define BLYNK_USE_DIRECT_CONNECT #include <BlynkSimpleEsp32_BLE.h> #include <BLEDevice.h> #include <BLEServer.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; void setup() { // Debug console Serial.begin(9600); Serial.println("Waiting for connections..."); Blynk.setDeviceName("Blynk"); Blynk.begin(auth); } void loop() { Blynk.run(); }
Read data from serial port
const int PIN_DATA = 4; const int PIN_LATCH = 3; const int PIN_CLOCK = 2; byte arrivalStatus = 1; void setup() { pinMode(PIN_DATA, OUTPUT); pinMode(PIN_CLOCK, OUTPUT); pinMode(PIN_LATCH, OUTPUT); } void loop() { digitalWrite(PIN_LATCH, LOW); shiftOut(PIN_DATA, PIN_CLOCK, MSBFIRST, arrivalStatus); digitalWrite(PIN_LATCH, HIGH); simulate_motion(); } /** * Pretend Update arrivalStatus as if this * was a bus that is getting closer to the * desired stop */ void simulate_motion() { arrivalStatus <<= 1; if (!arrivalStatus) arrivalStatus = 1; delay(1000); }
const int PIN_DATA = 4; const int PIN_LATCH = 3; const int PIN_CLOCK = 2; void setup() { //Initialize Shift register pinMode(PIN_DATA, OUTPUT); pinMode(PIN_CLOCK, OUTPUT); pinMode(PIN_LATCH, OUTPUT); //Initialize Serial Port Serial.begin(9600); } void loop() { //Wait for a single byte while (Serial.available() < 1); byte arrivalStatus = Serial.read(); Serial.write(arrivalStatus); //Update LEDs digitalWrite(PIN_LATCH, LOW); shiftOut(PIN_DATA, PIN_CLOCK, MSBFIRST, arrivalStatus); digitalWrite(PIN_LATCH, HIGH); }
Update map and bit mask
const byte SCALE_VALUE[] = { 0b00000100, 0b00001100, 0b00011100, 0b00111100}; int senzor = A0; void setup() { Serial.begin(9600); pinMode(senzor, INPUT); // porty 2,3,4,5 jako vystup DDRD |= 0b00111100; } void loop() { int light = analogRead(senzor); Serial.println(light); int scale = map(light, 400, 800, 0, 3); Serial.println(scale); PORTD = 0b00000000; PORTD |= (0b00000100 << scale); // PORTD |= SCALE_VALUE[scale]; delay(200); }
const byte SCALE_VALUE[] = { 0b00000100, 0b00001100, 0b00011100, 0b00111100}; // fotorezistor - A1, termistor - A0 int senzor = A1; void setup() { Serial.begin(9600); pinMode(senzor, INPUT); // porty 2,3,4,5 jako vystup DDRD |= 0b00111100; } void loop() { int light = analogRead(senzor); Serial.println(light); int scale = map(light, 300, 1000, 0, 3); Serial.println(scale); PORTD &= !0b00111100; // nastaveni vychoziho stavu - zhasnuto PORTD |= (0b00000100 << scale); // PORTD |= SCALE_VALUE[scale]; delay(200); }
Change initial state of all pins to LOW for new Relay Module
void setup() { Serial.begin(9600); pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); pinMode(10, OUTPUT); pinMode(11, OUTPUT); pinMode(12, OUTPUT); pinMode(13, OUTPUT); for (int x = 2; x<=13; x++){ digitalWrite(x, HIGH); } } void loop() { char c; char l; int pin; int state; if (Serial.available()) { c = Serial.read(); if (c == 'O') { pin = Serial.parseInt(); l = Serial.read(); state = Serial.parseInt(); if (pin == 99) { for (int x = 2; x<=13; x++){ digitalWrite(x, state); } } else { digitalWrite(pin, state); } Serial.println('r'); } } }
void setup() { Serial.begin(9600); pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); pinMode(10, OUTPUT); pinMode(11, OUTPUT); pinMode(12, OUTPUT); pinMode(13, OUTPUT); for (int x = 2; x<=13; x++){ digitalWrite(x, LOW); } } void loop() { char c; char l; int pin; int state; if (Serial.available()) { c = Serial.read(); if (c == 'O') { pin = Serial.parseInt(); l = Serial.read(); state = Serial.parseInt(); if (pin == 99) { for (int x = 2; x<=13; x++){ digitalWrite(x, state); } } else { digitalWrite(pin, state); } Serial.println('r'); } } }
Add blank line for tuto sample.
#define LED 53 void setup() { pinMode(LED, OUTPUT); } void loop() { digitalWrite(LED, HIGH); delay(500); digitalWrite(LED, LOW); delay(500); }
#define LED 53 void setup() { pinMode(LED, OUTPUT); } void loop() { digitalWrite(LED, HIGH); delay(500); digitalWrite(LED, LOW); delay(500); }
Revert "make editor folding happy"
void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: }
void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: }
Add backsteer to drone radio drive
#include <MINDS-i-Drone.h> ServoGenerator::Servo drive, steer; void setup() { drive.attach(12 /* APM pin 1 */); steer.attach(11 /* APM pin 2 */); ServoGenerator::begin(); //set the initial throttle/direction for the ESC/servo drive.write(90); steer.write(90); APMRadio::setup(); Serial.begin(9600); //delay 2 seconds for arming delay(2000); } void loop() { static uint32_t timer = micros(); uint32_t dt = timer+micros(); timer = -micros(); int driveSig = APMRadio::get(0); int steerSig = APMRadio::get(1); Serial.print(dt); Serial.print(" "); Serial.print(driveSig); Serial.print(" "); Serial.print(steerSig); Serial.println(); drive.write( driveSig ); steer.write( steerSig ); }
#include <MINDS-i-Drone.h> ServoGenerator::Servo drive, steer, backsteer; void setup() { drive.attach(12 /* APM pin 1 */); steer.attach(11 /* APM pin 2 */); backsteer.attach(8 /* APM pin 3 */); ServoGenerator::begin(); //set the initial throttle/direction for the ESC/servo drive.write(90); steer.write(90); backsteer.write(90); APMRadio::setup(); Serial.begin(9600); //delay 2 seconds for arming delay(2000); } void loop() { static uint32_t timer = micros(); uint32_t dt = timer+micros(); timer = -micros(); int driveSig = APMRadio::get(0); int steerSig = APMRadio::get(1); Serial.print(dt); Serial.print(" "); Serial.print(driveSig); Serial.print(" "); Serial.print(steerSig); Serial.println(); drive.write( driveSig ); steer.write( steerSig ); backsteer.write( 90 - steerSig ); }
Add SHT10 sensor and fix some setup
/* Arduino based self regulating kitchen garden */ #include <DHT.h> // temperature related setup #define DHTPIN 2 // Humidity and temperature sensor pin #define DHTTYPE DHT22 // Model DHT 22 (AM2302) DHT airSensor(DHTPIN, DHTTYPE); // setup DHT sensor float airHumidity; float airTemperature; // light related setup int lightSensorPin = 3; // Set to whereever light sensor is connected int lampRelay = 4; // Set to whereever relay for lamp is connected // activity led setup int ledPin = 13; // this is just for checking activity // Initialize settings void setup() { // Initialize output pins. pinMode(ledPin, OUTPUT); // Initialize input pins. pinMode(lightSensorPin, INPUT); airSensor.begin(); // begin DHT so it is ready for reading } // Main loop void loop() { // Read sensor values analogRead(lightSensorPin); airSensor.readHumidity(); // read humidity from DHT airSensor.readTemperature(); // read temperature from DHT }
/* Arduino based self regulating kitchen garden */ #include <SHT1x.h> #include <DHT.h> // soil related setup #define soilDataPin 3 #define soilClockPin 4 SHT1x soilSensor(soilDataPin, soilClockPin); float soilTemperature; float soilMoisture; // air temperature related setup #define DHTPIN 2 // Humidity and temperature sensor pin #define DHTTYPE DHT22 // Model DHT 22 (AM2302) DHT airSensor(DHTPIN, DHTTYPE); // setup DHT sensor float airHumidity; float airTemperature; // light related setup #define lightSensorPin A0 // Set to whereever light sensor is connected // activity led setup int ledPin = 13; // this is just for checking activity // Initialize settings void setup() { // Initialize output pins. pinMode(ledPin, OUTPUT); // Initialize input pins. pinMode(lightSensorPin, INPUT); // Is this needed? It is analog pin.. airSensor.begin(); // begin DHT so it is ready for reading } // Main loop void loop() { // Read sensor values analogRead(lightSensorPin); // read light level from LDR airSensor.readHumidity(); // read humidity from DHT airSensor.readTemperature(); // read temperature from DHT sht1x.readTemperatureC(); // read humidity from SHT10 sht1x.readHumidity(); // read temperature from SHT10 }
Add missing import to main .ino file
#ifndef BOLTARDUINO #define BOLTARDUINO #include "button.h" #include "led.h" #include "screen.h" #include "game.h" #include "const.h" #include "clock.h" void setup() { Serial.begin(115200); //Attach interrupt for 64 button shield attachInterrupt(digitalPinToInterrupt(P_BUTTON_INTERRUPT), button_ISR, FALLING); //Generate new random seed randomSeed(analogRead(0)); } void loop() { screen_display("READY"); led_set(1, LED_STATE_FLASHING); button_wait(1); game_start(); } #endif
#ifndef BOLTARDUINO #define BOLTARDUINO #include "button.h" #include "led.h" #include "screen.h" #include "game.h" #include "const.h" #include "clock.h" #include "controller.h" void setup() { Serial.begin(115200); //Attach interrupt for 64 button shield attachInterrupt(digitalPinToInterrupt(P_BUTTON_INTERRUPT), button_ISR, FALLING); //Generate new random seed randomSeed(analogRead(0)); } void loop() { screen_display("READY"); led_set(1, LED_STATE_FLASHING); button_wait(1); game_start(); } #endif
Put opening braces on separate line
#include <RunningAverage.h> #include <HX711.h> #include "TimerDisplay.h" #include "GramsDisplay.h" #define DISP_TIMER_CLK 2 #define DISP_TIMER_DIO 3 #define DISP_SCALE_CLK 8 #define DISP_SCALE_DIO 9 #define SCALE_DT A2 #define SCALE_SCK A1 #define FILTER_SIZE 10 #define SCALE_FACTOR 1874 #define SCALE_OFFSET 984550 TimerDisplay timerDisplay(DISP_TIMER_CLK, DISP_TIMER_DIO); GramsDisplay gramsDisplay(DISP_SCALE_CLK, DISP_SCALE_DIO); HX711 scale; RunningAverage filter(FILTER_SIZE); float weight_in_grams; void setup() { // Serial comm Serial.begin(38400); // Load cell scale.begin(SCALE_DT, SCALE_SCK); scale.set_scale(SCALE_FACTOR); scale.set_offset(SCALE_OFFSET); // Filter filter.clear(); } void loop() { filter.addValue(scale.get_units()); weight_in_grams = filter.getAverage(); gramsDisplay.displayGrams(weight_in_grams); if (weight_in_grams > 1) timerDisplay.start(); else timerDisplay.stop(); timerDisplay.refresh(); }
#include <RunningAverage.h> #include <HX711.h> #include "TimerDisplay.h" #include "GramsDisplay.h" #define DISP_TIMER_CLK 2 #define DISP_TIMER_DIO 3 #define DISP_SCALE_CLK 8 #define DISP_SCALE_DIO 9 #define SCALE_DT A2 #define SCALE_SCK A1 #define FILTER_SIZE 10 #define SCALE_FACTOR 1874 #define SCALE_OFFSET 984550 TimerDisplay timerDisplay(DISP_TIMER_CLK, DISP_TIMER_DIO); GramsDisplay gramsDisplay(DISP_SCALE_CLK, DISP_SCALE_DIO); HX711 scale; RunningAverage filter(FILTER_SIZE); float weight_in_grams; void setup() { // Serial comm Serial.begin(38400); // Load cell scale.begin(SCALE_DT, SCALE_SCK); scale.set_scale(SCALE_FACTOR); scale.set_offset(SCALE_OFFSET); // Filter filter.clear(); } void loop() { filter.addValue(scale.get_units()); weight_in_grams = filter.getAverage(); gramsDisplay.displayGrams(weight_in_grams); if (weight_in_grams > 1) timerDisplay.start(); else timerDisplay.stop(); timerDisplay.refresh(); }
Remove settin wakeup button from poserOFF example
#include <M5Stack.h> // the setup routine runs once when M5Stack starts up void setup(){ // initialize the M5Stack object M5.begin(); // Lcd display M5.Lcd.println("This is software power off demo"); M5.Lcd.println("Press the button A to power off."); // Set the wakeup button M5.Power.setWakeupButton(BUTTON_A_PIN); } // the loop routine runs over and over again forever void loop() { if(M5.BtnA.wasPressed()) { M5.Power.powerOFF(); } M5.update(); }
#include <M5Stack.h> // the setup routine runs once when M5Stack starts up void setup(){ // initialize the M5Stack object M5.begin(); // Lcd display M5.Lcd.println("This is software power off demo"); M5.Lcd.println("Press the button A to power off."); } // the loop routine runs over and over again forever void loop() { if(M5.BtnA.wasPressed()) { M5.Power.powerOFF(); } M5.update(); }
Convert global variables to local
#include <SPI.h> #define SPI_READ_CMD 0x03 #define CS_PIN 10 unsigned int num_bytes; unsigned int i; void setup() { Serial.begin(115200); pinMode(CS_PIN, OUTPUT); digitalWrite(CS_PIN, HIGH); SPI.begin(); } void read_eeprom(unsigned int num_bytes) { unsigned int addr; byte resp; digitalWrite(CS_PIN, LOW); /* transmit read command with 3 byte start address */ SPI.transfer(SPI_READ_CMD); SPI.transfer(0x00); SPI.transfer(0x00); SPI.transfer(0x00); for (addr = 0; addr < num_bytes; addr++) { resp = SPI.transfer(0xff); Serial.write(resp); } digitalWrite(CS_PIN, HIGH); } void loop() { /* wait for the integer with the requested number of bytes */ if (Serial.available() == 4) { num_bytes = 0; /* merge four bytes to single integer */ for (i = 0; i < 4; i++) num_bytes |= Serial.read() << (i * 8); read_eeprom(num_bytes); } }
#include <SPI.h> #define SPI_READ_CMD 0x03 #define CS_PIN 10 void setup() { Serial.begin(115200); pinMode(CS_PIN, OUTPUT); digitalWrite(CS_PIN, HIGH); SPI.begin(); } void read_eeprom(unsigned int num_bytes) { unsigned int addr; byte resp; digitalWrite(CS_PIN, LOW); /* transmit read command with 3 byte start address */ SPI.transfer(SPI_READ_CMD); SPI.transfer(0x00); SPI.transfer(0x00); SPI.transfer(0x00); for (addr = 0; addr < num_bytes; addr++) { resp = SPI.transfer(0xff); Serial.write(resp); } digitalWrite(CS_PIN, HIGH); } void loop() { unsigned int num_bytes; unsigned int i; /* wait for the integer with the requested number of bytes */ if (Serial.available() == 4) { num_bytes = 0; /* merge four bytes to single integer */ for (i = 0; i < 4; i++) num_bytes |= Serial.read() << (i * 8); read_eeprom(num_bytes); } }
Fix ghost press at launch
#include <Wire.h> #include <LiquidCrystal_I2C.h> static constexpr unsigned long TimeChunk = 2 * 1000; static LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); static unsigned long endTime; static bool previousPressed; void setup() { lcd.begin(16,2); lcd.backlight(); pinMode(A0, INPUT_PULLUP); delay(10); endTime = millis() + 10000 * TimeChunk; previousPressed = false; } void loop() { lcd.setCursor(0,0); unsigned long currentTime = millis(); if (currentTime >= endTime) { lcd.print("GAME OVER!"); } else { bool currentPressed = digitalRead(A0); if (currentPressed && !previousPressed) { endTime += 10 * TimeChunk; } previousPressed = currentPressed; unsigned long remainingChunk = (endTime - currentTime) / TimeChunk; char buf[12]; lcd.print(itoa(remainingChunk, buf, 10)); } delay(10); }
#include <Wire.h> #include <LiquidCrystal_I2C.h> static constexpr unsigned long TimeChunk = 2 * 1000; static LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); static unsigned long endTime; static bool previousPressed; void setup() { lcd.begin(16,2); lcd.backlight(); pinMode(A0, INPUT_PULLUP); delay(10); endTime = millis() + 10000 * TimeChunk; previousPressed = HIGH; } void loop() { lcd.setCursor(0,0); unsigned long currentTime = millis(); if (currentTime >= endTime) { lcd.print("GAME OVER!"); } else { bool currentPressed = digitalRead(A0); if (currentPressed && !previousPressed) { endTime += 10 * TimeChunk; } previousPressed = currentPressed; unsigned long remainingChunk = (endTime - currentTime) / TimeChunk; char buf[12]; lcd.print(itoa(remainingChunk, buf, 10)); } delay(10); }
Update readTag to fetch just the payload from the messages on the tag
#include "pn532_i2c_particle/pn532_i2c_particle.h" #include "pn532_i2c_particle/PN532.h" #include "pn532_i2c_particle/NfcAdapter.h" PN532_I2C pn532_i2c(Wire); NfcAdapter nfc = NfcAdapter(pn532_i2c); void setup(void) { Serial.begin(9600); Serial.println("NDEF Reader"); nfc.begin(); } void loop(void) { Serial.println("\nScan a NFC tag\n"); if (nfc.tagPresent()) { NfcTag tag = nfc.read(); //tag.print(); if(tag.hasNdefMessage()){ NdefMessage tagMessage = tag.getNdefMessage(); int i; for (i = 0; i < tagMessage.getRecordCount() ; i++) { // NdefRecord tagRecord = tagMessage.getRecord(i); tagRecord.print(); } } } delay(5000); }
#include "pn532_i2c_particle/pn532_i2c_particle.h" #include "pn532_i2c_particle/PN532.h" #include "pn532_i2c_particle/NfcAdapter.h" PN532_I2C pn532_i2c(Wire); NfcAdapter nfc = NfcAdapter(pn532_i2c); void setup(void) { Serial.begin(9600); Serial.println("NDEF Reader"); nfc.begin(); } void loop(void) { Serial.println("\nScan a NFC tag\n"); if (nfc.tagPresent()) { NfcTag tag = nfc.read(); if(tag.hasNdefMessage()){ NdefMessage tagMessage = tag.getNdefMessage(); int i; for (i = 0; i < tagMessage.getRecordCount() ; i++) { // NdefRecord tagRecord = tagMessage.getRecord(i); tagRecord.print(); } } } delay(5000); }
Disable the output after calibrating instead of deprecated stop
#include "Wire.h" #include "SPI.h" #include "MINDS-i-Drone.h" #include "platforms/Quadcopter.h" void setup(){ calibrateESCs(); } void loop(){ output.stop(); }
#include "Wire.h" #include "SPI.h" #include "MINDS-i-Drone.h" #include "platforms/Quadcopter.h" void setup(){ calibrateESCs(); output.disable(); } void loop(){ }
Update poser off example for new api.
#include <M5Stack.h> // the setup routine runs once when M5Stack starts up void setup(){ // initialize the M5Stack object M5.begin(); // Lcd display M5.Lcd.println("This is software power off demo"); M5.Lcd.println("Press the button A to power off."); // Set the wakeup button M5.setWakeupButton(BUTTON_A_PIN); } // the loop routine runs over and over again forever void loop() { if(M5.BtnA.wasPressed()) { M5.powerOFF(); } M5.update(); }
#include <M5Stack.h> // the setup routine runs once when M5Stack starts up void setup(){ // initialize the M5Stack object M5.begin(); // Lcd display M5.Lcd.println("This is software power off demo"); M5.Lcd.println("Press the button A to power off."); // Set the wakeup button M5.Power.setWakeupButton(BUTTON_A_PIN); } // the loop routine runs over and over again forever void loop() { if(M5.BtnA.wasPressed()) { M5.Power.deepSleep(); } M5.update(); }
Remove useless comments from ino
#include "lcd.h" #include "sensor.h" void setup() { LCD::setup(); LCD::helloworld(); // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: }
#include "lcd.h" #include "sensor.h" void setup() { LCD::setup(); LCD::helloworld(); } void loop() { }
Add some delays between setting channels + flash LED
#include "receiver.h" Receiver rx1 = Receiver(2, 3, 4); Receiver rx2 = Receiver(2, 3, 5); Receiver rx3 = Receiver(2, 3, 6); Receiver rx4 = Receiver(2, 3, 7); void setup() { // Wait for modules to settle. delay(1000); // Set to race frequencies. rx1.setFrequency(5665); rx2.setFrequency(5745); rx3.setFrequency(5885); rx4.setFrequency(5945); } void loop() { // Do nothing. delay(1000); }
#include "receiver.h" Receiver rx1 = Receiver(2, 3, 4); Receiver rx2 = Receiver(2, 3, 5); Receiver rx3 = Receiver(2, 3, 6); Receiver rx4 = Receiver(2, 3, 7); void setup() { // Wait for modules to settle. delay(2000); // Set to race frequencies. rx1.setFrequency(5805); delay(500); rx2.setFrequency(5745); delay(500); rx3.setFrequency(5885); delay(500); rx4.setFrequency(5945); } void loop() { // Flash the LED. digitalWrite(13, HIGH); delay(1000); digitalWrite(13, LOW); delay(1000); }
Move main to setup to not repeat
#include "button.h" #include "led.h" #include "screen.h" #include "game.h" #include "timer.h" #include "const.h" #include "controller.h" #include "flasher.h" #include "logger.h" #include "helper.h" void setup() { Serial.begin(115200); //Generate new random seed randomSeed(analogRead(0)); //Setup button::setup(); led::setup(); flasher::setup(); timer::setup(); logger::log(logger::TYPE_INFO, "main", "Setup done"); } void loop() { screen::display("READY"); //Wait for center button to be pressed led::setState(0, led::STATE_FLASHING); button::wait(0); led::setState(0, led::STATE_OFF); //Start game game::start(); helper::waitTime(5000); }
#include "button.h" #include "led.h" #include "screen.h" #include "game.h" #include "timer.h" #include "const.h" #include "controller.h" #include "flasher.h" #include "logger.h" #include "helper.h" void setup() { Serial.begin(115200); //Generate new random seed randomSeed(analogRead(0)); //Setup button::setup(); led::setup(); flasher::setup(); timer::setup(); logger::log(logger::TYPE_INFO, "main", "Setup done"); screen::display("READY"); //Wait for center button to be pressed led::setState(0, led::STATE_FLASHING); button::wait(0); led::setState(0, led::STATE_OFF); //Start game game::start(); helper::waitTime(5000); } void loop() { }
Use ds_addr instead of ds
/* Author: Andrea Stagi <stagi.andrea@gmail.com> Example: ReadAll Description: fetch all devices and relative temperatures on the wire bus on pin 5 and send them via serial port. */ #include <OneWire.h> #include <DSTemperature.h> DSTemperature ds(5); // on pin 5 void setup(void) { Serial.begin(9600); ds.begin(); } void sendAddress(DSAddress ds) { for(int i = 0 ; i < 8 ; i++) { Serial.print(ds.value[i], HEX); Serial.print(" "); } Serial.println(); } void loop(void) { for(int i = 0 ; i < ds.getDeviceCount() ; i++) { Serial.println("-------------------------------------------"); Serial.print("DEVICE ADDRESS: "); sendAddress(ds.getAddressFromIndex(i)); Serial.print("TEMPERATURE VALUE: "); Serial.print(ds.getCelsius(i)); Serial.println(" C"); } /* TODO: try to get index from 28 DA E5 D1 3 0 0 77 and 28 DA 19 0 0 0 20 32 */ }
/* Author: Andrea Stagi <stagi.andrea@gmail.com> Example: ReadAll Description: fetch all devices and relative temperatures on the wire bus on pin 5 and send them via serial port. */ #include <OneWire.h> #include <DSTemperature.h> DSTemperature ds(5); // on pin 5 void setup(void) { Serial.begin(9600); ds.begin(); } void sendAddress(DSAddress ds_addr) { for(int i = 0 ; i < 8 ; i++) { Serial.print(ds_addr.value[i], HEX); Serial.print(" "); } Serial.println(); } void loop(void) { for(int i = 0 ; i < ds.getDeviceCount() ; i++) { Serial.println("-------------------------------------------"); Serial.print("DEVICE ADDRESS: "); sendAddress(ds.getAddressFromIndex(i)); Serial.print("TEMPERATURE VALUE: "); Serial.print(ds.getCelsius(i)); Serial.println(" C"); } /* TODO: try to get index from 28 DA E5 D1 3 0 0 77 and 28 DA 19 0 0 0 20 32 */ }
Change code to count down instead of up
#include "Constants.h" #include "Display.h" #include "Buttons.h" Display display; Buttons buttons; unsigned long start_time = 0; void setup() { Serial.begin(9600); pinMode(13, OUTPUT); start_time = millis(); } void loop() { unsigned long current_time = millis() - start_time; display.displayTime( current_time / 1000 ); int button = buttons.get_button_press(); if ( button == BUTTON_RESTART ) { // reset the start time start_time = millis(); } }
#include "Constants.h" #include "Display.h" #include "Buttons.h" Display display; Buttons buttons; unsigned long countdown_ends; unsigned long countdown_duration; void setup() { Serial.begin(9600); pinMode(13, OUTPUT); countdown_ends = 0; countdown_duration = 900000; // 15 mins in ms countdown_ends = millis() + countdown_duration; } void loop() { long time_remaining = countdown_ends - millis(); Serial.println(countdown_duration); display.displayTime( time_remaining / 1000 ); int button = buttons.get_button_press(); if ( button == BUTTON_RESTART ) { // reset the start time countdown_ends = millis() + countdown_duration + 500; } }
Add i2c to thruster control sketch.
#include <ros.h> ros::NodeHandle nh; std_msgs::Float64 state; void callback(const std_msgs::Float64 cmd); { } ros::Publisher state_pub("state", &state); ros::Subscriber<std_msgs::Float64> cmd_sub("command", &callback); void setup() { nh.initNode(); nh.advertise(state_pub); } void loop() { nh.spinOnce(); state[0] = port_servo_pos; state[1] = stbd_servo_pos; state_pub.publish(&state); delay(33); }
#include <Wire.h> #include <ros.h> #include <std_msgs/Int8.h> ros::NodeHandle nh; std_msgs::Int8 state; ros::Publisher state_pub("state", &state); void callback(const std_msgs::Int8 &cmd) { state.data = 0; state_pub.publish(&state); Wire.beginTransmission(3); Wire.write(0x10); Wire.write(0x10); Wire.write(0x10); Wire.endTransmission(); delay(5); Wire.beginTransmission(3); Wire.write(0x20); Wire.write(0x20); Wire.write(0x20); Wire.endTransmission(); delay(5); Wire.requestFrom(0x10, 4); while(Wire.available()) { char c = Wire.read(); state.data = c; state_pub.publish(&state); } } ros::Subscriber<std_msgs::Int8> cmd_sub("command", &callback); void setup() { Wire.begin(); nh.initNode(); nh.advertise(state_pub); } void loop() { nh.spinOnce(); delay(33); }
Update pass through to work with Node
/** * Use this sketch to talk directly to the LoRa module. * * In Serial Monitor, select "Both NL & CR" and "9600 baud" in * the bottom right dropdowns and send command a command like: * * mac get deveui * sys reset */ #define loraSerial Serial1 #define debugSerial Serial void setup() { loraSerial.begin(57600); debugSerial.begin(9600); } void loop() { while (debugSerial.available()) { loraSerial.write(debugSerial.read()); } while (loraSerial.available()) { debugSerial.write(loraSerial.read()); } }
/** * Use this sketch to talk directly to the LoRa module. * * In Serial Monitor, select "Both NL & CR" and "115200 baud" in * the bottom right dropdowns and send command a command like: * * mac get deveui * sys reset */ #define loraSerial Serial1 #define debugSerial Serial void setup() { while(!debugSerial || !loraSerial); debugSerial.begin(115200); delay(1000); loraSerial.begin(57600); } void loop() { while (debugSerial.available()) { loraSerial.write(debugSerial.read()); } while (loraSerial.available()) { debugSerial.write(loraSerial.read()); } }
Use powerOFF on powerOFF example
#include <M5Stack.h> // the setup routine runs once when M5Stack starts up void setup(){ // initialize the M5Stack object M5.begin(); // Lcd display M5.Lcd.println("This is software power off demo"); M5.Lcd.println("Press the button A to power off."); // Set the wakeup button M5.Power.setWakeupButton(BUTTON_A_PIN); } // the loop routine runs over and over again forever void loop() { if(M5.BtnA.wasPressed()) { M5.Power.deepSleep(); } M5.update(); }
#include <M5Stack.h> // the setup routine runs once when M5Stack starts up void setup(){ // initialize the M5Stack object M5.begin(); // Lcd display M5.Lcd.println("This is software power off demo"); M5.Lcd.println("Press the button A to power off."); // Set the wakeup button M5.Power.setWakeupButton(BUTTON_A_PIN); } // the loop routine runs over and over again forever void loop() { if(M5.BtnA.wasPressed()) { M5.Power.powerOFF(); } M5.update(); }
Add link to EnableInterupt pin beastiary
/* This example is basically the same as SimpleSerialPrinter but utilize the EnableInterrupt library. EnableInterrupt make pin change interrupts available and thus allows to use arbitrary pins. */ // EnableInterrupt from https://github.com/GreyGnome/EnableInterrupt // include it before RadiationWatch.h #include "EnableInterrupt.h" #include "RadiationWatch.h" // Use any pin as you like // Here: signPin = 5, noisePin = 6 RadiationWatch radiationWatch(5, 6); void onRadiation() { Serial.println("A wild gamma ray appeared"); Serial.print(radiationWatch.uSvh()); Serial.print(" uSv/h +/- "); Serial.println(radiationWatch.uSvhError()); } void onNoise() { Serial.println("Argh, noise, please stop moving"); } void setup() { Serial.begin(9600); radiationWatch.setup(); // Register the callbacks. radiationWatch.registerRadiationCallback(&onRadiation); radiationWatch.registerNoiseCallback(&onNoise); } void loop() { radiationWatch.loop(); }
/* This example is basically the same as SimpleSerialPrinter but utilize the EnableInterrupt library. The EnableInterrupt library make pin change interrupts available and thus allows to use arbitrary pins. See a list of pins supported here: https://github.com/GreyGnome/EnableInterrupt/wiki/Usage#pin--port-bestiary You can install the library from the Arduino Library Manager: http://www.arduinolibraries.info/libraries/enable-interrupt */ // EnableInterrupt from https://github.com/GreyGnome/EnableInterrupt // include it before RadiationWatch.h #include "EnableInterrupt.h" #include "RadiationWatch.h" // Use any pin as you like // Here: signPin = 5, noisePin = 6 RadiationWatch radiationWatch(5, 6); void onRadiation() { Serial.println("A wild gamma ray appeared"); Serial.print(radiationWatch.uSvh()); Serial.print(" uSv/h +/- "); Serial.println(radiationWatch.uSvhError()); } void onNoise() { Serial.println("Argh, noise, please stop moving"); } void setup() { Serial.begin(9600); radiationWatch.setup(); // Register the callbacks. radiationWatch.registerRadiationCallback(&onRadiation); radiationWatch.registerNoiseCallback(&onNoise); } void loop() { radiationWatch.loop(); }
Update readTag to fetch just the payload from the messages on the tag
#include "pn532_i2c_particle/pn532_i2c_particle.h" #include "pn532_i2c_particle/PN532.h" #include "pn532_i2c_particle/NfcAdapter.h" PN532_I2C pn532_i2c(Wire); NfcAdapter nfc = NfcAdapter(pn532_i2c); void setup(void) { Serial.begin(9600); Serial.println("NDEF Reader"); nfc.begin(); } void loop(void) { Serial.println("\nScan a NFC tag\n"); if (nfc.tagPresent()) { NfcTag tag = nfc.read(); //tag.print(); if(tag.hasNdefMessage()){ NdefMessage tagMessage = tag.getNdefMessage(); } } } delay(5000); }
#include "pn532_i2c_particle/pn532_i2c_particle.h" #include "pn532_i2c_particle/PN532.h" #include "pn532_i2c_particle/NfcAdapter.h" PN532_I2C pn532_i2c(Wire); NfcAdapter nfc = NfcAdapter(pn532_i2c); void setup(void) { Serial.begin(9600); Serial.println("NDEF Reader"); nfc.begin(); } void loop(void) { Serial.println("\nScan a NFC tag\n"); if (nfc.tagPresent()) { NfcTag tag = nfc.read(); //tag.print(); if(tag.hasNdefMessage()){ NdefMessage tagMessage = tag.getNdefMessage(); int i; for (i = 0; i < tagMessage.getRecordCount() ; i++) { // NdefRecord tagRecord = tagMessage.getRecord(i); tagRecord.print(); } } } delay(5000); }
Reduce led brightness to save my eyes.
#include <FastLED.h> #define WIDTH 16 #define HEIGHT 16 #define NUM_LEDS (WIDTH * HEIGHT) #define PIN 6 #define BAUD 115200 #define BRIGHTNESS 32 CRGB leds[NUM_LEDS]; int r, g, b; int x, y, yy; void setup() { FastLED.addLeds<WS2812B, PIN>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip); FastLED.setBrightness(BRIGHTNESS); Serial.begin(BAUD); FastLED.show(); } void loop() { Serial.write("R"); for (x = 0; x < WIDTH; x++) { for (y = 0; y < HEIGHT; y++) { while (Serial.available() < 3); r = Serial.read(); g = Serial.read(); b = Serial.read(); if (x % 2 == 0) { yy = HEIGHT - y - 1; } else { yy = y; } leds[yy + x * HEIGHT] = CRGB(g, r, b); // Seems to be running as GRB, not RGB } } FastLED.show(); }
#include <FastLED.h> #define WIDTH 16 #define HEIGHT 16 #define NUM_LEDS (WIDTH * HEIGHT) #define PIN 6 #define BAUD 115200 #define BRIGHTNESS 8 CRGB leds[NUM_LEDS]; int r, g, b; int x, y, yy; void setup() { FastLED.addLeds<WS2812B, PIN>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip); FastLED.setBrightness(BRIGHTNESS); Serial.begin(BAUD); FastLED.show(); } void loop() { Serial.write("R"); for (x = 0; x < WIDTH; x++) { for (y = 0; y < HEIGHT; y++) { while (Serial.available() < 3); r = Serial.read(); g = Serial.read(); b = Serial.read(); if (x % 2 == 0) { yy = HEIGHT - y - 1; } else { yy = y; } leds[yy + x * HEIGHT] = CRGB(g, r, b); // Seems to be running as GRB, not RGB } } FastLED.show(); }
Use interrupt to IR sensors
#include <MiniRobot.h> MiniRobot robot; void setup() { } void loop() { if (robot.leftEdge() && robot.distanceToEnemy() == 0) { robot.leftBack(); } else { robot.leftForward(); } if (robot.rightEdge() && robot.distanceToEnemy() == 0) { robot.rightBack(); } else { robot.rightForward(); } }
#include <MiniRobot.h> MiniRobot robot; byte status = 2; /* 0 - don't need changes; 1 - counter only 2 - drive straight back; 3 - drive straight forward; 4 - spin around - enemy forward; */ int count = 0; void setup() { PCMSK1 |= bit(0) | bit(1); PCIFR |= bit(1); PCICR |= bit(1); pinMode(A0,INPUT); // set Pin as Input (default) digitalWrite(A0,HIGH); // enable pullup resistor pinMode(A1,INPUT); // set Pin as Input (default) digitalWrite(A1,HIGH); // enable pullup resistor } ISR (PCINT1_vect) { if (robot.leftEdge() || robot.rightEdge()) { status = 4; } } void loop() { switch (status) { case 1: count--; if (count <= 0) { status = 3; } break; case 2: robot.back(); count = 15; status = 1; break; case 3: robot.forward(); status = 0; break; case 4: robot.leftBack(); robot.rightForward(); count = 10; status = 1; break; } }
Send a response after the Arduino has completed its work.
#include "Watering.h" void setup () { //Init serial connection Serial.begin(SERIAL_BAUD); //Init LED Pin pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); } void loop() { if ( Serial.available() ) { byte command = Serial.read(); switch( command ) { case WATER_LEVEL: break; case SUNLIGHT_LEVEL: break; case RELAY_ON: digitalWrite(LED_PIN, HIGH); break; case RELAY_OFF: digitalWrite(LED_PIN, LOW); break; default: break; } } }
#include "Watering.h" void setup () { //Init serial connection Serial.begin(SERIAL_BAUD); //Init LED Pin pinMode(LED_PIN, OUTPUT); digitalWrite(LED_PIN, LOW); } void loop() { if ( Serial.available() ) { byte command = Serial.read(); byte output[4]; byte numBytes = 0; switch( command ) { case WATER_LEVEL: break; case SUNLIGHT_LEVEL: break; case RELAY_ON: digitalWrite(LED_PIN, HIGH); // Prepping to send a response output[0] = command; output[1] = 0; numBytes = 2; break; case RELAY_OFF: digitalWrite(LED_PIN, LOW); // Prepping to send a response output[0] = command; output[1] = 0; numBytes = 2; break; default: break; } //Sending a response after the command has completed Serial.write(output, numBytes); } }
Change on Serial stuff to show data
/* Pines of the first sensor. */ #define S1echo 7 #define S1trig 8 /* Pines of the second sensor. */ #define S2echo 10 #define S2trig 11 long duration, distance; void setup() { /* Setup of the echo & trig of everysensor. */ pinMode(S1echo, INPUT); //pinMode(S2echo, INPUT); pinMode(S1trig, OUTPUT); //pinMode(S2trig, OUTPUT); } void loop() { printReadings("Testing",0); estimateDistance(S1trig, S1echo); delayMicroseconds(1000); } void printReadings(String label, long value){ String phrase = label+": "+value; Serial.print(phrase); } /* Estimate the distance received from the ultrasonic sensor. */ int estimateDistance(int trig, int echo){ digitalWrite(trig,LOW); delayMicroseconds(2); digitalWrite(trig,HIGH); delayMicroseconds(10); digitalWrite(trig,LOW); //Claculate Duration of pulse. duration = pulseIn(echo,HIGH); printReadings("Duration", duration); //Distance in centimeters distance = duration/58.2; printReadings("Distance", distance); return distance; }
/* Pines of the first sensor. */ #define S1echo 7 #define S1trig 8 /* Pines of the second sensor. */ #define S2echo 10 #define S2trig 11 long duration, distance; void setup() { Serial.begin(9600); /* Setup of the echo & trig of everysensor. */ pinMode(S1echo, INPUT); //pinMode(S2echo, INPUT); pinMode(S1trig, OUTPUT); //pinMode(S2trig, OUTPUT); } void loop() { printString("Testing"); estimateDistance(S1trig, S1echo); delay(10000); } void printReadings(String label, long value){ String phrase = label+": "+value; printString(phrase); } void printString(String phrase){ Serial.println(phrase); Serial.println(" "); } /* Estimate the distance received from the ultrasonic sensor. */ int estimateDistance(int trig, int echo){ digitalWrite(trig,LOW); delayMicroseconds(2); digitalWrite(trig,HIGH); delayMicroseconds(10); digitalWrite(trig,LOW); //Calculate Duration of pulse. duration = pulseIn(echo,HIGH); printReadings("Duration", duration); //Distance in centimeters distance = duration/58.2; printReadings("Distance", distance); return distance; }
Switch chipKIT UNO32 to use new Stream API
/************************************************************** * Blynk is a platform with iOS and Android apps to control * Arduino, Raspberry Pi and the likes over the Internet. * You can easily build graphic interfaces for all your * projects by simply dragging and dropping widgets. * * Downloads, docs, tutorials: http://www.blynk.cc * Blynk community: http://community.blynk.cc * Social networks: http://www.fb.com/blynkapp * http://twitter.com/blynk_app * * Blynk library is licensed under MIT license * This example code is in public domain. * ************************************************************** * This example shows how to use ordinary Arduino Serial * to connect your project to Blynk. * Feel free to apply it to any other example. It's simple! * ************************************************************** * USB HOWTO: http://tiny.cc/BlynkUSB **************************************************************/ #define BLYNK_PRINT Serial1 #include <BlynkSimpleSerial.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; void setup() { // Debug prints on pins 39 (RX), 40 (TX) Serial1.begin(9600); // Blynk will work through Serial Serial.begin(9600); Blynk.begin(auth, Serial); } void loop() { Blynk.run(); }
/************************************************************** * Blynk is a platform with iOS and Android apps to control * Arduino, Raspberry Pi and the likes over the Internet. * You can easily build graphic interfaces for all your * projects by simply dragging and dropping widgets. * * Downloads, docs, tutorials: http://www.blynk.cc * Blynk community: http://community.blynk.cc * Social networks: http://www.fb.com/blynkapp * http://twitter.com/blynk_app * * Blynk library is licensed under MIT license * This example code is in public domain. * ************************************************************** * This example shows how to use ordinary Arduino Serial * to connect your project to Blynk. * Feel free to apply it to any other example. It's simple! * ************************************************************** * USB HOWTO: http://tiny.cc/BlynkUSB **************************************************************/ #define BLYNK_PRINT Serial1 #include <BlynkSimpleStream.h> // You should get Auth Token in the Blynk App. // Go to the Project Settings (nut icon). char auth[] = "YourAuthToken"; void setup() { // Debug prints on pins 39 (RX), 40 (TX) Serial1.begin(9600); // Blynk will work through Serial Serial.begin(9600); Blynk.begin(auth, Serial); } void loop() { Blynk.run(); }
Fix caps in constant example
#include <Homie.h> const int doorPin = 16; Bounce debouncer = Bounce(); // Bounce is built into Homie, so you can use it without including it first unsigned long lastDoorValue = -1; HomieNode doorNode("door", "door"); void loopHandler() { int doorValue = debouncer.read(); if (doorValue != lastDoorValue) { Serial.print("Door is now: "); Serial.println(doorValue ? "open" : "close"); if (Homie.setNodeProperty(doorNode, "open", String(doorValue ? "true" : "false"), true)) { lastDoorValue = doorValue; } else { Serial.println("Sending failed"); } } } void setup() { pinMode(doorPin, INPUT); digitalWrite(doorPin, HIGH); debouncer.attach(doorPin); debouncer.interval(50); Homie.setFirmware("awesome-door", "1.0.0"); Homie.registerNode(doorNode); Homie.setLoopFunction(loopHandler); Homie.setup(); } void loop() { Homie.loop(); debouncer.update(); }
#include <Homie.h> const int PIN_DOOR = 16; Bounce debouncer = Bounce(); // Bounce is built into Homie, so you can use it without including it first unsigned long lastDoorValue = -1; HomieNode doorNode("door", "door"); void loopHandler() { int doorValue = debouncer.read(); if (doorValue != lastDoorValue) { Serial.print("Door is now: "); Serial.println(doorValue ? "open" : "close"); if (Homie.setNodeProperty(doorNode, "open", String(doorValue ? "true" : "false"), true)) { lastDoorValue = doorValue; } else { Serial.println("Sending failed"); } } } void setup() { pinMode(PIN_DOOR, INPUT); digitalWrite(PIN_DOOR, HIGH); debouncer.attach(PIN_DOOR); debouncer.interval(50); Homie.setFirmware("awesome-door", "1.0.0"); Homie.registerNode(doorNode); Homie.setLoopFunction(loopHandler); Homie.setup(); } void loop() { Homie.loop(); debouncer.update(); }