hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
f75d055a1873f3d879ebda6e32fb15912b83309f
5,229
agda
Agda
src/Web/Semantic/DL/Category/Properties/Tensor/Functor.agda
agda/agda-web-semantic
8ddbe83965a616bff6fc7a237191fa261fa78bab
[ "MIT" ]
9
2015-09-13T17:46:41.000Z
2020-03-14T14:21:08.000Z
src/Web/Semantic/DL/Category/Properties/Tensor/Functor.agda
agda/agda-web-semantic
8ddbe83965a616bff6fc7a237191fa261fa78bab
[ "MIT" ]
4
2018-11-14T02:32:28.000Z
2021-01-04T20:57:19.000Z
src/Web/Semantic/DL/Category/Properties/Tensor/Functor.agda
agda/agda-web-semantic
8ddbe83965a616bff6fc7a237191fa261fa78bab
[ "MIT" ]
3
2017-12-03T14:52:09.000Z
2022-03-12T11:40:03.000Z
open import Data.Sum using ( _⊎_ ; inj₁ ; inj₂ ) open import Relation.Binary.PropositionalEquality using ( refl ) open import Web.Semantic.DL.ABox.Interp using ( ⌊_⌋ ; ind ; _*_ ) open import Web.Semantic.DL.ABox.Model using ( _⊨a_ ; ⊨a-resp-≡³ ; on-bnode ; bnodes ; _,_ ) open import Web.Semantic.DL.Category.Object using ( Object ; IN ) open import Web.Semantic.DL.Category.Morphism using ( _⇒_ ; BN ; impl ; _⊑_ ; _≣_ ; _,_ ) open import Web.Semantic.DL.Category.Composition using ( _∙_ ) open import Web.Semantic.DL.Category.Tensor using ( _⊗_ ; _⟨⊗⟩_ ) open import Web.Semantic.DL.Category.Wiring using ( identity ; id✓ ) open import Web.Semantic.DL.Category.Properties.Composition.Lemmas using ( compose-left ; compose-right ; compose-resp-⊨a ) open import Web.Semantic.DL.Category.Properties.Tensor.Lemmas using ( tensor-up ; tensor-down ; tensor-resp-⊨a ) open import Web.Semantic.DL.Category.Properties.Tensor.RespectsWiring using ( tensor-resp-wiring ) open import Web.Semantic.DL.Signature using ( Signature ) open import Web.Semantic.DL.TBox using ( TBox ) open import Web.Semantic.DL.TBox.Interp using ( Δ ) open import Web.Semantic.Util using ( id ; _∘_ ; _⊕_⊕_ ; inode ; bnode ; enode ; left ; right ; up ; down ) module Web.Semantic.DL.Category.Properties.Tensor.Functor {Σ : Signature} {S T : TBox Σ} where tensor-resp-id : ∀ (A₁ A₂ : Object S T) → ((identity A₁ ⟨⊗⟩ identity A₂) ≣ identity (A₁ ⊗ A₂)) tensor-resp-id A₁ A₂ = tensor-resp-wiring A₁ A₂ A₁ A₂ id (id✓ A₁) id (id✓ A₂) id (id✓ (A₁ ⊗ A₂)) (λ x → refl) (λ x → refl) tensor-resp-compose : ∀ {A₁ A₂ B₁ B₂ C₁ C₂ : Object S T} (F₁ : A₁ ⇒ B₁) (F₂ : A₂ ⇒ B₂) (G₁ : B₁ ⇒ C₁) (G₂ : B₂ ⇒ C₂) → (((F₁ ∙ G₁) ⟨⊗⟩ (F₂ ∙ G₂)) ≣ ((F₁ ⟨⊗⟩ F₂) ∙ (G₁ ⟨⊗⟩ G₂))) tensor-resp-compose {A₁} {A₂} {B₁} {B₂} {C₁} {C₂} F₁ F₂ G₁ G₂ = (LHS⊑RHS , RHS⊑LHS) where LHS⊑RHS : (F₁ ∙ G₁) ⟨⊗⟩ (F₂ ∙ G₂) ⊑ (F₁ ⟨⊗⟩ F₂) ∙ (G₁ ⟨⊗⟩ G₂) LHS⊑RHS I I⊨STA₁A₂ I⊨LHS = (f , I⊨RHS) where f : ((BN F₁ ⊎ BN F₂) ⊕ (IN B₁ ⊎ IN B₂) ⊕ (BN G₁ ⊎ BN G₂)) → Δ ⌊ I ⌋ f (inode (inj₁ v)) = ind I (bnode (inj₁ (inode v))) f (inode (inj₂ v)) = ind I (bnode (inj₂ (inode v))) f (bnode (inj₁ y)) = ind I (bnode (inj₁ (bnode y))) f (bnode (inj₂ y)) = ind I (bnode (inj₂ (bnode y))) f (enode (inj₁ w)) = ind I (bnode (inj₁ (enode w))) f (enode (inj₂ w)) = ind I (bnode (inj₂ (enode w))) Iˡ₁⊨F₁ : up * left * bnodes I f ⊨a impl F₁ Iˡ₁⊨F₁ = ⊨a-resp-≡³ (left * up * I) (on-bnode f (ind I) ∘ left ∘ up) refl (impl F₁) (compose-left F₁ G₁ (up * I) (tensor-up (F₁ ∙ G₁) (F₂ ∙ G₂) I I⊨LHS)) Iˡ₂⊨F₂ : down * (left * bnodes I f) ⊨a impl F₂ Iˡ₂⊨F₂ = ⊨a-resp-≡³ (left * down * I) (on-bnode f (ind I) ∘ left ∘ down) refl (impl F₂) (compose-left F₂ G₂ (down * I) (tensor-down (F₁ ∙ G₁) (F₂ ∙ G₂) I I⊨LHS)) Iʳ₁⊨G₁ : up * (right * bnodes I f) ⊨a impl G₁ Iʳ₁⊨G₁ = ⊨a-resp-≡³ (right * up * I) (on-bnode f (ind I) ∘ right ∘ up) refl (impl G₁) (compose-right F₁ G₁ (up * I) (tensor-up (F₁ ∙ G₁) (F₂ ∙ G₂) I I⊨LHS)) Iʳ₂⊨G₂ : down * (right * bnodes I f) ⊨a impl G₂ Iʳ₂⊨G₂ = ⊨a-resp-≡³ (right * down * I) (on-bnode f (ind I) ∘ right ∘ down) refl (impl G₂) (compose-right F₂ G₂ (down * I) (tensor-down (F₁ ∙ G₁) (F₂ ∙ G₂) I I⊨LHS)) I⊨RHS : bnodes I f ⊨a impl ((F₁ ⟨⊗⟩ F₂) ∙ (G₁ ⟨⊗⟩ G₂)) I⊨RHS = compose-resp-⊨a (F₁ ⟨⊗⟩ F₂) (G₁ ⟨⊗⟩ G₂) (bnodes I f) (tensor-resp-⊨a F₁ F₂ (left * bnodes I f) Iˡ₁⊨F₁ Iˡ₂⊨F₂) (tensor-resp-⊨a G₁ G₂ (right * bnodes I f) Iʳ₁⊨G₁ Iʳ₂⊨G₂) RHS⊑LHS : (F₁ ⟨⊗⟩ F₂) ∙ (G₁ ⟨⊗⟩ G₂) ⊑ (F₁ ∙ G₁) ⟨⊗⟩ (F₂ ∙ G₂) RHS⊑LHS I I⊨STA₁A₂ I⊨RHS = (f , I⊨LHS) where f : ((BN F₁ ⊕ IN B₁ ⊕ BN G₁) ⊎ (BN F₂ ⊕ IN B₂ ⊕ BN G₂)) → Δ ⌊ I ⌋ f (inj₁ (inode v)) = ind I (bnode (inode (inj₁ v))) f (inj₁ (bnode y)) = ind I (bnode (bnode (inj₁ y))) f (inj₁ (enode w)) = ind I (bnode (enode (inj₁ w))) f (inj₂ (inode v)) = ind I (bnode (inode (inj₂ v))) f (inj₂ (bnode y)) = ind I (bnode (bnode (inj₂ y))) f (inj₂ (enode w)) = ind I (bnode (enode (inj₂ w))) I₁ˡ⊨F₁ : left * up * bnodes I f ⊨a impl F₁ I₁ˡ⊨F₁ = ⊨a-resp-≡³ (up * left * I) (on-bnode f (ind I) ∘ up ∘ left) refl (impl F₁) (tensor-up F₁ F₂ (left * I) (compose-left (F₁ ⟨⊗⟩ F₂) (G₁ ⟨⊗⟩ G₂) I I⊨RHS)) I₁ʳ⊨G₁ : right * up * bnodes I f ⊨a impl G₁ I₁ʳ⊨G₁ = ⊨a-resp-≡³ (up * right * I) (on-bnode f (ind I) ∘ up ∘ right) refl (impl G₁) (tensor-up G₁ G₂ (right * I) (compose-right (F₁ ⟨⊗⟩ F₂) (G₁ ⟨⊗⟩ G₂) I I⊨RHS)) I₂ˡ⊨F₂ : left * down * bnodes I f ⊨a impl F₂ I₂ˡ⊨F₂ = ⊨a-resp-≡³ (down * left * I) (on-bnode f (ind I) ∘ down ∘ left) refl (impl F₂) (tensor-down F₁ F₂ (left * I) (compose-left (F₁ ⟨⊗⟩ F₂) (G₁ ⟨⊗⟩ G₂) I I⊨RHS)) I₂ʳ⊨G₂ : right * down * bnodes I f ⊨a impl G₂ I₂ʳ⊨G₂ = ⊨a-resp-≡³ (down * right * I) (on-bnode f (ind I) ∘ down ∘ right) refl (impl G₂) (tensor-down G₁ G₂ (right * I) (compose-right (F₁ ⟨⊗⟩ F₂) (G₁ ⟨⊗⟩ G₂) I I⊨RHS)) I⊨LHS : bnodes I f ⊨a impl ((F₁ ∙ G₁) ⟨⊗⟩ (F₂ ∙ G₂)) I⊨LHS = tensor-resp-⊨a (F₁ ∙ G₁) (F₂ ∙ G₂) (bnodes I f) (compose-resp-⊨a F₁ G₁ (up * bnodes I f) I₁ˡ⊨F₁ I₁ʳ⊨G₁) (compose-resp-⊨a F₂ G₂ (down * bnodes I f) I₂ˡ⊨F₂ I₂ʳ⊨G₂)
47.108108
85
0.565691
51782875136185c20ba23533438822bef87ef0e7
5,273
agda
Agda
WellScopedTermsModel.agda
jmchapman/Relative-Monads
74707d3538bf494f4bd30263d2f5515a84733865
[ "MIT" ]
21
2015-07-30T01:25:12.000Z
2021-02-13T18:02:18.000Z
WellScopedTermsModel.agda
jmchapman/Relative-Monads
74707d3538bf494f4bd30263d2f5515a84733865
[ "MIT" ]
3
2019-01-13T13:12:33.000Z
2019-05-29T09:50:26.000Z
WellScopedTermsModel.agda
jmchapman/Relative-Monads
74707d3538bf494f4bd30263d2f5515a84733865
[ "MIT" ]
1
2019-11-04T21:33:13.000Z
2019-11-04T21:33:13.000Z
module WellScopedTermsModel where open import Library open import WellScopedTerms open import RMonads open import RMonads.REM open import Categories.Sets _<<_ : ∀{n}{X : Set} → (Fin n → X) → X → Fin (suc n) → X (f << x) zero = x (f << x) (suc i) = f i record LambdaModel : Set₁ where field S : Set Env = λ n → Fin n → S field eval : ∀{n} → Env n → Tm n → S ap : S → S → S lawvar : ∀{n}{i : Fin n}{γ : Env n} → eval γ (var i) ≅ γ i lawapp : ∀{n}{t u : Tm n}{γ : Env n} → eval γ (app t u) ≅ ap (eval γ t) (eval γ u) lawlam : ∀{n}{t : Tm (suc n)}{γ : Env n}{s : S} → ap (eval γ (lam t)) s ≅ eval (γ << s) t lawext : ∀{f g : S} → ((a : S) → ap f a ≅ ap g a) → f ≅ g module Model (l : LambdaModel) where open LambdaModel l wk<< : ∀{m n}(α : Ren m n)(β : Env n) (v : S) → (y : Fin (suc m)) → ((β ∘ α) << v) y ≅ (β << v) (wk α y) wk<< α β v zero = refl wk<< α β v (suc i) = refl reneval : ∀{m n}(α : Ren m n)(β : Env n) (t : Tm m) → eval (β ∘ α) t ≅ (eval β ∘ ren α) t reneval α β (var i) = proof eval (β ∘ α) (var i) ≅⟨ lawvar ⟩ β (α i) ≅⟨ sym lawvar ⟩ eval β (var (α i)) ∎ reneval α β (lam t) = lawext λ a → proof ap (eval (β ∘ α) (lam t)) a ≅⟨ lawlam ⟩ eval ((β ∘ α) << a) t ≅⟨ cong (λ (f : Env _) → eval f t) (ext (wk<< α β a)) ⟩ eval ((β << a) ∘ wk α) t ≅⟨ reneval (wk α) (β << a) t ⟩ eval (β << a) (ren (wk α) t) ≅⟨ sym lawlam ⟩ ap (eval β (lam (ren (wk α) t))) a ∎ reneval α β (app t u) = proof eval (β ∘ α) (app t u) ≅⟨ lawapp ⟩ ap (eval (β ∘ α) t) (eval (β ∘ α) u) ≅⟨ cong₂ ap (reneval α β t) (reneval α β u) ⟩ ap (eval β (ren α t)) (eval β (ren α u)) ≅⟨ sym lawapp ⟩ eval β (app (ren α t) (ren α u)) ∎ lift<< : ∀{m n}(γ : Sub m n)(α : Env n) (a : S)(i : Fin (suc m)) → ((eval α ∘ γ ) << a) i ≅ (eval (α << a) ∘ lift γ) i lift<< γ α a zero = proof a ≅⟨ sym lawvar ⟩ eval (α << a) (var zero) ∎ lift<< γ α a (suc i) = proof eval α (γ i) ≡⟨⟩ eval ((α << a) ∘ suc) (γ i) ≅⟨ reneval suc (α << a) (γ i) ⟩ eval (α << a) (ren suc (γ i)) ∎ subeval : ∀{m n}(t : Tm m)(γ : Sub m n)(α : Env n) → eval (eval α ∘ γ) t ≅ (eval α ∘ sub γ) t subeval (var i) γ α = proof eval (eval α ∘ γ) (var i) ≅⟨ lawvar ⟩ eval α (γ i) ∎ subeval (lam t) γ α = lawext λ a → proof ap (eval (eval α ∘ γ) (lam t)) a ≅⟨ lawlam ⟩ eval ((eval α ∘ γ) << a) t ≅⟨ cong (λ (f : Env _) → eval f t) (ext (lift<< γ α a)) ⟩ eval (eval (α << a) ∘ lift γ) t ≅⟨ subeval t (lift γ) (α << a) ⟩ eval (α << a) (sub (lift γ) t) ≅⟨ sym lawlam ⟩ ap (eval α (lam (sub (lift γ) t))) a ∎ subeval (app t u) γ α = proof eval (eval α ∘ γ) (app t u) ≅⟨ lawapp ⟩ ap (eval (eval α ∘ γ) t) (eval (eval α ∘ γ) u) ≅⟨ cong₂ ap (subeval t γ α) (subeval u γ α) ⟩ ap (eval α (sub γ t)) (eval α (sub γ u)) ≅⟨ sym lawapp ⟩ eval α (app (sub γ t) (sub γ u)) ∎ TmRAlg : RAlg TmRMonad TmRAlg = record{ acar = S; astr = eval; alaw1 = ext λ _ → sym lawvar; alaw2 = ext λ t → subeval t _ _} module VEnv where open import Delay open import Size mutual Env : ℕ → Set Env n = Fin n → Val data Val : Set where clo : ∀{n} → Env n → Tm (suc n) → Val -- the RAlg is expecting a env containing 'values' here the values -- evaluator takes an env of undelayed values and makes a delayed -- values. mutual ev : ∀{i n} → Env n → Tm n → Delay Val i ev γ (var x) = now (γ x) ev γ (lam t) = now (clo γ t) ev γ (app t u) = ev γ t >>= λ f → ev γ u >>= λ v → f $$ v _∞$$_ : ∀{i} → Val → Val → ∞Delay Val i force (clo γ t ∞$$ v) = ev (γ << v) t _$$_ : ∀{i} → Val → Val → Delay Val i f $$ v = later (f ∞$$ v) module FusedVals where open import Size mutual data Env (i : Size) : (n : ℕ) → Set where ε : Env i zero _,_ : ∀ {n} (ρ : Env i n) (v : Val i) → Env i (suc n) data Val (i : Size) : Set where lam : forall {n} (t : Tm (suc n)) (ρ : Env i n) → Val i later : (v∞ : ∞Val i) → Val i record ∞Val (i : Size) : Set where coinductive constructor ∞val field vforce : {j : Size< i} → Val j open ∞Val lookup : ∀{i n} -> Env i n -> Fin n -> Val i lookup (ρ , v) zero = v lookup (ρ , v) (suc i) = lookup ρ i tabulate : ∀{i n} -> (Fin n -> Val i) -> Env i n tabulate {n = zero} f = ε tabulate {n = suc n} f = (tabulate {n = n} (f ∘ suc)) , f zero mutual ev : ∀{i n} -> Env i n -> Tm n -> Val i ev ρ (var x) = lookup ρ x ev ρ (lam t) = lam t ρ ev ρ (app t u) = ev ρ t $$ ev ρ u _$$_ : ∀{i} → Val i → Val i → Val i f $$ v = later (f ∞$$ v) _∞$$_ : ∀{i} → Val i → Val i → ∞Val i vforce (lam t ρ ∞$$ v) = ev (ρ , v) t vforce (later p ∞$$ v) = later (vforce p ∞$$ v) {- FRAlg : ∀ {i} -> RAlg TmRMonad FRAlg {i} = ralg (Val i) (ev ∘ tabulate) {!!} {!!} -}
26.497487
68
0.445287
a91bbd7a3e261c2dd8a1acfbcd4350ee9d7fd891
13,427
agda
Agda
agda/Harmony.agda
halfaya/MusicTools
04896c61b603d46011b7d718fcb47dd756e66021
[ "MIT" ]
28
2017-04-21T09:08:52.000Z
2022-03-04T18:04:07.000Z
agda/Harmony.agda
halfaya/MusicTools
04896c61b603d46011b7d718fcb47dd756e66021
[ "MIT" ]
1
2020-11-13T01:26:20.000Z
2020-11-17T00:58:55.000Z
agda/Harmony.agda
halfaya/MusicTools
04896c61b603d46011b7d718fcb47dd756e66021
[ "MIT" ]
3
2019-01-12T17:02:36.000Z
2020-11-10T04:04:40.000Z
{-# OPTIONS --cubical --safe #-} module Harmony where open import Data.Bool using (Bool; true; false; if_then_else_; _∨_; not; _∧_) open import Data.Fin using (#_; toℕ) renaming (zero to fz; suc to fs) open import Data.List using (List; map; []; _∷_; concatMap; foldr; head; zip; null) open import Data.Maybe using (fromMaybe; is-nothing; Maybe; just; nothing) open import Data.Nat using (ℕ; suc; _∸_; _<ᵇ_) open import Data.Nat.DivMod using (_mod_; _div_) open import Data.Product using (_×_; _,_; proj₁; proj₂; uncurry) open import Data.Vec using (Vec; toList; []; _∷_) open import Function using (_∘_) open import BitVec using (BitVec; empty; insert; elements; _∩_; _∈_) open import Counterpoint open import Diatonic using (DiatonicDegree; thirdUp; _≡ᵈ_; degree→PC; major; pitch→DegreeCMajor) open import Interval open import Music open import Note open import Pitch hiding (I) open import Util using (filter; concatMaybe) -- either 0 or 1 pitch class pointToPC : Point → List PC pointToPC (tone p) = pitchToClass p ∷ [] pointToPC (hold p) = pitchToClass p ∷ [] pointToPC rest = [] chordToPCes : {n : ℕ} → Chord n → List PC chordToPCes (chord ps) = concatMap pointToPC (toList ps) pitchClassListToSet : List PC → PCSet pitchClassListToSet = foldr insert empty pitchClassSetToList : PCSet → List PC pitchClassSetToList ps = fn 0 (toList ps) where fn : ℕ → List Bool → List PC fn i [] = [] fn i (false ∷ bs) = fn (suc i) bs fn i (true ∷ bs) = i mod s12 ∷ fn (suc i) bs -- Primary chords, assuming the tonic is pitch class 0. I-maj I-min IV-maj V-maj : PCSet I-maj = pitchClassListToSet (# 0 ∷ # 4 ∷ # 7 ∷ []) I-min = pitchClassListToSet (# 0 ∷ # 3 ∷ # 7 ∷ []) IV-maj = pitchClassListToSet (# 0 ∷ # 5 ∷ # 9 ∷ []) V-maj = pitchClassListToSet (# 2 ∷ # 7 ∷ # 11 ∷ []) -- Triads, without quality data Triad : Set where I : Triad II : Triad III : Triad IV : Triad V : Triad VI : Triad VII : Triad --data Triad : Set where -- I : Triad; II : Triad; III : Triad; IV : Triad; V : Triad; VI : Triad; VII : Triad allTriads : List Triad allTriads = I ∷ II ∷ III ∷ IV ∷ V ∷ VI ∷ VII ∷ [] triadRoot : Triad → DiatonicDegree triadRoot I = (# 0) triadRoot II = (# 1) triadRoot III = (# 2) triadRoot IV = (# 3) triadRoot V = (# 4) triadRoot VI = (# 5) triadRoot VII = (# 6) rootTriad : DiatonicDegree → Triad rootTriad fz = I rootTriad ((fs fz)) = II rootTriad ((fs (fs fz))) = III rootTriad ((fs (fs (fs fz)))) = IV rootTriad ((fs (fs (fs (fs fz))))) = V rootTriad ((fs (fs (fs (fs (fs fz)))))) = VI rootTriad ((fs (fs (fs (fs (fs (fs fz))))))) = VII triadDegrees : Triad → Vec DiatonicDegree 3 triadDegrees t = let root = triadRoot t third = thirdUp root fifth = thirdUp third in root ∷ third ∷ fifth ∷ [] infix 4 _≡ᵗ_ _≡ᵗ_ : Triad → Triad → Bool t ≡ᵗ u = triadRoot t ≡ᵈ triadRoot u TriadSet : Set TriadSet = BitVec s7 triadListToSet : List Triad → TriadSet triadListToSet [] = empty triadListToSet (t ∷ ts) = insert (triadRoot t) (triadListToSet ts) triadSetToList : TriadSet → List Triad triadSetToList ts = map rootTriad (elements ts) containingTriads : DiatonicDegree → List Triad containingTriads fz = I ∷ IV ∷ VI ∷ [] containingTriads ((fs fz)) = II ∷ V ∷ VII ∷ [] containingTriads ((fs (fs fz))) = III ∷ VI ∷ I ∷ [] containingTriads ((fs (fs (fs fz)))) = IV ∷ VII ∷ II ∷ [] containingTriads ((fs (fs (fs (fs fz))))) = V ∷ I ∷ III ∷ [] containingTriads ((fs (fs (fs (fs (fs fz)))))) = VI ∷ II ∷ IV ∷ [] containingTriads ((fs (fs (fs (fs (fs (fs fz))))))) = VII ∷ III ∷ V ∷ [] -- from Table of Usual Root Progressions (Major Mode), Harmony (Piston 5e), page 23 record NextTriad : Set where constructor nextTriad field usual : List Triad sometimes : List Triad rare : List Triad open NextTriad rootProgression : Triad → NextTriad rootProgression I = nextTriad (IV ∷ V ∷ []) (VI ∷ []) (II ∷ III ∷ []) rootProgression II = nextTriad (V ∷ []) (IV ∷ VI ∷ []) (I ∷ III ∷ []) rootProgression III = nextTriad (VI ∷ []) (IV ∷ []) (I ∷ II ∷ V ∷ []) rootProgression IV = nextTriad (V ∷ []) (I ∷ II ∷ []) (III ∷ VI ∷ []) rootProgression V = nextTriad (I ∷ []) (IV ∷ VI ∷ []) (II ∷ III ∷ []) rootProgression VI = nextTriad (II ∷ V ∷ []) (III ∷ IV ∷ []) (I ∷ []) rootProgression VII = nextTriad (I ∷ III ∷ []) (VI ∷ []) (II ∷ IV ∷ V ∷ []) previousTriads : Triad → List Triad previousTriads I = V ∷ IV ∷ VII ∷ [] previousTriads II = VI ∷ IV ∷ [] previousTriads III = VI ∷ VII ∷ [] previousTriads IV = I ∷ V ∷ II ∷ III ∷ [] previousTriads V = I ∷ IV ∷ II ∷ VI ∷ [] previousTriads VI = IV ∷ I ∷ II ∷ V ∷ VII ∷ [] previousTriads VII = [] harmonizations : {n : ℕ} → Vec DiatonicDegree n → List (Vec Triad n) harmonizations [] = [] harmonizations (d ∷ []) = map (_∷ []) (containingTriads d) harmonizations (d ∷ d' ∷ ds) = let tss = harmonizations (d' ∷ ds) dTriads = containingTriads d in concatMap (λ t → concatMaybe (map (prependTriad t) tss)) dTriads where prevOk : Triad → Triad → Bool prevOk t x = (triadRoot t) ∈ triadListToSet (previousTriads x) prependTriad : {n : ℕ} → Triad → Vec Triad (suc n) → Maybe (Vec Triad (suc (suc n))) prependTriad t ts = if prevOk t (Data.Vec.head ts) then just (t ∷ ts) else nothing halfCadence : {n : ℕ} → Vec Triad n → Bool halfCadence [] = false halfCadence (t ∷ []) = t ≡ᵗ V halfCadence (_ ∷ t ∷ ts) = halfCadence (t ∷ ts) -- Given a pitch p and a diatontic degree d, return a pitch that -- has degree d and is 1-2 octaves lower than p. pitchLower : Pitch → DiatonicDegree → Pitch pitchLower p d = let (c , o) = absoluteToRelative p c' = degree→PC major d in relativeToAbsolute (c' , o ∸ 2) -- Given a soporano voice s a pitch and the other voices -- as diatonic degrees of a major scale, voice the -- accompaniment in close position. voiceChord : Pitch → Vec DiatonicDegree 3 → Vec Pitch 3 voiceChord s (a ∷ t ∷ b ∷ []) = let (s' , o) = absoluteToRelative s a' = degree→PC major a t' = degree→PC major t b' = degree→PC major b ao = downOctave a' s' o to = downOctave t' a' ao bo = downOctave b' t' to in relativeToAbsolute (a' , ao) ∷ relativeToAbsolute (t' , to) ∷ relativeToAbsolute (b' , bo) ∷ [] where downOctave : PC → PC → Octave → Octave downOctave pc₁ pc₂ o = if toℕ pc₁ <ᵇ toℕ pc₂ then o else (o ∸ 1) -- Given a soprano pitch p and a triad harmonization t, -- generate a list of possible bass notes. -- Assumes p is in t. Only the root of the triad is -- allowed to be doubled. -- Each bass note is pitched 1-2 octaves below p. bassNotes : Pitch → Triad → List Pitch bassNotes p t = let sop = pitch→DegreeCMajor p root = triadRoot t ds = toList (triadDegrees t) ds' = filter (λ d → (sop ≡ᵈ root) ∨ not (sop ≡ᵈ d)) ds in map (pitchLower p) ds' -- Given a soprano pitch p and a triad harmonization t, -- generate a harmonizing chord in root position. -- Assumes p is in t. Only the root of the triad is -- allowed to be doubled. -- Each bass note is pitched 1-2 octaves below p. -- Alto and Tenor fit inside. -- Currently root or third is preferred for alto. harmonizingChord : Pitch → Triad → Vec Pitch 3 harmonizingChord p t = let sop = pitch→DegreeCMajor p root = triadRoot t third = thirdUp root fifth = thirdUp third alto = if sop ≡ᵈ root then third else root tenor = if sop ≡ᵈ fifth then third else fifth in voiceChord p (alto ∷ tenor ∷ root ∷ []) where remove : DiatonicDegree → Vec DiatonicDegree 3 → Vec DiatonicDegree 2 remove sop (d ∷ d₁ ∷ d₂ ∷ []) = if d ≡ᵈ sop then d₁ ∷ d₂ ∷ [] else (if d₁ ≡ᵈ sop then d ∷ d₂ ∷ [] else d ∷ d₁ ∷ []) -- Create 4 part harmonizations ending in V for a melody in C major. voicedHarmonizations : {n : ℕ} → Vec Pitch n → List (Vec (Vec Pitch 4) n) voicedHarmonizations {n} ps = let ds = Data.Vec.map pitch→DegreeCMajor ps hs : List (Vec Triad n) hs = filter halfCadence (harmonizations ds) in map (λ ts → Data.Vec.map (λ pt → proj₁ pt ∷ harmonizingChord (proj₁ pt) (proj₂ pt)) (Data.Vec.zip ps ts)) hs -- Check interval between each pair of voices. intervalsOkFilter : Vec Pitch 4 → Bool intervalsOkFilter (s ∷ a ∷ t ∷ b ∷ []) = null (concatMaybe (map (intervalCheck ∘ toPitchInterval) -- ((s , a) ∷ (s , t) ∷ (s , b) ∷ (a , t) ∷ (a , b) ∷ (t , b) ∷ []))) ((s , a) ∷ (s , b) ∷ (s , t) ∷ []))) filterIntervalsOk : {n : ℕ} → List (Vec (Vec Pitch 4) n) → List (Vec (Vec Pitch 4) n) filterIntervalsOk xs = let f : List (Vec Pitch 4) → Bool f xs = foldr _∧_ true (map intervalsOkFilter xs) in filter (f ∘ toList) xs motionErrors : {n : ℕ} → Vec (Vec Pitch 4) n → List MotionError motionErrors xs = let ss = Data.Vec.map (Data.Vec.head) xs as = Data.Vec.map (Data.Vec.head ∘ Data.Vec.tail) xs ts = Data.Vec.map (Data.Vec.head ∘ Data.Vec.tail ∘ Data.Vec.tail) xs bs = Data.Vec.map (Data.Vec.head ∘ Data.Vec.tail ∘ Data.Vec.tail ∘ Data.Vec.tail) xs sas = map toPitchInterval (toList (Data.Vec.zip as ss)) sts = map toPitchInterval (toList (Data.Vec.zip ts ss)) sbs = map toPitchInterval (toList (Data.Vec.zip bs ss)) ats = map toPitchInterval (toList (Data.Vec.zip ts as)) abs = map toPitchInterval (toList (Data.Vec.zip bs as)) tbs = map toPitchInterval (toList (Data.Vec.zip bs ts)) in concatMap checkMotion (sas ∷ sts ∷ sbs ∷ ats ∷ abs ∷ tbs ∷ []) --filterSBMotionOk : {n : ℕ} → List (Vec (Vec Pitch 4) n) → List (Vec (Vec Pitch 4) n) --filterSBMotionOk = filter motionOkFilter -- Given a soprano line with harmonization, generate -- a list of possible bass lines 1-1 with soprano notes. -- The SB counterpoint must satisfy 1st species -- interval and motion rules. bassLines : List (Pitch × Triad) → List (List Pitch) -- We need to make the base case a singleton list of an empty list for -- the general case to work. Possibly look into modifying the general -- case to handle a base case of an empty list. bassLines [] = [] ∷ [] bassLines ((sop , triad) ∷ pts) = let pss = bassLines pts basses = bassNotes sop triad intervalOkSBs : List PitchInterval -- list of bass notes with interval (to sop) that pass intervalCheck intervalOkSBs = filter (is-nothing ∘ intervalCheck) (map (toPitchInterval ∘ (_, sop)) basses) intervalOkBs = map proj₁ intervalOkSBs intervalOkBassLines = concatMap (λ ps → (map (_∷ ps) intervalOkBs)) pss in filter (mCheck sop (Data.Maybe.map proj₁ (head pts))) intervalOkBassLines where -- Given a soprano pitch, possibly a second soprano pitch and a list of -- bass pitches, if the second soprano pitch exists and there are at -- least two bass pitches, check that the motion from the first SB pair to -- the second is allowed. If there aren't two SB pairs, return true. mCheck : Pitch → Maybe Pitch → List Pitch → Bool mCheck _ nothing _ = true mCheck _ (just _) [] = true mCheck _ (just _) (_ ∷ []) = true mCheck s₁ (just s₂) (b₁ ∷ b₂ ∷ _) = let sb₁ = toPitchInterval (b₁ , s₁) sb₂ = toPitchInterval (b₂ , s₂) in (is-nothing ∘ uncurry motionCheck) (sb₁ , sb₂) -- Given a soprano line with harmonization, generate -- a list of possible triads 1-1 with soprano notes. -- All pairwise counterpoint must satisfy 1st species -- interval and motion rules. chordProg : List (Pitch × Triad) → List (List Pitch) -- We need to make the base case a singleton list of an empty list for -- the general case to work. Possibly look into modifying the general -- case to handle a base case of an empty list. chordProg [] = [] ∷ [] chordProg ((sop , triad) ∷ pts) = let pss = chordProg pts basses = bassNotes sop triad intervalOkSBs : List PitchInterval -- list of bass notes with interval (to sop) that pass intervalCheck intervalOkSBs = filter (is-nothing ∘ intervalCheck) (map (toPitchInterval ∘ (_, sop)) basses) intervalOkBs = map proj₁ intervalOkSBs intervalOkBassLines = concatMap (λ ps → (map (_∷ ps) intervalOkBs)) pss in filter (mCheck sop (Data.Maybe.map proj₁ (head pts))) intervalOkBassLines where -- Given a soprano pitch, possibly a second soprano pitch and a list of -- bass pitches, if the second soprano pitch exists and there are at -- least two bass pitches, check that the motion from the first SB pair to -- the second is allowed. If there aren't two SB pairs, return true. mCheck : Pitch → Maybe Pitch → List Pitch → Bool mCheck _ nothing _ = true mCheck _ (just _) [] = true mCheck _ (just _) (_ ∷ []) = true mCheck s₁ (just s₂) (b₁ ∷ b₂ ∷ _) = let sb₁ = toPitchInterval (b₁ , s₁) sb₂ = toPitchInterval (b₂ , s₂) in (is-nothing ∘ uncurry motionCheck) (sb₁ , sb₂)
41.313846
109
0.614583
624e711fb414a1e4dfaae95b14744fad7f1fd1bd
457
agda
Agda
src/Syntax/Types.agda
DimaSamoz/temporal-type-systems
7d993ba55e502d5ef8707ca216519012121a08dd
[ "MIT" ]
4
2018-05-31T20:37:04.000Z
2022-01-04T09:33:48.000Z
src/Syntax/Types.agda
DimaSamoz/temporal-type-systems
7d993ba55e502d5ef8707ca216519012121a08dd
[ "MIT" ]
null
null
null
src/Syntax/Types.agda
DimaSamoz/temporal-type-systems
7d993ba55e502d5ef8707ca216519012121a08dd
[ "MIT" ]
null
null
null
{- Type system of the language. -} module Syntax.Types where -- Abstract syntax of types for the language. data Type : Set where -- Unit type Unit : Type -- Product type _&_ : Type -> Type -> Type -- Sum type _+_ : Type -> Type -> Type -- Function type _=>_ : Type -> Type -> Type -- Event type Event : Type -> Type -- Signal type Signal : Type -> Type infixr 65 _=>_ infixl 68 _+_ infixl 70 _&_
20.772727
45
0.568928
ce18b5fd012f3a89ed785f601bfcb34f3c179a33
4,405
agda
Agda
TotalRecognisers/Simple/AlternativeBackend.agda
nad/parser-combinators
76774f54f466cfe943debf2da731074fe0c33644
[ "MIT" ]
1
2020-07-03T08:56:13.000Z
2020-07-03T08:56:13.000Z
TotalRecognisers/Simple/AlternativeBackend.agda
nad/parser-combinators
76774f54f466cfe943debf2da731074fe0c33644
[ "MIT" ]
null
null
null
TotalRecognisers/Simple/AlternativeBackend.agda
nad/parser-combinators
76774f54f466cfe943debf2da731074fe0c33644
[ "MIT" ]
null
null
null
------------------------------------------------------------------------ -- An alternative backend ------------------------------------------------------------------------ -- Acknowledgements: -- -- • The use of parsing "processes" is based on implementation C from -- Koen Claessen's paper Parallel parsing processes. -- -- • The idea to use toProc is due to Jean-Philippe Bernardy. -- It is not obvious how to adapt this backend so that it can handle -- parsers which are simultaneously left and right recursive, like -- TotalRecognisers.LeftRecursion.leftRight. open import Relation.Binary open import Relation.Binary.PropositionalEquality module TotalRecognisers.Simple.AlternativeBackend (Tok : Set) (_≟_ : Decidable (_≡_ {A = Tok})) -- The tokens must come with decidable equality. where open import Codata.Musical.Notation open import Data.Bool hiding (_≟_) open import Data.List open import Relation.Nullary.Decidable import TotalRecognisers.Simple as S open S Tok _≟_ hiding (_∈?_) ------------------------------------------------------------------------ -- Parsing "processes" data Proc : Set where tokenBind : (p : Tok → ∞ Proc) → Proc emptyOr : (p : Proc) → Proc fail : Proc -- The semantics of Proc is given by run: run p s is true iff s is a -- member of the language defined by p. run : Proc → List Tok → Bool run (tokenBind p) (c ∷ s) = run (♭ (p c)) s run (emptyOr p) s = null s ∨ run p s run _ _ = false ------------------------------------------------------------------------ -- Parsers can be turned into processes -- Here I use my technique for "beating the productivity checker". -- Process "programs". infixl 5 _∣_ data ProcP : Set where -- Process primitives. tokenBind : (p : Tok → ∞ ProcP) → ProcP emptyOr : (p : ProcP) → ProcP fail : ProcP -- Symmetric choice. _∣_ : (p₁ p₂ : ProcP) → ProcP -- Embedding of parsers. toProc : ∀ {n} (p : P n) (κ : ProcP) → ProcP -- WHNFs. data ProcW : Set where tokenBind : (p : Tok → ∞ ProcP) → ProcW emptyOr : (p : ProcW) → ProcW fail : ProcW -- WHNFs can be turned into programs. program : ProcW → ProcP program (tokenBind p) = tokenBind p program (emptyOr p) = emptyOr (program p) program fail = fail -- Symmetric choice for WHNFs. _∣W_ : ProcW → ProcW → ProcW tokenBind p₁ ∣W tokenBind p₂ = tokenBind (λ c → ♯ (♭ (p₁ c) ∣ ♭ (p₂ c))) emptyOr p₁ ∣W emptyOr p₂ = emptyOr (p₁ ∣W p₂) emptyOr p₁ ∣W p₂ = emptyOr (p₁ ∣W p₂) p₁ ∣W emptyOr p₂ = emptyOr (p₁ ∣W p₂) fail ∣W p₂ = p₂ p₁ ∣W fail = p₁ -- Interpretation of toProc. mutual toProcW′ : ∀ {n} → P n → if n then ProcW else ProcP → ProcW toProcW′ fail κ = fail toProcW′ empty κ = κ toProcW′ (tok t) κ = tokenBind (λ t′ → if ⌊ t ≟ t′ ⌋ then ♯ κ else ♯ fail) toProcW′ (_∣_ {n₁ = true } {n₂ = true } p₁ p₂) κ = toProcW′ p₁ κ ∣W toProcW′ p₂ κ toProcW′ (_∣_ {n₁ = true } {n₂ = false} p₁ p₂) κ = toProcW′ p₁ κ ∣W toProcW p₂ κ toProcW′ (_∣_ {n₁ = false} {n₂ = true } p₁ p₂) κ = toProcW p₁ κ ∣W toProcW′ p₂ κ toProcW′ (_∣_ {n₁ = false} {n₂ = false} p₁ p₂) κ = toProcW′ p₁ κ ∣W toProcW′ p₂ κ toProcW′ (_·_ {n₁ = true } p₁ p₂) κ = toProcW′ p₁ (toProcW′ p₂ κ) toProcW′ (_·_ {n₁ = false} p₁ p₂) κ = toProcW′ p₁ (toProc (♭ p₂) κ) toProcW : ∀ {n} → P n → ProcW → ProcW toProcW {true } p κ = toProcW′ p κ toProcW {false} p κ = toProcW′ p (program κ) -- Programs can be turned into WHNFs. whnf : ProcP → ProcW whnf (tokenBind p) = tokenBind p whnf (emptyOr p) = emptyOr (whnf p) whnf fail = fail whnf (p₁ ∣ p₂) = whnf p₁ ∣W whnf p₂ whnf (toProc p κ) = toProcW p (whnf κ) -- Programs can be turned into processes. mutual ⟦_⟧W : ProcW → Proc ⟦ tokenBind p ⟧W = tokenBind (λ c → ♯ ⟦ ♭ (p c) ⟧P) ⟦ emptyOr p ⟧W = emptyOr ⟦ p ⟧W ⟦ fail ⟧W = fail ⟦_⟧P : ProcP → Proc ⟦ p ⟧P = ⟦ whnf p ⟧W ------------------------------------------------------------------------ -- Alternative backend -- I have not proved that this implementation is correct. infix 4 _∈?_ _∈?_ : ∀ {n} → List Tok → P n → Bool s ∈? p = run ⟦ toProc p (emptyOr fail) ⟧P s
30.590278
90
0.537117
dcce79f5b28d082ca607724f9b8a42bcf1c83003
4,105
agda
Agda
LibraBFT/Concrete/Records.agda
cwjnkins/bft-consensus-agda
71aa2168e4875ffdeece9ba7472ee3cee5fa9084
[ "UPL-1.0" ]
null
null
null
LibraBFT/Concrete/Records.agda
cwjnkins/bft-consensus-agda
71aa2168e4875ffdeece9ba7472ee3cee5fa9084
[ "UPL-1.0" ]
null
null
null
LibraBFT/Concrete/Records.agda
cwjnkins/bft-consensus-agda
71aa2168e4875ffdeece9ba7472ee3cee5fa9084
[ "UPL-1.0" ]
null
null
null
{- Byzantine Fault Tolerant Consensus Verification in Agda, version 0.9. Copyright (c) 2020, 2021, Oracle and/or its affiliates. Licensed under the Universal Permissive License v 1.0 as shown at https://opensource.oracle.com/licenses/upl -} {-# OPTIONS --allow-unsolved-metas #-} open import Optics.All open import LibraBFT.Prelude open import LibraBFT.Lemmas open import LibraBFT.Base.KVMap open import LibraBFT.Base.PKCS open import LibraBFT.Base.Types open import LibraBFT.Impl.Base.Types open import LibraBFT.Impl.Consensus.Types.EpochIndep open import LibraBFT.Impl.NetworkMsg open import LibraBFT.Impl.Util.Crypto open import LibraBFT.Abstract.Types.EpochConfig UID NodeId open WithAbsVote -- Here we have the abstraction functions that connect -- the datatypes defined in LibraBFT.Impl.Consensus.Types -- to the abstract records from LibraBFT.Abstract.Records -- for a given EpochConfig. -- module LibraBFT.Concrete.Records (𝓔 : EpochConfig) where open import LibraBFT.Impl.Consensus.Types.EpochDep 𝓔 open import LibraBFT.Abstract.Abstract UID _≟UID_ NodeId 𝓔 ConcreteVoteEvidence as Abs hiding (bId; qcVotes; Block) open EpochConfig 𝓔 -------------------------------- -- Abstracting Blocks and QCs -- -------------------------------- α-Block : Block → Abs.Block α-Block b with ₋bdBlockType (₋bBlockData b) ...| NilBlock = record { bId = ₋bId b ; bPrevQC = just (b ^∙ (bBlockData ∙ bdQuorumCert ∙ qcVoteData ∙ vdParent ∙ biId)) ; bRound = b ^∙ bBlockData ∙ bdRound } ...| Genesis = record { bId = b ^∙ bId ; bPrevQC = nothing ; bRound = b ^∙ bBlockData ∙ bdRound } ...| Proposal cmd α = record { bId = b ^∙ bId ; bPrevQC = just (b ^∙ bBlockData ∙ bdQuorumCert ∙ qcVoteData ∙ vdParent ∙ biId) ; bRound = b ^∙ bBlockData ∙ bdRound } α-VoteData-Block : VoteData → Abs.Block α-VoteData-Block vd = record { bId = vd ^∙ vdProposed ∙ biId ; bPrevQC = just (vd ^∙ vdParent ∙ biId) ; bRound = vd ^∙ vdProposed ∙ biRound } α-Vote : (qc : QuorumCert)(valid : MetaIsValidQC qc) → ∀ {as} → as ∈ qcVotes qc → Abs.Vote α-Vote qc v {as} as∈QC = α-ValidVote (rebuildVote qc as) (₋ivvMember (All-lookup (₋ivqcMetaVotesValid v) as∈QC)) -- Abstraction of votes produce votes that carry evidence -- they have been cast. α-Vote-evidence : (qc : QuorumCert)(valid : MetaIsValidQC qc) → ∀{vs} (prf : vs ∈ qcVotes qc) → ConcreteVoteEvidence (α-Vote qc valid prf) α-Vote-evidence qc valid {as} v∈qc = record { ₋cveVote = rebuildVote qc as ; ₋cveIsValidVote = All-lookup (₋ivqcMetaVotesValid valid) v∈qc ; ₋cveIsAbs = refl } α-QC : Σ QuorumCert MetaIsValidQC → Abs.QC α-QC (qc , valid) = record { qCertBlockId = qc ^∙ qcVoteData ∙ vdProposed ∙ biId ; qRound = qc ^∙ qcVoteData ∙ vdProposed ∙ biRound ; qVotes = All-reduce (α-Vote qc valid) All-self ; qVotes-C1 = {! MetaIsValidQC.₋ivqcMetaIsQuorum valid!} ; qVotes-C2 = All-reduce⁺ (α-Vote qc valid) (λ _ → refl) All-self ; qVotes-C3 = All-reduce⁺ (α-Vote qc valid) (λ _ → refl) All-self ; qVotes-C4 = All-reduce⁺ (α-Vote qc valid) (α-Vote-evidence qc valid) All-self } -- What does it mean for an (abstract) Block or QC to be represented in a NetworkMsg? data _α-∈NM_ : Abs.Record → NetworkMsg → Set where qc∈NM : ∀ {cqc q nm} → (valid : MetaIsValidQC cqc) → cqc QC∈NM nm → q ≡ α-QC (cqc , valid) → Abs.Q q α-∈NM nm b∈NM : ∀ {cb pm nm} → nm ≡ P pm → pm ^∙ pmProposal ≡ cb → Abs.B (α-Block cb) α-∈NM nm -- Our system model contains a message pool, which is a list of NodeId-NetworkMsg pairs. The -- following relation expresses that an abstract record r is represented in a given message pool -- sm. data _α-Sent_ (r : Abs.Record) (sm : List (NodeId × NetworkMsg)) : Set where ws : ∀ {p nm} → getEpoch nm ≡ epoch → (p , nm) ∈ sm → r α-∈NM nm → r α-Sent sm
40.643564
116
0.629963
b4180197df4ced117af4888ff59c846ca35ba298
1,485
agda
Agda
test/Succeed/normalise-bug.agda
KDr2/agda
98c9382a59f707c2c97d75919e389fc2a783ac75
[ "BSD-2-Clause" ]
1
2022-03-05T00:25:14.000Z
2022-03-05T00:25:14.000Z
test/Succeed/normalise-bug.agda
Seanpm2001-Agda-lang/agda
b5b3b1657556f720a7310cb7744edb1fac71eaf4
[ "BSD-2-Clause" ]
6
2021-10-18T08:12:24.000Z
2021-11-24T08:31:10.000Z
test/Succeed/normalise-bug.agda
Seanpm2001-Agda-lang/agda
b5b3b1657556f720a7310cb7744edb1fac71eaf4
[ "BSD-2-Clause" ]
null
null
null
open import Agda.Builtin.Reflection renaming (bindTC to _>>=_) open import Agda.Builtin.Sigma open import Agda.Builtin.List open import Agda.Builtin.Unit open import Agda.Builtin.Nat open import Agda.Builtin.Equality infixr 0 _$_ _$_ : ∀ {a b}{A : Set a}{B : Set b} → (A → B) → (A → B) f $ x = f x map : {A B : Set} → (A → B) → List A → List B map f [] = [] map f (x ∷ xs) = f x ∷ map f xs reverseAcc : {A : Set} → List A → List A → List A reverseAcc [] ys = ys reverseAcc (x ∷ xs) ys = reverseAcc xs (x ∷ ys) reverse : {A : Set} → List A → List A reverse xs = reverseAcc xs [] data Vec (A : Set) : Nat → Set where [] : Vec A 0 _∷_ : ∀ {n} (x : A) (xs : Vec A n) → Vec A (suc n) macro ntest : Name → Term → TC ⊤ ntest f a = do (function te@(clause tel _ t ∷ [])) ← withReconstructed $ getDefinition f where _ → typeError $ strErr "ERROR" ∷ [] t ← withReconstructed $ inContext (reverse tel) $ normalise t quoteTC t >>= unify a -- A record with parameters. record X {n} (x : Vec Nat n) : Set where constructor mk field c : Nat -- A function that we will call at the unknown argument position -- when defining the type of `f`. [_] : ∀ {X} → X → Vec X 1 [ x ] = x ∷ [] -- The function that has two reconstructable arguments in the body. f : X [ 1 ] f = mk 1 -- Normalisation of the body of the function should also -- normalise reconstructed arguments. test : ntest f ≡ con (quote mk) (_ ∷ arg _ (con (quote Vec._∷_) _) ∷ _) test = refl
27
84
0.614815
73c441936290d98e0457fa72ca1f6adc2a8b993b
1,777
agda
Agda
code-examples/agda/prelude.agda
mstone/poly
425de958985aacbd3284d3057fe21fd682e315ea
[ "MIT" ]
53
2021-02-18T16:31:04.000Z
2022-03-22T23:08:27.000Z
code-examples/agda/prelude.agda
dspivak/poly
425de958985aacbd3284d3057fe21fd682e315ea
[ "MIT" ]
2
2021-09-02T02:29:39.000Z
2022-01-12T10:06:32.000Z
code-examples/agda/prelude.agda
dspivak/poly
425de958985aacbd3284d3057fe21fd682e315ea
[ "MIT" ]
4
2021-07-10T17:19:37.000Z
2022-01-30T11:45:57.000Z
module prelude where open import Function using (id; _∘_) public open import Data.Sum renaming (inj₁ to Σ₁; inj₂ to Σ₂) using (_⊎_) public open import Data.Product renaming (proj₁ to π₁; proj₂ to π₂) using (Σ; _×_; _,_; ∃; Σ-syntax) public open import Agda.Builtin.Unit using (⊤; tt) public open import Data.Empty using (⊥) public open import Data.Nat as Nat renaming (suc to ℕs; zero to ℕz; _+_ to _ℕ+_) using (ℕ) public open import Relation.Binary.PropositionalEquality.Core as Eq using (_≡_; _≢_; refl; sym; trans; subst) renaming (cong to _⟨$⟩_) public open Eq.≡-Reasoning using (_≡⟨⟩_; step-≡; _∎) public postulate extensionality : {A : Set} {B : A → Set} {f g : (x : A) → B x} → (∀ x → f x ≡ g x) → f ≡ g extensionality2 : {A : Set} {B : A → Set} {C : (x : A) → B x → Set} {f g : (x : A) (y : B x) → C x y } → (∀ x y → f x y ≡ g x y) → f ≡ g extensionality2 λλf≡g = extensionality λ x → extensionality λ y → λλf≡g x y trans-refl : {A : Set} {x y : A} (p : x ≡ y) → trans p refl ≡ p trans-refl p rewrite p = refl subst⋯ : {A : Set} {x y z : A} (P : A → Set) (p : x ≡ y) (q : y ≡ z) (Px : P x) → subst P (trans p q) Px ≡ subst P q (subst P p Px) subst⋯ _ p _ _ rewrite p = refl _×⁼_ : {A X : Set} {a b : A} {x y : X} → a ≡ b → x ≡ y → (a , x) ≡ (b , y) _×⁼_ refl refl = refl _⨄_ : {A B : Set} → (A → Set) → (B → Set) → A ⊎ B → Set (F ⨄ G) (Σ₁ x) = F x (F ⨄ G) (Σ₂ y) = G y _⨃_ _⨉_ : {A B : Set} → (A → Set) → (B → Set) → A × B → Set F ⨃ G = λ (a , b) → F a ⊎ G b F ⨉ G = λ (a , b) → F a × G b _$₁_ : ∀ {A B X : Set} (f : A → B) → A × X → B × X f $₁ (a , x) = f a , x _⁻¹ : {A B : Set} → (A → B) → B → Set _⁻¹ {A} {B} f b = Σ[ a ∈ A ] (f a ≡ b) uncurry : {a b c : Set} → (a → b → c) → (a × b) → c uncurry f (a , b) = f a b
41.325581
134
0.515476
55264e646052e1b60e1c1adfb43d3ded7450bbb9
1,119
agda
Agda
test/asset/agda-stdlib-1.0/Data/Product/Categorical/Right/Base.agda
omega12345/agda-mode
0debb886eb5dbcd38dbeebd04b34cf9d9c5e0e71
[ "MIT" ]
5
2020-10-07T12:07:53.000Z
2020-10-10T21:41:32.000Z
test/asset/agda-stdlib-1.0/Data/Product/Categorical/Right/Base.agda
omega12345/agda-mode
0debb886eb5dbcd38dbeebd04b34cf9d9c5e0e71
[ "MIT" ]
null
null
null
test/asset/agda-stdlib-1.0/Data/Product/Categorical/Right/Base.agda
omega12345/agda-mode
0debb886eb5dbcd38dbeebd04b34cf9d9c5e0e71
[ "MIT" ]
1
2021-11-04T06:54:45.000Z
2021-11-04T06:54:45.000Z
------------------------------------------------------------------------ -- The Agda standard library -- -- Base definitions for the right-biased universe-sensitive functor -- and monad instances for the Product type. -- -- To minimize the universe level of the RawFunctor, we require that -- elements of B are "lifted" to a copy of B at a higher universe level -- (a ⊔ b). See the Data.Product.Categorical.Examples for how this is -- done. ------------------------------------------------------------------------ {-# OPTIONS --without-K --safe #-} open import Level module Data.Product.Categorical.Right.Base {b} (B : Set b) (a : Level) where open import Data.Product using (_×_; map₁; proj₁; proj₂; <_,_>) open import Category.Functor using (RawFunctor) open import Category.Comonad using (RawComonad) ------------------------------------------------------------------------ -- Definitions Productᵣ : Set (a ⊔ b) → Set (a ⊔ b) Productᵣ A = A × B functor : RawFunctor Productᵣ functor = record { _<$>_ = map₁ } comonad : RawComonad Productᵣ comonad = record { extract = proj₁ ; extend = <_, proj₂ > }
29.447368
72
0.563003
17cd2016d9a799b298eea4c2b23dc7876fb5ab1a
126
agda
Agda
agda/Relation/Nullary/Decidable.agda
oisdk/combinatorics-paper
3c176d4690566d81611080e9378f5a178b39b851
[ "MIT" ]
4
2021-01-05T14:07:44.000Z
2021-01-05T15:32:14.000Z
agda/Relation/Nullary/Decidable.agda
oisdk/combinatorics-paper
3c176d4690566d81611080e9378f5a178b39b851
[ "MIT" ]
null
null
null
agda/Relation/Nullary/Decidable.agda
oisdk/combinatorics-paper
3c176d4690566d81611080e9378f5a178b39b851
[ "MIT" ]
1
2021-01-05T14:05:30.000Z
2021-01-05T14:05:30.000Z
{-# OPTIONS --cubical --safe #-} module Relation.Nullary.Decidable where open import Relation.Nullary.Decidable.Base public
21
50
0.769841
2ff86ab0b2115c4e7d15e3a0c47f99fd3c51c488
899
agda
Agda
Setoids/Functions/Lemmas.agda
Smaug123/agdaproofs
0f4230011039092f58f673abcad8fb0652e6b562
[ "MIT" ]
4
2019-08-08T12:44:19.000Z
2022-01-28T06:04:15.000Z
Setoids/Functions/Lemmas.agda
Smaug123/agdaproofs
0f4230011039092f58f673abcad8fb0652e6b562
[ "MIT" ]
14
2019-01-06T21:11:59.000Z
2020-04-11T11:03:39.000Z
Setoids/Functions/Lemmas.agda
Smaug123/agdaproofs
0f4230011039092f58f673abcad8fb0652e6b562
[ "MIT" ]
1
2021-11-29T13:23:07.000Z
2021-11-29T13:23:07.000Z
{-# OPTIONS --safe --warning=error --without-K #-} open import LogicalFormulae open import Agda.Primitive using (Level; lzero; lsuc; _⊔_) open import Setoids.Setoids open import Setoids.Subset open import Setoids.Functions.Definition open import Sets.EquivalenceRelations module Setoids.Functions.Lemmas {a b c d : _} {A : Set a} {B : Set b} {S : Setoid {a} {c} A} {T : Setoid {b} {d} B} {f : A → B} (w : WellDefined S T f) where inverseImagePred : {e : _} → {pred : B → Set e} → (sub : subset T pred) → A → Set (b ⊔ d ⊔ e) inverseImagePred {pred = pred} subset a = Sg B (λ b → (pred b) && (Setoid._∼_ T (f a) b)) inverseImageWellDefined : {e : _} {pred : B → Set e} → (sub : subset T pred) → subset S (inverseImagePred sub) inverseImageWellDefined sub {x} {y} x=y (b , (predB ,, fx=b)) = f x , (sub (symmetric fx=b) predB ,, symmetric (w x=y)) where open Setoid T open Equivalence eq
44.95
157
0.649611
977507fa9b787ee136b0357eb70cd9a4f8c784dd
4,277
agda
Agda
archive/agda-1/New.agda
m0davis/oscar
52e1cdbdee54d9a8eaee04ee518a0d7f61d25afb
[ "RSA-MD" ]
null
null
null
archive/agda-1/New.agda
m0davis/oscar
52e1cdbdee54d9a8eaee04ee518a0d7f61d25afb
[ "RSA-MD" ]
1
2019-04-29T00:35:04.000Z
2019-05-11T23:33:04.000Z
archive/agda-1/New.agda
m0davis/oscar
52e1cdbdee54d9a8eaee04ee518a0d7f61d25afb
[ "RSA-MD" ]
null
null
null
module New where module _ where open import Agda.Primitive record IsBottom {ℓ-⊥} (⊥ : Set ℓ-⊥) ℓ-elim : Set (lsuc ℓ-elim ⊔ ℓ-⊥) where field ⊥-elim : ⊥ → {A : Set ℓ-elim} → A open IsBottom ⦃ … ⦄ public record Bottom ℓ-⊥ ℓ-elim : Set (lsuc (ℓ-elim ⊔ ℓ-⊥)) where field ⊥ : Set ℓ-⊥ instance ⦃ isBottom ⦄ : IsBottom ⊥ ℓ-elim ¬_ : ∀ {a} → Set a → Set (a ⊔ ℓ-⊥) ¬_ p = p → ⊥ open Bottom ⦃ … ⦄ public record IsEquivalence {a} {A : Set a} {ℓ} (_≈_ : A → A → Set ℓ) : Set (a ⊔ ℓ) where field reflexivity : ∀ x → x ≈ x symmetry : ∀ x y → x ≈ y → y ≈ x transitivity : ∀ x y z → x ≈ y → y ≈ z → x ≈ z open IsEquivalence ⦃ … ⦄ public record Equivalence {a} (A : Set a) ℓ : Set (a ⊔ lsuc ℓ) where infix 4 _≈_ field _≈_ : A → A → Set ℓ ⦃ isEquivalence ⦄ : IsEquivalence _≈_ open Equivalence ⦃ … ⦄ public {-# DISPLAY Equivalence._≈_ _ = _≈_ #-} infix 4 _≉_ _≉_ : ∀ {a} {A : Set a} {ℓ} ⦃ _ : Equivalence A ℓ ⦄ {b} ⦃ _ : Bottom b ℓ ⦄ → A → A → Set (b ⊔ ℓ) _≉_ {ℓ = ℓ} x y = ¬ (x ≈ y) record _and_ {ℓ} (A : Set ℓ) (B : Set ℓ) : Set ℓ where field and₁ : A and₂ : B record _NOR_ {ℓ} (A : Set ℓ) (B : Set ℓ) : Set (lsuc ℓ) where field ⦃ bottom ⦄ : Bottom ℓ ℓ nor₁ : A → ⊥ nor₂ : B → ⊥ NOT : ∀ {ℓ} (A : Set ℓ) → Set (lsuc ℓ) NOT A = A NOR A _AND_ : ∀ {ℓ} (A B : Set ℓ) → Set (lsuc (lsuc ℓ)) _AND_ A B = (NOT A) NOR (NOT B) _OR_ : ∀ {ℓ} (A B : Set ℓ) → Set (lsuc (lsuc ℓ)) _OR_ A B = NOT (A NOR B) record Natlike {a} (A : Set a) ℓ b : Set (lsuc (b ⊔ a ⊔ ℓ)) where field zero : A suc : A → A ⦃ equivalence ⦄ : Equivalence A ℓ ⦃ bottom ⦄ : Bottom b ℓ suc-inj : ∀ {x} {y} → suc x ≈ suc y → x ≈ y cong-suc : ∀ {x y} → x ≈ y → suc x ≈ suc y zero≉one : zero ≉ suc zero zero-is-bottommost : ∀ x → suc x ≉ zero break-suc1 : suc zero ≉ suc (suc zero) break-suc1 x = zero≉one (suc-inj x) break-suc : ∀ x → suc x ≉ suc (suc x) break-suc x x₁ = {!suc-inj x₁!} record Isomorphic {a} (A : Set a) ℓᵃ ⦃ _ : Equivalence A ℓᵃ ⦄ {b} (B : Set b) ℓᵇ ⦃ _ : Equivalence B ℓᵇ ⦄ : Set (a ⊔ ℓᵃ ⊔ b ⊔ ℓᵇ) where field toB : A → B toA : B → A isoA : ∀ x → toA (toB x) ≈ x isoB : ∀ x → toB (toA x) ≈ x open import Agda.Builtin.Nat open import Agda.Builtin.Equality instance IsEquivalence≡ : ∀ {a} {A : Set a} → IsEquivalence {a} {A} _≡_ IsEquivalence.reflexivity IsEquivalence≡ x = refl IsEquivalence.symmetry IsEquivalence≡ x .x refl = refl IsEquivalence.transitivity IsEquivalence≡ x .x z refl x₂ = x₂ module _ where open import Prelude using (it) instance EquivalenceNat : Equivalence Nat lzero Equivalence._≈_ EquivalenceNat = _≡_ record NatIso {a} (A : Set a) ℓ : Set (a ⊔ lsuc ℓ) where field ⦃ equivalence ⦄ : Equivalence A ℓ isoNat : Isomorphic A ℓ Nat lzero record Op₂ {a} (A : Set a) : Set a where infixl 6 _∙_ field _∙_ : A → A → A open Op₂ ⦃ … ⦄ public record Op₀ {a} (A : Set a) : Set a where field ε : A open Op₀ ⦃ … ⦄ public record MonoidWithSuc {a} (A : Set a) : Set a where field instance op2 : Op₂ A op0 : Op₀ A ¡ : A → A open MonoidWithSuc ⦃ … ⦄ public private module ZC where private module ASD where open import Prelude.Nat using () instance MonoidWithSucLevel : MonoidWithSuc Level Op₂._∙_ (MonoidWithSuc.op2 MonoidWithSucLevel) = _⊔_ Op₀.ε (MonoidWithSuc.op0 MonoidWithSucLevel) = lzero MonoidWithSuc.¡ MonoidWithSucLevel = lsuc module _ where open import Agda.Builtin.Nat instance MonoidWithSucNat : MonoidWithSuc Nat Op₂._∙_ (MonoidWithSuc.op2 MonoidWithSucNat) = _+_ Op₀.ε (MonoidWithSuc.op0 MonoidWithSucNat) = 0 MonoidWithSuc.¡ MonoidWithSucNat = suc open import Agda.Builtin.Nat open import Agda.Builtin.Equality instance op0fromm : ∀ {a} {A : Set a} ⦃ _ : MonoidWithSuc A ⦄ → Op₀ A op0fromm = op0 module _ where private foo : Nat → Set (¡ ε) foo x = x ∙ x ≡ x → Set bar : 4 ∙ 2 ≡ Nat.suc 5 bar = refl module _ where open import Agda.Primitive infix -65536 ℞_ ℞_ : ∀ ℓ → Set (lsuc ℓ) ℞_ ℓ = Set ℓ module _ where open import Agda.Primitive
24.722543
137
0.564648
9e2b503890a0c64413c1047d9bdf6551d2b3aa46
7,232
agda
Agda
cohomology/FunctionOver.agda
UlrikBuchholtz/HoTT-Agda
f8fa68bf753d64d7f45556ca09d0da7976709afa
[ "MIT" ]
1
2021-06-30T00:17:55.000Z
2021-06-30T00:17:55.000Z
cohomology/FunctionOver.agda
nicolaikraus/HoTT-Agda
939a2d83e090fcc924f69f7dfa5b65b3b79fe633
[ "MIT" ]
null
null
null
cohomology/FunctionOver.agda
nicolaikraus/HoTT-Agda
939a2d83e090fcc924f69f7dfa5b65b3b79fe633
[ "MIT" ]
null
null
null
{-# OPTIONS --without-K #-} open import HoTT {- Useful lemmas for computing the effect of transporting a function - across an equivalence in the domain or codomain. - TODO: find a better place for this. -} module cohomology.FunctionOver where {- transporting a function along an equivalence or path in the domain -} module _ {i} {j} {B : Type i} {C : Type j} (g : B → C) where domain-over-path : {A : Type i} (p : A == B) → g ∘ coe p == g [ (λ D → (D → C)) ↓ p ] domain-over-path idp = idp domain-over-equiv : {A : Type i} (e : A ≃ B) → g ∘ –> e == g [ (λ D → (D → C)) ↓ ua e ] domain-over-equiv e = ↓-app→cst-in $ λ q → ap g (↓-idf-ua-out e q) module _ {i} {j} {A : Type i} {C : Type j} (f : A → C) where domain!-over-path : {B : Type i} (p : A == B) → f == f ∘ coe! p [ (λ D → (D → C)) ↓ p ] domain!-over-path idp = idp domain!-over-equiv : {B : Type i} (e : A ≃ B) → f == f ∘ <– e [ (λ D → (D → C)) ↓ ua e ] domain!-over-equiv e = ↓-app→cst-in $ λ q → ap f (! (<–-inv-l e _) ∙ ap (<– e) (↓-idf-ua-out e q)) {- transporting a ptd function along a equivalence or path in the domain -} module _ {i} {j} {Y : Ptd i} {Z : Ptd j} (g : fst (Y ⊙→ Z)) where domain-over-⊙path : {X : Ptd i} (p : fst X == fst Y) (q : coe p (snd X) == snd Y) → g ⊙∘ (coe p , q) == g [ (λ W → fst (W ⊙→ Z)) ↓ pair= p (↓-idf-in p q) ] domain-over-⊙path idp idp = idp domain-over-⊙equiv : {X : Ptd i} (e : X ⊙≃ Y) → g ⊙∘ ⊙–> e == g [ (λ W → fst (W ⊙→ Z)) ↓ ⊙ua e ] domain-over-⊙equiv {X = X} e = ap (λ w → g ⊙∘ w) (! $ ⊙λ= (coe-β (⊙≃-to-≃ e)) idp) ◃ domain-over-⊙path (ua (⊙≃-to-≃ e)) (coe-β (⊙≃-to-≃ e) (snd X) ∙ snd (⊙–> e)) module _ {i} {j} {X : Ptd i} {Z : Ptd j} (f : fst (X ⊙→ Z)) where domain!-over-⊙path : {Y : Ptd i} (p : fst X == fst Y) (q : coe p (snd X) == snd Y) → f == f ⊙∘ (coe! p , ap (coe! p) (! q) ∙ coe!-inv-l p (snd X)) [ (λ W → fst (W ⊙→ Z)) ↓ pair= p (↓-idf-in p q) ] domain!-over-⊙path idp idp = idp domain!-over-⊙equiv : {Y : Ptd i} (e : X ⊙≃ Y) → f == f ⊙∘ (⊙<– e) [ (λ W → fst (W ⊙→ Z)) ↓ ⊙ua e ] domain!-over-⊙equiv {Y = Y} e = (! (ap (λ w → f ⊙∘ w) (⊙<–-inv-l e)) ∙ ! (⊙∘-assoc f _ (⊙–> e))) ◃ domain-over-⊙equiv (f ⊙∘ (⊙<– e)) e {- transporting a function along an equivalence or path in the codomain -} module _ {i} {j} {A : Type i} {B : Type j} (f : A → B) where codomain-over-path : {C : Type j} (p : B == C) → f == coe p ∘ f [ (λ D → (A → D)) ↓ p ] codomain-over-path idp = idp codomain-over-equiv : {C : Type j} (e : B ≃ C) → f == –> e ∘ f [ (λ D → (A → D)) ↓ ua e ] codomain-over-equiv e = ↓-cst→app-in $ λ _ → ↓-idf-ua-in e idp module _ {i} {j} {A : Type i} {C : Type j} (g : A → C) where codomain!-over-path : {B : Type j} (p : B == C) → coe! p ∘ g == g [ (λ D → (A → D)) ↓ p ] codomain!-over-path idp = idp codomain!-over-equiv : {B : Type j} (e : B ≃ C) → <– e ∘ g == g [ (λ D → (A → D)) ↓ ua e ] codomain!-over-equiv e = ↓-cst→app-in $ λ _ → ↓-idf-ua-in e (<–-inv-r e _) {- transporting a ptd function along a equivalence or path in the codomain -} module _ {i} {j} {X : Ptd i} {Y : Ptd j} (f : fst (X ⊙→ Y)) where codomain-over-⊙path : {Z : Ptd j} (p : fst Y == fst Z) (q : coe p (snd Y) == snd Z) → f == (coe p , q) ⊙∘ f [ (λ W → fst (X ⊙→ W)) ↓ pair= p (↓-idf-in p q) ] codomain-over-⊙path idp idp = pair= idp (! (∙-unit-r _ ∙ ap-idf (snd f))) codomain-over-⊙equiv : {Z : Ptd j} (e : Y ⊙≃ Z) → f == (⊙–> e) ⊙∘ f [ (λ W → fst (X ⊙→ W)) ↓ ⊙ua e ] codomain-over-⊙equiv {Z = Z} e = codomain-over-⊙path (ua (⊙≃-to-≃ e)) (coe-β (⊙≃-to-≃ e) (snd Y) ∙ snd (⊙–> e)) ▹ ap (λ w → w ⊙∘ f) (⊙λ= (coe-β (⊙≃-to-≃ e)) idp) module _ {i} {j} {X : Ptd i} {Z : Ptd j} (g : fst (X ⊙→ Z)) where codomain!-over-⊙path : {Y : Ptd j} (p : fst Y == fst Z) (q : coe p (snd Y) == snd Z) → (coe! p , ap (coe! p) (! q) ∙ coe!-inv-l p (snd Y)) ⊙∘ g == g [ (λ W → fst (X ⊙→ W)) ↓ pair= p (↓-idf-in p q) ] codomain!-over-⊙path idp idp = pair= idp (∙-unit-r _ ∙ ap-idf (snd g)) codomain!-over-⊙equiv : {Y : Ptd j} (e : Y ⊙≃ Z) → (⊙<– e) ⊙∘ g == g [ (λ W → fst (X ⊙→ W)) ↓ ⊙ua e ] codomain!-over-⊙equiv {Y = Y} e = codomain-over-⊙equiv (⊙<– e ⊙∘ g) e ▹ ! (⊙∘-assoc (⊙–> e) _ g) ∙ ap (λ w → w ⊙∘ g) (⊙<–-inv-r e) ∙ ⊙∘-unit-l g module _ {i j} where function-over-paths : {A₁ B₁ : Type i} {A₂ B₂ : Type j} {f : A₁ → A₂} {g : B₁ → B₂} (p₁ : A₁ == B₁) (p₂ : A₂ == B₂) → coe p₂ ∘ f == g ∘ coe p₁ → f == g [ (λ {(A , B) → A → B}) ↓ pair×= p₁ p₂ ] function-over-paths idp idp α = α function-over-equivs : {A₁ B₁ : Type i} {A₂ B₂ : Type j} {f : A₁ → A₂} {g : B₁ → B₂} (e₁ : A₁ ≃ B₁) (e₂ : A₂ ≃ B₂) → –> e₂ ∘ f == g ∘ –> e₁ → f == g [ (λ {(A , B) → A → B}) ↓ pair×= (ua e₁) (ua e₂) ] function-over-equivs {f = f} {g = g} e₁ e₂ α = function-over-paths (ua e₁) (ua e₂) $ transport (λ {(h , k) → h ∘ f == g ∘ k}) (pair×= (! (λ= (coe-β e₂))) (! (λ= (coe-β e₁)))) α {- transporting a group homomorphism along an isomorphism -} domain-over-iso : ∀ {i j} {G H : Group i} {K : Group j} {φ : G →ᴳ H} {ie : is-equiv (GroupHom.f φ)} {ψ : G →ᴳ K} {χ : H →ᴳ K} → GroupHom.f ψ == GroupHom.f χ [ (λ A → A → Group.El K) ↓ ua (GroupHom.f φ , ie) ] → ψ == χ [ (λ J → J →ᴳ K) ↓ group-ua (φ , ie) ] domain-over-iso {K = K} {φ = φ} {ie} {ψ} {χ} p = hom=-↓ _ _ $ ↓-ap-out _ Group.El _ $ transport (λ q → GroupHom.f ψ == GroupHom.f χ [ (λ A → A → Group.El K) ↓ q ]) (! (group-ua-el (φ , ie))) p codomain-over-iso : ∀ {i j} {G : Group i} {H K : Group j} {φ : H →ᴳ K} {ie : is-equiv (GroupHom.f φ)} {ψ : G →ᴳ H} {χ : G →ᴳ K} → GroupHom.f ψ == GroupHom.f χ [ (λ A → Group.El G → A) ↓ ua (GroupHom.f φ , ie) ] → ψ == χ [ (λ J → G →ᴳ J) ↓ group-ua (φ , ie) ] codomain-over-iso {G = G} {φ = φ} {ie} {ψ} {χ} p = hom=-↓ _ _ $ ↓-ap-out _ Group.El _ $ transport (λ q → GroupHom.f ψ == GroupHom.f χ [ (λ A → Group.El G → A) ↓ q ]) (! (group-ua-el (φ , ie))) p hom-over-isos : ∀ {i j} {G₁ H₁ : Group i} {G₂ H₂ : Group j} {φ₁ : G₁ →ᴳ H₁} {ie₁ : is-equiv (GroupHom.f φ₁)} {φ₂ : G₂ →ᴳ H₂} {ie₂ : is-equiv (GroupHom.f φ₂)} {ψ : G₁ →ᴳ G₂} {χ : H₁ →ᴳ H₂} → GroupHom.f ψ == GroupHom.f χ [ (λ {(A , B) → A → B}) ↓ pair×= (ua (GroupHom.f φ₁ , ie₁)) (ua (GroupHom.f φ₂ , ie₂)) ] → ψ == χ [ uncurry _→ᴳ_ ↓ pair×= (group-ua (φ₁ , ie₁)) (group-ua (φ₂ , ie₂)) ] hom-over-isos {φ₁ = φ₁} {ie₁} {φ₂} {ie₂} {ψ} {χ} p = hom=-↓ _ _ $ ↓-ap-out (λ {(A , B) → A → B}) (λ {(G , H) → (Group.El G , Group.El H)}) _ $ transport (λ q → GroupHom.f ψ == GroupHom.f χ [ (λ {(A , B) → A → B}) ↓ q ]) (ap2 (λ p q → pair×= p q) (! (group-ua-el (φ₁ , ie₁))) (! (group-ua-el (φ₂ , ie₂))) ∙ ! (lemma Group.El Group.El (group-ua (φ₁ , ie₁)) (group-ua (φ₂ , ie₂)))) p where lemma : ∀ {i j k l} {A : Type i} {B : Type j} {C : Type k} {D : Type l} (f : A → C) (g : B → D) {x y : A} {w z : B} (p : x == y) (q : w == z) → ap (λ {(a , b) → (f a , g b)}) (pair×= p q) == pair×= (ap f p) (ap g q) lemma f g idp idp = idp
40.629213
80
0.456997
63b4eca2ed51372e95f9128a405b541a556df547
194
als
Alloy
alloy4fun_models/trashltl/models/19/2au7SrHqdwusS6WDq.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trashltl/models/19/2au7SrHqdwusS6WDq.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trashltl/models/19/2au7SrHqdwusS6WDq.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
open main pred id2au7SrHqdwusS6WDq_prop20 { always all p: Protected | always p in Trash } pred __repair { id2au7SrHqdwusS6WDq_prop20 } check __repair { id2au7SrHqdwusS6WDq_prop20 <=> prop20o }
27.714286
57
0.798969
9a4b20f704e29ec795bbe6f527772fe2ceb69ef9
179
als
Alloy
alloy4fun_models/trashltl/models/1/Kgi5TjQRcFYqzaHdo.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trashltl/models/1/Kgi5TjQRcFYqzaHdo.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trashltl/models/1/Kgi5TjQRcFYqzaHdo.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
open main pred idKgi5TjQRcFYqzaHdo_prop2 { all f : File | no f since some f } pred __repair { idKgi5TjQRcFYqzaHdo_prop2 } check __repair { idKgi5TjQRcFYqzaHdo_prop2 <=> prop2o }
25.571429
55
0.776536
19b7daca2fab15bbf31b292dbdf4d35fc71da18a
3,797
als
Alloy
alloy_model/memalloc/size.als
vasil-sd/engineering-sw-hw-model-checking-letures
b6aaa096eb033670a5643cc5ae1d5b63798e38f0
[ "MIT" ]
16
2020-09-08T09:51:28.000Z
2022-01-30T09:07:00.000Z
alloy_model/memalloc/size.als
vasil-sd/engineering-sw-hw-model-checking-letures
b6aaa096eb033670a5643cc5ae1d5b63798e38f0
[ "MIT" ]
null
null
null
alloy_model/memalloc/size.als
vasil-sd/engineering-sw-hw-model-checking-letures
b6aaa096eb033670a5643cc5ae1d5b63798e38f0
[ "MIT" ]
null
null
null
module size open order[Size] as o -- подключаем модуль линейного порядка и параметризуем его сигнатурой 'Size' sig Size { Add: Size -> Size } -- объявляем сигнатуру 'Size' и отношение 'Add' /* Немного про способы задания операций/функций в Alloy (да и в логике тоже). Простые операции, можно определить через выражения, используя 'fun' Но часть бывает удобно определить функцию/операцию через отношение. Например, операция сложения может быть определена как тернарное отношение: 'A + B = C' == 'Sum(A,B,C)', где Sum - это отношение или предикат, который становится истинным, на тех триплетах, которые отвечают уравнению 'A + B = C' В данном случае операция сложения у нас несколько специфическая, поэтому её проще определить через отношение. Ещё напомню, что отношение 'Add' привязано к сигнатуре 'Size', как метод у класса в Java. Поэтому в действительности оно трёхместное, где первый параметр неявный, как this/self у методов класса. То есть, отношение 'Add' на самом деле такое: 'Size -> Size -> Size' Будем считать, что первый два параметра это 'A' и 'B' соответственно, а последний 'C' - результат их сложения. */ --fun zero : one Size { o/first } -- для удобства введём константу 'zero' --fun max : one Size { o/last } -- и 'max' -- вместо функций zero/max лучше сделать дополнительные сигнатуры -- это нужно, чтобы потом на просмотрщике моделей нормально были видны -- 'zero' и 'max' атомы. one sig zero in Size {} {zero = o/first} one sig max in Size {} {max = o/last} -- Для удобства определим функцию 'Sum', чтобы запись сложения была привычнее fun Sum[LHS, RHS: Size] : Size { LHS.Add[RHS] } fun SumAll[S : set Size] : one Size { no S implies zero else #S = 1 implies S else #S = 2 implies S.Sum2 else #S = 3 implies S.Sum3 else #S = 4 implies S.Sum4 else #S = 5 implies S.Sum5 else #S = 6 implies S.Sum6 else #S = 7 implies S.Sum7 else #S = 8 implies S.Sum8 else zero } fun Sum2[S : set Size] : one Size { Sum[S.minimum, S - S.minimum] } fun Sum3[S : set Size] : one Size { Sum[S.minimum, Sum2[S - S.minimum]] } fun Sum4[S : set Size] : one Size { Sum[S.minimum, Sum3[S - S.minimum]] } fun Sum5[S : set Size] : one Size { Sum[S.minimum, Sum4[S - S.minimum]] } fun Sum6[S : set Size] : one Size { Sum[S.minimum, Sum5[S - S.minimum]] } fun Sum7[S : set Size] : one Size { Sum[S.minimum, Sum6[S - S.minimum]] } fun Sum8[S : set Size] : one Size { Sum[S.minimum, Sum7[S - S.minimum]] } example_SumAll: run { some s1,s2,s3 : Size | SumAll[s1+s2] = s3 } for 7 -- теперь свойства нашей операции/отношения -- по аналогии с математической операцией fact { all s1, s2: Size | Sum[s1, s2] = Sum[s2, s1] -- перестановка слагаемых не меняет результат (коммутативность) all s: Size | Sum[zero, s] = s -- ноль является нейтральным элементом all s1, s2, s3: Size | Sum[Sum[s1,s2],s3] = Sum[s1, Sum[s2,s3]] -- ассоциативность } -- а тут более специализированные свойства fact { all s1, s2:Size | lone Sum[s1,s2] -- для любых 'Size' их сумма, если определена, то однозначно all s: Size - zero | no Sum[max, s] -- максимальный ни с каким кроме 'zero' сложить нельзя -- b > c следовательно a + b > a + c для всех a из 'Size' all s1,s2,s3:Size | greater[s2, s3] implies greater[Sum[s1,s2], Sum[s1, s3]] -- а вот это специальное свойство, оно делает отношение максимальным, -- в видеоролике есть более подробные объяснения all s: Size | #Sum[s, Size] = add[#s.all_greater, 1] } -- дополнительный предикат для удобства, проверяет, что в переданном множестве размеров нет нулевого размера pred non_zero[S: set Size] { zero not in S } -- просмотр моделей по 5 элементов 'Size' -- 'Size' всегда будет максимальное количество элементов, которое позволяет -- настройка, так как модуль 'order' у параметра имеет атрибут 'exactly' example: run {} for 5
41.271739
110
0.702133
a8a448f49dfc6df39511954a727e8bcc87f4b3bd
311
als
Alloy
alloy4fun_models/trainstlt/models/13/cEyhPCpFSELFoCwrJ.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trainstlt/models/13/cEyhPCpFSELFoCwrJ.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trainstlt/models/13/cEyhPCpFSELFoCwrJ.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
open main pred idcEyhPCpFSELFoCwrJ_prop14 { always ( all t:Train | eventually (some t.pos and one (t.pos.signal :>Green) and t.pos' !=t. pos and some t.pos' ) implies (t.pos.signal in Signal-Green) ) } pred __repair { idcEyhPCpFSELFoCwrJ_prop14 } check __repair { idcEyhPCpFSELFoCwrJ_prop14 <=> prop14o }
38.875
159
0.733119
13bc49a54758b8ea782cb70dd50fb0a5db506cab
532
als
Alloy
2-a-whirlwind-tour/2-2-dynamics-adding-operations/2.2.3.als
freddiefujiwara/software-abstractions
4f11acc1d947d7bbfb0f25a8c3736fba1eaae458
[ "MIT" ]
null
null
null
2-a-whirlwind-tour/2-2-dynamics-adding-operations/2.2.3.als
freddiefujiwara/software-abstractions
4f11acc1d947d7bbfb0f25a8c3736fba1eaae458
[ "MIT" ]
null
null
null
2-a-whirlwind-tour/2-2-dynamics-adding-operations/2.2.3.als
freddiefujiwara/software-abstractions
4f11acc1d947d7bbfb0f25a8c3736fba1eaae458
[ "MIT" ]
null
null
null
module tour/addressBook1 sig Name, Addr {} sig Book { addr: Name -> lone Addr } pred showAdd (b,b': Book, n: Name, a:Addr){ add [b,b',n,a] #Name.(b.addr) > 1 } pred add (b,b': Book, n: Name, a:Addr){ b'.addr = b.addr + n -> a } pred del (b,b': Book, n: Name){ b'.addr = b.addr - n -> Addr } fun lookup (b: Book, n: Name): set Addr{ n.(b.addr) } assert delUndoesAdd { all b,b',b'' : Book, n: Name , a :Addr | no n.(b.addr) and add[b,b',n,a] and del[b',b'',n] implies b.addr = b''.addr } check delUndoesAdd for 3
20.461538
50
0.569549
efed7ca127329379ec7725b8d957c7a47da4f5cc
187
als
Alloy
alloy4fun_models/trashltl/models/4/W6tLcocdDWrpRLXsE.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trashltl/models/4/W6tLcocdDWrpRLXsE.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trashltl/models/4/W6tLcocdDWrpRLXsE.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
open main pred idW6tLcocdDWrpRLXsE_prop5 { some f : File | eventually f not in File } pred __repair { idW6tLcocdDWrpRLXsE_prop5 } check __repair { idW6tLcocdDWrpRLXsE_prop5 <=> prop5o }
31.166667
55
0.786096
3a6c8c1fab0b5143c06056970601889c61406cbb
232
als
Alloy
alloy4fun_models/trashltl/models/11/hGe8agrkzFKZAErXu.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trashltl/models/11/hGe8agrkzFKZAErXu.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trashltl/models/11/hGe8agrkzFKZAErXu.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
open main pred idhGe8agrkzFKZAErXu_prop12 { eventually some f : File | f in Trash => after (always eventually f not in Trash) } pred __repair { idhGe8agrkzFKZAErXu_prop12 } check __repair { idhGe8agrkzFKZAErXu_prop12 <=> prop12o }
38.666667
83
0.780172
46c00cfeb24cd54fd3fc08336c8b06b3626c73ce
4,600
als
Alloy
models/hol/sygus/let_benchmarks/logcount.als
johnwickerson/alloystar
c673de3f99c97544c4f8bcb8d545b05a7075dde3
[ "BSD-3-Clause" ]
2
2017-01-20T09:48:52.000Z
2021-04-11T19:45:20.000Z
models/hol/sygus/let_benchmarks/logcount.als
johnwickerson/alloystar
c673de3f99c97544c4f8bcb8d545b05a7075dde3
[ "BSD-3-Clause" ]
null
null
null
models/hol/sygus/let_benchmarks/logcount.als
johnwickerson/alloystar
c673de3f99c97544c4f8bcb8d545b05a7075dde3
[ "BSD-3-Clause" ]
3
2016-04-20T16:09:06.000Z
2020-12-04T04:21:15.000Z
module logcount open util/integer as b /** * https://github.com/rishabhs/sygus-comp14/blob/master/benchmarks/let-benchmarks/logcount.sl */ -------------------------------------------------------------------------------- -- AST Nodes -------------------------------------------------------------------------------- abstract sig Node {} abstract sig IntNode extends Node {} abstract sig IntVar extends IntNode {} one sig X1 extends IntVar {} sig ConstBV in Int {} sig ShiftConst in Int {} sig Let extends IntNode { tmp: one Node, m: one ConstBV, n: one ShiftConst } pred semanticsLet[eval: Node->Int, l: Let] { eval[l] = bvadd[bvand[eval[l.tmp], l.m], bvand[bvshr[eval[l.tmp], l.n], l.m]] } pred semantics[eval: Node->Int] { all n: Node | one eval[n] all n: Let | semanticsLet[eval, n] } pred acyclic[r: univ->univ, s: set univ] { all x: s | x !in x.^r } fact { acyclic[tmp, Node] } fun sumBits[x: Int]: Int { bvadd[bvadd[bvadd[bvadd[bvadd[bvadd[bvadd[bveq[bvand[x, 0x01], 0x01] implies 1 else 0, bveq[bvand[x, 0x02], 0x02] implies 1 else 0], bveq[bvand[x, 0x04], 0x04] implies 1 else 0], bveq[bvand[x, 0x08], 0x08] implies 1 else 0], bveq[bvand[x, 0x10], 0x10] implies 1 else 0], bveq[bvand[x, 0x20], 0x20] implies 1 else 0], bveq[bvand[x, 0x40], 0x40] implies 1 else 0], bveq[bvand[x, 0x80], 0x80] implies 1 else 0] } pred synth[countSketch: Node] { all env: IntVar -> one Int { some eval: IntNode->Int when { env in eval semantics[eval] }{ let x1=eval[X1] | sumBits[x1] = eval[countSketch] } } } -------------------------------------------------------------------------------- -- Commands -------------------------------------------------------------------------------- // only necessary constants --> SAT (~10s) run synth for 0 but 8 Int, {bitwidth: 8, atoms: [0x00, 0x55, 0x33, 0x0F, 0x01, 0x02, 0x04]} ConstBV, {bitwidth: 8, atoms: [0x00, 0x55, 0x33, 0x0F, 0x01, 0x02, 0x04]} ShiftConst, exactly 3 Let // larger scope forconstants constants --> SAT (~190s) run synth for 0 but 8 Int, {atoms: 1..100} ConstBV, {atoms: 1..100} ShiftConst, exactly 3 Let // full scope for constants --> SAT // (https://github.com/rishabhs/sygus-comp14/blob/master/benchmarks/let-benchmarks/logcount-d5.sl) run synth for 0 but 8 Int, 8 ConstBV, 8 ShiftConst, exactly 3 Let // full scope for constants with optimization for ShiftConst --> SAT (~190s) run synth for 0 but 8 Int, 8 ConstBV, {atoms: 0..7} ShiftConst, exactly 3 Let // with constants from https://github.com/rishabhs/sygus-comp14/blob/master/benchmarks/let-benchmarks/logcount-d1.sl // --> UNSAT run synth for 0 but 8 Int, {bitwidth: 8, atoms: [0x00, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, 0x01, 0x02, 0x04]} ConstBV, {bitwidth: 8, atoms: [0x00, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, 0x01, 0x02, 0x04]} ShiftConst, exactly 3 Let expect 0 // with constants from https://github.com/rishabhs/sygus-comp14/blob/master/benchmarks/let-benchmarks/logcount.sl // --> UNSAT run synth for 0 but 8 Int, {bitwidth: 8, atoms: [0x00, 0xAA, 0xCC, 0xE0, 0x01, 0x02, 0x04]} ConstBV, {bitwidth: 8, atoms: [0x00, 0xAA, 0xCC, 0xE0, 0x01, 0x02, 0x04]} ShiftConst, exactly 3 Let expect 0 -------------------------------------------------------------------------------- -- Checks for verifying expected/found solutions -------------------------------------------------------------------------------- fun sumBitsExpected[x: Int]: Int { let x = bvadd[bvand[x, 0x55], bvand[bvshr[x, 1], 0x55]] | let x = bvadd[bvand[x, 0x33], bvand[bvshr[x, 2], 0x33]] | let x = bvadd[bvand[x, 0x0F], bvand[bvshr[x, 4], 0x0F]] | x } // fine because the semantics of bvshr in alloy/kodkod is bvshr[x, m] = bvshr[x, m % bitwidth(x)] fun sumBitsFoundByAlloy[x: Int]: Int { let x = bvadd[bvand[x, 0x55], bvand[bvshr[x, 57], 0x55]] | let x = bvadd[bvand[x, 0x33], bvand[bvshr[x, 58], 0x33]] | let x = bvadd[bvand[x, 0x7], bvand[bvshr[x, 68], 0x7]] | x } check checkExpectedSol { all x: Int | sumBits[x] = sumBitsExpected[x] } for 8 Int check checkFoundSol { all x: Int | sumBits[x] = sumBitsFoundByAlloy[x] } for 8 Int
39.316239
157
0.541957
23eabc56d486f9a51e54885d0f90d44598118bc1
124
als
Alloy
models/tests/test64a.als
transclosure/Amalgam
59f7f2d7f518f9e2f4953faf8690c8f6b2bb75c6
[ "MIT" ]
4
2020-10-22T01:11:32.000Z
2022-01-18T16:52:06.000Z
models/tests/test64a.als
transclosure/amalgam
59f7f2d7f518f9e2f4953faf8690c8f6b2bb75c6
[ "MIT" ]
1
2018-05-11T20:57:17.000Z
2018-05-11T20:57:17.000Z
models/tests/test64a.als
transclosure/Amalgam
59f7f2d7f518f9e2f4953faf8690c8f6b2bb75c6
[ "MIT" ]
2
2020-11-12T02:20:31.000Z
2020-11-30T20:48:46.000Z
module tests/test open tests/test64b as b open tests/test64c as c let mac=4 run { this/mac=4 b/mac=5 c/mac=6 } expect 1
17.714286
46
0.709677
f0da2006986843c720714f4bd72d8b1933c42e56
163
als
Alloy
alloy4fun_models/trainstlt/models/2/FAJYgJrWG6wkKkRxd.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trainstlt/models/2/FAJYgJrWG6wkKkRxd.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trainstlt/models/2/FAJYgJrWG6wkKkRxd.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
open main pred idFAJYgJrWG6wkKkRxd_prop3 { always no Train } pred __repair { idFAJYgJrWG6wkKkRxd_prop3 } check __repair { idFAJYgJrWG6wkKkRxd_prop3 <=> prop3o }
23.285714
55
0.803681
4d268edd94b32b49052ee5340f737825f4958410
191
als
Alloy
alloy4fun_models/trashltl/models/4/LsSCZZxLKCfLFyNcw.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trashltl/models/4/LsSCZZxLKCfLFyNcw.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trashltl/models/4/LsSCZZxLKCfLFyNcw.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
open main pred idLsSCZZxLKCfLFyNcw_prop5 { eventually (some f : File | File' = File - f) } pred __repair { idLsSCZZxLKCfLFyNcw_prop5 } check __repair { idLsSCZZxLKCfLFyNcw_prop5 <=> prop5o }
31.833333
55
0.764398
48a3f9bd4af68498c0290c6e338be321c305ed7e
180
als
Alloy
alloy4fun_models/trashltl/models/10/WK9Qo2oGbrWDosq6t.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trashltl/models/10/WK9Qo2oGbrWDosq6t.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
alloy4fun_models/trashltl/models/10/WK9Qo2oGbrWDosq6t.als
Kaixi26/org.alloytools.alloy
1671f0f6ff1a1449f71b0ba0b725afbcaf8020c4
[ "Apache-2.0" ]
null
null
null
open main pred idWK9Qo2oGbrWDosq6t_prop11 { Protected + Trash = Protected' } pred __repair { idWK9Qo2oGbrWDosq6t_prop11 } check __repair { idWK9Qo2oGbrWDosq6t_prop11 <=> prop11o }
30
57
0.805556
dab37f4d0ca0fb838b6e0af72ddcd8a38463c2f3
447
vhost
ApacheConf
config/example.vhost
jamesacampbell/fugitive
0b4e8bbd4871046c6969849c27932225882176e9
[ "MIT" ]
2
2017-10-03T15:48:16.000Z
2020-09-11T05:06:18.000Z
config/example.vhost
jamesacampbell/fugitive
0b4e8bbd4871046c6969849c27932225882176e9
[ "MIT" ]
5
2017-09-24T20:50:27.000Z
2017-12-12T13:19:09.000Z
config/example.vhost
jamesacampbell/fugitive
0b4e8bbd4871046c6969849c27932225882176e9
[ "MIT" ]
null
null
null
server { listen 80 default_server; listen [::]:80 default_server; root /path to repo /public/; index index.php index.html index.htm index.nginx-debian.html; server_name server_domain_or_IP; location / { try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.0-fpm.sock; } location ~ /\.ht { deny all; } }
19.434783
65
0.597315
85edd5e87a83cfb6fb92a01f2175e67385f73b59
61
applescript
AppleScript
Classes/text/as text/text as POSIX file/test.applescript
looking-for-a-job/applescript-examples
071248da8f00862b17530a014d8fd004a0ed329a
[ "Unlicense" ]
1
2021-03-15T22:07:49.000Z
2021-03-15T22:07:49.000Z
Classes/text/as text/text as POSIX file/test.applescript
andrewp-as-is/applescript-examples
071248da8f00862b17530a014d8fd004a0ed329a
[ "Unlicense" ]
null
null
null
Classes/text/as text/text as POSIX file/test.applescript
andrewp-as-is/applescript-examples
071248da8f00862b17530a014d8fd004a0ed329a
[ "Unlicense" ]
null
null
null
#!/usr/bin/osascript "/Users/user/.gitignore" as POSIX file
15.25
38
0.721311
433509bcb3b448aed5b3f3843b59463c9e0dacdd
59
applescript
AppleScript
Task/Pick-random-element/AppleScript/pick-random-element.applescript
LaudateCorpus1/RosettaCodeData
9ad63ea473a958506c041077f1d810c0c7c8c18d
[ "Info-ZIP" ]
1
2021-05-05T13:42:20.000Z
2021-05-05T13:42:20.000Z
Task/Pick-random-element/AppleScript/pick-random-element.applescript
seanwallawalla-forks/RosettaCodeData
9ad63ea473a958506c041077f1d810c0c7c8c18d
[ "Info-ZIP" ]
null
null
null
Task/Pick-random-element/AppleScript/pick-random-element.applescript
seanwallawalla-forks/RosettaCodeData
9ad63ea473a958506c041077f1d810c0c7c8c18d
[ "Info-ZIP" ]
null
null
null
get some item of [1, "two", pi, "4", 5 > 4, 5 + 1, Sunday]
29.5
58
0.508475
2fea0c76141cdb8040d86533b674d201fd7c2809
2,756
applescript
AppleScript
images_treatment_photoshop_imagemagick_docker/good_photoshop_test_15_demo.applescript
bflaven/BlogArticlesExamples
5df2dfc26170ffbbade78ba136bf3172391e3b2a
[ "MIT" ]
5
2018-05-03T08:16:02.000Z
2021-09-04T03:44:24.000Z
images_treatment_photoshop_imagemagick_docker/good_photoshop_test_15_demo.applescript
bflaven/BlogArticlesExamples
5df2dfc26170ffbbade78ba136bf3172391e3b2a
[ "MIT" ]
1
2022-01-28T19:27:19.000Z
2022-01-28T19:27:19.000Z
images_treatment_photoshop_imagemagick_docker/good_photoshop_test_15_demo.applescript
bflaven/BlogArticlesExamples
5df2dfc26170ffbbade78ba136bf3172391e3b2a
[ "MIT" ]
2
2020-09-10T13:33:27.000Z
2022-02-09T11:07:38.000Z
(* Made for ZNBC (https://znbc.com) to process images in batch with photoshop *) (* Description: Description: You have to create a script in Photoshop then all the files presented in the source folder will be proceeded with actions you have made in the script and be saved in the destination folder. For the moment the photoshop script executed is "resize_60_percent_solar_apply" from a directory named "bruno". ! CAUTION ! - Name for script and directory in Photoshop are case-sensitive. - Do not register a save action and close action in your Photoshop script. Version: 1.1 Author: Bruno Flaven Author URI: http://flaven.fr *) -- This chooses the master folder where all your sub folders with images are stored say "Choose your source Folder for this batch job" using "Victoria" set raw_folder to choose folder -- This chooses the destination folder where all your result images are stored say "Choose your destination Folder for the processed files" using "Victoria" set live_folder to choose folder -- This checks when the batch started and stores the date value set startTime to time of (current date) (* for actions *) -- This the file counter set fileCounter to 0 tell application "Finder" set itemList to files in raw_folder end tell repeat with j from 1 to (number of itemList) set fileCounter to fileCounter + 1 end repeat (* for fileCounter *) (* for fileCounter *) --source and destination folders for the images tell application "Finder" set imageSet to get every file of folder raw_folder end tell tell application "Finder" repeat with i from 1 to (count of imageSet) -- coerce Finder style path to string set currentImg to (item i of imageSet) as string tell application "Adobe Photoshop CS6" -- no dialog box set display dialogs to never activate open alias currentImg set currentImg to current document -- tell current document -- choose your action in the folder, caution the naming is case sensitive (* The script name is "resize_50_percent_demo" from the directory "demo" from the Actions tabs inside Adobe Photoshop CS6 *) do action "resize_to_60_percent_good" from "demo_1" -- close the file in photoshop after the job is done close every document without saving end tell end repeat (* for actions *) set endTime to time of (current date) (* end *) say "The job is done, please have a look to the destination folder. The operation took " & endTime - startTime & " seconds. The directory contains " & fileCounter & " files." using "Victoria" (* Dialog box if needed *) -- display dialog "nThe operation took " & endTime - startTime & " seconds" & ".nThe directory contains " & fileCounter & " files.n" end tell
30.285714
329
0.738026
de8fb0b39cffd04bd12900c71d7c8381493a08ff
386
applescript
AppleScript
scripts/spotify-read-info.applescript
epochblue/annoy-a-tron
5542431551c3edaeb3185110f9dfdf0d935a3a74
[ "Unlicense" ]
63
2015-04-14T17:56:33.000Z
2021-12-27T20:04:38.000Z
scripts/spotify-read-info.applescript
epochblue/annoy-a-tron
5542431551c3edaeb3185110f9dfdf0d935a3a74
[ "Unlicense" ]
6
2015-04-17T17:09:08.000Z
2017-01-31T02:59:43.000Z
scripts/spotify-read-info.applescript
epochblue/annoy-a-tron
5542431551c3edaeb3185110f9dfdf0d935a3a74
[ "Unlicense" ]
12
2015-04-16T22:06:09.000Z
2021-06-02T17:23:01.000Z
#!/usr/bin/env osascript tell application "Spotify" set playerState to player state as string if (playerState is equal to "playing") then set currentTrack to name of current track as string set currentArtist to artist of current track as string pause say "now playing: " & currentTrack & " by " & currentArtist play end if end tell
27.571429
67
0.668394
d3a137debbe8ac6ba4d27d2c723000f2641af3bc
519
applescript
AppleScript
VPN Autoconnect/VPN Autoconnect/NullVPNService.applescript
agorskih/vpn-autoconnect
8e9c41057f175493663d5ff02988de243e8be264
[ "MIT" ]
1
2020-02-15T03:40:33.000Z
2020-02-15T03:40:33.000Z
VPN Autoconnect/VPN Autoconnect/NullVPNService.applescript
agorskih/vpn-autoconnect
8e9c41057f175493663d5ff02988de243e8be264
[ "MIT" ]
null
null
null
VPN Autoconnect/VPN Autoconnect/NullVPNService.applescript
agorskih/vpn-autoconnect
8e9c41057f175493663d5ff02988de243e8be264
[ "MIT" ]
null
null
null
-- -- NullVPNService.applescript -- Null VPN service -- -- Created by Alexander Gorskih on 25.09.13. -- Copyright (c) 2013 Alexander Gorskih. All rights reserved. -- MIT-style copyright and disclaimer apply script NullVPNService property parent : class "VPNService" property identifier : "" -- Public methods: on autoconnected() return false end to enable() display alert "No connection selected." end to disable() -- do nothing end end script
19.222222
62
0.647399
f04454c0d105714450f906c48fb3df565f71b735
161
applescript
AppleScript
Task/Conditional-structures/AppleScript/conditional-structures.applescript
mullikine/RosettaCodeData
4f0027c6ce83daa36118ee8b67915a13cd23ab67
[ "Info-ZIP" ]
1
2018-11-09T22:08:38.000Z
2018-11-09T22:08:38.000Z
Task/Conditional-structures/AppleScript/conditional-structures.applescript
seanwallawalla-forks/RosettaCodeData
9ad63ea473a958506c041077f1d810c0c7c8c18d
[ "Info-ZIP" ]
null
null
null
Task/Conditional-structures/AppleScript/conditional-structures.applescript
seanwallawalla-forks/RosettaCodeData
9ad63ea473a958506c041077f1d810c0c7c8c18d
[ "Info-ZIP" ]
1
2018-11-09T22:08:40.000Z
2018-11-09T22:08:40.000Z
if myVar is "ok" then return true set i to 0 if i is 0 then return "zero" else if i mod 2 is 0 then return "even" else return "odd" end if
14.636364
33
0.608696
c209b786c16160dcc50abf61e76389d3a0a403e4
57
applescript
AppleScript
paste.applescript
simon-johansson/menubar-faker
d39c750f6c362af56e2800e8eda673e97e3f6fc0
[ "MIT" ]
2
2015-09-15T12:06:03.000Z
2015-09-17T11:50:15.000Z
paste.applescript
simon-johansson/menubar-faker
d39c750f6c362af56e2800e8eda673e97e3f6fc0
[ "MIT" ]
null
null
null
paste.applescript
simon-johansson/menubar-faker
d39c750f6c362af56e2800e8eda673e97e3f6fc0
[ "MIT" ]
null
null
null
tell application "System Events" keystroke "v" end tell
14.25
32
0.77193
1a7eb542cddae49c1a15b91e0f112874ae364b5f
103
applescript
AppleScript
Applications/Brave Browser/url.applescript
looking-for-a-job/applescript-examples
071248da8f00862b17530a014d8fd004a0ed329a
[ "Unlicense" ]
1
2021-03-15T22:07:49.000Z
2021-03-15T22:07:49.000Z
Applications/Brave Browser/url.applescript
andrewp-as-is/applescript-examples
071248da8f00862b17530a014d8fd004a0ed329a
[ "Unlicense" ]
null
null
null
Applications/Brave Browser/url.applescript
andrewp-as-is/applescript-examples
071248da8f00862b17530a014d8fd004a0ed329a
[ "Unlicense" ]
null
null
null
#!/usr/bin/env osascript tell application "Brave Browser" to return URL of active tab of front window
25.75
76
0.776699
cc28ed6ffca3d66808d5df7e265c0afeb7169d2a
128
applescript
AppleScript
Applications/Google-Chrome/window/front tab/front tab.applescript
looking-for-a-job/applescript-examples
071248da8f00862b17530a014d8fd004a0ed329a
[ "Unlicense" ]
1
2021-03-15T22:07:49.000Z
2021-03-15T22:07:49.000Z
Applications/Google-Chrome/window/front tab/front tab.applescript
andrewp-as-is/applescript-examples
071248da8f00862b17530a014d8fd004a0ed329a
[ "Unlicense" ]
null
null
null
Applications/Google-Chrome/window/front tab/front tab.applescript
andrewp-as-is/applescript-examples
071248da8f00862b17530a014d8fd004a0ed329a
[ "Unlicense" ]
null
null
null
#!/usr/bin/osascript tell application "Google Chrome" if count of windows is not 0 then front tab of (front window) end tell
18.285714
62
0.75
9577c5aac68b6223b08ee062988a309e70590f43
501
applescript
AppleScript
code_sender/chrome/chrome-jupyter.applescript
fredcallaway/SendCode
3d34f58c45bbf4c885e07a52010f7c80dac3325a
[ "MIT" ]
177
2017-04-10T11:29:14.000Z
2022-02-22T10:19:20.000Z
code_sender/chrome/chrome-jupyter.applescript
fredcallaway/SendCode
3d34f58c45bbf4c885e07a52010f7c80dac3325a
[ "MIT" ]
136
2017-04-03T18:25:04.000Z
2022-02-07T16:46:45.000Z
code_sender/chrome/chrome-jupyter.applescript
fredcallaway/SendCode
3d34f58c45bbf4c885e07a52010f7c80dac3325a
[ "MIT" ]
27
2017-04-18T18:29:49.000Z
2022-02-26T20:12:23.000Z
on run argv tell application "Google Chrome" set URL of front window's active tab to "javascript:{" & " var mycell = IPython.notebook.get_selected_cell(); mycell.set_text(\"" & item 1 of argv & "\"); mycell.execute(); var nextcell = IPython.notebook.insert_cell_below(); IPython.notebook.select_next(); IPython.notebook.scroll_to_cell(IPython.notebook.find_cell_index(nextcell)); " & "}" end tell end run
38.538462
88
0.608782
1c978828d372584cf02bcdb319806e83bded2457
162
applescript
AppleScript
mac/jm.applescript
tBoccinfuso/AvariavsLauncher
839560cb845a4b8ca3d407608a24d32593bf6d63
[ "MIT" ]
null
null
null
mac/jm.applescript
tBoccinfuso/AvariavsLauncher
839560cb845a4b8ca3d407608a24d32593bf6d63
[ "MIT" ]
null
null
null
mac/jm.applescript
tBoccinfuso/AvariavsLauncher
839560cb845a4b8ca3d407608a24d32593bf6d63
[ "MIT" ]
null
null
null
tell application "Safari" tell window 1 set current tab to (make new tab with properties {URL:"https://juncturemedia.com/"}) end tell end tell
32.4
93
0.67284
493ffc385d8022ca5cc5bab3b56c65e66a3abfdb
88
arc
Arc
src/list.arc
awwx/amacx
53ffbd7a729597f396bee13ccf70704a5f92b31a
[ "MIT" ]
3
2019-01-04T14:41:33.000Z
2022-03-05T22:30:37.000Z
src/list.arc
awwx/amacx
53ffbd7a729597f396bee13ccf70704a5f92b31a
[ "MIT" ]
1
2019-01-26T22:38:10.000Z
2019-01-26T22:38:10.000Z
src/list.arc
awwx/amacx
53ffbd7a729597f396bee13ccf70704a5f92b31a
[ "MIT" ]
1
2019-01-26T21:37:17.000Z
2019-01-26T21:37:17.000Z
(use arcboot named-fn) ; (def list args args) (assign list (named-fn list args args))
14.666667
39
0.693182
61f3c65a03fe08aefd11af3ced44c3031c3c0dcd
233
arc
Arc
day04p2.arc
knarka/aoc2021
fa540c6728f280a50f00a53a1106dee3361e8586
[ "MIT" ]
null
null
null
day04p2.arc
knarka/aoc2021
fa540c6728f280a50f00a53a1106dee3361e8586
[ "MIT" ]
null
null
null
day04p2.arc
knarka/aoc2021
fa540c6728f280a50f00a53a1106dee3361e8586
[ "MIT" ]
null
null
null
(load "day04p1.arc") (def play-bingo () (while (len> cards 0) (draw-number) (each card cards (awhen (is-winner card) (= winning-card card) (= winning-seq it) (pull card cards)))) (calculate-score winning-card))
19.416667
32
0.622318
32b818b0e046853806e241687bed6272b8c60cc5
541
arc
Arc
buildroot/arch/arch.mk.arc
bramkragten/operating-system
27fc2de146f1ef047316a4b58a236c72d26da81c
[ "Apache-2.0" ]
349
2021-08-17T08:46:53.000Z
2022-03-30T06:25:25.000Z
buildroot/arch/arch.mk.arc
bramkragten/operating-system
27fc2de146f1ef047316a4b58a236c72d26da81c
[ "Apache-2.0" ]
8
2020-04-02T22:51:47.000Z
2020-04-27T03:24:55.000Z
buildroot/arch/arch.mk.arc
bramkragten/operating-system
27fc2de146f1ef047316a4b58a236c72d26da81c
[ "Apache-2.0" ]
12
2021-08-17T20:10:30.000Z
2022-01-06T10:52:54.000Z
ifeq ($(BR2_arc),y) # -matomic is always required when the ARC core has the atomic extensions ifeq ($(BR2_ARC_ATOMIC_EXT),y) ARCH_TOOLCHAIN_WRAPPER_OPTS = -matomic endif # Explicitly set LD's "max-page-size" instead of relying on some defaults ifeq ($(BR2_ARC_PAGE_SIZE_4K),y) ARCH_TOOLCHAIN_WRAPPER_OPTS += -Wl,-z,max-page-size=4096 else ifeq ($(BR2_ARC_PAGE_SIZE_8K),y) ARCH_TOOLCHAIN_WRAPPER_OPTS += -Wl,-z,max-page-size=8192 else ifeq ($(BR2_ARC_PAGE_SIZE_16K),y) ARCH_TOOLCHAIN_WRAPPER_OPTS += -Wl,-z,max-page-size=16384 endif endif
30.055556
73
0.77634
59078c436a59f1db227c6563b84527275608c144
2,751
arc
Arc
src/Applications/NCEP_Etc/NCEP_enkf/scripts/gmao/etc/atmens_storage.arc
GEOS-ESM/GEOSadas
8e3665af71eb37c48573c65ed0e9daa5ca429535
[ "NASA-1.3", "Apache-2.0" ]
2
2019-09-07T09:00:32.000Z
2021-03-12T02:25:56.000Z
src/Applications/NCEP_Etc/NCEP_enkf/scripts/gmao/etc/atmens_storage.arc
GEOS-ESM/GEOSadas
8e3665af71eb37c48573c65ed0e9daa5ca429535
[ "NASA-1.3", "Apache-2.0" ]
81
2019-07-05T19:28:50.000Z
2022-03-04T19:37:47.000Z
src/Applications/NCEP_Etc/NCEP_enkf/scripts/gmao/etc/atmens_storage.arc
GEOS-ESM/GEOSadas
8e3665af71eb37c48573c65ed0e9daa5ca429535
[ "NASA-1.3", "Apache-2.0" ]
null
null
null
# # Archiving rules for fvDAS output. # # This is a PESTO (Put Experiment in Mass Storage) resource file. # # The environment variable PESTOROOT refers to the destination archive # location, e.g., # # a) for moving files to SILO: # setenv PESTOROOT '/scratch/johndoe' # # b) for moving files to MASS STORAGE: # setenv PESTOROOT 'johndoe@machine.nas.nasa.gov:' # # This file has been automatically generated by fvsetup. #........................................................................... # # --------------------------- # Atmospheric Ensemble # --------------------------- # ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_ebkg.%y4%m2%d2_%h2z.tar.gz ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_ecbkg.%y4%m2%d2_%h2z.tar.gz ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_erst.%y4%m2%d2_%h2z.tar.gz ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_fstat.%y4%m2%d2_%h2z.tar.gz ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_stat.%y4%m2%d2_%h2z.tar.gz ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_olog.%y4%m2%d2_%c%c%c.tar.gz ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_zeit.log.%y4%m2%d2_%c%c%c.txt ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atm_enkf.log.%y4%m2%d2_%c%c%c.txt ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.rndperts.dates.%y4%m2%d2_%c%c%c.txt ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.add_infl.%y4%m2%d2_%c%c%c.txt # ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_osens.%y4%m2%d2_%c%c%c.bin ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_osens.%y4%m2%d2_%c%c%c.ods # ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_eana_arec.%y4%m2%d2_%h2z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_eana_brec.%y4%m2%d2_%h2z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_easm.%y4%m2%d2_21z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_ebkg.%y4%m2%d2_%h2z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_ecbkg.%y4%m2%d2_%h2z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_eana.%y4%m2%d2_%h2z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_eniana.%y4%m2%d2_%h2z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_eaaer.%y4%m2%d2_%h2z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_ebaer.%y4%m2%d2_%h2z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_edia.%y4%m2%d2_%h2z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_eoi0.%y4%m2%d2_%h2z.tar #${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_eprg.%y4%m2%d2_21z.tar #${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_eprg.%y4%m2%d2_15z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_erst.%y4%m2%d2_21z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_evtk.%y4%m2%d2_%h2z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_fstat.%y4%m2%d2_%h2z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_stat.%y4%m2%d2_%h2z.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_olog.%y4%m2%d2_%c%c%c.tar ${PESTOROOT}%s/atmens/Y%y4/M%m2/%s.atmens_etrj.%y4%m2%d2_%h2z.tar #
47.431034
76
0.661941
28c15ffa5fa691ab6a59b599841cdf4f42bf7dcf
3,464
ino
Arduino
Loadout/UATV/UATV.ino
nitinsonker78/PATENT
d3798a5e119921ebef68a742bc24d164e929f5ea
[ "Unlicense" ]
null
null
null
Loadout/UATV/UATV.ino
nitinsonker78/PATENT
d3798a5e119921ebef68a742bc24d164e929f5ea
[ "Unlicense" ]
null
null
null
Loadout/UATV/UATV.ino
nitinsonker78/PATENT
d3798a5e119921ebef68a742bc24d164e929f5ea
[ "Unlicense" ]
null
null
null
#include "Remote.h" #include "Servo.h" #include "Servomotor.h" #include "conversion.h" #include "control_param.h" #define MODE 11 #define DXL_BUS_SERIAL1 1 Servo servo1; Servo servo2; Servo servo3; Servo servo4; Dynamixel Dxl(DXL_BUS_SERIAL1); int ID[] = {1, 2, 3, 4, 5, 6}; void setup() { Dxl.begin(3); Dxl.setPacketType(DXL_PACKET_TYPE2); delay(1000); pinMode(rcPin1, INPUT); pinMode(rcPin2, INPUT); pinMode(rcPin3, INPUT); pinMode(rcPin4, INPUT); pinMode(rcPin5, INPUT); pinMode(rcPin6, INPUT); //Set all motors to wheel mode int i=1; while(i<7) { Dxl.wheelMode(i); i++; } delay(1000); servo1.attach(s1); servo2.attach(s2); servo3.attach(s3); servo4.attach(s4); } void loop() { // put your main code here, to run repeatedly: } //Servo void Servo_close() { int i = servo1.read(); for(angle1 = 180; angle1>=1; angle1-=1) // goes from 180 degrees to 0 degrees { servo1.write(angle1);// tell servo to go to position in variable 'pos' delay(5); // waits 15ms for the servo to reach the position } i = servo2.read(); for(angle2 = 180; angle2>=1; angle2-=1) // goes from 180 degrees to 0 degrees { servo2.write(angle2);// tell servo to go to position in variable 'pos' delay(5); // waits 15ms for the servo to reach the position } i = servo3.read(); for(angle3 = 180; angle3>=1; angle3-=1) // goes from 180 degrees to 0 degrees { servo3.write(angle3);// tell servo to go to position in variable 'pos' delay(5); // waits 15ms for the servo to reach the position } i = servo4.read(); for(angle4 = 180; angle4>=1; angle4-=1) // goes from 180 degrees to 0 degrees { servo4.write(angle4);// tell servo to go to position in variable 'pos' delay(5); // waits 15ms for the servo to reach the position } } void Servo_open() { int i = servo1.read(); for(angle1 = i; angle1 < 180; angle1 += 1) // goes from 0 degrees to 180 degrees { // in steps of 1 degree servo1.write(angle1);// tell servo to go to position in variable 'pos' delay(5); // waits 15ms for the servo to reach the position } i = servo2.read(); for(angle2 = i; angle2 < 180; angle2 += 1) // goes from 0 degrees to 180 degrees { // in steps of 1 degree servo2.write(angle2);// tell servo to go to position in variable 'pos' delay(5); // waits 15ms for the servo to reach the position } i = servo3.read(); for(angle3 = i; angle3 < 180; angle3 += 1) { // in steps of 1 degree servo3.write(angle3);// tell servo to go to position in variable 'pos' delay(5); } i = servo4.read(); for(angle4 = i; angle4 < 180; angle4 += 1) { // in steps of 1 degree servo4.write(angle4);// tell servo to go to position in variable 'pos' delay(5); } }
30.121739
109
0.517032
bf84f5c697a5b9fbbd1bf1a0b9325c5fca080e84
349
ino
Arduino
src/array_demo/array_demo.ino
BackToTech-Study/ArduinoReadWriteSerial
7c5529a6a50b7a0c108eaf5211647bc551a7f145
[ "MIT" ]
null
null
null
src/array_demo/array_demo.ino
BackToTech-Study/ArduinoReadWriteSerial
7c5529a6a50b7a0c108eaf5211647bc551a7f145
[ "MIT" ]
null
null
null
src/array_demo/array_demo.ino
BackToTech-Study/ArduinoReadWriteSerial
7c5529a6a50b7a0c108eaf5211647bc551a7f145
[ "MIT" ]
null
null
null
#include "MainMenu.h" void setup() { // put your setup code here, to run once: Serial.begin(SerialSpeed); Serial.setTimeout(SerialReadTimeout); } void loop() { // put your main code here, to run repeatedly: int selectedOptionIndex = getMainMenuSelection(); Serial.print("You selected option: "); showOption(selectedOptionIndex); }
20.529412
51
0.716332
b69488aa47d99d28d52c5b442b6cd7ff5b5af31d
881
ino
Arduino
Alarme_de_Incendio.ino
arduinoomega/ebook-arduino-avancado
74a82798f766e68d671226089c7993d9aa3669b7
[ "MIT" ]
null
null
null
Alarme_de_Incendio.ino
arduinoomega/ebook-arduino-avancado
74a82798f766e68d671226089c7993d9aa3669b7
[ "MIT" ]
null
null
null
Alarme_de_Incendio.ino
arduinoomega/ebook-arduino-avancado
74a82798f766e68d671226089c7993d9aa3669b7
[ "MIT" ]
null
null
null
int sensorA = A9; // Pino analógico do sensor na porta A9 int sensorD = 4; // Pino digital do sensor na porta Digital 4 int buzzer = 3; // Buzzer na porta 3 int led = 2; // LED na porta 2 int analogico; int digital; void setup() { // Definindo componentes como entradas ou saída pinMode(sensorA, INPUT); pinMode(sensorD, INPUT); pinMode(led, OUTPUT); pinMode(buzzer, OUTPUT); } void loop() { digital = digitalRead(sensorD); // lendo pino digital do sensor analogico = analogRead(sensorA); // lendo pino analógico do sensor if (digital == 0){ // Se o Sensor detectar fumaça ou gás digitalWrite(buzzer, HIGH); // Buzzer emite som digitalWrite(led, HIGH); // LED acende }else{ // Se não digitalWrite(buzzer, LOW); // Buzzer permanece desligado digitalWrite(led, LOW); // LED permanece desligado delay(500); } }
25.911765
68
0.662883
d064ab90629fc8a92e3fb26b311af84c80d6f670
1,114
ino
Arduino
BUCLE_FOR.ino
ItsMonxxu/Arduino
6faff3613ed1199cf224edfae7fc7f9de6f4b095
[ "MIT" ]
null
null
null
BUCLE_FOR.ino
ItsMonxxu/Arduino
6faff3613ed1199cf224edfae7fc7f9de6f4b095
[ "MIT" ]
null
null
null
BUCLE_FOR.ino
ItsMonxxu/Arduino
6faff3613ed1199cf224edfae7fc7f9de6f4b095
[ "MIT" ]
null
null
null
int switchState = 0; //variables globales const int redPin = 2; const int bluePin = 6; const int buttonPin = 4; void setup() { // put your setup code here, to run once: //Iniciando leds pinMode(redPin, OUTPUT); pinMode(bluePin, OUTPUT); //Ininiando botón pinMode(buttonPin, INPUT); } void loop() { //leer el estado del botón switchState = digitalRead(buttonPin); // esto es un comentario if (switchState == LOW){ //el botón no esta pulsadeo digitalWrite(redPin,HIGH); //se enciende el rojo digitalWrite(bluePin,LOW); //se apaga el azul } else { //elsa let it go //pulsamos el botón //el botón esta pulsado //se enciende el rojo for(int blinks = 0; blinks <100; blinks++) { digitalWrite(bluePin,HIGH); //se enciende el azul delay(250); digitalWrite(redPin,LOW); // apagar el rojo delay(250); //espera medio segundo digitalWrite(bluePin,LOW); //se apaga el azul delay(250); digitalWrite(redPin,HIGH); //encender el rojo delay(250); //espera medio segundo } //lave del for } //llave del else } //vuelve al inicio del bucle (llave del loop)
22.28
53
0.675045
364a7a89736ebf83fbcd3331cd62b33ea35b7951
1,634
ino
Arduino
lib/ESP8266Audio-master/examples/PlayMP3FromSPIFFS/PlayMP3FromSPIFFS.ino
ChSt98/KraftPad
2f1d60893ded6d0f079e8067980016992a72794b
[ "BSD-3-Clause" ]
null
null
null
lib/ESP8266Audio-master/examples/PlayMP3FromSPIFFS/PlayMP3FromSPIFFS.ino
ChSt98/KraftPad
2f1d60893ded6d0f079e8067980016992a72794b
[ "BSD-3-Clause" ]
null
null
null
lib/ESP8266Audio-master/examples/PlayMP3FromSPIFFS/PlayMP3FromSPIFFS.ino
ChSt98/KraftPad
2f1d60893ded6d0f079e8067980016992a72794b
[ "BSD-3-Clause" ]
null
null
null
#include <Arduino.h> #ifdef ESP32 #include <WiFi.h> #include "SPIFFS.h" #else #include <ESP8266WiFi.h> #endif #include "AudioFileSourceSPIFFS.h" #include "AudioFileSourceID3.h" #include "AudioGeneratorMP3.h" #include "AudioOutputI2SNoDAC.h" // To run, set your ESP8266 build to 160MHz, and include a SPIFFS of 512KB or greater. // Use the "Tools->ESP8266/ESP32 Sketch Data Upload" menu to write the MP3 to SPIFFS // Then upload the sketch normally. // pno_cs from https://ccrma.stanford.edu/~jos/pasp/Sound_Examples.html AudioGeneratorMP3 *mp3; AudioFileSourceSPIFFS *file; AudioOutputI2SNoDAC *out; AudioFileSourceID3 *id3; // Called when a metadata event occurs (i.e. an ID3 tag, an ICY block, etc. void MDCallback(void *cbData, const char *type, bool isUnicode, const char *string) { (void)cbData; Serial.printf("ID3 callback for: %s = '", type); if (isUnicode) { string += 2; } while (*string) { char a = *(string++); if (isUnicode) { string++; } Serial.printf("%c", a); } Serial.printf("'\n"); Serial.flush(); } void setup() { WiFi.mode(WIFI_OFF); Serial.begin(115200); delay(1000); SPIFFS.begin(); Serial.printf("Sample MP3 playback begins...\n"); audioLogger = &Serial; file = new AudioFileSourceSPIFFS("/pno-cs.mp3"); id3 = new AudioFileSourceID3(file); id3->RegisterMetadataCB(MDCallback, (void*)"ID3TAG"); out = new AudioOutputI2SNoDAC(); mp3 = new AudioGeneratorMP3(); mp3->begin(id3, out); } void loop() { if (mp3->isRunning()) { if (!mp3->loop()) mp3->stop(); } else { Serial.printf("MP3 done\n"); delay(1000); } }
22.383562
86
0.668911
767ca69d96df1710f9f308203861736c9a02e2c1
2,411
ino
Arduino
examples/qtmatrix-text/qtmatrix-text.ino
apendley/Adafruit_IS31FL3741
1c3b67df3e595b0d57b9dabe526558b6076d05af
[ "MIT" ]
8
2021-10-04T16:29:30.000Z
2022-03-19T22:43:02.000Z
examples/qtmatrix-text/qtmatrix-text.ino
apendley/Adafruit_IS31FL3741
1c3b67df3e595b0d57b9dabe526558b6076d05af
[ "MIT" ]
4
2021-09-26T03:22:43.000Z
2021-12-27T15:16:19.000Z
examples/qtmatrix-text/qtmatrix-text.ino
apendley/Adafruit_IS31FL3741
1c3b67df3e595b0d57b9dabe526558b6076d05af
[ "MIT" ]
3
2021-09-26T03:03:33.000Z
2022-02-28T09:11:27.000Z
// Scrolling text example for the Adafruit IS31FL3741 13x9 PWM RGB LED // Matrix Driver w/STEMMA QT / Qwiic connector. This is the simplest // version and should fit on small microcontrollers like Arduino Uno. // Tradeoff is that animation isn't always as smooth as seen in the // buffered example. Each LED changes state immediately when accessed, // there is no show() or display() function as with NeoPixels or some // OLED screens. #include <Adafruit_IS31FL3741.h> Adafruit_IS31FL3741_QT matrix; // If colors appear wrong on matrix, try invoking constructor like so: // Adafruit_IS31FL3741_QT matrix(IS3741_RBG); // Some boards have just one I2C interface, but some have more... TwoWire *i2c = &Wire; // e.g. change this to &Wire1 for QT Py RP2040 char text[] = "ADAFRUIT!"; // A message to scroll int text_x = matrix.width(); // Initial text position = off right edge int text_y = 1; int text_min; // Pos. where text resets (calc'd later) void setup() { Serial.begin(115200); Serial.println("Adafruit QT RGB Matrix Scrolling Text Test"); if (! matrix.begin(IS3741_ADDR_DEFAULT, i2c)) { Serial.println("IS41 not found"); while (1); } Serial.println("IS41 found!"); // By default the LED controller communicates over I2C at 400 KHz. // Arduino Uno can usually do 800 KHz, and 32-bit microcontrollers 1 MHz. i2c->setClock(800000); // Set brightness to max and bring controller out of shutdown state matrix.setLEDscaling(0xFF); matrix.setGlobalCurrent(0xFF); Serial.print("Global current set to: "); Serial.println(matrix.getGlobalCurrent()); matrix.fill(0); matrix.enable(true); // bring out of shutdown matrix.setRotation(0); matrix.setTextWrap(false); // Get text dimensions to determine X coord where scrolling resets uint16_t w, h; int16_t ignore; matrix.getTextBounds(text, 0, 0, &ignore, &ignore, &w, &h); text_min = -w; // Off left edge this many pixels } void loop() { matrix.setCursor(text_x, text_y); for (int i = 0; i < (int)strlen(text); i++) { // set the color thru the rainbow uint32_t color888 = matrix.ColorHSV(65536 * i / strlen(text)); uint16_t color565 = matrix.color565(color888); matrix.setTextColor(color565, 0); // backound is '0' to erase previous text! matrix.print(text[i]); // write the letter } if (--text_x < text_min) { text_x = matrix.width(); } delay(25); }
33.486111
80
0.702613
92b8c069a80f70d7e6208fc39de5250cdc76d9ff
1,931
ino
Arduino
Software/struct-to-flash/struct-to-flash.ino
rckTom/RTVC
96407f1f2c4f2b3cf24f826ed614b1dbbf9f45df
[ "MIT" ]
8
2018-11-25T20:45:27.000Z
2021-11-07T11:37:51.000Z
Software/struct-to-flash/struct-to-flash.ino
rckTom/RTVC
96407f1f2c4f2b3cf24f826ed614b1dbbf9f45df
[ "MIT" ]
null
null
null
Software/struct-to-flash/struct-to-flash.ino
rckTom/RTVC
96407f1f2c4f2b3cf24f826ed614b1dbbf9f45df
[ "MIT" ]
2
2018-12-08T03:40:06.000Z
2021-06-22T10:55:02.000Z
#include <SPI.h> #include "DataFlash.h" static const int csPin = 10; static const int resetPin = 8; static const int wpPin = 7; DataFlash dataflash; struct State { float qw; float qx; float qy; float qz; float dx; float dz; float ux; float uz; }; void setup() { Serial.begin(115200); Serial.println(sizeof(State)); SPI.begin(); dataflash.setup(csPin, resetPin, wpPin); Serial.println("Dataflash set up"); dataflash.begin(); Serial.println("Dataflash started"); State state = { 0.865, 0.501, 0.328, 0.761, -0.321, 0.086, 12.3, -3.2 }; State emptyState = { 0, 0, 0, 0, 0, 0, 0, 0 }; byte* p = (byte*) &state; byte* e = (byte*) &emptyState; Serial.println(emptyState.qw); Serial.println(emptyState.qx); Serial.println(emptyState.qy); Serial.println(emptyState.qz); Serial.println(emptyState.dx); Serial.println(emptyState.dz); Serial.println(emptyState.ux); Serial.println(emptyState.uz); Serial.println("State variables and pointer initialized"); long start = micros(); dataflash.bufferWrite(1, 0); for(int i = 0; i < sizeof(State); i++) { SPI.transfer(*p++); } dataflash.bufferToPage(1, 3); long end = micros(); long duration = end - start; Serial.print("Duration of bufferWrite, transfer and bufferToPage operations: "); Serial.println(duration); dataflash.pageToBuffer(3, 2); dataflash.bufferRead(2, 0); for(int i = 0; i < sizeof(State); i++) { uint8_t data = SPI.transfer(0xff); *e = data; e++; Serial.print(data); Serial.print(" "); } Serial.println(); Serial.println(emptyState.qw); Serial.println(emptyState.qx); Serial.println(emptyState.qy); Serial.println(emptyState.qz); Serial.println(emptyState.dx); Serial.println(emptyState.dz); Serial.println(emptyState.ux); Serial.println(emptyState.uz); SPI.end(); } void loop() { // put your main code here, to run repeatedly: }
22.453488
82
0.660798
d0f31d16417b86d98b3a3448b8b6586baa5b33c0
5,426
ino
Arduino
Watt_5V_GLCD_Clock.ino
morlac/GLCD_Clock
3a2d846b3d6dd44e821fdc6b07f3cdfcc0594d71
[ "MIT" ]
null
null
null
Watt_5V_GLCD_Clock.ino
morlac/GLCD_Clock
3a2d846b3d6dd44e821fdc6b07f3cdfcc0594d71
[ "MIT" ]
null
null
null
Watt_5V_GLCD_Clock.ino
morlac/GLCD_Clock
3a2d846b3d6dd44e821fdc6b07f3cdfcc0594d71
[ "MIT" ]
null
null
null
//#define DEBUG #include <avr/sleep.h> #include <avr/power.h> #include <avr/eeprom.h> #include <avr/io.h> #include <avr/pgmspace.h> // Workaround for http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734 #ifdef PROGMEM #undef PROGMEM #define PROGMEM __attribute__((section(".progmem.data"))) #endif #include <openGLCD.h> // openGLCD library #include <Wire.h> #include <Time.h> #include <DS1307RTC.h> #include "DHT.h" #define DHTPIN 3 #define DHTPOWER 2 #define DHTTYPE DHT22 int16_t TimeZone; uint16_t TimeZoneAddr = 1; // for voltage-measurement #define voltage_pin A7 #define voltage_r1 1003000.0 #define voltage_r2 102500.0 #define resistorFactor (1023.0 * (voltage_r2 / (voltage_r1 + voltage_r2))) / 1.0 DHT dht(DHTPIN, DHTTYPE); static time_t prevtime; float h, t, vbat, temp; #define LED_MAX_COUNT 1 uint8_t led_count = 0; bool led_on = false; void DHT_on() { digitalWrite(DHTPOWER, HIGH); pinMode(DHTPIN, INPUT_PULLUP); } void DHT_off() { digitalWrite(DHTPOWER, LOW); pinMode(DHTPIN, OUTPUT); digitalWrite(DHTPIN, LOW); } void LED_on() { digitalWrite(13, HIGH); led_on = true; #ifdef DEBUG Serial.println("LED on"); #endif } void LED_off() { digitalWrite(13, LOW); led_on = false; #ifdef DEBUG Serial.println("LED off"); #endif } void setup() { pinMode(13, OUTPUT); digitalWrite(13, LOW); pinMode(A6, OUTPUT); digitalWrite(A6, LOW); /* // is only run once for first EEPROM-init while (!eeprom_is_ready()); eeprom_write_word((uint16_t*)TimeZoneAddr, 7200); */ Serial.begin(9600); setSyncProvider(RTC.get); // the function to get the time from the RTC /* if (timeStatus() != timeSet) { RTC.set(DateTime(__DATE__, __TIME__)); } */ GLCD.Init(); // initialize the display analogReference(INTERNAL); pinMode(voltage_pin, INPUT); vbat = analogRead(voltage_pin) / resistorFactor;// * 1.1; pinMode(DHTPOWER, OUTPUT); DHT_on(); dht.begin(); h = dht.readHumidity(); t = dht.readTemperature(); DHT_off(); power_adc_disable(); // we ned Analog-Digital-Converter for Voltage-Check .. but not all the time .. power_spi_disable(); power_timer1_disable(); power_timer2_disable(); pinMode(voltage_pin, OUTPUT); digitalWrite(voltage_pin, LOW); } void loop() { time_t current_time; char buf[12]; char dht_str[6]; uint8_t s; if (Serial.available()) { processSyncMessage(); } if (prevtime != now()) { // if 1 second has gone by, update display prevtime = now(); s = second(); while (!eeprom_is_ready()); TimeZone = eeprom_read_word((uint16_t*)TimeZoneAddr); current_time = prevtime + TimeZone; #ifdef DEBUG Serial.print(F("T1: ")); snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hour(current_time), minute(), s); Serial.println(buf); #endif current_time += IsDst(hour(current_time), day(current_time), month(current_time), weekday(current_time)) ? 60 * 60 : 0; GLCD.SelectFont(lcdnums12x16); snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hour(current_time), minute(), s); #ifdef DEBUG Serial.print(F("T2: ")); Serial.println(buf); #endif GLCD.DrawString(buf, gTextfmt_center, gTextfmt_row(0)); snprintf(buf, sizeof(buf), "%04d-%02d-%02d", year(current_time), month(current_time), day(current_time)); // #ifdef DEBUG // Serial.println(buf); // #endif GLCD.DrawString(buf, gTextfmt_center, gTextfmt_row(1)); GLCD.DrawString(F(" "), gTextfmt_center, gTextfmt_row(2)); GLCD.DrawString(ftoa(dht_str, h, 1), gTextfmt_center, gTextfmt_row(2)); GLCD.DrawString(F(" "), gTextfmt_center, gTextfmt_row(3)); GLCD.DrawString(ftoa(dht_str, t, 1), gTextfmt_center, gTextfmt_row(3)); GLCD.SelectFont(utf8font10x16); GLCD.DrawString(F("Hum:"), gTextfmt_left, gTextfmt_row(2)); GLCD.DrawString(F("% Rh"), gTextfmt_col(8), gTextfmt_row(2)); GLCD.DrawString(F("Temp:"), gTextfmt_left, gTextfmt_row(3)); GLCD.DrawString(F("* C"), gTextfmt_col(8), gTextfmt_row(3)); GLCD.SelectFont(Wendy3x5); GLCD.DrawString(F(" "), gTextfmt_right, gTextfmt_bottom); GLCD.DrawString(ftoa(dht_str, vbat, 3), gTextfmt_right, gTextfmt_bottom); // swith LED if ((s % 10 == 0) && (led_count == 0)) { LED_on(); } } led_count += (led_count < LED_MAX_COUNT) && led_on ? 1 : 0; if (led_count >= LED_MAX_COUNT) { LED_off(); led_count = 0; } if (s == 57) { // if (s == 7 | s == 17 | s == 27 | s == 37 | s == 47 | s == 57) { #ifdef DEBUG Serial.println("turning on DHT11 & ADC"); #endif DHT_on(); power_adc_enable(); pinMode(voltage_pin, INPUT); } if (s == 0) { // if (s % 10 == 0) { #ifdef DEBUG Serial.println("measuring"); #endif temp = dht.readHumidity(); h = isnan(temp) ? h : temp; temp = dht.readTemperature(); t = isnan(temp) ? t : temp; analogReference(INTERNAL); vbat = analogRead(voltage_pin) / resistorFactor * 1.1; #ifdef DEBUG Serial.print("s : "); Serial.println(s); Serial.print("h : "); Serial.println(h); Serial.print("t : "); Serial.println(t); Serial.print("vbat: "); Serial.println(vbat); #endif #ifdef DEBUG Serial.println("turning off DHT & ADC"); #endif DHT_off(); power_adc_disable(); pinMode(voltage_pin, OUTPUT); digitalWrite(voltage_pin, LOW); } else { delay(250); } }
22.146939
123
0.645042
073466c94083f6390f7e156d12c394a6643bb04c
2,425
ino
Arduino
examples/DummyPressureSensor/DummyPressureSensor.ino
107-systems/107-Arduino-Sensor
826ce3fbe816972716cf95607aa5b8d7a4157f60
[ "MIT" ]
null
null
null
examples/DummyPressureSensor/DummyPressureSensor.ino
107-systems/107-Arduino-Sensor
826ce3fbe816972716cf95607aa5b8d7a4157f60
[ "MIT" ]
null
null
null
examples/DummyPressureSensor/DummyPressureSensor.ino
107-systems/107-Arduino-Sensor
826ce3fbe816972716cf95607aa5b8d7a4157f60
[ "MIT" ]
1
2021-09-06T07:15:11.000Z
2021-09-06T07:15:11.000Z
/** * @brief This example demonstrates the basic usage of this library by creating a fake (dummy) pressure sensor. * @author Alexander Entinger, MSc / LXRobotics GmbH */ /************************************************************************************** * INCLUDE **************************************************************************************/ #include <107-Arduino-Sensor.hpp> /************************************************************************************** * CLASS DECLARATION **************************************************************************************/ class DummyPressureSensor : public drone::PressureSensorBase { public: DummyPressureSensor() : drone::PressureSensorBase("BMP388", 0.0 * drone::unit::pascal, 1000.0 * drone::unit::pascal, 25.0 * drone::unit::hertz, [](drone::unit::Pressure const pressure) { Serial.print("[ASYNC] p = "); Serial.print(pressure.value()); Serial.println(" Pascal"); }) { } virtual ~DummyPressureSensor() { } virtual void get(drone::unit::Pressure & val) override { val = drone::unit::Pressure(1023.0 * drone::unit::pascal); } void onExternalEvent() { /* Retrieve value from sensor. */ drone::unit::Pressure const latest_sensor_val = drone::unit::Pressure(65.8 * drone::unit::pascal); /* Invoke callback function. */ onSensorValueUpdate(latest_sensor_val); } }; /************************************************************************************** * GLOBAL VARIABLES **************************************************************************************/ DummyPressureSensor pressure_sensor; /************************************************************************************** * SETUP/LOOP **************************************************************************************/ void setup() { Serial.begin(9600); while (!Serial) { } Serial.println(pressure_sensor); drone::unit::Pressure pressure_val = 0.0 * drone::unit::pascal; Serial.print("[SYNC] p = "); Serial.print(pressure_val.value()); Serial.println(" Pascal"); Serial.println(); pressure_sensor.onExternalEvent(); } void loop() { }
31.493506
119
0.40866
a90a0b9ccc59cc5725ecfe75a60555e0b4ac6a75
3,116
ino
Arduino
wcpaddapp_wifi/wcpaddapp_wifi.ino
jamr123/wcpaddapp
b4d4d15f426b9efc67efacca0b39583de2b995eb
[ "MIT" ]
null
null
null
wcpaddapp_wifi/wcpaddapp_wifi.ino
jamr123/wcpaddapp
b4d4d15f426b9efc67efacca0b39583de2b995eb
[ "MIT" ]
null
null
null
wcpaddapp_wifi/wcpaddapp_wifi.ino
jamr123/wcpaddapp
b4d4d15f426b9efc67efacca0b39583de2b995eb
[ "MIT" ]
null
null
null
#include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266HTTPClient.h> #include <SoftwareSerial.h> #include <TinyGPS.h> TinyGPS gps; SoftwareSerial ss(5, 4); int ledRed = 14; int boton = 12; int valBoton = 1; unsigned long time1 = 0; unsigned long time2 = 0; unsigned long time3 = 0; float flat, flon; unsigned long age; void setup() { Serial.begin(9600); ss.begin(9600); pinMode(ledRed, OUTPUT); pinMode(boton, INPUT_PULLUP); resetWifi(); time1 = millis(); time2 = millis(); } void loop() { valBoton = digitalRead(boton); // read input value if (valBoton == LOW) { // check if the input is HIGH (button released) delay(50); valBoton = digitalRead(boton); // read input value if (valBoton == LOW) { // check if the input is HIGH (button released) resetWifi(); } } if ( millis() > (time1 + 1000)) { getGps(); time1 = millis(); } if ( millis() > (time2 + 15000)) { if (WiFi.status() == WL_CONNECTED) { http_post(); } else { Serial.println("Error in WiFi connection"); } time2 = millis(); } } void http_post() { HTTPClient http; http.begin("http://www.wcpaddapp.com/arduino/report2.php"); http.addHeader("Content-Type", "application/x-www-form-urlencoded"); int httpCode = http.POST("lat=" + String(flat) + "&lng=" + String(flon) + "&device_id=0002"); String payload = http.getString(); Serial.println(httpCode); //Print HTTP return code Serial.println(payload); //Print request response payload http.end(); int e=0; String req = getValue(payload, ',', 0); if (req != "ok") { e++; if (e == 3) { e = 0; resetWifi(); } } } void getGps() { bool newData = false; unsigned long chars; unsigned short sentences, failed; // For one second we parse GPS data and report some key values for (unsigned long start = millis(); millis() - start < 1000;) { while (ss.available()) { char c = ss.read(); if (gps.encode(c)) newData = true; } } if (newData) { gps.f_get_position(&flat, &flon, &age); flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flat, 6; flon == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flon, 6; Serial.println(flat); Serial.println(flon); } } void resetWifi() { digitalWrite(ledRed, HIGH); WiFi.mode(WIFI_STA); WiFi.begin("TP-LINK_7F84", "95056258"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } digitalWrite(ledRed, LOW); Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } String getValue(String data, char separator, int index) { int found = 0; int strIndex[] = {0, -1}; int maxIndex = data.length() - 1; for (int i = 0; i <= maxIndex && found <= index; i++) { if (data.charAt(i) == separator || i == maxIndex) { found++; strIndex[0] = strIndex[1] + 1; strIndex[1] = (i == maxIndex) ? i + 1 : i; } } return found > index ? data.substring(strIndex[0], strIndex[1]) : ""; }
18.884848
95
0.597882
e9cc49cec03dea3ccd089870e88c4486a0669725
1,199
ino
Arduino
libraries/ArbotiX/examples/tests/MXSimpleTest/MXSimpleTest.ino
bouraqadi/ArbotiX-M
6056a8086f0d2ad67909c1433d7544fc02d435d1
[ "MIT" ]
1
2019-11-14T11:49:20.000Z
2019-11-14T11:49:20.000Z
libraries/ArbotiX/examples/tests/MXSimpleTest/MXSimpleTest.ino
bouraqadi/ArbotiX-M
6056a8086f0d2ad67909c1433d7544fc02d435d1
[ "MIT" ]
null
null
null
libraries/ArbotiX/examples/tests/MXSimpleTest/MXSimpleTest.ino
bouraqadi/ArbotiX-M
6056a8086f0d2ad67909c1433d7544fc02d435d1
[ "MIT" ]
1
2021-09-14T01:49:30.000Z
2021-09-14T01:49:30.000Z
/*************************** * AXSimpleTest * This sketch sends positional commands to the AX servo * attached to it - the servo must set to ID # 1 * The sketch will send a value, i, to the servo. * 'For' loops are used to increment and decrement the value of 'i' ***************************/ //import ax12 library to send DYNAMIXEL commands #include <ax12.h> const int SERVO_ID = 1; //servo id to control void setup() { dxlInit(57600); //start the DYNAMIXEL chain at 57600, the defualt baud for MX servos. set to 1mbps if you have changed the servo baus //dxlInit(1000000); //start the DYNAMIXEL chain at SetPosition(SERVO_ID,0); //set the position of servo # 1 to '0' delay(1000);//wait for servo to move } void loop() { //increment from 0 to 4095 for(int i=0; i <=4095; i++) { dxlSetGoalPosition(SERVO_ID,i); //set the position of servo #1 to the current value of 'i' delay(33);//wait for servo to move / send data at 30hz } //decrement from 1024 to 0 for(int i=4095; i>0; i--) { dxlSetGoalPosition(SERVO_ID,i);//set the position of servo #1 to the current value of 'i' delay(33);//wait for servo to move / send data at 30hz } }
29.243902
138
0.64387
317ab9a0749be0a068db262f3d8059bc6a6354fa
6,863
ino
Arduino
intervalometer_dolly_LED.ino
skvark/Arduino-intervalometer---time-lapse-dolly
71c3c6ab3a6ee297db35a10bbc16e99018d77c5b
[ "MIT" ]
1
2021-03-06T01:07:59.000Z
2021-03-06T01:07:59.000Z
intervalometer_dolly_LED.ino
skvark/Arduino-intervalometer---time-lapse-dolly
71c3c6ab3a6ee297db35a10bbc16e99018d77c5b
[ "MIT" ]
null
null
null
intervalometer_dolly_LED.ino
skvark/Arduino-intervalometer---time-lapse-dolly
71c3c6ab3a6ee297db35a10bbc16e99018d77c5b
[ "MIT" ]
1
2018-04-10T04:27:17.000Z
2018-04-10T04:27:17.000Z
// Intervalometer and dolly motor controller // Olli-Pekka Heinisuo 2011 // Licensed under MIT license, see LICENSE.txt // AFMotor library #include <AFMotor.h> // library for 7 segment displays using 74HC595 shift register #include <LED7Segment.h> // pin that will trigger the camera #define CAMERA_PIN 13 // "exposing" or not, if false, sends pulse to the optocoupler which // triggers the camera bool exposing = false; // motor speed, increments by 20 // no "zero" speed, because it can cause DC gearmotor to stall // -> max current passes trough it, if no fuse is used the motor // can suffer damage int speed[] = {75, 95, 115, 135, 155, 175, 195, 215, 235, 255}; int c,s,t,r,e,b,m,p = 0; int n = 9; int pause; int counter = 0; int interval; int state; int divi; unsigned long time = 0; int mot; // These are for shift registers const int latchPin = 9; // connected to ST_CP of 74HC595 const int clockPin = 5; // connected to SH_CP of 74HC595 const int dataPin = 10; // connected to DS of 74HC595 AF_DCMotor motor(1, MOTOR12_64KHZ); void setup() { pinMode(13, OUTPUT); pinMode(A5, INPUT); // pins for the buttons pinMode(A4, INPUT); pinMode(A3, INPUT); pinMode(CAMERA_PIN, OUTPUT); // to the optocoupler pinMode(latchPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(dataPin, OUTPUT); } // These functions return a value when the corresponding button is pressed // 1,8 kohm resistors were used between 6 buttons (7 resistors) // More info: http://tronixstuff.wordpress.com/2011/01/11/tutorial-using-analog-input-for-multiple-buttons/ // // Switches: // 1 kohm resistors were used with 2 switches, total 6 resistors // Reset button int resetButton(int pin) { c=analogRead(pin); if (c<160 && c>100) { r = 1; // reset button } return r; } /* coming later, sensor buttons for dolly int shutDown(int pin) { c=analogRead(pin); if (c< && c>) { r = 1; // stop&reset to prevent any damage } return r; } */ // digit 1 value control int dig1Button(int pin) { c=analogRead(pin); if (c>160 && c<180) { delay(250); // if not set, value will increment as long as the button // was pressed and we don't want that to happen (about 100-200 ms) e++; } if (e < 10) { // can't show numbers bigger than 9 return e; } else { // if value goes over 9, automatic reset will occur return e=0; } } // digit 2 value control int dig2Button(int pin) { c=analogRead(pin); if (c>180 && c<210) { delay(250); b++; } if (b < 10) { return b; } else { return b=0; } } // digit 3 value control = motor speed int dig3Button(int pin) { c=analogRead(pin); if (c>330 && c<370) { delay(250); n++; } if (n < 10) { return n; } else { return n=0; } } // digit 4 value control = pause time int dig4Button(int pin) { c=analogRead(pin); if (c>240 && c<270) { delay(250); p++; } if (p < 10) { return p; } else { return p=0; } } // Start & stop int startButton(int pin) { c=analogRead(pin); if (c>500 && c<600) { delay(250); s++; } if (s <= 1) { return s; } else if (s > 1) { // stop return s=0; } } // select time range, default (0) is 0,0 - 9,9 seconds, (1) is 0-99 seconds int timingSwitch(int pin) { c=analogRead(pin); if (c>450 && c < 550) { return t=1; } else if (c < 450 && c>300) { return t=0; } else if (c == 0) { return t=2; } else { return t=0; } } // switch for choosing motor behavior: if on, motor moves // without pauses, if off motor pauses when pic is taken int motorSwitch(int pin) { c=analogRead(pin); if (c>450 && c < 550) { return m=1; } else if (c < 450 && c>300) { return m=0; } else if (c == 0) { return m=2; } else { return m=0; } } // This is where the magic happens void loop() { // If the reset button is pressed -> pause + every v // variable returns to their default values if (r == 1 ) { digitalWrite(CAMERA_PIN, LOW); t = 0; s = 0; r = 0; b = 0; e = 0; p = 0; // default speed is 9 (maximum) n = 9; m = 0; counter = 0; motor.run(RELEASE); } // constantly updating the values enables the possibility // to modify interval time on the fly e = dig1Button(5); // first digit b = dig2Button(5); // second digit n = dig3Button(5); // third digit, motor speed p = dig4Button(5); // fourth digit, pause time s = startButton(5); // start r = resetButton(5); // reset (and stop) t = timingSwitch(4); // time range m = motorSwitch(3); // pause / continuous mode // The shiftout for the 74HC595's and displays digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, LSBFIRST, ledCharSet[4]); // motor speed shiftOut(dataPin, clockPin, LSBFIRST, ledCharSet[4]); // pause time shiftOut(dataPin, clockPin, LSBFIRST, ledCharSet[4]); // time, first digit shiftOut(dataPin, clockPin, LSBFIRST, ledCharSet[4]); // time, second digit digitalWrite(latchPin, HIGH); // Set the motor speed, 0 slowest and 9 fastest // depends on motor type and supplied voltage motor.setSpeed(speed[n]); if (s == 1) { if (m == 1) { motor.run(FORWARD); // starts the dolly movement when // in continuous movement mode } // These statements control the interval times if (t == 0) { interval = e*1000 + b*100; // turning the display values // into milliseconds, max value being 9900 ms (9,9 seconds) pause = p*100; // pause time, equivalent to exposure time divi = 10; // pulse length divider } else if (t == 1) { interval = e*10000 + b*1000; // full seconds // values from 0 to 99 seconds accepted pause = p*1000; // pause time, equivalent to exposure time divi = 20; // pulse length divider } if (exposing == false) { // shut motor down if option chosen if (m == 0 && mot == 1) { motor.run(RELEASE); // stops the dolly movement mot = 0; } // enable optocoupler digitalWrite(CAMERA_PIN, HIGH); // set state 'high' for the pulse statement state = HIGH; time = millis(); exposing = true; counter++; // counter, if LCD is in use } // The circuit needs to be closed for about 100 milliseconds so // the camera has time to react // pulse length (how long the circuit is closed) // example: interval 2 sec, time range 0,1-9,9s: // length 2000 ms / 10 = 200 ms else if ( millis() - time >= interval / divi && state == HIGH && exposing == true) { digitalWrite(CAMERA_PIN, LOW); state = LOW; } // pause time ends, starts the dolly movement again (if mode in use) else if ( millis() - time >= pause && exposing == true && mot == 0) { motor.run(FORWARD); mot = 1; } // sets the exposing flag to false when interval time has passed else if ( millis() - time >= interval && exposing == true) { exposing = false; } } // force motor shutdown to prevent any damage else { motor.run(RELEASE); } }
19.664756
107
0.633105
1a2daad1f353738600efd7409a037785f26dfbb2
10,607
ino
Arduino
FHaTbadge.ino
TildenG/FHaTbadge
ddde6a6b238f24017d22d3d56a2d13b26161449e
[ "MIT" ]
1
2020-10-05T00:57:12.000Z
2020-10-05T00:57:12.000Z
FHaTbadge.ino
TildenG/FHaTbadge
ddde6a6b238f24017d22d3d56a2d13b26161449e
[ "MIT" ]
null
null
null
FHaTbadge.ino
TildenG/FHaTbadge
ddde6a6b238f24017d22d3d56a2d13b26161449e
[ "MIT" ]
1
2019-03-04T01:38:20.000Z
2019-03-04T01:38:20.000Z
/* MIT License Copyright (c) 2019, Tilden Groves Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma GCC optimize("-O2") #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #include <DNSServer.h> #include <FS.h> #include "WebFiles.h" #include <ArduinoOTA.h> #include "OTAHandler.h" #include "LEDMatrix.h" #include "Config.h" #include <Ticker.h> // name and password for home network const char* ssidForAP = "home_network_name"; // home network name const char* passwordForAP = "home_network_password"; // home network password // ESP8266 name const char* ESP8266Name = "fhatbadge"; // use http://fhatbadge.local to connect to webpage in your browser (may not work in EDGE or android devices) // name and password for connecting to ESP8266 as an Accesspoint const char *password = "12345678"; // This is the Wifi Password (only numbers and letters, not . , |) const char *AP_Name = "FHaTbadge"; // This is the Wifi Name(SSID), some numbers will be added for clarity (mac address) ESP8266WebServer server(80); DNSServer dnsServer; HandleTheOTA otaHandler(&dnsServer,AP_Name,password); LEDMatrix matrix; Ticker animationTimer; Ticker powerSaver; ADC_MODE(ADC_VCC); // to be able to read VCC WiFiEventHandler stationConnectedHandler; WiFiEventHandler stationDisconnectedHandler; byte clientsConnected = 0; #define DIAG // comment out to turn of diagnostics void setup(){ WiFi.setOutputPower(MAX_TRANSMIT_POWER); // 0 - 20.5 this will effect station mode pinMode(SW1_Pin,INPUT_PULLUP); pinMode(SW2_Pin,INPUT_PULLUP); pinMode(SW3_Pin,INPUT_PULLUP); setupMatrix(); matrix.setMatrix(uint64_t(0x181818422499423c),0); // show wifi symbol Serial.begin(115200); SPIFFS.begin(); //start SPIFFS setupWiFi(); //setup wifi scrollTest(F("Flinders & Hackerspace at Tonsley"),85);// test scroll function // power saving if (otaHandler.getAPMode()) WiFi.setOutputPower(0.25); // 0 - 20.5 powerSaver.attach_ms(1000,powerOffAP); stationConnectedHandler = WiFi.onSoftAPModeStationConnected(&onStationConnected); stationDisconnectedHandler = WiFi.onSoftAPModeStationDisconnected(&onStationDisconnected); #ifdef DIAG Serial.println(F("\r\nSetup Complete")); rst_info *resetInfo; resetInfo = ESP.getResetInfoPtr(); Serial.print((*resetInfo).reason); //REASON_DEFAULT_RST = 0, /* normal startup by power on */ //REASON_WDT_RST = 1, /* hardware watch dog reset */ //REASON_EXCEPTION_RST = 2, /* exception reset, GPIO status won't change */ //REASON_SOFT_WDT_RST = 3, /* software watch dog reset, GPIO status won't change */ //REASON_SOFT_RESTART = 4, /* software restart ,system_restart , GPIO status won't change */ //REASON_DEEP_SLEEP_AWAKE = 5, /* wake up from deep-sleep */ //REASON_EXT_SYS_RST = 6 /* external system reset */ Serial.println(": Reset Reason: " + ESP.getResetReason()); Serial.println(ESP.getResetInfo()); Serial.println("VCC: " + String(ESP.getVcc()) + " V"); #endif } void powerOffAP(){ powerSaver.detach(); if (otaHandler.getAPMode()){// make sure its in AP Mode WiFi.setOutputPower(0.25); // 0 - 20.5 powerSaver.attach_ms(5000,powerOnAP); } } void powerOnAP(){ powerSaver.detach(); WiFi.setOutputPower(MAX_TRANSMIT_POWER); // 0 - 20.5 powerSaver.attach_ms(180,powerOffAP); } void onStationConnected(const WiFiEventSoftAPModeStationConnected& evt) { char buf[20]; snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x", evt.mac[0], evt.mac[1], evt.mac[2], evt.mac[3], evt.mac[4], evt.mac[5]); Serial.println("station connected: " + String(buf)); powerSaver.detach(); WiFi.setOutputPower(MAX_TRANSMIT_POWER); // 0 - 20.5 clientsConnected++; } void onStationDisconnected(const WiFiEventSoftAPModeStationDisconnected& evt) { clientsConnected--; char buf[20]; snprintf(buf, sizeof(buf), "%02x:%02x:%02x:%02x:%02x:%02x", evt.mac[0], evt.mac[1], evt.mac[2], evt.mac[3], evt.mac[4], evt.mac[5]); Serial.println("station disconnected: " + String(buf)); Serial.println("Stations still connected: " + String(clientsConnected)); if (clientsConnected == 0){ WiFi.setOutputPower(0.25); // 0 - 20.5 powerSaver.attach_ms(300,powerOffAP); } } void loop(){ delay(1); // power saving in station mode drops power usage. ArduinoOTA.handle(); // handle OTA update requests. ArduinoOTA.onStart(disableTimer); // disable screen updates if there is an update in progress. dnsServer.processNextRequest(); // maintain DNS server. server.handleClient(); // handle client requests. } void scrollTest(String text,unsigned long frameDelay){ matrix.text = text; animationTimer.detach(); matrix.setMode(textScrollMode); animationTimer.attach_ms(frameDelay,animationCallback); } void animationCallback(){ matrix.update(); } void setupWiFi(){ WiFi.mode(WIFI_STA); if (SPIFFS.exists("/APData.csv")){ // check to see if theres any data from the last AP change otaHandler.loadDatafile(ESP8266Name); }else{ //No Saved data File, load defaults WiFi.begin(ssidForAP, passwordForAP); // connect to home Accesspoint(Wifi) WiFi.hostname(ESP8266Name); } otaHandler.connectToAP(); if (!otaHandler.getAPMode()){ ArduinoOTA.setHostname(ESP8266Name); ArduinoOTA.begin(); } // setup server callbacks server.on(F("/"), handleRoot); server.on(F("/pattern"), handlePattern); server.on(F("/save"), handleSave); server.on(F("/text"), handleText); server.on(F("/directory"), handleLoad); server.on(F("/waterfall"), handelMatrixWaterfall); server.on(F("/fireEffect"), handleFireEffect); server.on(F("/gameOfLife"), handleGameOfLife); server.onNotFound(handleNotFound); server.begin(); } // server callbacks void handleGameOfLife(){ matrix.startGameOfLife(); animationTimer.detach(); matrix.setMode(gameOfLifeMode); animationTimer.attach_ms(125,animationCallback); } void handleFireEffect(){ animationTimer.detach(); matrix.setMode(displayFireMode); animationTimer.attach_ms(70,animationCallback); } void handelMatrixWaterfall(){ sendNoContent(&server); animationTimer.detach(); matrix.setMode(matrixWaterfall); animationTimer.attach_ms(48,animationCallback); } void handleText(){ if (server.hasArg(F("scrollText"))){ matrix.newScrollText(server.arg(F("scrollText"))); animationTimer.detach(); sendNoContent(&server); matrix.setMode(textScrollMode); animationTimer.attach_ms(75,animationCallback); }else{ matrix.newScrollText(server.arg(F("fadeText"))); animationTimer.detach(); sendNoContent(&server); matrix.setMode(fadeTextMode); animationTimer.attach_ms(110,animationCallback); } } void handleSave(){ sendNoContent(&server); String pattern = server.arg(F("saveData")); String anDelay = server.arg(F("delay")); String fileName = "/" + server.arg(F("fileName")); if (!fileName.endsWith(".FHaT")) fileName += ".FHaT"; //TODO: see if file already exists ie. SPIFFS.exists(path) , ask for overwrite etc ... //TODO: Make sure theres enough free space //FSInfo fs_info; //SPIFFS.info(fs_info); //Serial.println("Free SPIFFS memory: " + String((fs_info.totalBytes - fs_info.usedBytes)/1000000.0) +" MB"); File dataFile = SPIFFS.open(fileName, "w"); if (!dataFile){ //TODO: Error handeling } dataFile.print(pattern + "|" + anDelay); dataFile.close(); } void handleLoad(){ String fileName = "/"; fileName += F("Directory"); File dataFile = SPIFFS.open(fileName, "w"); Dir dir = SPIFFS.openDir("/"); FSInfo fs_info; SPIFFS.info(fs_info); dataFile.println("Free FHaTbadge storage: " + String((fs_info.totalBytes - fs_info.usedBytes)/1000000.0) +" MB\r\n"); while (dir.next()) { if (dir.fileName().endsWith(".FHaT")){ dataFile.println(dir.fileName().substring(1,dir.fileName().length())); } } dataFile.close(); sendFile(fileName,&server); } void handlePattern(){ sendNoContent(&server); String pattern = server.arg(F("pattern")); uint8_t frameNumber=0; String anDelay = server.arg(F("delay")); unsigned long animationDelay = strtoul(anDelay.substring(0,8).c_str(),NULL,10); while (pattern.length()>10){ uint64_t number = matrix.rotateCW(strtoull(pattern.substring(0,16).c_str(), NULL, 16)); matrix.createAnimation(number,frameNumber,animationDelay); frameNumber++; pattern.remove(0,17); } animationTimer.detach(); matrix.setMode(animationMode); animationTimer.attach_ms(animationDelay,animationCallback); } void handleRoot(){ if (server.hasArg(F("NAME")) && server.arg(F("NAME")) != "" && server.arg(F("PASSWORD")) != "") { sendFile(F("/restarting.html"), &server); otaHandler.saveAPData(server.arg(F("NAME")),server.arg(F("PASSWORD"))); delay(1000); ESP.restart(); } else { sendFile(server.uri(), &server); } } void handleNotFound(){ sendFile(server.uri(),&server); } // timer functions void setupMatrix(){ matrix.ticks = clockCyclesPerMs / frequency; disableTimer(); enableTimer(); } void disableTimer(){ timer1_disable(); timer1_detachInterrupt(); matrix.clearMatrix(); } void enableTimer(){ timer1_isr_init(); timer1_attachInterrupt(T1IntHandler); timer1_enable(TIM_DIV1, TIM_EDGE, TIM_LOOP); timer1_write(matrix.ticks); // ticks before interrupt fires, maximum ticks 8388607 } ICACHE_RAM_ATTR void T1IntHandler(){ matrix.T1IntHandler(); }
35.356667
120
0.701895
e9bf04c3a57ee777821e637046ee0bb833563827
1,809
ino
Arduino
firmware/legacy_and_tests/neop_tripple_strip_test/neop_tripple_strip_test.ino
nathanshaw/Parrot
a4f7b2983e5aea961dfab1b8abc6a4e3990cd9fb
[ "MIT" ]
null
null
null
firmware/legacy_and_tests/neop_tripple_strip_test/neop_tripple_strip_test.ino
nathanshaw/Parrot
a4f7b2983e5aea961dfab1b8abc6a4e3990cd9fb
[ "MIT" ]
null
null
null
firmware/legacy_and_tests/neop_tripple_strip_test/neop_tripple_strip_test.ino
nathanshaw/Parrot
a4f7b2983e5aea961dfab1b8abc6a4e3990cd9fb
[ "MIT" ]
null
null
null
/* WS2812Serial BasicTest Example Test LEDs by turning then 7 different colors. This example code is in the public domain. */ #include <WS2812Serial.h> const int numled = 10; // Usable pins: // Teensy LC: 1, 4, 5, 24 // Teensy 3.2: 1, 5, 8, 10, 31 (overclock to 120 MHz for pin 8) // Teensy 3.5: 1, 5, 8, 10, 26, 32, 33, 48 // Teensy 3.6: 1, 5, 8, 10, 26, 32, 33 byte drawingMemory[numled*3]; // 3 bytes per LED DMAMEM byte displayMemory[numled*12]; // 12 bytes per LED WS2812Serial leds5(numled, displayMemory, drawingMemory, 5, WS2812_GRB); WS2812Serial leds8(numled, displayMemory, drawingMemory, 8, WS2812_GRB); WS2812Serial leds10(numled, displayMemory, drawingMemory, 10, WS2812_GRB); #define RED 0xFF0000 #define GREEN 0x00FF00 #define BLUE 0x0000FF #define YELLOW 0xFFFF00 #define PINK 0xFF1088 #define ORANGE 0xE05800 #define WHITE 0xFFFFFF // Less intense... /* #define RED 0x160000 #define GREEN 0x001600 #define BLUE 0x000016 #define YELLOW 0x101400 #define PINK 0x120009 #define ORANGE 0x100400 #define WHITE 0x101010 */ void setup() { leds5.begin(); leds8.begin(); leds10.begin(); } void loop() { // change all the LEDs in 1.5 seconds rainbowStrip(leds5); rainbowStrip(leds8); rainbowStrip(leds10); } void rainbowStrip(WS2812Serial &leds) { int microsec = 150000 / leds.numPixels(); colorWipe(leds, RED, microsec); colorWipe(leds, GREEN, microsec); colorWipe(leds, BLUE, microsec); colorWipe(leds, YELLOW, microsec); colorWipe(leds, PINK, microsec); colorWipe(leds, ORANGE, microsec); colorWipe(leds, WHITE, microsec); } void colorWipe(WS2812Serial &leds, int color, int wait) { for (int i=0; i < leds.numPixels(); i++) { leds.setPixel(i, color); leds.show(); delayMicroseconds(wait); } }
24.780822
74
0.693753
31e05824e58290b27b5ac786aab9f4a02af0a847
2,038
ino
Arduino
.pio/libdeps/nodemcuv2/CayenneMQTT/examples/Actuators/MotorSwitch/MotorSwitch.ino
sunCox1337/Beer_control_CayenneMQTT
b1ba96be4b651a09ba3c14187c6ba7c6c48114e7
[ "Apache-2.0" ]
null
null
null
.pio/libdeps/nodemcuv2/CayenneMQTT/examples/Actuators/MotorSwitch/MotorSwitch.ino
sunCox1337/Beer_control_CayenneMQTT
b1ba96be4b651a09ba3c14187c6ba7c6c48114e7
[ "Apache-2.0" ]
1
2019-03-19T13:42:36.000Z
2019-03-19T14:38:59.000Z
Libraries/CayenneMQTT/examples/Actuators/MotorSwitch/MotorSwitch.ino
Carl-Philippe/Aquaponie
478277c703423bfd5b14dbf0b7ca06a9c5bf22b3
[ "Apache-2.0" ]
null
null
null
/* Cayenne Motor Switch Actuator Example This sketch shows how to set up a Motor Switch with Cayenne. The Arduino cannot drive a motor because it does not output the needed current. As a result, in order to make this example work, various electronic components are necessary to drive the DC motor. To keep it simple, you will need an external power source, transistor (eg. PN2222), diode (eg. 1N4001), and a 270 ohm resistor. The CayenneMQTT Library is required to run this sketch. If you have not already done so you can install it from the Arduino IDE Library Manager. Steps: 1. In the Cayenne Dashboard add a new Motor Switch widget. 2. Select a virtual channel number for the widget. 3. Set the VIRTUAL_CHANNEL value below to the virtual channel you selected. 4. Set up your motor schematic and attach it to a PWM pin (3, 5, 6, 9, 10, and 11 on most Arduino boards). 5. Set the ACTUATOR_PIN value below to the PWM pin number you selected. 6. Set the Cayenne authentication info to match the authentication info from the Dashboard. 7. Compile and upload this sketch. 8. Once the Arduino connects to the Dashboard you can use the widget button to turn the motor on and off. */ #define CAYENNE_PRINT Serial // Comment this out to disable prints and save space #include <CayenneMQTTEthernet.h> // Cayenne authentication info. This should be obtained from the Cayenne Dashboard. char username[] = "MQTT_USERNAME"; char password[] = "MQTT_PASSWORD"; char clientID[] = "CLIENT_ID"; #define VIRTUAL_CHANNEL 1 #define ACTUATOR_PIN 3 void setup() { Serial.begin(9600); Cayenne.begin(username, password, clientID); } void loop() { Cayenne.loop(); } // Enable or disable the motor based on value received on virtual channel. CAYENNE_IN(VIRTUAL_CHANNEL) { int speed = 155; // Read the integer value which should be 0 or 1. int enabled = getValue.asInt(); if (enabled == 1) { // Turn on the motor at the specified speed. analogWrite(ACTUATOR_PIN, speed); } else { // Turn off the motor. analogWrite(ACTUATOR_PIN, 0); } }
34.542373
144
0.756133
33a08957cb5ad1255d6264a58f0f34b5735ddd8d
4,606
ino
Arduino
samples/Button/Button.ino
tigerfarm/arduino
e51f111a092fe6737646b146a825f4eecbd05d44
[ "OLDAP-2.4", "OLDAP-2.7" ]
2
2021-12-12T23:27:10.000Z
2022-02-17T14:01:21.000Z
samples/Button/Button.ino
tigerfarm/arduino
e51f111a092fe6737646b146a825f4eecbd05d44
[ "OLDAP-2.4", "OLDAP-2.7" ]
null
null
null
samples/Button/Button.ino
tigerfarm/arduino
e51f111a092fe6737646b146a825f4eecbd05d44
[ "OLDAP-2.4", "OLDAP-2.7" ]
4
2021-08-29T19:55:49.000Z
2022-02-15T08:30:15.000Z
// ----------------------------------------------------------------------------- /* Button Sample LED and button options, use only one at a time: 1. blinkLed(); + Not button, just blink the onboard LED. 2. checkButton(); + If the button is not pressed (circuit open), LED blinks. If the button is pressed (circuit closed), LED is on. 3. toggleButton(); + Toggle, if First press, toggle on, LED is on. Second press, toggle off, LED is off. The circuit for either an Arduino Uno, Nano, or a NodeMCU. - Button side 1, connect to Arduino +5V or NodeMCU +3.3V. - Button side 2, connect to a 10K resistor which is connected to ground. - Button side 2, connect to board pin (BUTTON_PIN), example: D4 on Nano. - Connect an external LED positive is connected to onboard LED pin. - Or use the on board LED: on pin 13 on Nano, pin 2 on NodeMCU. +++ ESP8266 ESP-12E NodeMCU pins used in this project. Label Pin:GPIO D0 16 D1 05 Button/toggle switch to have LED on only, not blinking D2 04 D3 00 D4(TX) 02 Built in, on board LED. Out to an LED(+). LED(-) to a resister, then to ground. --- 3V 3v output G Ground --- D5 14 D6 12 D7(RX) 13 D8(TX) 15 RX(D9) 03 TX(D10) 01 . --- G Ground To breadboard ground (-). 3V 3v output To breadboard power (+). --- Note, must not have button connected to TX(D10) when uploading compiled sketch because the computer will not connect to the NodeMCU. Also, if using TX(D10), if button is pressed, Serial.print will not work. */ // ----------------------------------------------------------------------------- // Button Controls // Built in LED on NodeMCU, LOW is LED on. // Built in LED on NodeMCU, HIGH is LED off. // // PIN X set to LOW (0) will turn the LED on. // PIN X set to HIGH (1) will turn the LED off. // Built in, on board LED: GPIO2 which is D04 on NodeMCU. // Built in, on board LED: GPI13 which is D13 on Nano and Uno. #define LED_ONBOARD_PIN 13 #define LED_PIN LED_ONBOARD_PIN const int BUTTON_PIN = 4; // Nano D4 // ----------------------------------------------------------------------------- // Blink the LED on and off. void blinkLed() { Serial.println("+ Blink: LED on."); digitalWrite(LED_PIN, HIGH); delay(300); Serial.println("+ Blink: LED off."); digitalWrite(LED_PIN, LOW); delay(300); } // ----------------------------------------------------------------------------- // Turn light on when the button is pressed. // Only do the action once, don't repeat if the button is held down. // Don't repeat action if the button is not pressed. boolean setButtonState = true; void checkButton() { // If the button is pressed (circuit closed), the button status is HIGH. if (digitalRead(BUTTON_PIN) == HIGH) { if (!setButtonState) { digitalWrite(LED_PIN, HIGH); Serial.println("+ checkButton(), turn LED on."); setButtonState = false; } setButtonState = true; } else { if (setButtonState) { digitalWrite(LED_PIN, LOW); Serial.println("+ checkButton(), turn LED off."); setButtonState = false; } } } // ----------------------------------------------------------------------------- // Toggle light on and off each time the button is pressed. boolean theToggle = true; boolean buttonAction = true; // Case the button is pressed and held, only toggle once. void toggleButton() { // If the button is pressed (circuit closed), the button status is HIGH. if (digitalRead(BUTTON_PIN) == HIGH) { if (buttonAction) { if (theToggle) { theToggle = false; Serial.println("+ toggleButton(), turn off."); digitalWrite(LED_PIN, LOW); } else { theToggle = true; Serial.println("+ toggleButton(), turn on."); digitalWrite(LED_PIN, HIGH); } } buttonAction = false; } else { buttonAction = true; } } // ----------------------------------------------------------------------------- void setup() { Serial.begin(115200); delay(100); Serial.println(); Serial.println("+++ Setup."); // Initialize the LED pin. pinMode(LED_PIN, OUTPUT); // Initialize the button pin. pinMode(BUTTON_PIN, INPUT); Serial.println("+ Start loop()"); } // ----------------------------------------------------------------------------- void loop() { delay(60); // LED and button options: // blinkLed(); checkButton(); // toggleButton(); } // -----------------------------------------------------------------------------
30.302632
101
0.549718
c2f2ecfc5364eb0a37ef901a8bc0a1fd6bb17f10
783
ino
Arduino
examples/esp_blink_webclient/esp_blink_webclient.ino
tinkerspy/Automaton-Esp8266
093cbdc752aed69a8bc73a226036e5e7d21437cd
[ "MIT" ]
19
2016-10-02T11:42:01.000Z
2020-09-09T13:56:38.000Z
examples/esp_blink_webclient/esp_blink_webclient.ino
tinkerspy/Automaton-Esp8266
093cbdc752aed69a8bc73a226036e5e7d21437cd
[ "MIT" ]
7
2017-03-27T18:27:40.000Z
2022-01-07T20:40:50.000Z
examples/esp_blink_webclient/esp_blink_webclient.ino
tinkerspy/Automaton-Esp8266
093cbdc752aed69a8bc73a226036e5e7d21437cd
[ "MIT" ]
7
2016-07-27T01:53:08.000Z
2020-01-07T14:45:15.000Z
#include <Automaton.h> #include <Atm_esp8266.h> Atm_esp8266_httpc_simple client1, client2; Atm_button button1, button2; // Two buttons on D2 & D7 send out /on and /off web requests // Could be used as a remote control for the esp_blink example char ap_ssid[] = "MySSID"; char ap_password[] = "MyPASSWORD"; char client_host[] = "172.22.22.220"; void setup() { wifi.begin( ap_ssid, ap_password ) .led( LED_BUILTIN, true ) // Esp8266 built in led shows wifi status .start(); client1.begin( client_host ) .get( "/on" ); client2.begin( client_host ) .get( "/off" ); button1.begin( D2 ) .onPress( client1, client1.EVT_START ); button2.begin( D7 ) .onPress( client2, client2.EVT_START ); } void loop() { automaton.run(); }
21.75
71
0.653895
0fd0678618eff17a7b6d966fc01b675cf7f8c58f
5,062
ino
Arduino
SSID_RSSI_BSS_OLED_WICED.ino
wifijt/SSID_RSSI_BSS_OLED_WICED
0dc4b8e4255dbd9cf36ee52436188ae831b42eeb
[ "MIT" ]
null
null
null
SSID_RSSI_BSS_OLED_WICED.ino
wifijt/SSID_RSSI_BSS_OLED_WICED
0dc4b8e4255dbd9cf36ee52436188ae831b42eeb
[ "MIT" ]
null
null
null
SSID_RSSI_BSS_OLED_WICED.ino
wifijt/SSID_RSSI_BSS_OLED_WICED
0dc4b8e4255dbd9cf36ee52436188ae831b42eeb
[ "MIT" ]
1
2019-11-20T10:41:42.000Z
2019-11-20T10:41:42.000Z
/* The MIT License (MIT) Copyright (c) 2016 John W. Turner Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* THIS WAS TESTED ON the Adafruit WICED board */ #include <adafruit_feather.h> #include <SPI.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include <Fonts/FreeSans18pt7b.h>//load some cool fonts #define OLED_RESET 3 //Pin of the OLED (this code used the OLED Feather wing sheild from Adafruit Adafruit_SSD1306 display(OLED_RESET); #define LOGO16_GLCD_HEIGHT 16 #define LOGO16_GLCD_WIDTH 16 #define MAX_SCAN_NUM 20 wl_ap_info_t scan_result[MAX_SCAN_NUM]; String sssid; uint8_t encryptionType; int32_t RSSI; uint8_t* BSSID; int32_t channel; bool isHidden; uint8_t curBss; String targetSSID = "linksis54"; // change this to match your networks SSID uint8_t prevRssi; void setup() { Serial.begin(9600); display.begin(SSD1306_SWITCHCAPVCC, 0x3C); display.display(); delay(200); display.clearDisplay(); } void loop() { byte available_networks = Feather.scanNetworks(scan_result, MAX_SCAN_NUM); int netnum = 0; prevRssi = 0; // Serial.print("Found networks "); // Serial.println (available_networks); // first lets find the SSID of the network you are looking for // by iterating through all of the avaialble networks // since in an enterprise there may be more than one BSSID for the SSID // Lets find the stringest one for (int network = 0; network < available_networks; network++) { // Serial.println (scan_result[network].ssid); if (String(scan_result[network].ssid)== targetSSID) { // Serial.print("Found one "); // Serial.println (scan_result[network].rssi); // Serial.println (scan_result[network].bssid[5],HEX); if ((uint8_t)scan_result[network].rssi > prevRssi) { netnum = network; prevRssi = (uint8_t)scan_result[network].rssi; } } } if (scan_result[netnum].bssid[5] != curBss){ Serial.println("New Bss!"); curBss = scan_result[netnum].bssid[5]; Serial.println(curBss,HEX); } Serial.print("Signal strength: "); int bars; // int bars = map(RSSI,-80,-44,1,6); // this method doesn't refelct the Bars well // simple if then to set the number of bars if (scan_result[netnum].rssi > -55) { bars = 5; } else if (scan_result[netnum].rssi < -55 & scan_result[netnum].rssi > -65) { bars = 4; } else if (scan_result[netnum].rssi < -65 & scan_result[netnum].rssi > -70) { bars = 3; } else if (scan_result[netnum].rssi < -70 & scan_result[netnum].rssi > -78) { bars = 2; } else if (scan_result[netnum].rssi < -78 & scan_result[netnum].rssi > -82) { bars = 1; } else { bars = 0; } display.clearDisplay(); // Do some simple loop math to draw rectangles as the bars // Draw one bar for each "bar" Duh... for (int b=0; b <= bars; b++) { display.fillRect(59 + (b*5),33 - (b*5),3,b*5,WHITE); } // This is what all 5 bars would look like if you coded them manually // display.fillRect(64,28,3,5,WHITE); // display.fillRect(69,23,3,10,WHITE); // display.fillRect(74,18,3,15,WHITE); // display.fillRect(79,13,3,20,WHITE); // display.fillRect(84,8,3,25,WHITE); display.setTextColor(WHITE); display.setTextSize(1); display.setCursor(0,26); display.setFont(&FreeSans18pt7b); //I like fonts display.print(scan_result[netnum].rssi); display.setFont(); // change back to the default font to print the BSSID display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(0,0); for(int i=0;i<5;i++){ // loop through the first 5 BSSID values in the arrray display.print(scan_result[netnum].bssid[i],HEX); display.print(":"); } display.println(scan_result[netnum].bssid[5],HEX); // then print the last BSSID value in the array display.display(); //print this out on the Serial console for debugging Serial.print(scan_result[netnum].rssi); Serial.println("dBm"); Serial.print("BSS: "); for(int i=0;i<5;i++){ Serial.print(scan_result[netnum].bssid[i],HEX); Serial.print(":"); } Serial.println(scan_result[netnum].bssid[5],HEX); Serial.print(bars); Serial.println(" bars"); }
33.746667
100
0.71533
86555a3fc895b55a1c98f60374ec4430ab8f2cd0
2,938
ino
Arduino
ESP32CAM_Projects/ESP32_CAM_Dashcam_FLUTTER/ESP32_CAM_WEBSOCKET_SERVER/ESP32_CAM_WEBSOCKET_SERVER.ino
askfind/ThatProject
8a6027d6bc6fa4f2aa236320d7beea8f299be94d
[ "Apache-2.0" ]
363
2019-07-23T23:36:21.000Z
2021-03-24T17:20:06.000Z
ESP32CAM_Projects/ESP32_CAM_Dashcam_FLUTTER/ESP32_CAM_WEBSOCKET_SERVER/ESP32_CAM_WEBSOCKET_SERVER.ino
askfind/ThatProject
8a6027d6bc6fa4f2aa236320d7beea8f299be94d
[ "Apache-2.0" ]
14
2019-11-29T14:41:03.000Z
2021-03-12T05:36:48.000Z
ESP32CAM_Projects/ESP32_CAM_Dashcam_FLUTTER/ESP32_CAM_WEBSOCKET_SERVER/ESP32_CAM_WEBSOCKET_SERVER.ino
askfind/ThatProject
8a6027d6bc6fa4f2aa236320d7beea8f299be94d
[ "Apache-2.0" ]
283
2019-08-29T22:26:38.000Z
2021-03-24T17:41:46.000Z
#include "esp_camera.h" #include <WiFi.h> #include <WebSocketsServer.h> #define CAMERA_MODEL_AI_THINKER #include "camera_pins.h" WebSocketsServer webSocket = WebSocketsServer(8888); const char* ssid = "ESP32-THAT-PROJECT"; const char* password = "California"; bool isClientConnected; void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) { switch(type) { case WStype_DISCONNECTED: Serial.println("Disconnected!"); break; case WStype_CONNECTED: { IPAddress ip = webSocket.remoteIP(num); Serial.print("Connected IP address:"); Serial.println(ip); isClientConnected = true; } break; case WStype_TEXT: case WStype_BIN: case WStype_ERROR: case WStype_FRAGMENT_TEXT_START: case WStype_FRAGMENT_BIN_START: case WStype_FRAGMENT: case WStype_FRAGMENT_FIN: break; } } void setup() { Serial.begin(115200); Serial.setDebugOutput(true); Serial.println(); camera_config_t config; config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.pin_d0 = Y2_GPIO_NUM; config.pin_d1 = Y3_GPIO_NUM; config.pin_d2 = Y4_GPIO_NUM; config.pin_d3 = Y5_GPIO_NUM; config.pin_d4 = Y6_GPIO_NUM; config.pin_d5 = Y7_GPIO_NUM; config.pin_d6 = Y8_GPIO_NUM; config.pin_d7 = Y9_GPIO_NUM; config.pin_xclk = XCLK_GPIO_NUM; config.pin_pclk = PCLK_GPIO_NUM; config.pin_vsync = VSYNC_GPIO_NUM; config.pin_href = HREF_GPIO_NUM; config.pin_sscb_sda = SIOD_GPIO_NUM; config.pin_sscb_scl = SIOC_GPIO_NUM; config.pin_pwdn = PWDN_GPIO_NUM; config.pin_reset = RESET_GPIO_NUM; config.xclk_freq_hz = 10000000; config.pixel_format = PIXFORMAT_JPEG; //init with high specs to pre-allocate larger buffers if(psramFound()){ config.frame_size = FRAMESIZE_VGA; config.jpeg_quality = 40; config.fb_count = 2; } else { config.frame_size = FRAMESIZE_SVGA; config.jpeg_quality = 12; config.fb_count = 1; } // camera init esp_err_t err = esp_camera_init(&config); if (err != ESP_OK) { Serial.printf("Camera init failed with error 0x%x", err); return; } delay(1000); WiFi.softAP(ssid, password); IPAddress IP = WiFi.softAPIP(); Serial.print("AP IP address: "); Serial.println(IP); webSocket.begin(); webSocket.onEvent(webSocketEvent); } void loop() { webSocket.loop(); if(isClientConnected){ camera_fb_t *fb = NULL; esp_err_t res = ESP_OK; fb = esp_camera_fb_get(); if(!fb){ Serial.println("Camera capture failed"); esp_camera_fb_return(fb); return; } size_t fb_len = 0; if(fb->format != PIXFORMAT_JPEG){ Serial.println("Non-JPEG data not implemented"); return; } webSocket.broadcastBIN((const uint8_t*) fb->buf, fb->len); esp_camera_fb_return(fb); } }
24.689076
83
0.670184
742e6c6bb21a1024bb467ad51026102bcad886f4
539
ino
Arduino
lightseekingmotor_uno/lightseekingmotor_uno.ino
Greh/cockroaches
fb4f01beab46fc9b329532a4b8062d7147ccc7dd
[ "MIT" ]
null
null
null
lightseekingmotor_uno/lightseekingmotor_uno.ino
Greh/cockroaches
fb4f01beab46fc9b329532a4b8062d7147ccc7dd
[ "MIT" ]
null
null
null
lightseekingmotor_uno/lightseekingmotor_uno.ino
Greh/cockroaches
fb4f01beab46fc9b329532a4b8062d7147ccc7dd
[ "MIT" ]
null
null
null
int TLpin = 5; int TRpin = 3; int BLpin = 11; int BRpin = 12; int light = A1; int val = 0; int valnew = 0; void setup(){ pinMode(TLpin, OUTPUT); pinMode(TRpin, OUTPUT); pinMode(BLpin, OUTPUT); pinMode(BRpin, OUTPUT); pinMode(light, INPUT); Serial.begin(9600); } void loop(){ digitalWrite(BLpin, HIGH); digitalWrite(BRpin, HIGH); val = analogRead(light); Serial.println(val); valnew = map (val, 0, 1023, 0, 255); //Serial.println(valnew); digitalWrite(BRpin, LOW); analogWrite(TLpin, valnew); delay(1000); }
18.586207
38
0.654917
efb861fc27a0334dca97b4b8a7864520fe35a1ad
32,822
ino
Arduino
OpenDSKY-revised-2019-06/OpenDSKY-revised-2019-06.ino
rondiamond/https-github.com-rondiamond-OpenDSKY
f417171a39c94ab2d759e4ac4b5343d6aca790a7
[ "MIT" ]
5
2019-06-17T00:19:12.000Z
2020-12-01T01:43:18.000Z
OpenDSKY-revised-2019-06/OpenDSKY-revised-2019-06.ino
rondiamond/OpenDSKY
f417171a39c94ab2d759e4ac4b5343d6aca790a7
[ "MIT" ]
null
null
null
OpenDSKY-revised-2019-06/OpenDSKY-revised-2019-06.ino
rondiamond/OpenDSKY
f417171a39c94ab2d759e4ac4b5343d6aca790a7
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2019 Ron Diamond Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Adafruit_NeoPixel.h> #define PIN 6 #define NUMPIXELS 18 Adafruit_NeoPixel neoPixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800); #include "LedControl.h" LedControl ledControl = LedControl(12,10,11,4); #include "RTClib.h" RTC_DS1307 realTimeClock; #include<Wire.h> const int MPU_addr=0x69; // I2C address of the MPU-6050 enum Action { none = 0, displayIMUAttitude = 1, displayRealTimeClock = 2, displayGPS = 3, displayRangeWith1202Error = 4, setTime = 5, setDate = 6, }; enum Mode { modeIdle = 0, modeInputVerb = 1, modeInputNoun = 2, modeInputProgram = 3, modeLampTest = 4 }; enum programNumber { programNone = 0, programJFKAudio = 62, programApollo11Audio = 69, programApollo13Audio = 70 }; enum lampNumber { lampNoun = 0, lampProg = 1, lampVerb = 2, lampCompActy = 3, lampOprErr = 13, // ? lampKeyRelease = 14, lampUplinkActy = 17 // ? // ... }; enum keyValues { // symbolic references to individual keys keyNone = 20, keyVerb = 10, keyNoun = 11, keyPlus = 12, keyMinus = 13, keyNumber0 = 0, keyNumber1 = 1, keyNumber2 = 2, keyNumber3 = 3, keyNumber4 = 4, keyNumber5 = 5, keyNumber6 = 6, keyNumber7 = 7, keyNumber8 = 8, keyNumber9 = 9, keyClear = 18, keyProceed = 14, keyRelease = 16, keyEnter = 15, keyReset = 17 }; enum verbValues { verbNone = 0, verbLampTest = 35, verbDisplayDecimal = 16, verbSetComponent = 21 }; enum nounValues { nounNone = 0, nounIMUAttitude = 17, nounClockTime = 36, nounDate = 37, nounLatLongAltitude = 43, nounRangeTgoVelocity = 68 }; enum registerDisplayPositions { register1Position = 4, register2Position = 5, register3Position = 6 }; long valueForDisplay[7]; byte digitValue[7][7]; byte keyValue = keyNone; byte oldKey = none; bool fresh = true; byte action = none; byte currentAction = none; byte verb = verbNone; byte verbNew[2]; byte verbOld[2]; byte noun = 0; byte nounNew[2]; byte nounOld[2]; byte currentProgram = programNone; byte progNew[2]; byte progOld[2]; byte count = 0; byte mode = modeIdle; byte oldMode = modeIdle; bool toggle = false; byte toggleCount = 0; bool error = 0; bool newAction = false; byte audioTrack = 1; void setup() { pinMode(A0, INPUT); pinMode(A1, INPUT); pinMode(A2, INPUT); pinMode(A7, INPUT); pinMode(7, OUTPUT); digitalWrite(7, LOW); randomSeed(analogRead(A7)); neoPixels.begin(); for (int index = 0; index < 4; index++) { ledControl.shutdown(index,false); ledControl.setIntensity(index, 8); ledControl.clearDisplay(index); } Wire.begin(); Wire.beginTransmission(MPU_addr); Wire.write(0x6B); // PWR_MGMT_1 register Wire.write(0); // set to zero (wakes up the MPU-6050) Wire.endTransmission(true); realTimeClock.begin(); Serial.begin(9600); } void loop() { if (currentProgram == programJFKAudio) { jfk(1); } else if (currentProgram == programApollo11Audio) { jfk(2); } else if (currentProgram == programApollo13Audio) { jfk(3); } if (mode == modeIdle) { executeIdleMode(); } else if (mode == modeInputVerb) { executeVerbInputMode(); } else if (mode == modeInputNoun) { executeNounInputMode(); } else if (mode == modeInputProgram) { executeProgramInputMode(); } else if (mode == modeLampTest) { executeLampTestModeWithDuration(5000); } if (toggleCount == 4) { toggleCount = 0; if (toggle == false) { toggle == true; } else { toggle = false; } } toggleCount++; if (action == displayGPS) { toggleCount = 4; delay(200); } else { delay(100); } delay(100); if (action == displayIMUAttitude) { actionReadIMU(); // V16N17 ReadIMU } else if (action == displayRealTimeClock) { actionReadTime(); // V16N36 ReadTime } else if (action == displayGPS) { actionReadGPS(); // V16N43 Read GPS } else if (action == setTime) { actionSetTime(); // V21N36 Set The Time } else if (action == setDate) { actionSetDate(); // V21N37 Set The Date } Serial.print(verb); Serial.print(" "); Serial.print(noun); Serial.print(" "); //Serial.println(action); }; void executeIdleMode() { // no action set just reading the kb if (newAction == true) { validateAction(); } else { if (error == 1) { flasher(); } keyValue = readKeyboard(); processIdleMode(); } } void processIdleMode() { if (keyValue != oldKey) { fresh = true; oldKey = keyValue; } if (fresh == true) { if (keyValue == keyVerb) { // verb mode = modeInputVerb; fresh = false; byte keeper = verb; for (int index = 0; keeper >= 10 ; keeper = (keeper - 10)) { index++; verbOld[0] = index; } for (int index = 0; keeper >= 1; keeper = (keeper - 1)) { index++; verbOld[1] = index; } } else if (keyValue == keyNoun) { // noun mode = modeInputNoun; fresh = false; byte keeper = noun; for (int index = 0; keeper >= 10; keeper = (keeper - 10)) { index++; nounOld[0] = index; } for (int index = 0;keeper >= 1; keeper = (keeper - 1)) { index++; nounOld[1] = index; } } else if (keyValue == keyProceed) { // program mode = modeInputProgram; fresh = false; } else if (keyValue == keyReset) { // resrt reeor error = 0; turnOffLampNumber(13); fresh = false; } } } void executeVerbInputMode() { // inputting the verb illuminateWithRGBAndLampNumber(0, 150, 0, lampVerb); toggleKeyReleaseLamp(); if (error == 1) { flasher(); } keyValue = readKeyboard(); processVerbInputMode(); } void processVerbInputMode() { if (keyValue == oldKey) { fresh = false; } else { fresh = true; oldKey = keyValue; if ((error == 1) && (keyValue == keyReset) && (fresh == true)) { error = 0; turnOffLampNumber(lampOprErr); fresh = false; } //resrt reeor if ((keyValue == keyEnter) && (fresh == true)) { fresh = false; verb = ((verbNew[0] * 10) + (verbNew[1])); if ((verb != verbDisplayDecimal) && (verb != verbSetComponent) && (verb != verbLampTest) && (verb != verbNone)) { error = 1; verb = ((verbOld[0] * 10) + verbOld[1]); // restore prior verb } else { turnOffLampNumber(lampOprErr); turnOffLampNumber(lampKeyRelease); turnOffLampNumber(lampVerb); mode = modeIdle; count = 0; fresh = false; error = 0; newAction = true; } } if (fresh == true) { if (keyValue == keyRelease) { mode = oldMode; turnOffLampNumber(lampKeyRelease); turnOffLampNumber(lampVerb); count = 0; fresh = false; if (verb == verbNone) { ledControl.setRow(0,0,0); ledControl.setRow(0,1,0); } else { setDigits(0, 0, verbOld[0]); setDigits(0, 1, verbOld[1]); } } else if (keyValue == keyNoun) { mode = modeInputNoun; turnOffLampNumber(lampVerb); count = 0; fresh = false; } else if (keyValue == keyProceed) { //program mode = modeInputProgram; turnOffLampNumber(lampVerb); count = 0; fresh = false; } } if ((keyValue <= keyNumber9) && (count < 2)) { verbNew[count] = keyValue; setDigits(0, count, keyValue); count++; fresh = false; } } } void executeNounInputMode() { // inputting the noun illuminateWithRGBAndLampNumber(0, 150, 0, lampNoun); toggleKeyReleaseLamp(); if (error == 1) { flasher(); } keyValue = readKeyboard(); processNounInputMode(); } void processNounInputMode() { if (keyValue == oldKey) { fresh = false; } else { fresh = true; oldKey = keyValue; if ((error == 1) && (keyValue == keyReset) && (fresh == true)) { error = 0; turnOffLampNumber(lampOprErr); fresh = false; } //resrt reeor if ((keyValue == keyEnter) && (fresh == true)) { fresh = false; noun = ((nounNew[0] * 10) + (nounNew[1])); fresh = false; if ((noun != nounIMUAttitude) && (noun != nounClockTime) && (noun != nounLatLongAltitude) && (noun != nounRangeTgoVelocity) && (noun != nounNone)) { noun = ((nounOld[0] * 10) + nounOld[1]); // restore prior noun error = 1; } else { turnOffLampNumber(lampOprErr); turnOffLampNumber(lampKeyRelease); turnOffLampNumber(lampNoun); mode = modeIdle; count = 0; fresh = false; error = 0; newAction = true; }} if ((keyValue == keyRelease) && (fresh == true)) { mode = oldMode; turnOffLampNumber(lampKeyRelease); turnOffLampNumber(lampNoun); count = 0; fresh = false; if (noun == 0) { //verb ledControl.setRow(0, 4, 0); ledControl.setRow(0, 5, 0); } else { setDigits(0, 4, nounOld[0]); setDigits(0, 5, nounOld[1]); }} if ((keyValue == keyVerb) && (fresh == true)) { //verb mode = modeInputVerb; turnOffLampNumber(lampNoun); count = 0; fresh = false; } if ((keyValue == keyProceed) && (fresh == true)) { mode = modeInputProgram; turnOffLampNumber(lampNoun); count = 0; fresh = false; //program } if ((keyValue <= keyNumber9) && (count < 2)) { nounNew[count] = keyValue; setDigits(0, (count + 4), keyValue); count++; } } } void executeProgramInputMode() { // inputting the program illuminateWithRGBAndLampNumber(0, 150, 0, lampProg); toggleKeyReleaseLamp(); if (error == 1) { flasher(); } keyValue = readKeyboard(); processProgramInputMode(); } void processProgramInputMode() { if ((error == 1) && (keyValue == keyReset) && (fresh == true)) { error = 0; turnOffLampNumber(13); fresh = false; } //resrt reeor if ((keyValue == keyEnter) && (fresh == true)) { currentProgram = ((progNew[0] * 10) + (progNew[1])); fresh = false; if ((currentProgram != 16) && (currentProgram != 21) && (currentProgram != 35) && (currentProgram != programJFKAudio) && (currentProgram != programApollo11Audio) && (currentProgram != programApollo13Audio) && (currentProgram != programNone)) { error = 1; } else { progOld[0] = progNew[0]; progOld[1] = progNew[1]; turnOffLampNumber(13); mode = modeIdle; turnOffLampNumber(lampKeyRelease); turnOffLampNumber(lampProg); count = 0; fresh = false; error = 0; newAction = true; } } if (keyValue != oldKey) { fresh = true; oldKey = keyValue; } if ((keyValue == keyRelease) && (fresh == true)) { // verb mode = oldMode; turnOffLampNumber(lampKeyRelease); turnOffLampNumber(lampProg); count = 0; fresh = false; } if ((keyValue == keyNoun) && (fresh == true)) { // noun mode = modeInputNoun; turnOffLampNumber(lampProg); count = 0; fresh = false; } if ((keyValue == keyVerb) && (fresh == true)) { // verb mode = modeInputVerb; turnOffLampNumber(lampProg); count = 0; fresh = false; } if ((keyValue <= keyNumber9) && (count < 2)) { progNew[count] = keyValue; setDigits(0, (count + 2), keyValue); count++; } } //void processkeytime() { //} void executeLampTestModeWithDuration(int durationInMilliseconds) { for (int index = 11; index < 18; index++) { // Uplink Acty, No Att, Stby, Key Rel, Opr Err, --, -- illuminateWithRGBAndLampNumber(100, 100, 60, index); // less blue = more white } for (int index = 4; index < 11; index++) { // Temp, Gimbal Loc, Prog, Restart, Tracker, Alt, Vel illuminateWithRGBAndLampNumber(120, 110, 0, index); // more yellow } for (int lampNumber = 0; lampNumber < 4; lampNumber++) { // Comp Acty, Prog, Verb, Noun illuminateWithRGBAndLampNumber(0, 150, 0, lampNumber); } int lampTestDigitValue = 8; // passes number "8" to all the 7-segment numeric displays for (int row = 0; row < 4; row++) { // row 0 = Prog/Verb/Noun // row 1 = Register 1 // row 2 = Register 2 // row 3 = Register 3 // ... each has six positions // note: 'digit' # 0 in the three registers is the plus/minus sign for (int digitPosition = 0; digitPosition < 6; digitPosition++) { setDigits(row, digitPosition, lampTestDigitValue); } } delay(durationInMilliseconds); // reset all lamps for (int index = 0; index < 4; index++) { turnOffLampNumber(index); } for (int index = 4; index < 11; index++) { turnOffLampNumber(index); } for (int index = 11; index < 18; index++) { turnOffLampNumber(index); } for (int index = 0; index < 4; index++) { ledControl.clearDisplay(index); } // restore previously-displayed values for Verb and Noun verbNew[0] = verbOld[0]; verbNew[1] = verbOld[1]; // blank Verb readout if needed verb = ((verbOld[0] * 10) + verbOld[1]); if (verb == verbNone) { ledControl.setRow(0, 0, 0); ledControl.setRow(0, 1, 0); } else { setDigits(0, 0, verbOld[0]); setDigits(0, 1, verbOld[1]); } // blank Prog readout if needed if (currentProgram == programNone) { ledControl.setRow(0, 2, 0); ledControl.setRow(0, 3, 0); } else { setDigits(0, 0, progNew[0]); setDigits(0, 1, progNew[1]); } // blank Noun readout if needed if (noun == 0) { ledControl.setRow(0, 4, 0); ledControl.setRow(0, 5, 0); } else { setDigits(0, 4, nounNew[0]); setDigits(0, 5, nounNew[1]); } keyValue = keyNone; mode = modeIdle; validateAction(); } void actionReadIMU() { readIMU(); } void actionReadTime() { // read time from real-time clock (RTC) DateTime now = realTimeClock.now(); valueForDisplay[register1Position] = (now.hour()); valueForDisplay[register2Position] = (now.minute()); valueForDisplay[register3Position] = (now.second() * 100); setDigits(); } void actionReadGPS() { // read GPS digitalWrite(7, HIGH); delay(20); byte data[83]; while (Serial.available() > 0) { int x = Serial.read(); } while (Serial.available() < 1) { int x = 1; } delay(6); int index = 0; while (Serial.available() > 0) { data[index] = Serial.read(); delayMicroseconds(960); index++; if (index >= 72) { index = 71; } } int latitude = 0; int longitude = 0; int altitude = 0; if (count < 10) { count++; latitude = (((data[18] - 48) * 1000) + ((data[19] -48) * 100) + ((data[20] - 48) * 10) + ((data[21] - 48))); longitude = (((data[30] - 48) * 10000) + ((data[31] - 48) * 1000) + ((data[32] -48) * 100) + ((data[33] - 48) * 10) + ((data[34] - 48))); altitude = (((data[52] -48) * 100) + ((data[53] - 48) * 10) + ((data[54] - 48))); } else { count++; latitude = (((data[21] - 48) * 10000) + ((data[23] - 48) * 1000) + ((data[24] -48) * 100) + ((data[25] - 48) * 10) + ((data[26] - 48))); longitude = (((data[34] - 48) * 10000) + ((data[36] - 48) * 1000) + ((data[37] -48) * 100) + ((data[38] - 48) * 10) + ((data[39] - 48))); altitude = (((data[52] -48) * 100) + ((data[53] - 48) * 10) + ((data[54] - 48))); } if (count > 25) { count = 0; } if (data[28] != 78) { latitude = ((latitude - (latitude + latitude))); } if (data[41] != 69) { longitude = ((longitude - (longitude + longitude))); } valueForDisplay[register1Position] = latitude; valueForDisplay[register2Position] = longitude; valueForDisplay[register3Position] = altitude; digitalWrite(7, LOW); setDigits(); } void actionSetTime() { // read & display time from hardware real-time clock (RTC) DateTime now = realTimeClock.now(); int nowYear = now.year(); int nowMonth = now.month(); int nowDay = now.day(); int nowHour = now.hour(); int nowMinute = now.minute(); int nowSecond = now.second(); while (keyValue == keyEnter) { keyValue = readKeyboard(); } while (keyValue != keyEnter) { Serial.println(keyValue); keyValue = readKeyboard(); if (keyValue != oldKey) { oldKey = keyValue; if (keyValue == keyPlus) { nowHour++; } if (keyValue == keyMinus) { nowHour--; } if (nowHour > 23) { nowHour = 0; } if (nowHour < 0) { nowHour = 23; } } valueForDisplay[register1Position] = nowHour; valueForDisplay[register2Position] = nowMinute; valueForDisplay[register3Position] = (nowSecond * 100); // emulate milliseconds setDigits(); delay(200); ledControl.clearDisplay(1); delay(50); } while (keyValue == keyEnter) { keyValue = readKeyboard(); } while (keyValue != keyEnter) { keyValue = readKeyboard(); if (keyValue != oldKey) { oldKey = keyValue; if (keyValue == keyPlus) { nowMinute++; } if (keyValue == keyMinus) { nowMinute--; } if (nowMinute > 59) { nowMinute = 0; } if (nowMinute < 0) { nowMinute = 59; } } valueForDisplay[register1Position] = nowHour; valueForDisplay[register2Position] = nowMinute; valueForDisplay[register3Position] = (nowSecond * 100); setDigits(); delay(200); ledControl.clearDisplay(2); delay(50); } while (keyValue == keyEnter) { keyValue = readKeyboard(); } while (keyValue != keyEnter) { keyValue = readKeyboard(); if (keyValue != oldKey) { oldKey = keyValue; if (keyValue == keyPlus) { nowSecond++; } if (keyValue == keyMinus) { nowSecond--; } if (nowSecond > 59) { nowSecond = 0; } if (nowSecond < 0) { nowSecond = 59; } } valueForDisplay[register1Position] = nowHour; valueForDisplay[register2Position] = nowMinute; valueForDisplay[register3Position] = (nowSecond *100); setDigits(); delay(200); ledControl.clearDisplay(3); delay(50); } realTimeClock.adjust(DateTime(nowYear, nowMonth, nowDay, nowHour, nowMinute, nowSecond)); action = displayRealTimeClock; setDigits(0, 0, 1); setDigits(0, 1, 6); verb = verbDisplayDecimal; verbOld[0] = 1; verbOld[1] = 6; } void actionSetDate() { byte yearToSet[4]; byte monthToSet[2]; byte dayToSet[2]; byte hourToSet[2]; byte minuteToSet[2]; byte secondToSet[2]; DateTime now = realTimeClock.now(); int nowYear = now.year(); int nowMonth = now.month(); int nowDay = now.day(); int nowHour = now.hour(); int nowMinute = now.minute(); int nowSecond = now.second(); realTimeClock.adjust(DateTime( ((yearToSet[0] * 10^3) + (yearToSet[1] * 10^2) + (yearToSet[2] * 10) + yearToSet[3]), ((monthToSet[0] * 10) + monthToSet[1]), ((dayToSet[0] * 10) + dayToSet[1]), nowHour, nowMinute, nowSecond) ); } /* void mode11() { flashUplinkAndComputerActivityRandomly(); } */ int readKeyboard() { int oddRowDividerVoltage1 = 225; int oddRowDividerVoltage2 = 370; int oddRowDividerVoltage3 = 510; int oddRowDividerVoltage4 = 650; int oddRowDividerVoltage5 = 790; int oddRowDividerVoltage6 = 930; int evenRowDividerVoltage1 = 200; int evenRowDividerVoltage2 = 330; int evenRowDividerVoltage3 = 455; int evenRowDividerVoltage4 = 577; int evenRowDividerVoltage5 = 700; int evenRowDividerVoltage6 = 823; int evenRowDividerVoltage7 = 930; int value_row1 = analogRead(A0); int value_row2 = analogRead(A1); int value_row3 = analogRead(A2); if ((value_row1 > oddRowDividerVoltage6) && (value_row2 > oddRowDividerVoltage6) && (value_row3 > oddRowDividerVoltage6)) { return keyNone; // no key } // keyboard ~top row else if (value_row1 < oddRowDividerVoltage1) return keyVerb; else if (value_row1 < oddRowDividerVoltage2) return keyPlus; else if (value_row1 < oddRowDividerVoltage3) return keyNumber7; else if (value_row1 < oddRowDividerVoltage4) return keyNumber8; else if (value_row1 < oddRowDividerVoltage5) return keyNumber9; else if (value_row1 < oddRowDividerVoltage6) return keyClear; // keyboard ~middle row else if (value_row2 < evenRowDividerVoltage1) return keyNoun; else if (value_row2 < evenRowDividerVoltage2) return keyMinus; else if (value_row2 < evenRowDividerVoltage3) return keyNumber4; else if (value_row2 < evenRowDividerVoltage4) return keyNumber5; else if (value_row2 < evenRowDividerVoltage5) return keyNumber6; else if (value_row2 < evenRowDividerVoltage6) return keyProceed; else if (value_row2 < evenRowDividerVoltage7) return keyEnter; // keyboard ~bottom row else if (value_row3 < oddRowDividerVoltage1) return keyNumber0; else if (value_row3 < oddRowDividerVoltage2) return keyNumber1; else if (value_row3 < oddRowDividerVoltage3) return keyNumber2; else if (value_row3 < oddRowDividerVoltage4) return keyNumber3; else if (value_row3 < oddRowDividerVoltage5) return keyRelease; else if (value_row3 < oddRowDividerVoltage6) return keyReset; } void flashUplinkAndComputerActivityRandomly() { int randomNumber = random(10, 30); if ((randomNumber == 15) || (randomNumber == 25)) { illuminateWithRGBAndLampNumber(0, 150, 0, lampCompActy); } else { turnOffLampNumber(lampCompActy); } if ((randomNumber == 17) || (randomNumber == 25)) { illuminateWithRGBAndLampNumber(90, 90, 90, lampUplinkActy); } else { turnOffLampNumber(lampUplinkActy); } } void turnOffLampNumber(int lampNumber) { illuminateWithRGBAndLampNumber(0, 0, 0, lampNumber); } void illuminateWithRGBAndLampNumber(byte r, byte g, byte b, int lamp) { neoPixels.setPixelColor(lamp, neoPixels.Color(r,g,b)); neoPixels.show(); // show the updated pixel color on the hardware } void toggleKeyReleaseLamp() { if (toggle == false) { illuminateWithRGBAndLampNumber(100, 100, 100, lampKeyRelease); } else { turnOffLampNumber(lampKeyRelease); } } void flasher() { if (toggle == false) { illuminateWithRGBAndLampNumber(100, 100, 100, lampOprErr); } else { turnOffLampNumber(lampOprErr); } } void validateAction() { if (verb == verbLampTest) { mode = modeLampTest; newAction = false; } else if ((verb == verbDisplayDecimal) && (noun == nounIMUAttitude)) { action = displayIMUAttitude; newAction = false; } else if ((verb == verbDisplayDecimal) && (noun == nounClockTime)) { action = displayRealTimeClock; newAction = false; } else if ((verb == verbDisplayDecimal) && (noun == nounLatLongAltitude)) { // Display current GPS action = displayGPS; newAction = false; count = 0; } else if ((verb == verbDisplayDecimal) && (noun == nounRangeTgoVelocity)) { // Display Range With 1202 ERROR action = displayRangeWith1202Error; newAction = false; } else if ((verb == verbSetComponent) && (noun == nounClockTime)) { action = setTime; newAction = false; } else if ((verb == verbSetComponent) && (noun == nounDate)) { action = setDate; newAction = false; } else { // not (yet) a valid verb/noun combination action = none; newAction = false; } } void readIMU() { flashUplinkAndComputerActivityRandomly(); Wire.beginTransmission(MPU_addr); Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) Wire.endTransmission(false); Wire.requestFrom(MPU_addr,14,true); // request a total of 14 registers valueForDisplay[0] = (Wire.read() << 8) | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L) valueForDisplay[1] = (Wire.read() << 8) | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L) valueForDisplay[2] = (Wire.read() << 8) | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L) valueForDisplay[3] = (Wire.read() << 8) | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L) valueForDisplay[register1Position] = (Wire.read() << 8) | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L) valueForDisplay[register2Position] = (Wire.read() << 8) | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L) valueForDisplay[register3Position] = (Wire.read() << 8) | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L) valueForDisplay[3] = (valueForDisplay[3] / 340.00 + 36.53); //equation for temperature in degrees C from datasheet /* Serial.print("AcX = "); Serial.print(valueForDisplay[0]); Serial.print(" | AcY = "); Serial.print(valueForDisplay[1]); Serial.print(" | AcZ = "); Serial.print(valueForDisplay[2]); Serial.print(" | Tmp = "); Serial.print(valueForDisplay[3]); Serial.print(" | GyX = "); Serial.print(valueForDisplay[4]); Serial.print(" | GyY = "); Serial.print(valueForDisplay[5]); Serial.print(" | GyZ = "); Serial.println(valueForDisplay[6]); */ setDigits(); } void setDigits(byte maximum, byte digit, byte value) {//Serial.println("setDigits(byte ...)"); ledControl.setDigit(maximum, digit, value, false); } void setDigits() { for (int indexa = 0; indexa < 8; indexa ++) { for (int index = 0; index < 7; index++) { digitValue[indexa][index] = 0; } } for (int indexa = 0; indexa < 7; indexa ++) { if (valueForDisplay[indexa] < 0) { valueForDisplay[indexa] = (valueForDisplay[indexa] - (valueForDisplay[indexa] + valueForDisplay[indexa])); digitValue[indexa][0] = 1; } else { digitValue[indexa][0] = 0; } for (int index = 0; valueForDisplay[indexa] >= 100000; valueForDisplay[indexa] = (valueForDisplay[indexa] - 100000)) { index++; } for (int index = 0; valueForDisplay[indexa] >= 10000; valueForDisplay[indexa] = (valueForDisplay[indexa] - 10000)) { index++; digitValue[indexa][1] = index; } for (int index = 0; valueForDisplay[indexa] >= 1000; valueForDisplay[indexa] = (valueForDisplay[indexa] - 1000)) { index++; digitValue[indexa][2] = index; } for (int index = 0; valueForDisplay[indexa] >= 100; valueForDisplay[indexa] = (valueForDisplay[indexa] - 100)) { index++; digitValue[indexa][3] = index; } for (int index = 0; valueForDisplay[indexa] >= 10; valueForDisplay[indexa] = (valueForDisplay[indexa] - 10)) { index++; digitValue[indexa][4] = index; } for (int index = 0; valueForDisplay[indexa] >= 1; valueForDisplay[indexa] = (valueForDisplay[indexa] - 1)) { index++; digitValue[indexa][5] = index; } } for (int index = 0; index < 3; index++) { // ledControl.clearDisplay(index+1); for (int i = 0; i < 6; i++) { if (i == 0) { if (digitValue[(index+4)][i] == 1) { ledControl.setRow(index+1, i, B00100100); } else { ledControl.setRow(index+1, i, B01110100); } } else { ledControl.setDigit(index+1, i, digitValue[index + 4][i], false); } } } } void jfk(byte jfk) { if (audioTrack > 3) { audioTrack = 1; } while (audioTrack != jfk) { pinMode(9, OUTPUT); delay(100); pinMode(9, INPUT); delay(100); audioTrack++; if (audioTrack > 3) { audioTrack = 1; } } pinMode(9, OUTPUT); delay(100); pinMode(9, INPUT); audioTrack++; currentProgram = programNone; }
29.865332
145
0.533819
f7cddade9ae04a20139f5bbc1df30d6f83b928e4
504
ino
Arduino
Arduino/Elegoo/code/Lesson 9 Servo/servo/servo.ino
j1fvandenbosch/IOT-Workarea-Storage
3232f1e9afc3d8d05828de11fc85c226ef46a716
[ "MIT" ]
null
null
null
Arduino/Elegoo/code/Lesson 9 Servo/servo/servo.ino
j1fvandenbosch/IOT-Workarea-Storage
3232f1e9afc3d8d05828de11fc85c226ef46a716
[ "MIT" ]
null
null
null
Arduino/Elegoo/code/Lesson 9 Servo/servo/servo.ino
j1fvandenbosch/IOT-Workarea-Storage
3232f1e9afc3d8d05828de11fc85c226ef46a716
[ "MIT" ]
null
null
null
//www.elegoo.com //2018.12.19 #include <Servo.h> Servo myservo; void setup(){ myservo.attach(9); myservo.write(90);// move servos to center position -> 90° } void loop(){ myservo.write(90);// move servos to center position -> 90° delay(1000); myservo.write(30);// move servos to center position -> 60° delay(1000); myservo.write(90);// move servos to center position -> 90° delay(1000); myservo.write(150);// move servos to center position -> 120° delay(1000); }
25.2
63
0.642857
d992ea4e9b2681eda8134f2397c957e90a760dbf
2,165
ino
Arduino
src/OrangutanAnalog/examples/OrangutanAnalogExample2/OrangutanAnalogExample2.ino
flibbertigibbet/libpololu-avr
2f6b62d314993e9d4005b793f83f111af714a9e1
[ "MIT" ]
26
2015-02-04T04:55:20.000Z
2021-09-03T10:48:58.000Z
src/OrangutanAnalog/examples/OrangutanAnalogExample2/OrangutanAnalogExample2.ino
flibbertigibbet/libpololu-avr
2f6b62d314993e9d4005b793f83f111af714a9e1
[ "MIT" ]
3
2015-03-11T18:35:03.000Z
2016-10-02T17:03:31.000Z
src/OrangutanAnalog/examples/OrangutanAnalogExample2/OrangutanAnalogExample2.ino
flibbertigibbet/libpololu-avr
2f6b62d314993e9d4005b793f83f111af714a9e1
[ "MIT" ]
37
2015-02-11T09:21:35.000Z
2020-07-08T18:05:43.000Z
#include <OrangutanLCD.h> #include <OrangutanAnalog.h> /* * OrangutanAnalogExample2: for the Orangutan LV-168 * * This sketch uses the OrangutanAnalog library to read the voltage output * of the trimpot (in millivolts) and to read the Orangutan LV-168's * temperature sensor in degrees Farenheit. These values are printed to * the LCD 10 times per second. This example is intended for use with the * Orangutan LV-168, though all but the temperature-measuring portion * will work on the 3pi robot (on the 3pi, analog input 6 connects to 2/3rds * of the battery voltage rather than a temperature sensor) and the * Orangutan SV-xx8 (on the SV-xx8, analog input 6 connects to 1/3rd of * the battery voltage). * * You should see the trimpot voltage change as you turn it, and you can * get the temperature reading to slowly increase by holding a finger on the * underside of the Orangutan LV-168's PCB near the center of the board. * Be careful not to zap the board with electrostatic discharge if you * try this! */ OrangutanLCD lcd; OrangutanAnalog analog; void setup() // run once, when the sketch starts { analog.setMode(MODE_10_BIT); // 10-bit analog-to-digital conversions } void loop() // run over and over again { lcd.gotoXY(0,0); // LCD cursor to home position (upper-left) lcd.print(analog.toMillivolts(analog.readTrimpot())); // trimpot output in mV lcd.print(" mV "); // added spaces are to overwrite left over chars lcd.gotoXY(0, 1); // LCD cursor to start of the second line unsigned int temp = analog.readTemperatureF(); // get temp in tenths of a degree F lcd.print(temp/10); // get the whole number of degrees lcd.print('.'); // print the decimal point lcd.print(temp - (temp/10)*10); // print the tenths digit lcd.print((char)223); // print a degree symbol lcd.print("F "); // added spaces are to overwrite left over chars delay(100); // wait for 100 ms (otherwise LCD flickers too much) }
45.104167
87
0.656813
1570670e50f33b82555c2d4b994467be864f3a90
1,872
ino
Arduino
examples/TemperatureSensor/TemperatureSensor.ino
lutzb91/stm32-homie
22a7c7acadffb3eadad08bf4826be56426439b6c
[ "MIT" ]
null
null
null
examples/TemperatureSensor/TemperatureSensor.ino
lutzb91/stm32-homie
22a7c7acadffb3eadad08bf4826be56426439b6c
[ "MIT" ]
null
null
null
examples/TemperatureSensor/TemperatureSensor.ino
lutzb91/stm32-homie
22a7c7acadffb3eadad08bf4826be56426439b6c
[ "MIT" ]
null
null
null
#include <SPI.h> #include <Ethernet.h> #include <Device.h> uint8_t mac[6] = {0x74,0x69,0x69,0x2D,0x30,0x35}; EthernetClient client; /* Nodes */ Node tempOutside("out", "Sensor Outside", "sensor"); Node tempInside("in", "Sensor Inside", "sensor"); void setup() { delay(500); Device::setFirmware("TemperatureSensor", "1.0.0"); Device::setName("Temp1"); tempOutside.exposeProperty("temperature").setName("Temperature Outside").setDatatype(Datatype::FLOAT).setUnit("°C"); tempOutside.exposeProperty("humidity").setName("Humidity Outside").setDatatype(Datatype::INTEGER).setUnit("%"); tempInside.exposeProperty("temperature").setName("Temperature Inside").setDatatype(Datatype::FLOAT).setUnit("°C"); tempInside.exposeProperty("humidity").setName("Humidity Inside").setDatatype(Datatype::INTEGER).setUnit("%"); if(Ethernet.begin(mac) == 0) { // Ethernet connection failed for(;;); } Device::setup(mac, Ethernet.localIP(), client); } uint32_t lastMillis = 0; /* Dummy values */ double tempOut = 6.4; double tempIn = 22.1; int humidityOut = 30; int humidityIn = 50; void readTemperatures() { if(tempOut <= 10) { tempOut += 0.1; } else { tempOut = 6.4; } if(tempIn <= 25) { tempIn += 0.2; } else { tempIn = 22.1; } if(humidityOut <= 45) { humidityOut += 2; } else { humidityOut = 30; } if(humidityIn <= 60) { humidityIn += 1; } else { humidityIn = 50; } } void loop() { Device::loop(); if(millis() - lastMillis >= 10000) { // Every 10 seconds readTemperatures(); tempOutside.sendProperty("temperature", String(tempOut).c_str()); tempOutside.sendProperty("humidity", String(humidityOut).c_str()); tempInside.sendProperty("temperature", String(tempIn).c_str()); tempInside.sendProperty("humidity", String(humidityIn).c_str()); lastMillis = millis(); } }
24.96
118
0.660256
f78d0e7d6367216e980203947dedc3ea66c4ba5c
1,948
ino
Arduino
example/DFRobot_WT61PC/DFRobot_WT61PC.ino
DFRobotdl/DFRobot_WT61PC
e966e51dae1f239408f050dc4d8bbe1b94b21d4a
[ "MIT" ]
null
null
null
example/DFRobot_WT61PC/DFRobot_WT61PC.ino
DFRobotdl/DFRobot_WT61PC
e966e51dae1f239408f050dc4d8bbe1b94b21d4a
[ "MIT" ]
null
null
null
example/DFRobot_WT61PC/DFRobot_WT61PC.ino
DFRobotdl/DFRobot_WT61PC
e966e51dae1f239408f050dc4d8bbe1b94b21d4a
[ "MIT" ]
null
null
null
/*! @file getLightIntensity.ino @Set the frequency of data output by the sensor, read the acceleration, angular velocity, and angle of X, Y, and Z axes. @n Experimental phenomenon: when the sensor starts, it outputs data at the set frequency and the data will be displayed on serial monitor @copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com) @licence The MIT License (MIT) @author [huyujie](yujie.hu@dfrobot.com) @version V1.0 @date 2020-12-03 @https://github.com/DFRobot */ #include <DFRobot_WT61PC.h> #include <SoftwareSerial.h> //Use software serial port RX:10,TX:11 SoftwareSerial mySerial(10, 11); DFRobot_WT61PC sensor(&mySerial); void setup() { //Use Serial as debugging serial port Serial.begin(115200); //Use software serial port mySerial as communication seiral port mySerial.begin(9600); //Revise the data output frequncy of sensor FREQUENCY_0_1HZ for 0.1Hz, FREQUENCY_0_5HZ for 0.5Hz, FREQUENCY_1HZ for 1Hz, FREQUENCY_2HZ for 2Hz, // FREQUENCY_5HZ for 5Hz, FREQUENCY_10HZ for 10Hz, FREQUENCY_20HZ for 20Hz, FREQUENCY_50HZ for 50Hz, // FREQUENCY_100HZ for 100Hz, FREQUENCY_125HZ for 125Hz, FREQUENCY_200HZ for 200Hz. sensor.modifyFrequency(FREQUENCY_10HZ); } void loop() { if (sensor.available()) { Serial.print("Acc\t"); Serial.print(sensor.Acc.X); Serial.print("\t"); Serial.print(sensor.Acc.Y); Serial.print("\t"); Serial.println(sensor.Acc.Z); //acceleration information of X,Y,Z Serial.print("Gyro\t"); Serial.print(sensor.Gyro.X); Serial.print("\t"); Serial.print(sensor.Gyro.Y); Serial.print("\t"); Serial.println(sensor.Gyro.Z); //angular velocity information of X,Y,Z Serial.print("Angle\t"); Serial.print(sensor.Angle.X); Serial.print("\t"); Serial.print(sensor.Angle.Y); Serial.print("\t"); Serial.println(sensor.Angle.Z); //angle information of X, Y, Z Serial.println(" "); } }
45.302326
196
0.705852
1dfe710ab31235d1481527a354592508e85ad461
3,779
ino
Arduino
arduino/ws2812_controller/ws2812_controller.ino
gleeds/Systematic-LEDs
c12de0ca15416bf80bab4ca589d32614141b5967
[ "MIT" ]
101
2018-03-02T14:12:53.000Z
2021-12-10T18:21:40.000Z
arduino/ws2812_controller/ws2812_controller.ino
gleeds/Systematic-LEDs
c12de0ca15416bf80bab4ca589d32614141b5967
[ "MIT" ]
83
2018-03-02T03:27:53.000Z
2020-11-15T07:38:24.000Z
arduino/ws2812_controller/ws2812_controller.ino
gleeds/Systematic-LEDs
c12de0ca15416bf80bab4ca589d32614141b5967
[ "MIT" ]
47
2018-03-04T16:48:17.000Z
2021-01-19T23:30:38.000Z
#include <Arduino.h> #include <ArduinoOTA.h> #include <ESP8266WiFi.h> #include <WiFiUdp.h> #define FASTLED_ESP8266_DMA // better control for ESP8266 will output or RX pin requires fork https://github.com/coryking/FastLED #define FASTLED_ALLOW_INTERRUPTS 0 // Reduce flickering #include "FastLED.h" /************ Network Information (CHANGE THESE FOR YOUR SETUP) ************************/ const char* ssid = "WIFI_SSID"; const char* password = "WIFI_PASSWORD"; const char* sensor_name = "TEST_SENSOR_HOSTNAME"; const char* ota_password = "OTA_PASSWORD"; const bool static_ip = false; IPAddress ip(192, 168, 137, 170); IPAddress gateway(192, 168, 137, 1); IPAddress subnet(255, 255, 255, 0); const int udp_port = 7778; /*********************************** FastLED Defintions ********************************/ #define NUM_LEDS 74 #define DATA_PIN 7 //#define CLOCK_PIN 2 #define CHIPSET WS2812B #define COLOR_ORDER GRB /*********************************** Globals *******************************************/ WiFiUDP port; CRGB leds[NUM_LEDS]; /********************************** Start Setup ****************************************/ void setup() { Serial.begin(115200); // Setup FastLED #ifdef CLOCK_PIN FastLED.addLeds<CHIPSET, DATA_PIN, CLOCK_PIN, COLOR_ORDER>(leds, NUM_LEDS); #else FastLED.addLeds<CHIPSET, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS); #endif // Setup the wifi connection setup_wifi(); // Setup OTA firmware updates setup_ota(); // Initialize the UDP port port.begin(udp_port); } void setup_wifi() { delay(10); Serial.println(); Serial.print("Connecting to "); Serial.print(ssid); if (static_ip) { WiFi.config(ip, gateway, subnet); } WiFi.hostname(sensor_name); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected!"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); } void setup_ota() { ArduinoOTA.setHostname(sensor_name); ArduinoOTA.setPassword(ota_password); ArduinoOTA.onStart([]() { Serial.println("Starting"); }); ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); } void loop() { if (WiFi.status() != WL_CONNECTED) { delay(1); Serial.print("WIFI Disconnected. Attempting reconnection."); setup_wifi(); return; } ArduinoOTA.handle(); // TODO: Hookup either a more elaborate protocol, or a secondary // communication channel (i.e. mqtt) for functional control. This // will also give the ability to have some non-reative effects to // be driven completely locally making them less glitchy. // Handle UDP data int packetSize = port.parsePacket(); if (packetSize == sizeof(leds)) { port.read((char*)leds, sizeof(leds)); Serial.printf("."); FastLED.show(); // flush the serial buffer while(Serial.available()) { Serial.read(); } } else if (packetSize) { Serial.printf("Invalid packet size: %u (expected %u)\n", packetSize, sizeof(leds)); port.flush(); return; } else { Serial.printf("~"); } }
27.384058
129
0.63059
9b945098029fbd23d3b196234c166618c88bd341
2,186
ino
Arduino
CodeArduino/Avion.ino
PabloCerv/math-teaching-app-with-TUI
1a61d207efd29a0f01be89ac61bcf07864b6398a
[ "MIT" ]
2
2020-04-13T21:04:28.000Z
2022-02-08T03:50:16.000Z
CodeArduino/Avion.ino
PabloCerv/math-teaching-app-with-TUI
1a61d207efd29a0f01be89ac61bcf07864b6398a
[ "MIT" ]
null
null
null
CodeArduino/Avion.ino
PabloCerv/math-teaching-app-with-TUI
1a61d207efd29a0f01be89ac61bcf07864b6398a
[ "MIT" ]
null
null
null
//--------------VARIABLES----------------- String cadena_a_enviar; //---------------------------------------- void setup() { //-------------------------------------- cadena_a_enviar = "";//Se limpia cadena //-------------------------------------- // SE DECLARAN LOS BOTONES COMO ENTRADAS pinMode(2, INPUT); pinMode(3, INPUT); pinMode(4, INPUT); pinMode(5, INPUT); pinMode(6, INPUT); pinMode(7, INPUT); pinMode(8, INPUT); pinMode(9, INPUT); pinMode(10, INPUT); pinMode(11, INPUT); //------------------------------------- //-----------Velocidad----------------- Serial.begin(9600); //------------------------------------- } void loop() { cadena_a_enviar = "";//Se limpia cadena //------------------------------------------------------------- //Se va generando cadena deacuerdo a los estados de los botones //-----Cadena resultante: xxxxxxxxxx donde x puede se 1 ó 0---- if(digitalRead(2) == HIGH) { cadena_a_enviar+="1"; } else { cadena_a_enviar+="0"; } if(digitalRead(3) == HIGH) { cadena_a_enviar+="1"; } else { cadena_a_enviar+="0"; } if(digitalRead(4) == HIGH) { cadena_a_enviar+="1"; } else { cadena_a_enviar+="0"; } if(digitalRead(5) == HIGH) { cadena_a_enviar+="1"; } else { cadena_a_enviar+="0"; } if(digitalRead(6) == HIGH) { cadena_a_enviar+="1"; } else { cadena_a_enviar+="0"; } if(digitalRead(7) == HIGH) { cadena_a_enviar+="1"; } else { cadena_a_enviar+="0"; } if(digitalRead(8) == HIGH) { cadena_a_enviar+="1"; } else { cadena_a_enviar+="0"; } if(digitalRead(9) == HIGH) { cadena_a_enviar+="1"; } else { cadena_a_enviar+="0"; } if(digitalRead(10) == HIGH) { cadena_a_enviar+="1"; } else { cadena_a_enviar+="0"; } if(digitalRead(11) == HIGH) { cadena_a_enviar+="1"; } else { cadena_a_enviar+="0"; } //------------------------------------------------------------- //------------Se envía la cadena generada---------------------- Serial.println(cadena_a_enviar); //------------------------------------------------------------- delay(200);//Cinco veces por segundo -- cada 200 ms. }
25.126437
65
0.464776
ef959439ade5c4b8c09797faedc60a2fb2dc6404
3,183
ino
Arduino
sds011.ino
21isenough/SDS011-Dust-Sensor
fc93f8327eb3a353d88fc43e57a8d2044515f4bc
[ "MIT" ]
1
2021-08-25T15:17:13.000Z
2021-08-25T15:17:13.000Z
sds011.ino
21isenough/SDS011-Dust-Sensor
fc93f8327eb3a353d88fc43e57a8d2044515f4bc
[ "MIT" ]
null
null
null
sds011.ino
21isenough/SDS011-Dust-Sensor
fc93f8327eb3a353d88fc43e57a8d2044515f4bc
[ "MIT" ]
null
null
null
/** * Dust Sensor with ESP8266 and ThingSpeak upload (SDS011) */ #include "SdsDustSensor.h" #include "ThingSpeak.h" #include "secrets.h" #include <ESP8266WiFi.h> int rxPin = D1; int txPin = D2; int powerPin = D5; SdsDustSensor sds(rxPin, txPin); char ssid[] = SECRET_SSID; // your network SSID (name) char pass[] = SECRET_PASS; // your network password WiFiClient client; unsigned long myChannelNumber = SECRET_CH_ID; const char * myWriteAPIKey = SECRET_WRITE_APIKEY; void setup() { Serial.begin(9600); Serial.setTimeout(2000); // Wait for serial to initialize. while(!Serial) { } WiFi.mode(WIFI_STA); ThingSpeak.begin(client); // Initialize ThingSpeak // Connect or reconnect to WiFi if(WiFi.status() != WL_CONNECTED){ Serial.print("Attempting to connect to SSID: "); Serial.println(SECRET_SSID); int attempts = 0; while(attempts != 5){ WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network. Change this line if using open or WEP network // Serial.print("."); delay(10000); attempts++; // Serial.println(attempts); if (WiFi.status() == WL_CONNECTED) { Serial.println("\nConnected."); break; } else { Serial.println("Could not connect to Wifi. Attempts: " + String(attempts) + "/5"); } } } // Serial.println("I'm awake."); sds.begin(); Serial.println(sds.queryFirmwareVersion().toString()); // prints firmware version Serial.println(sds.setQueryReportingMode().toString()); // ensures sensor is in 'query' reporting mode pinMode(powerPin, OUTPUT); // pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output digitalWrite(powerPin, HIGH); // Power up SDS via Mosfet // delay(5000); sds.wakeup(); // digitalWrite(LED_BUILTIN, LOW); Turn the LED on (Note that LOW is the voltage level delay(15000); // waiting 15 seconds before measuring PmResult pm = sds.queryPm(); if (pm.isOk()) { Serial.print("PM2.5 = "); Serial.print(pm.pm25); Serial.print(", PM10 = "); Serial.println(pm.pm10); // if you want to just print the measured values, you can use toString() method as well Serial.println(pm.toString()); ThingSpeak.setField(1, pm.pm25); ThingSpeak.setField(2, pm.pm10); int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); if(x == 200){ Serial.println("Channel update successful."); } else{ Serial.println("Problem updating channel. HTTP error code " + String(x)); } } else { Serial.print("Could not read values from sensor, reason: "); Serial.println(pm.statusToString()); } digitalWrite(powerPin, LOW); // Power cut SDS via Mosfet delay(1000); WorkingStateResult state = sds.sleep(); if (state.isWorking()) { Serial.println("Problem with sleeping the sensor."); } else { Serial.println("\nSensor is sleeping"); } Serial.println("Going into deep sleep for 10 seconds"); ESP.deepSleep(10e6); // 10e6 is 10 seconds } void loop() { }
26.747899
113
0.629909
54978867109a221344fbeb3ae45a94e7b53f6499
2,437
ino
Arduino
examples/ThingSpeakPutTemperature/ThingSpeakPutTemperature.ino
Wiznet/WizFi250_arduino_library
fbb1fc71b4acbe0cc50abbd2121b0be91202c20a
[ "Apache-2.0" ]
5
2016-07-27T02:08:51.000Z
2022-03-07T18:29:41.000Z
examples/ThingSpeakPutTemperature/ThingSpeakPutTemperature.ino
Wiznet/WizFi250_arduino_library
fbb1fc71b4acbe0cc50abbd2121b0be91202c20a
[ "Apache-2.0" ]
null
null
null
examples/ThingSpeakPutTemperature/ThingSpeakPutTemperature.ino
Wiznet/WizFi250_arduino_library
fbb1fc71b4acbe0cc50abbd2121b0be91202c20a
[ "Apache-2.0" ]
4
2016-10-06T00:47:59.000Z
2019-10-16T05:35:05.000Z
#include "DHT.h" #include <SPI.h> #include "WizFi250.h" char ssid[] = "SSID"; // your network SSID (name) char pass[] = "PASSWORD"; // your network password String apiKey = "YOUR API KEY"; const char* server = "api.thingspeak.com"; //#define DHTPIN 7 //DHT dht(DHTPIN, DHT11,15); int status = WL_IDLE_STATUS; WiFiClient client; void printWifiStatus(); void setup() { Serial.begin(115200); WiFi.init(); // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi shield not present"); // don't continue: while (true); } // attempt to connect to WiFi network while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to WPA SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network status = WiFi.begin(ssid, pass); } Serial.println("Connected to wifi"); printWifiStatus(); } void loop() { float h = dht.readHumidity(); float t = dht.readTemperature(); if (isnan(h) || isnan(t)) { Serial.println(F("Failed to read from DHT sensor!")); return; } if (client.connect(server,80)) { // "184.106.153.149" or api.thingspeak.com String postStr = apiKey; postStr +="&field1="; postStr += String(t); postStr +="&field2="; postStr += String(h); postStr += "\r\n\r\n"; client.print("POST /update HTTP/1.1\n"); client.print("Host: api.thingspeak.com\n"); client.print("Connection: close\n"); client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n"); client.print("Content-Type: application/x-www-form-urlencoded\n"); client.print("Content-Length: "); client.print(postStr.length()); client.print("\n\n"); client.print(postStr); Serial.print("Temperature: "); Serial.print(t); Serial.print(" degrees Celcius Humidity: "); Serial.print(h); Serial.println("% send to Thingspeak"); } client.stop(); Serial.println("Waiting…"); // thingspeak needs minimum 15 sec delay between updates delay(20000); } void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); }
24.867347
77
0.643414
a25a8fb1d5a63bb4c43a080537eaac1cc856f057
6,525
ino
Arduino
MadgwickAHRS.ino
hyeminyoo/rcProto-v4
4d945fbfc533c6e6dd956f58cf1f88d73fe0efbe
[ "MIT" ]
null
null
null
MadgwickAHRS.ino
hyeminyoo/rcProto-v4
4d945fbfc533c6e6dd956f58cf1f88d73fe0efbe
[ "MIT" ]
null
null
null
MadgwickAHRS.ino
hyeminyoo/rcProto-v4
4d945fbfc533c6e6dd956f58cf1f88d73fe0efbe
[ "MIT" ]
null
null
null
//===================================================================================================== // MadgwickAHRS.c //===================================================================================================== // // Implementation of Madgwick's IMU and AHRS algorithms. // See: http://www.x-io.co.uk/node/8#open_source_ahrs_and_imu_algorithms // // Date Author Notes // 29/09/2011 SOH Madgwick Initial release // 02/10/2011 SOH Madgwick Optimised for reduced CPU load // 19/02/2012 SOH Madgwick Magnetometer measurement is normalised // //===================================================================================================== //--------------------------------------------------------------------------------------------------- // AHRS algorithm update void MadgwickAHRSupdate(float gx, float gy, float gz, float ax, float ay, float az, float mx, float my, float mz) { float recipNorm; float s0, s1, s2, s3; float qDot1, qDot2, qDot3, qDot4; float hx, hy; float _2q0mx, _2q0my, _2q0mz, _2q1mx, _2bx, _2bz, _4bx, _4bz, _8bx, _8bz, _2q0, _2q1, _2q2, _2q3, _2q0q2, _2q2q3, q0q0, q0q1, q0q2, q0q3, q1q1, q1q2, q1q3, q2q2, q2q3, q3q3; float q0 = q[0]; float q1 = q[1]; float q2 = q[2]; float q3 = q[3]; // Use IMU algorithm if magnetometer measurement invalid (avoids NaN in magnetometer normalisation) if ((mx == 0.0f) && (my == 0.0f) && (mz == 0.0f)) { return; } int nstep = 1; for (int n = 0; n < nstep; n++) { // Rate of change of quaternion from gyroscope qDot1 = 0.5f * (-q1 * gx - q2 * gy - q3 * gz); qDot2 = 0.5f * (q0 * gx + q2 * gz - q3 * gy); qDot3 = 0.5f * (q0 * gy - q1 * gz + q3 * gx); qDot4 = 0.5f * (q0 * gz + q1 * gy - q2 * gx); // Compute feedback only if accelerometer measurement valid (avoids NaN in accelerometer normalisation) if (!((ax == 0.0f) && (ay == 0.0f) && (az == 0.0f))) { // Normalise accelerometer measurement recipNorm = invSqrt(ax * ax + ay * ay + az * az); ax *= recipNorm; ay *= recipNorm; az *= recipNorm; // Normalise magnetometer measurement recipNorm = invSqrt(mx * mx + my * my + mz * mz); mx *= recipNorm; my *= recipNorm; mz *= recipNorm; // Auxiliary variables to avoid repeated arithmetic _2q0mx = 2.0f * q0 * mx; _2q0my = 2.0f * q0 * my; _2q0mz = 2.0f * q0 * mz; _2q1mx = 2.0f * q1 * mx; _2q0 = 2.0f * q0; _2q1 = 2.0f * q1; _2q2 = 2.0f * q2; _2q3 = 2.0f * q3; _2q0q2 = 2.0f * q0 * q2; _2q2q3 = 2.0f * q2 * q3; q0q0 = q0 * q0; q0q1 = q0 * q1; q0q2 = q0 * q2; q0q3 = q0 * q3; q1q1 = q1 * q1; q1q2 = q1 * q2; q1q3 = q1 * q3; q2q2 = q2 * q2; q2q3 = q2 * q3; q3q3 = q3 * q3; // Reference direction of Earth's magnetic field hx = mx * q0q0 - _2q0my * q3 + _2q0mz * q2 + mx * q1q1 + _2q1 * my * q2 + _2q1 * mz * q3 - mx * q2q2 - mx * q3q3; hy = _2q0mx * q3 + my * q0q0 - _2q0mz * q1 + _2q1mx * q2 - my * q1q1 + my * q2q2 + _2q2 * mz * q3 - my * q3q3; _2bx = sqrt(hx * hx + hy * hy); _2bz = -_2q0mx * q2 + _2q0my * q1 + mz * q0q0 + _2q1mx * q3 - mz * q1q1 + _2q2 * my * q3 - mz * q2q2 + mz * q3q3; _4bx = 2.0f * _2bx; _4bz = 2.0f * _2bz; _8bx = 2.0f * _4bx; _8bz = 2.0f * _4bz; // Gradient decent algorithm corrective step s0 = -_2q2 * (2.0f * (q1q3 - q0q2) - ax) + _2q1 * (2.0f * (q0q1 + q2q3) - ay) + -_4bz * q2 * (_4bx * (0.5 - q2q2 - q3q3) + _4bz * (q1q3 - q0q2) - mx) + (-_4bx * q3 + _4bz * q1) * (_4bx * (q1q2 - q0q3) + _4bz * (q0q1 + q2q3) - my) + _4bx * q2 * (_4bx * (q0q2 + q1q3) + _4bz * (0.5 - q1q1 - q2q2) - mz); s1 = _2q3 * (2.0f * (q1q3 - q0q2) - ax) + _2q0 * (2.0f * (q0q1 + q2q3) - ay) + -4.0f * q1 * (2.0f * (0.5 - q1q1 - q2q2) - az) + _4bz * q3 * (_4bx * (0.5 - q2q2 - q3q3) + _4bz * (q1q3 - q0q2) - mx) + (_4bx * q2 + _4bz * q0) * (_4bx * (q1q2 - q0q3) + _4bz * (q0q1 + q2q3) - my) + (_4bx * q3 - _8bz * q1) * (_4bx * (q0q2 + q1q3) + _4bz * (0.5 - q1q1 - q2q2) - mz); s2 = -_2q0 * (2.0f * (q1q3 - q0q2) - ax) + _2q3 * (2.0f * (q0q1 + q2q3) - ay) + (-4.0f * q2) * (2.0f * (0.5 - q1q1 - q2q2) - az) + (-_8bx * q2 - _4bz * q0) * (_4bx * (0.5 - q2q2 - q3q3) + _4bz * (q1q3 - q0q2) - mx) + (_4bx * q1 + _4bz * q3) * (_4bx * (q1q2 - q0q3) + _4bz * (q0q1 + q2q3) - my) + (_4bx * q0 - _8bz * q2) * (_4bx * (q0q2 + q1q3) + _4bz * (0.5 - q1q1 - q2q2) - mz); s3 = _2q1 * (2.0f * (q1q3 - q0q2) - ax) + _2q2 * (2.0f * (q0q1 + q2q3) - ay) + (-_8bx * q3 + _4bz * q1) * (_4bx * (0.5 - q2q2 - q3q3) + _4bz * (q1q3 - q0q2) - mx) + (-_4bx * q0 + _4bz * q2) * (_4bx * (q1q2 - q0q3) + _4bz * (q0q1 + q2q3) - my) + (_4bx * q1) * (_4bx * (q0q2 + q1q3) + _4bz * (0.5 - q1q1 - q2q2) - mz); recipNorm = invSqrt(s0 * s0 + s1 * s1 + s2 * s2 + s3 * s3); // normalise step magnitude s0 *= recipNorm; s1 *= recipNorm; s2 *= recipNorm; s3 *= recipNorm; // Apply feedback step qDot1 -= beta * s0; qDot2 -= beta * s1; qDot3 -= beta * s2; qDot4 -= beta * s3; } // Integrate rate of change of quaternion to yield quaternion q0 += qDot1 * (deltat / (float)nstep); q1 += qDot2 * (deltat / (float)nstep); q2 += qDot3 * (deltat / (float)nstep); q3 += qDot4 * (deltat / (float)nstep); } // Normalise quaternion recipNorm = invSqrt(q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3); q0 *= recipNorm; q1 *= recipNorm; q2 *= recipNorm; q3 *= recipNorm; q[0] = q0; q[1] = q1; q[2] = q2; q[3] = q3; return; } int instability_fix = 0; //--------------------------------------------------------------------------------------------------- // Fast inverse square-root // See: http://en.wikipedia.org/wiki/Fast_inverse_square_root float invSqrt(float x) { if (instability_fix == 0) { /* original code */ float halfx = 0.5f * x; float y = x; long i = *(long*)&y; i = 0x5f3759df - (i >> 1); y = *(float*)&i; y = y * (1.5f - (halfx * y * y)); return y; } else if (instability_fix == 1) { /* close-to-optimal method with low cost from http://pizer.wordpress.com/2008/10/12/fast-inverse-square-root */ long i = 0x5f1f1412 - (*(long*)&x >> 1); float tmp = *(float*)&i; return tmp * (1.69000231f - 0.714158168f * x * tmp * tmp); } else { /* optimal but expensive method: */ return 1.0f / sqrtf(x); } }
38.382353
398
0.482912
c8ecbfa92a4059c1dba129b7e651db36801e08ec
545
ino
Arduino
_27._Serial_RGB_LED_Control/_27._Serial_RGB_LED_Control.ino
imd93shk/Learning-Arduino
c26c23f2c1d2195f17218e8c7cb376389a6162d9
[ "Apache-2.0" ]
null
null
null
_27._Serial_RGB_LED_Control/_27._Serial_RGB_LED_Control.ino
imd93shk/Learning-Arduino
c26c23f2c1d2195f17218e8c7cb376389a6162d9
[ "Apache-2.0" ]
null
null
null
_27._Serial_RGB_LED_Control/_27._Serial_RGB_LED_Control.ino
imd93shk/Learning-Arduino
c26c23f2c1d2195f17218e8c7cb376389a6162d9
[ "Apache-2.0" ]
null
null
null
const int Red_LED = 11; const int Green_LED = 10; const int Blue_LED = 9; int Rval = 0; int Gval = 0; int Bval = 0; void setup() { pinMode(Red_LED,OUTPUT); pinMode(Green_LED,OUTPUT); pinMode(Blue_LED,OUTPUT); Serial.begin(9600); } void loop() { while (Serial.available() > 0) { Rval = Serial.parseInt(); Gval = Serial.parseInt(); Bval = Serial.parseInt(); if (Serial.read() == '\n') { analogWrite(Red_LED, Rval); analogWrite(Green_LED, Gval); analogWrite(Blue_LED, Bval); } } }
17.03125
37
0.60367
d707407d76257a6bccdf14b9924e7b57be43a9fb
1,378
ino
Arduino
hardware/hamster/hamster/libraries/hamster/examples/wall_follow/wall_follow.ino
chcbaram/hamster_arduino
68ca4dc8dffb900f34d2d646322b2ece9eaded5f
[ "Apache-2.0" ]
1
2021-02-08T14:24:57.000Z
2021-02-08T14:24:57.000Z
hardware/hamster/hamster/libraries/hamster/examples/wall_follow/wall_follow.ino
chcbaram/hamster_arduino
68ca4dc8dffb900f34d2d646322b2ece9eaded5f
[ "Apache-2.0" ]
null
null
null
hardware/hamster/hamster/libraries/hamster/examples/wall_follow/wall_follow.ino
chcbaram/hamster_arduino
68ca4dc8dffb900f34d2d646322b2ece9eaded5f
[ "Apache-2.0" ]
null
null
null
#include <hamster.h> Hamster hamster; void setup() { // put your setup code here, to run once: hamster.begin("COM16"); } void loop() { int left; int right; int length; int error; int error_handle; int motor_speed = 0; int l_speed = 0; int r_speed = 0; int speed_control_out; int handle_control_out; int error_margin = 3; left = hamster.leftProximity(); right = hamster.rightProximity(); length = left+right / 2; error = 60 - length; speed_control_out = error / 1; if (speed_control_out < error_margin && speed_control_out > -error_margin) { speed_control_out = 0; } error_handle = (left - right); handle_control_out = error_handle / 1; if (handle_control_out < error_margin && handle_control_out > -error_margin) { handle_control_out = 0; } l_speed = speed_control_out - handle_control_out; r_speed = speed_control_out + handle_control_out; l_speed = constrain(l_speed, -100, 100); r_speed = constrain(r_speed, -100, 100); if (length == 0) { l_speed = 0; r_speed = 0; } Serial.print(length); Serial.print(" "); Serial.print(error); Serial.print(" "); Serial.print(speed_control_out); Serial.print(" "); Serial.print(handle_control_out); Serial.print(" "); Serial.print(motor_speed); Serial.println(""); hamster.wheels(l_speed, r_speed); delay(20); }
20.264706
78
0.664731
869064f30e544e8d91bbbbbd91ce991f2abf7a6e
37,033
ino
Arduino
examples/Generic_WS2812_Strip.ino
argueta-xyz/rPy-WS281x-Server
db0a78367460f752115c5ceaee82a69b1644aafd
[ "BSD-2-Clause" ]
null
null
null
examples/Generic_WS2812_Strip.ino
argueta-xyz/rPy-WS281x-Server
db0a78367460f752115c5ceaee82a69b1644aafd
[ "BSD-2-Clause" ]
null
null
null
examples/Generic_WS2812_Strip.ino
argueta-xyz/rPy-WS281x-Server
db0a78367460f752115c5ceaee82a69b1644aafd
[ "BSD-2-Clause" ]
null
null
null
#include <FS.h> #include <ESP8266WiFi.h> #include <ESP8266mDNS.h> #include <WiFiUdp.h> #include <ESP8266HTTPUpdateServer.h> #include <ESP8266WebServer.h> #include <NeoPixelBus.h> #include <WiFiManager.h> #include <ArduinoJson.h> IPAddress address ( 192, 168, 0, 95); // choose an unique IP Adress IPAddress gateway ( 192, 168, 0, 1); // Router IP IPAddress submask(255, 255, 255, 0); struct state { uint8_t colors[3], bri = 100, sat = 254, colorMode = 2; bool lightState; int ct = 200, hue; float stepLevel[3], currentColors[3], x, y; }; //core #define entertainmentTimeout 1500 // millis state lights[10]; bool inTransition, entertainmentRun, useDhcp = true; byte mac[6], packetBuffer[46]; long lastEPMillis; //settings char *lightName = "Hue rgb strip"; uint8_t scene, startup, onPin = 4, offPin = 5; bool hwSwitch = false; uint8_t lightsCount = 3; uint16_t pixelCount = 60, lightLedsCount; uint8_t transitionLeds = 6; // must be even number ESP8266WebServer server(80); WiFiUDP Udp; ESP8266HTTPUpdateServer httpUpdateServer; RgbColor red = RgbColor(255, 0, 0); RgbColor green = RgbColor(0, 255, 0); RgbColor white = RgbColor(255); RgbColor black = RgbColor(0); NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod>* strip = NULL; void convertHue(uint8_t light) { double hh, p, q, t, ff, s, v; long i; s = lights[light].sat / 255.0; v = lights[light].bri / 255.0; if (s <= 0.0) { // < is bogus, just shuts up warnings lights[light].colors[0] = v; lights[light].colors[1] = v; lights[light].colors[2] = v; return; } hh = lights[light].hue; if (hh >= 65535.0) hh = 0.0; hh /= 11850, 0; i = (long)hh; ff = hh - i; p = v * (1.0 - s); q = v * (1.0 - (s * ff)); t = v * (1.0 - (s * (1.0 - ff))); switch (i) { case 0: lights[light].colors[0] = v * 255.0; lights[light].colors[1] = t * 255.0; lights[light].colors[2] = p * 255.0; break; case 1: lights[light].colors[0] = q * 255.0; lights[light].colors[1] = v * 255.0; lights[light].colors[2] = p * 255.0; break; case 2: lights[light].colors[0] = p * 255.0; lights[light].colors[1] = v * 255.0; lights[light].colors[2] = t * 255.0; break; case 3: lights[light].colors[0] = p * 255.0; lights[light].colors[1] = q * 255.0; lights[light].colors[2] = v * 255.0; break; case 4: lights[light].colors[0] = t * 255.0; lights[light].colors[1] = p * 255.0; lights[light].colors[2] = v * 255.0; break; case 5: default: lights[light].colors[0] = v * 255.0; lights[light].colors[1] = p * 255.0; lights[light].colors[2] = q * 255.0; break; } } void convertXy(uint8_t light) { int optimal_bri = lights[light].bri; if (optimal_bri < 5) { optimal_bri = 5; } float Y = lights[light].y; float X = lights[light].x; float Z = 1.0f - lights[light].x - lights[light].y; // sRGB D65 conversion float r = X * 3.2406f - Y * 1.5372f - Z * 0.4986f; float g = -X * 0.9689f + Y * 1.8758f + Z * 0.0415f; float b = X * 0.0557f - Y * 0.2040f + Z * 1.0570f; // Apply gamma correction r = r <= 0.04045f ? r / 12.92f : pow((r + 0.055f) / (1.0f + 0.055f), 2.4f); g = g <= 0.04045f ? g / 12.92f : pow((g + 0.055f) / (1.0f + 0.055f), 2.4f); b = b <= 0.04045f ? b / 12.92f : pow((b + 0.055f) / (1.0f + 0.055f), 2.4f); if (r > b && r > g) { // red is biggest if (r > 1.0f) { g = g / r; b = b / r; r = 1.0f; } } else if (g > b && g > r) { // green is biggest if (g > 1.0f) { r = r / g; b = b / g; g = 1.0f; } } else if (b > r && b > g) { // blue is biggest if (b > 1.0f) { r = r / b; g = g / b; b = 1.0f; } } r = r < 0 ? 0 : r; g = g < 0 ? 0 : g; b = b < 0 ? 0 : b; lights[light].colors[0] = (int) (r * optimal_bri); lights[light].colors[1] = (int) (g * optimal_bri); lights[light].colors[2] = (int) (b * optimal_bri); } void convertCt(uint8_t light) { int hectemp = 10000 / lights[light].ct; int r, g, b; if (hectemp <= 66) { r = 255; g = 99.4708025861 * log(hectemp) - 161.1195681661; b = hectemp <= 19 ? 0 : (138.5177312231 * log(hectemp - 10) - 305.0447927307); } else { r = 329.698727446 * pow(hectemp - 60, -0.1332047592); g = 288.1221695283 * pow(hectemp - 60, -0.0755148492); b = 255; } r = r > 255 ? 255 : r; g = g > 255 ? 255 : g; b = b > 255 ? 255 : b; lights[light].colors[0] = r * (lights[light].bri / 255.0f); lights[light].colors[1] = g * (lights[light].bri / 255.0f); lights[light].colors[2] = b * (lights[light].bri / 255.0f); } void handleNotFound() { String message = "File Not Found\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); } void infoLight(RgbColor color) { // Flash the strip in the selected color. White = booted, green = WLAN connected, red = WLAN could not connect for (int i = 0; i < pixelCount; i++) { strip->SetPixelColor(i, color); strip->Show(); delay(10); strip->SetPixelColor(i, black); strip->Show(); } } void apply_scene(uint8_t new_scene) { for (uint8_t light = 0; light < lightsCount; light++) { if ( new_scene == 1) { lights[light].bri = 254; lights[light].ct = 346; lights[light].colorMode = 2; convertCt(light); } else if ( new_scene == 2) { lights[light].bri = 254; lights[light].ct = 233; lights[light].colorMode = 2; convertCt(light); } else if ( new_scene == 3) { lights[light].bri = 254; lights[light].ct = 156; lights[light].colorMode = 2; convertCt(light); } else if ( new_scene == 4) { lights[light].bri = 77; lights[light].ct = 367; lights[light].colorMode = 2; convertCt(light); } else if ( new_scene == 5) { lights[light].bri = 254; lights[light].ct = 447; lights[light].colorMode = 2; convertCt(light); } else if ( new_scene == 6) { lights[light].bri = 1; lights[light].x = 0.561; lights[light].y = 0.4042; lights[light].colorMode = 1; convertXy(light); } else if ( new_scene == 7) { lights[light].bri = 203; lights[light].x = 0.380328; lights[light].y = 0.39986; lights[light].colorMode = 1; convertXy(light); } else if ( new_scene == 8) { lights[light].bri = 112; lights[light].x = 0.359168; lights[light].y = 0.28807; lights[light].colorMode = 1; convertXy(light); } else if ( new_scene == 9) { lights[light].bri = 142; lights[light].x = 0.267102; lights[light].y = 0.23755; lights[light].colorMode = 1; convertXy(light); } else if ( new_scene == 10) { lights[light].bri = 216; lights[light].x = 0.393209; lights[light].y = 0.29961; lights[light].colorMode = 1; convertXy(light); } else { lights[light].bri = 144; lights[light].ct = 447; lights[light].colorMode = 2; convertCt(light); } } } void processLightdata(uint8_t light, float transitiontime) { transitiontime *= 17 - (pixelCount / 40); //every extra led add a small delay that need to be counted if (lights[light].colorMode == 1 && lights[light].lightState == true) { convertXy(light); } else if (lights[light].colorMode == 2 && lights[light].lightState == true) { convertCt(light); } else if (lights[light].colorMode == 3 && lights[light].lightState == true) { convertHue(light); } for (uint8_t i = 0; i < 3; i++) { if (lights[light].lightState) { lights[light].stepLevel[i] = ((float)lights[light].colors[i] - lights[light].currentColors[i]) / transitiontime; } else { lights[light].stepLevel[i] = lights[light].currentColors[i] / transitiontime; } } } RgbColor blending(float left[3], float right[3], uint8_t pixel) { uint8_t result[3]; for (uint8_t i = 0; i < 3; i++) { float percent = (float) pixel / (float) (transitionLeds + 1); result[i] = (left[i] * (1.0f - percent) + right[i] * percent) / 2; } return RgbColor((uint8_t)result[0], (uint8_t)result[1], (uint8_t)result[2]); } RgbColor convInt(float color[3]) { return RgbColor((uint8_t)color[0], (uint8_t)color[1], (uint8_t)color[2]); } RgbColor convFloat(float color[3]) { return RgbColor((uint8_t)color[0], (uint8_t)color[1], (uint8_t)color[2]); } void lightEngine() { for (int light = 0; light < lightsCount; light++) { if (lights[light].lightState) { if (lights[light].colors[0] != lights[light].currentColors[0] || lights[light].colors[1] != lights[light].currentColors[1] || lights[light].colors[2] != lights[light].currentColors[2]) { inTransition = true; for (uint8_t k = 0; k < 3; k++) { if (lights[light].colors[k] != lights[light].currentColors[k]) lights[light].currentColors[k] += lights[light].stepLevel[k]; if ((lights[light].stepLevel[k] > 0.0 && lights[light].currentColors[k] > lights[light].colors[k]) || (lights[light].stepLevel[k] < 0.0 && lights[light].currentColors[k] < lights[light].colors[k])) lights[light].currentColors[k] = lights[light].colors[k]; } if (lightsCount > 1) { if (light == 0) { for (uint8_t pixel = 0; pixel < lightLedsCount + transitionLeds / 2; pixel++) { if (pixel < lightLedsCount - transitionLeds / 2) { strip->SetPixelColor(pixel, convFloat(lights[light].currentColors)); } else { strip->SetPixelColor(pixel, blending(lights[0].currentColors, lights[1].currentColors, pixel + 1 - (lightLedsCount - transitionLeds / 2 ))); } } } else if (light == lightsCount - 1) { for (uint8_t pixel = 0; pixel < lightLedsCount + transitionLeds / 2 ; pixel++) { if (pixel < transitionLeds) { strip->SetPixelColor(pixel - transitionLeds / 2 + lightLedsCount * light, blending( lights[light - 1].currentColors, lights[light].currentColors, pixel + 1)); } else { strip->SetPixelColor(pixel - transitionLeds / 2 + lightLedsCount * light, convFloat(lights[light].currentColors)); } } } else { for (uint8_t pixel = 0; pixel < lightLedsCount + transitionLeds; pixel++) { if (pixel < transitionLeds) { strip->SetPixelColor(pixel - transitionLeds / 2 + lightLedsCount * light, blending( lights[light - 1].currentColors, lights[light].currentColors, pixel + 1)); } else if (pixel > lightLedsCount - 1) { strip->SetPixelColor(pixel - transitionLeds / 2 + lightLedsCount * light, blending( lights[light].currentColors, lights[light + 1].currentColors, pixel + 1 - lightLedsCount)); } else { strip->SetPixelColor(pixel - transitionLeds / 2 + lightLedsCount * light, convFloat(lights[light].currentColors)); } } } } else { strip->ClearTo(convFloat(lights[light].currentColors), 0, pixelCount - 1); } strip->Show(); } } else { if (lights[light].currentColors[0] != 0 || lights[light].currentColors[1] != 0 || lights[light].currentColors[2] != 0) { inTransition = true; for (uint8_t k = 0; k < 3; k++) { if (lights[light].currentColors[k] != 0) lights[light].currentColors[k] -= lights[light].stepLevel[k]; if (lights[light].currentColors[k] < 0) lights[light].currentColors[k] = 0; } if (lightsCount > 1) { if (light == 0) { for (uint8_t pixel = 0; pixel < lightLedsCount + transitionLeds / 2; pixel++) { if (pixel < lightLedsCount - transitionLeds / 2) { strip->SetPixelColor(pixel, convFloat(lights[light].currentColors)); } else { strip->SetPixelColor(pixel, blending( lights[light].currentColors, lights[light + 1].currentColors, pixel + 1 - (lightLedsCount - transitionLeds / 2 ))); } } } else if (light == lightsCount - 1) { for (uint8_t pixel = 0; pixel < lightLedsCount + transitionLeds / 2 ; pixel++) { if (pixel < transitionLeds) { strip->SetPixelColor(pixel - transitionLeds / 2 + lightLedsCount * light, blending( lights[light - 1].currentColors, lights[light].currentColors, pixel + 1)); } else { strip->SetPixelColor(pixel - transitionLeds / 2 + lightLedsCount * light, convFloat(lights[light].currentColors)); } } } else { for (uint8_t pixel = 0; pixel < lightLedsCount + transitionLeds; pixel++) { if (pixel < transitionLeds) { strip->SetPixelColor(pixel - transitionLeds / 2 + lightLedsCount * light, blending( lights[light - 1].currentColors, lights[light].currentColors, pixel + 1)); } else if (pixel > lightLedsCount - 1) { strip->SetPixelColor(pixel - transitionLeds / 2 + lightLedsCount * light, blending( lights[light].currentColors, lights[light + 1].currentColors, pixel + 1 - lightLedsCount)); } else { strip->SetPixelColor(pixel - transitionLeds / 2 + lightLedsCount * light, convFloat(lights[light].currentColors)); } } } } else { strip->ClearTo(convFloat(lights[light].currentColors), 0, pixelCount - 1); } strip->Show(); } } } if (inTransition) { delay(6); inTransition = false; } else if (hwSwitch == true) { if (digitalRead(onPin) == HIGH) { int i = 0; while (digitalRead(onPin) == HIGH && i < 30) { delay(20); i++; } for (int light = 0; light < lightsCount; light++) { if (i < 30) { // there was a short press lights[light].lightState = true; } else { // there was a long press lights[light].bri += 56; if (lights[light].bri > 255) { // don't increase the brightness more then maximum value lights[light].bri = 255; } } } } else if (digitalRead(offPin) == HIGH) { int i = 0; while (digitalRead(offPin) == HIGH && i < 30) { delay(20); i++; } for (int light = 0; light < lightsCount; light++) { if (i < 30) { // there was a short press lights[light].lightState = false; } else { // there was a long press lights[light].bri -= 56; if (lights[light].bri < 1) { // don't decrease the brightness less than minimum value. lights[light].bri = 1; } } } } } } void saveState() { DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); for (uint8_t i = 0; i < lightsCount; i++) { JsonObject& light = json.createNestedObject((String)i); light["on"] = lights[i].lightState; light["bri"] = lights[i].bri; if (lights[i].colorMode == 1) { light["x"] = lights[i].x; light["y"] = lights[i].y; } else if (lights[i].colorMode == 2) { light["ct"] = lights[i].ct; } else if (lights[i].colorMode == 3) { light["hue"] = lights[i].hue; light["sat"] = lights[i].sat; } } File stateFile = SPIFFS.open("/state.json", "w"); json.printTo(stateFile); } void restoreState() { File stateFile = SPIFFS.open("/state.json", "r"); if (!stateFile) { saveState(); return; } size_t size = stateFile.size(); // Allocate a buffer to store contents of the file. std::unique_ptr<char[]> buf(new char[size]); // We don't use String here because ArduinoJson library requires the input // buffer to be mutable. If you don't use ArduinoJson, you may as well // use configFile.readString instead. stateFile.readBytes(buf.get(), size); DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); if (!json.success()) { //Serial.println("Failed to parse config file"); return; } for (JsonPair& state : json) { const char* key = state.key; int lightId = atoi(key); JsonObject& values = state.value; lights[lightId].lightState = values["on"]; lights[lightId].bri = (uint8_t)values["bri"]; if (values.containsKey("x")) { lights[lightId].x = values["x"]; lights[lightId].y = values["y"]; lights[lightId].colorMode = 1; } else if (values.containsKey("ct")) { lights[lightId].ct = values["ct"]; lights[lightId].colorMode = 2; } else { if (values.containsKey("hue")) { lights[lightId].hue = values["hue"]; lights[lightId].colorMode = 3; } if (values.containsKey("sat")) { lights[lightId].sat = (uint8_t) values["sat"]; lights[lightId].colorMode = 3; } } } } bool saveConfig() { DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); json["name"] = lightName; json["startup"] = startup; json["scene"] = scene; json["on"] = onPin; json["off"] = offPin; json["hw"] = hwSwitch; json["dhcp"] = useDhcp; json["lightsCount"] = lightsCount; json["pixelCount"] = pixelCount; json["transLeds"] = transitionLeds; JsonArray& addr = json.createNestedArray("addr"); addr.add(address[0]); addr.add(address[1]); addr.add(address[2]); addr.add(address[3]); JsonArray& gw = json.createNestedArray("gw"); gw.add(gateway[0]); gw.add(gateway[1]); gw.add(gateway[2]); gw.add(gateway[3]); JsonArray& mask = json.createNestedArray("mask"); mask.add(submask[0]); mask.add(submask[1]); mask.add(submask[2]); mask.add(submask[3]); File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { //Serial.println("Failed to open config file for writing"); return false; } json.printTo(configFile); return true; } bool loadConfig() { File configFile = SPIFFS.open("/config.json", "r"); if (!configFile) { //Serial.println("Create new file with default values"); return saveConfig(); } size_t size = configFile.size(); if (size > 1024) { //Serial.println("Config file size is too large"); return false; } // Allocate a buffer to store contents of the file. std::unique_ptr<char[]> buf(new char[size]); // We don't use String here because ArduinoJson library requires the input // buffer to be mutable. If you don't use ArduinoJson, you may as well // use configFile.readString instead. configFile.readBytes(buf.get(), size); //Serial.println(buf.get()); DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); if (!json.success()) { //Serial.println("Failed to parse config file"); return false; } strcpy(lightName, json["name"]); startup = (uint8_t) json["startup"]; scene = (uint8_t) json["scene"]; onPin = (uint8_t) json["on"]; offPin = (uint8_t) json["off"]; hwSwitch = json["hw"]; lightsCount = (uint16_t) json["lightsCount"]; pixelCount = (uint16_t) json["pixelCount"]; transitionLeds = (uint8_t) json["transLeds"]; useDhcp = json["dhcp"]; address = {json["addr"][0], json["addr"][1], json["addr"][2], json["addr"][3]}; submask = {json["mask"][0], json["mask"][1], json["mask"][2], json["mask"][3]}; gateway = {json["gw"][0], json["gw"][1], json["gw"][2], json["gw"][3]}; return true; } void ChangeNeoPixels(uint16_t newCount) { if (strip != NULL) { delete strip; // delete the previous dynamically created strip } strip = new NeoPixelBus<NeoGrbFeature, Neo800KbpsMethod>(newCount); // and recreate with new count strip->Begin(); } void setup() { //Serial.begin(115200); //Serial.println(); delay(1000); //Serial.println("mounting FS..."); if (!SPIFFS.begin()) { //Serial.println("Failed to mount file system"); return; } if (!loadConfig()) { //Serial.println("Failed to load config"); } else { ////Serial.println("Config loaded"); } lightLedsCount = pixelCount / lightsCount; ChangeNeoPixels(pixelCount); if (startup == 1) { for (uint8_t i = 0; i < lightsCount; i++) { lights[i].lightState = true; } } if (startup == 0) { restoreState(); } else { apply_scene(scene); } for (uint8_t i = 0; i < lightsCount; i++) { processLightdata(i, 4); } if (lights[0].lightState) { for (uint8_t i = 0; i < 200; i++) { lightEngine(); } } WiFiManager wifiManager; if (!useDhcp) { wifiManager.setSTAStaticIPConfig(address, gateway, submask); } if (!wifiManager.autoConnect(lightName)) { delay(3000); ESP.reset(); delay(5000); } if (useDhcp) { address = WiFi.localIP(); gateway = WiFi.gatewayIP(); submask = WiFi.subnetMask(); } if (! lights[0].lightState) { infoLight(white); while (WiFi.status() != WL_CONNECTED) { infoLight(red); delay(500); } // Show that we are connected infoLight(green); } WiFi.macAddress(mac); httpUpdateServer.setup(&server); Udp.begin(2100); if (hwSwitch == true) { pinMode(onPin, INPUT); pinMode(offPin, INPUT); } server.on("/state", HTTP_PUT, []() { bool stateSave = false; DynamicJsonBuffer newBuffer; JsonObject& root = newBuffer.parseObject(server.arg("plain")); if (!root.success()) { server.send(404, "text/plain", "FAIL. " + server.arg("plain")); } else { for (JsonPair& state : root) { const char* key = state.key; int light = atoi(key) - 1; JsonObject& values = state.value; int transitiontime = 4; if (values.containsKey("xy")) { lights[light].x = values["xy"][0]; lights[light].y = values["xy"][1]; lights[light].colorMode = 1; } else if (values.containsKey("ct")) { lights[light].ct = values["ct"]; lights[light].colorMode = 2; } else { if (values.containsKey("hue")) { lights[light].hue = values["hue"]; lights[light].colorMode = 3; } if (values.containsKey("sat")) { lights[light].sat = values["sat"]; lights[light].colorMode = 3; } } if (values.containsKey("on")) { if (values["on"]) { lights[light].lightState = true; } else { lights[light].lightState = false; } if (startup == 0) { stateSave = true; } } if (values.containsKey("bri")) { lights[light].bri = values["bri"]; } if (values.containsKey("bri_inc")) { lights[light].bri += (int) values["bri_inc"]; if (lights[light].bri > 255) lights[light].bri = 255; else if (lights[light].bri < 1) lights[light].bri = 1; } if (values.containsKey("transitiontime")) { transitiontime = values["transitiontime"]; } if (values.containsKey("alert") && values["alert"] == "select") { if (lights[light].lightState) { lights[light].currentColors[0] = 0; lights[light].currentColors[1] = 0; lights[light].currentColors[2] = 0; lights[light].currentColors[3] = 0; } else { lights[light].currentColors[3] = 126; lights[light].currentColors[4] = 126; } } processLightdata(light, transitiontime); } String output; root.printTo(output); server.send(200, "text/plain", output); if (stateSave) { saveState(); } } }); server.on("/state", HTTP_GET, []() { uint8_t light = server.arg("light").toInt() - 1; DynamicJsonBuffer newBuffer; JsonObject& root = newBuffer.createObject(); root["on"] = lights[light].lightState; root["bri"] = lights[light].bri; JsonArray& xy = root.createNestedArray("xy"); xy.add(lights[light].x); xy.add(lights[light].y); root["ct"] = lights[light].ct; root["hue"] = lights[light].hue; root["sat"] = lights[light].sat; if (lights[light].colorMode == 1) root["colormode"] = "xy"; else if (lights[light].colorMode == 2) root["colormode"] = "ct"; else if (lights[light].colorMode == 3) root["colormode"] = "hs"; String output; root.printTo(output); server.send(200, "text/plain", output); }); server.on("/detect", []() { char macString[32] = {0}; sprintf(macString, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); DynamicJsonBuffer newBuffer; JsonObject& root = newBuffer.createObject(); root["name"] = lightName; root["lights"] = lightsCount; root["protocol"] = "native_multi"; root["modelid"] = "LST002"; root["type"] = "ws2812_strip"; root["mac"] = String(macString); root["version"] = 2.0; String output; root.printTo(output); server.send(200, "text/plain", output); }); server.on("/config", []() { DynamicJsonBuffer newBuffer; JsonObject& root = newBuffer.createObject(); root["name"] = lightName; root["scene"] = scene; root["startup"] = startup; root["hw"] = hwSwitch; root["on"] = onPin; root["off"] = offPin; root["hwswitch"] = (int)hwSwitch; root["lightscount"] = lightsCount; root["pixelcount"] = pixelCount; root["transitionleds"] = transitionLeds; root["dhcp"] = (int)useDhcp; root["addr"] = (String)address[0] + "." + (String)address[1] + "." + (String)address[2] + "." + (String)address[3]; root["gw"] = (String)gateway[0] + "." + (String)gateway[1] + "." + (String)gateway[2] + "." + (String)gateway[3]; root["sm"] = (String)submask[0] + "." + (String)submask[1] + "." + (String)submask[2] + "." + (String)submask[3]; String output; root.printTo(output); server.send(200, "text/plain", output); }); server.on("/", []() { if (server.hasArg("scene")) { server.arg("name").toCharArray(lightName, server.arg("name").length() + 1); startup = server.arg("startup").toInt(); scene = server.arg("scene").toInt(); lightsCount = server.arg("lightscount").toInt(); pixelCount = server.arg("pixelcount").toInt(); transitionLeds = server.arg("transitionleds").toInt(); hwSwitch = server.arg("hwswitch").toInt(); onPin = server.arg("on").toInt(); offPin = server.arg("off").toInt(); saveConfig(); } else if (server.hasArg("dhcp")) { useDhcp = server.arg("dhcp").toInt(); address.fromString(server.arg("addr")); gateway.fromString(server.arg("gw")); submask.fromString(server.arg("sm")); saveConfig(); } const char * htmlContent = "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <title>Hue Light</title> <link rel=\"stylesheet\" href=\"https://diyhue.org/cdn/bootstrap.min.css\"> <link rel=\"stylesheet\" href=\"https://diyhue.org/cdn/ion.rangeSlider.min.css\"/> <script src=\"https://diyhue.org/cdn/jquery-3.3.1.min.js\"></script> <script src=\"https://diyhue.org/cdn/bootstrap.min.js\"></script> <script src=\"https://diyhue.org/cdn/ion.rangeSlider.min.js\"></script> </head> <body> <nav class=\"navbar navbar-expand-lg navbar-light bg-light rounded\"> <button class=\"navbar-toggler\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarToggler\" aria-controls=\"navbarToggler\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <h2></h2> <div class=\"collapse navbar-collapse justify-content-md-center\" id=\"navbarToggler\"> <ul class=\"nav nav-pills\"> <li class=\"nav-item\"> <a class=\"nav-link active\" data-toggle=\"pill\" href=\"#home\">Home</a> </li><li class=\"nav-item\"> <a class=\"nav-link\" data-toggle=\"pill\" href=\"#menu1\">Settings</a> </li><li class=\"nav-item\"> <a class=\"nav-link\" data-toggle=\"pill\" href=\"#menu2\">Network</a> </li><li class=\"nav-item\"> <a class=\"nav-link\" data-toggle=\"pill\" href=\"#\" disabled> </a> </li><li class=\"nav-item\"> <a class=\"nav-link\" data-toggle=\"pill\" href=\"#\" disabled> </a> </li></ul> </div></nav> <div class=\"tab-content\"> <div class=\"tab-pane container active\" id=\"home\"> <br><br><form> <div class=\"form-group row\"> <label for=\"power\" class=\"col-sm-2 col-form-label\">Power</label> <div class=\"col-sm-10\"> <div id=\"power\" class=\"btn-group\" role=\"group\"> <button type=\"button\" class=\"btn btn-default border\" id=\"power-on\">On</button> <button type=\"button\" class=\"btn btn-default border\" id=\"power-off\">Off</button> </div></div></div><div class=\"form-group row\"> <label for=\"bri\" class=\"col-sm-2 col-form-label\">Brightness</label> <div class=\"col-sm-10\"> <input type=\"text\" id=\"bri\" class=\"js-range-slider\" name=\"bri\" value=\"\"/> </div></div><div class=\"form-group row\"> <label for=\"hue\" class=\"col-sm-2 col-form-label\">Color</label> <div class=\"col-sm-10\"> <canvas id=\"hue\" width=\"320px\" height=\"320px\" style=\"border:1px solid #d3d3d3;\"></canvas> </div></div><div class=\"form-group row\"> <label for=\"color\" class=\"col-sm-2 col-form-label\">Color Temp</label> <div class=\"col-sm-10\"> <canvas id=\"ct\" width=\"320px\" height=\"50px\" style=\"border:1px solid #d3d3d3;\"></canvas> </div></div></form> </div><div class=\"tab-pane container fade\" id=\"menu1\"> <br><form method=\"POST\" action=\"/\"> <div class=\"form-group row\"> <label for=\"name\" class=\"col-sm-2 col-form-label\">Light Name</label> <div class=\"col-sm-6\"> <input type=\"text\" class=\"form-control\" id=\"name\" name=\"name\"> </div></div><div class=\"form-group row\"> <label class=\"control-label col-sm-2\" for=\"startup\">Default Power:</label> <div class=\"col-sm-4\"> <select class=\"form-control\" name=\"startup\" id=\"startup\"> <option value=\"0\">Last State</option> <option value=\"1\">On</option> <option value=\"2\">Off</option> </select> </div></div><div class=\"form-group row\"> <label class=\"control-label col-sm-2\" for=\"scene\">Default Scene:</label> <div class=\"col-sm-4\"> <select class=\"form-control\" name=\"scene\" id=\"scene\"> < <option value=\"0\">Relax</option> <option value=\"1\">Read</option> <option value=\"2\">Concentrate</option> <option value=\"3\">Energize</option> <option value=\"4\">Bright</option> <option value=\"5\">Dimmed</option> <option value=\"6\">Nightlight</option> <option value=\"7\">Savanna sunset</option> <option value=\"8\">Tropical twilight</option> <option value=\"9\">Arctic aurora</option> <option value=\"10\">Spring blossom</option> </select> </div></div><div class=\"form-group row\"> <label for=\"pixelcount\" class=\"col-sm-2 col-form-label\">Pixel Count</label> <div class=\"col-sm-3\"> <input type=\"number\" class=\"form-control\" id=\"pixelcount\" name=\"pixelcount\" placeholder=\"\"> </div></div><div class=\"form-group row\"> <label for=\"lightscount\" class=\"col-sm-2 col-form-label\">Lights Count</label> <div class=\"col-sm-3\"> <input type=\"number\" class=\"form-control\" id=\"lightscount\" name=\"lightscount\" placeholder=\"\"> </div></div><div class=\"form-group row\"> <label class=\"control-label col-sm-2\" for=\"transitionleds\">Transition Leds:</label> <div class=\"col-sm-3\"> <select class=\"form-control\" name=\"transitionleds\" id=\"transitionleds\"> <option value=\"0\">0</option> <option value=\"2\">2</option> <option value=\"4\">4</option> <option value=\"6\">6</option> <option value=\"8\">8</option> <option value=\"10\">10</option> </select> </div></div><div class=\"form-group row\"> <label class=\"control-label col-sm-2\" for=\"hwswitch\">HW Switch:</label> <div class=\"col-sm-2\"> <select class=\"form-control\" name=\"hwswitch\" id=\"hwswitch\"> <option value=\"1\">Yes</option> <option value=\"0\">No</option> </select> </div></div><div class=\"form-group row\"> <label for=\"on\" class=\"col-sm-2 col-form-label\">On Pin</label> <div class=\"col-sm-3\"> <input type=\"number\" class=\"form-control\" id=\"on\" name=\"on\" placeholder=\"\"> </div></div><div class=\"form-group row\"> <label for=\"off\" class=\"col-sm-2 col-form-label\">Off Pin</label> <div class=\"col-sm-3\"> <input type=\"number\" class=\"form-control\" id=\"off\" name=\"off\" placeholder=\"\"> </div></div><div class=\"form-group row\"> <div class=\"col-sm-10\"> <button type=\"submit\" class=\"btn btn-primary\">Save</button> </div></div></form> </div><div class=\"tab-pane container fade\" id=\"menu2\"> <br><form method=\"POST\" action=\"/\"> <div class=\"form-group row\"> <label class=\"control-label col-sm-2\" for=\"dhcp\">DHCP:</label> <div class=\"col-sm-3\"> <select class=\"form-control\" name=\"dhcp\" id=\"dhcp\"> <option value=\"1\">On</option> <option value=\"0\">Off</option> </select> </div></div><div class=\"form-group row\"> <label for=\"addr\" class=\"col-sm-2 col-form-label\">Ip</label> <div class=\"col-sm-4\"> <input type=\"text\" class=\"form-control\" id=\"addr\" name=\"addr\"> </div></div><div class=\"form-group row\"> <label for=\"sm\" class=\"col-sm-2 col-form-label\">Submask</label> <div class=\"col-sm-4\"> <input type=\"text\" class=\"form-control\" id=\"sm\" name=\"sm\"> </div></div><div class=\"form-group row\"> <label for=\"gw\" class=\"col-sm-2 col-form-label\">Gateway</label> <div class=\"col-sm-4\"> <input type=\"text\" class=\"form-control\" id=\"gw\" name=\"gw\"> </div></div><div class=\"form-group row\"> <div class=\"col-sm-10\"> <button type=\"submit\" class=\"btn btn-primary\">Save</button> </div></div></form> </div></div><script src=\"https://diyhue.org/cdn/color-multi.min.js\"></script> </body></html>"; server.send(200, "text/html", htmlContent); if (server.args()) { delay(100); ESP.reset(); } }); server.on("/reset", []() { server.send(200, "text/html", "reset"); delay(100); ESP.reset(); }); server.onNotFound(handleNotFound); server.begin(); } RgbColor blendingEntert(float left[3], float right[3], float pixel) { uint8_t result[3]; for (uint8_t i = 0; i < 3; i++) { float percent = (float) pixel / (float) (transitionLeds + 1); result[i] = (left[i] * (1.0f - percent) + right[i] * percent) / 2; } return RgbColor((uint8_t)result[0], (uint8_t)result[1], (uint8_t)result[2]); } void entertainment() { uint8_t packetSize = Udp.parsePacket(); if (packetSize) { if (!entertainmentRun) { entertainmentRun = true; } lastEPMillis = millis(); Udp.read(packetBuffer, packetSize); for (uint8_t i = 0; i < packetSize / 4; i++) { lights[packetBuffer[i * 4]].currentColors[0] = packetBuffer[i * 4 + 1]; lights[packetBuffer[i * 4]].currentColors[1] = packetBuffer[i * 4 + 2]; lights[packetBuffer[i * 4]].currentColors[2] = packetBuffer[i * 4 + 3]; } for (uint8_t light = 0; light < lightsCount; light++) { if (lightsCount > 1) { if (light == 0) { for (uint8_t pixel = 0; pixel < lightLedsCount + transitionLeds / 2; pixel++) { if (pixel < lightLedsCount - transitionLeds / 2) { strip->SetPixelColor(pixel, convInt(lights[light].currentColors)); } else { strip->SetPixelColor(pixel, blendingEntert(lights[0].currentColors, lights[1].currentColors, pixel + 1 - (lightLedsCount - transitionLeds / 2 ))); } } } else if (light == lightsCount - 1) { for (uint8_t pixel = 0; pixel < lightLedsCount - transitionLeds / 2 ; pixel++) { strip->SetPixelColor(pixel + transitionLeds / 2 + lightLedsCount * light, convInt(lights[light].currentColors)); } } else { for (uint8_t pixel = 0; pixel < lightLedsCount; pixel++) { if (pixel < lightLedsCount - transitionLeds) { strip->SetPixelColor(pixel + transitionLeds / 2 + lightLedsCount * light, convInt(lights[light].currentColors)); } else { strip->SetPixelColor(pixel + transitionLeds / 2 + lightLedsCount * light, blendingEntert(lights[light].currentColors, lights[light + 1].currentColors, pixel - (lightLedsCount - transitionLeds ) + 1)); } } } } else { strip->ClearTo(RgbColor(lights[0].colors[0], lights[0].colors[1], lights[0].colors[2]), 0, lightLedsCount - 1); } } strip->Show(); } } void loop() { server.handleClient(); if (!entertainmentRun) { lightEngine(); } else { if ((millis() - lastEPMillis) >= entertainmentTimeout) { entertainmentRun = false; for (uint8_t i = 0; i < lightsCount; i++) { processLightdata(i, 4); //return to original colors with 0.4 sec transition } } } entertainment(); }
41.147778
7,018
0.592742
6e9442cf2f438f2599b637a5b9116001efb076e7
781
ino
Arduino
Progetto-03/src/sd-edge/sd-edge.ino
MatteoRagazzini/IoT-Projects
a8298e4e649264c9cf803c6876d6bd5006f1389c
[ "MIT" ]
null
null
null
Progetto-03/src/sd-edge/sd-edge.ino
MatteoRagazzini/IoT-Projects
a8298e4e649264c9cf803c6876d6bd5006f1389c
[ "MIT" ]
null
null
null
Progetto-03/src/sd-edge/sd-edge.ino
MatteoRagazzini/IoT-Projects
a8298e4e649264c9cf803c6876d6bd5006f1389c
[ "MIT" ]
null
null
null
#include "Dumpster.h" #include <ESP8266HTTPClient.h> #include <ESP8266WiFi.h> /* wifi network name */ char* ssidName = "Matteo"; /* WPA2 PSK password */ char* pwd = "ciaociao"; /* service IP address */ String address = "http://68c04524.ngrok.io"; Dumpster* dumpster = new Dumpster(address); void setup() { Serial.begin(115200); WiFi.begin(ssidName, pwd); Serial.print("Connecting..."); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("Connected"); } void loop() { if (WiFi.status()== WL_CONNECTED){ dumpster->manageState(); } else { Serial.println("Error in WiFi connection"); } delay(2000); }
20.552632
56
0.560819
70d952f48924805760c7739bbdd6d209cbe38a58
1,803
ino
Arduino
software/control_unit_software/esp8266_officenv_switch/esp8266_officenv_switch.ino
teancake/Indoor-Air-Quality-Monitoring-and-Control-System
41d20948321e1f5ee58f052f39a14f2073bca0d8
[ "MIT" ]
null
null
null
software/control_unit_software/esp8266_officenv_switch/esp8266_officenv_switch.ino
teancake/Indoor-Air-Quality-Monitoring-and-Control-System
41d20948321e1f5ee58f052f39a14f2073bca0d8
[ "MIT" ]
2
2017-02-22T01:52:05.000Z
2017-04-12T04:34:04.000Z
software/control_unit_software/esp8266_officenv_switch/esp8266_officenv_switch.ino
teancake/Indoor-Air-Quality-Monitoring-and-Control-System
41d20948321e1f5ee58f052f39a14f2073bca0d8
[ "MIT" ]
null
null
null
/* Control unit software for the office environment monitoring and control * system. The program should be programmed into the ESP8266 chip. * Xiaoke Yang (das.xiaoke@hotmail.com) * IFFPC, Beihang University * Last Modified: Mon 16 Jan 2017 17:06:39 CST */ #include <ESP8266WiFi.h> #include <PubSubClient.h> #define RELAY_PIN 4 /************************* WiFi Access Point *********************************/ #define WLAN_SSID "wifissid" #define WLAN_PASS "wifipassword" /************************* Adafruit.io Setup *********************************/ #define AIO_SERVER "192.168.xx.xxx" #define AIO_SERVERPORT 1883 #define AIO_CID "airpurifier_switch" #define AIO_USERNAME "mqtt_username" #define AIO_KEY "mqtt_password" #define MQTT_TOPIC_CONTROL "office/switch/airpurifier" WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; char msg[50]; int value = 0; void setup_wifi() { WiFi.begin(WLAN_SSID, WLAN_PASS); while (WiFi.status() != WL_CONNECTED) { delay(1000); } } void callback(char* topic, byte* payload, unsigned int length) { if ((char)payload[0] == '0') { digitalWrite(RELAY_PIN, LOW); } else { digitalWrite(RELAY_PIN, HIGH); } } void reconnect() { while (!client.connected()) { if (client.connect(AIO_CID, AIO_USERNAME, AIO_KEY )) { // subscribe control actions topic client.subscribe(MQTT_TOPIC_CONTROL); } else { // Wait 5 seconds before retrying delay(5000); } } } void setup() { pinMode(RELAY_PIN, OUTPUT); // Initialize the BUILTIN_LED pin as an output setup_wifi(); client.setServer(AIO_SERVER, AIO_SERVERPORT); client.setCallback(callback); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); }
22.822785
80
0.637271
0b630e976780ea35d65600c94af3b43c856383f4
9,868
ino
Arduino
Arduino/arduino_sketches/project_e/temp_control/temp_control.ino
torstefan/derp
9fb26f339560fc44d8a499dc7f0ef0a56d8389ce
[ "Beerware" ]
null
null
null
Arduino/arduino_sketches/project_e/temp_control/temp_control.ino
torstefan/derp
9fb26f339560fc44d8a499dc7f0ef0a56d8389ce
[ "Beerware" ]
null
null
null
Arduino/arduino_sketches/project_e/temp_control/temp_control.ino
torstefan/derp
9fb26f339560fc44d8a499dc7f0ef0a56d8389ce
[ "Beerware" ]
null
null
null
#include <Button.h> #include <SoftwareSerial.h> #include <OneWire.h> #include <DallasTemperature.h> #include <Potentiometer.h> #include <MemoryFree.h> #include <PID_v1.h> #define POTENTIOMETER_PIN A0 #define DISPLAY_TX_PIN 8 #define DISPLAY_RX_PIN 10 #define DISPLAY_RESET_PIN 7 #define BIG_BUTTON_PIN 2 #define L_BUTTON_PIN 4 #define R_BUTTON_PIN 5 #define REMOTE_PWR_ON 10 #define REMOTE_PWR_OFF 11 #define TEMPERATURE_PROBE_PIN 9 #define TEMPERATURE_PRECISION 12 #define PRETTY_PRINT_MULTIPLIER 10 #define MIN_PWR_SWITCH_PAUSE 10 enum { COMMA=5, COMMA_10=6, COLON, NONE }; enum { ON=10, OFF=11 }; const int led = 12; boolean isLedOn = false; long timeSincePwrSwitch; unsigned long lastPollPeriod = 0; const int pollPeriod = 1000; unsigned long lastTimeChangePeriod = 0; float lastTempChangePeriod = 0.0; int lastPowerState; int holdTemp = 0; float acceptedChange = 0.0; int pwr_switch_pause_addition = 0; int menuItemSelected; Potentiometer potentiometer = Potentiometer(POTENTIOMETER_PIN); Button big_button = Button(BIG_BUTTON_PIN,BUTTON_PULLUP); Button l_button = Button(L_BUTTON_PIN,BUTTON_PULLUP); Button r_button = Button(R_BUTTON_PIN,BUTTON_PULLUP); SoftwareSerial s7s(DISPLAY_RX_PIN, DISPLAY_TX_PIN); OneWire oneWire(TEMPERATURE_PROBE_PIN); DallasTemperature temp_probe(&oneWire); String out; // // PID - Global variables // //Define Variables we'll be connecting to double Setpoint, Input, Output; //Specify the links and initial tuning parameters PID myPID(&Input, &Output, &Setpoint,30,3,5, DIRECT); int WindowSize = 5000; unsigned long windowStartTime; void setup() { Serial.begin(115200); Serial.println(F("Project C - SousVide Edition")); Serial.println(F("Setup staring.")); pinMode(led,OUTPUT); pinMode(DISPLAY_RESET_PIN, OUTPUT); pinMode(BIG_BUTTON_PIN, INPUT_PULLUP); // Enable internal pull-up resistor on pin pinMode(L_BUTTON_PIN, INPUT_PULLUP); // Enable internal pull-up resistor on pin pinMode(R_BUTTON_PIN, INPUT_PULLUP); // Enable internal pull-up resistor on pin pinMode(REMOTE_PWR_ON, OUTPUT); pinMode(REMOTE_PWR_OFF, OUTPUT); reset_display(DISPLAY_RESET_PIN); s7s.begin(9600); temp_probe.begin(); temp_probe.setResolution(TEMPERATURE_PRECISION); potentiometer.setSectors(2); // Two choises for the menu. Temp control ON, or OFF Serial.println(F("Turning off remote power ")); remote_power_on(); delay(5000); remote_power_off(); print_power_state(); reset_display(DISPLAY_RESET_PIN); // // Pid - Setup // windowStartTime = millis(); //initialize the variables we're linked to Setpoint = 100; //tell the PID to range between 0 and the full window size myPID.SetOutputLimits(0, WindowSize); //turn the PID on myPID.SetMode(AUTOMATIC); } void loop() { menuItemSelected = potentiometer.getSector(); if((millis() - lastPollPeriod) > pollPeriod) { lastPollPeriod = millis(); isLedOn = !isLedOn; digitalWrite(led, isLedOn ? HIGH : LOW ); out = ""; get_new_variables_from_serial(); print_power_state(); float temp = get_temp(); int temp_do_display = temp * PRETTY_PRINT_MULTIPLIER; print_status(temp); if(menuItemSelected == 1){ if(big_button.isPressed()){ myPID.SetMode(MANUAL); holdTemp = get_new_hold_temp(); myPID.SetMode(AUTOMATIC); } // Main magic - Does temp control on heater, and writes the result to dispaly if(do_temp_control(temp, holdTemp)){ write_text("H" + (String)(temp_do_display),COMMA); }else{ write_text("C" + (String)(temp_do_display),COMMA); } }else{ write_text((String)(temp_do_display) ,COMMA); } Serial.println(out); } switch_remote_pwr(l_button.isPressed() ? ON : NONE); switch_remote_pwr(r_button.isPressed() ? OFF : NONE); } String to_string_from_float(float input){ char outstr[15]; dtostrf(input,sizeof(input), 2, outstr); // input float, output size, trailing digits after . , putput buffer. return (String)outstr; } void print_status(float temp){ out += "Menu_selected="; out += menuItemSelected; // Converts the float into a serial out += " Temp_hr_0="; out += to_string_from_float(temp); out += " "; out += "Hold_temp=" + (String)holdTemp + " "; float tempChange = get_temp_change(10, temp); out += "Temp_change="; out += to_string_from_float(tempChange) + " "; } float get_temp_change(unsigned int per_n_second, float temp_now){ if((millis() - lastTimeChangePeriod) > (per_n_second * 1000)){ float temp_change = temp_now - lastTempChangePeriod; lastTimeChangePeriod = millis(); lastTempChangePeriod = temp_now; return temp_change; }else{ return 0; } } void get_new_variables_from_serial(){ int new_holdTemp; // Tells the arduno which temperature to reach. int new_pwr_switch_pause_addition; // The pause time between switching the remote power on off. float new_acceptedChange; if(Serial.available() >0){ new_holdTemp = Serial.parseInt(); if(Serial.read() == '\n'){ if(new_holdTemp >= 0){ holdTemp = new_holdTemp; out = out + "\nnew_hold_temp=" + (String)holdTemp +"\n"; } } } out = out + "PSP=" + (String)(MIN_PWR_SWITCH_PAUSE + pwr_switch_pause_addition) + " "; } int get_new_hold_temp(){ int temp = (int)get_temp(); clear_display(); delay(200); write_text((String)(temp * PRETTY_PRINT_MULTIPLIER),COMMA); delay(1000); clear_display(); delay(200); return temp; } // // Magic happens here! // boolean do_temp_control(float temp, int holdTemp){ print_pid_params(); Input = (double)get_temp(); Setpoint = (double) holdTemp; myPID.Compute(); // Output is a global variable from the myPID object. out += "PID_output=" + (String)Output + " "; /************************************************ * turn the output pin on/off based on pid output ************************************************/ unsigned long now = millis(); if(now - windowStartTime>WindowSize) { //time to shift the Relay Window windowStartTime += WindowSize; } out +="PID_gt=" + (String)(now - windowStartTime) + " "; if(Output > now - windowStartTime) { switch_remote_pwr(ON); return true; }else{ switch_remote_pwr(OFF); return false; } } void print_pid_params(){ out += "Kp=" + (String)myPID.GetKp() + " "; out += "Ki=" + (String)myPID.GetKi() + " "; out += "Kd=" + (String)myPID.GetKd() + " "; out += "PID_mode=" + (String)myPID.GetMode() + " "; out += "PID_direction=" + (String)myPID.GetDirection() + " "; } void print_power_state(){ out = out + "Last_Power_State="; lastPowerState == 11 ? out = out + "OFF " : out = out + "ON "; } void switch_remote_pwr(int power_status){ if (power_status == NONE){ return; } int power_switch_pause_seconds = MIN_PWR_SWITCH_PAUSE + pwr_switch_pause_addition; long deltaTime = millis() - timeSincePwrSwitch; out = out + "delta_lock="; if(deltaTime > (power_switch_pause_seconds * 1000)){ out = out + "OFF "; }else{ out = out + "ON "; } if(power_status != lastPowerState && deltaTime > (power_switch_pause_seconds * 1000)){ switch(power_status) { case ON: remote_power_on(); break; case OFF: remote_power_off(); break; default: break; } }else if (l_button.isPressed() || r_button.isPressed()) { if(power_status == lastPowerState && deltaTime < (power_switch_pause_seconds * 1000)){ power_status == ON ? write_text("ON", NONE) : write_text("OFF", NONE); }else{ write_text((String)(deltaTime / 1000), NONE); delay(500); write_text("D"+(String)power_switch_pause_seconds, NONE); delay(500); } } } void remote_power_off(){ digitalWrite(REMOTE_PWR_OFF, HIGH); delay(100); digitalWrite(REMOTE_PWR_OFF, LOW); lastPowerState = OFF; timeSincePwrSwitch = millis(); write_text((String)"OFF", NONE); delay(500); } void remote_power_on(){ digitalWrite(REMOTE_PWR_ON, HIGH); delay(100); digitalWrite(REMOTE_PWR_ON, LOW); lastPowerState = ON; timeSincePwrSwitch = millis(); write_text((String)"ON", NONE); delay(500); } float get_temp(){ temp_probe.requestTemperatures(); // Send the command to get temperatures //temp_probe.setResolution(TEMPERATURE_PRECISION); float t = temp_probe.getTempCByIndex(0); return t; } void blink_led(int led){ digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level) delay(100); // wait for a second digitalWrite(led, LOW); // turn the LED off by making the voltage LOW } void reset_display(int resetDispPin){ digitalWrite(resetDispPin, LOW); delay(300); digitalWrite(resetDispPin, HIGH); } void write_text(String text, int punct_mark ){ char tempString[10]; // Will be used with sprintf to create strings char t[5]; text.toCharArray(t,5); sprintf(tempString, "%4s", t); s7s.print(tempString); switch(punct_mark) { case COLON: set_decimals(0b00010000); // Sets digit 3 decimal on break; case COMMA: set_decimals(0b00000100); // Sets digit 3 decimal on break; case COMMA_10: set_decimals(0b00000010); // Sets digit 3 decimal on break; default: set_decimals(0b00000000); } delay(100); } void clear_display(){ s7s.write(0x76); } void set_decimals(byte decimals) { s7s.write(0x77); s7s.write(decimals); }
22.427273
114
0.64998
cb01d703c2b2cf44dc7f9fc81919bb898b2a4eb2
268
ino
Arduino
main2/main/doPrintResults.ino
giacomocalabria/arduino-react-time-speed
b01da02d7a4559a8b602e41e7e61789430c58e89
[ "MIT" ]
null
null
null
main2/main/doPrintResults.ino
giacomocalabria/arduino-react-time-speed
b01da02d7a4559a8b602e41e7e61789430c58e89
[ "MIT" ]
null
null
null
main2/main/doPrintResults.ino
giacomocalabria/arduino-react-time-speed
b01da02d7a4559a8b602e41e7e61789430c58e89
[ "MIT" ]
null
null
null
void doPrintResults(){ for (int i=0;i<ArrayLeght;i++){ Serial.println(sqrt(square(reactX[i]-offsetX)+square(reactY[i]-offsetY)+square(reactZ[i]-offsetZ))); delay(5); } for (int i=0;i<ArrayLeght;i++){ Serial.println(reactInstant[i]); delay(5); } }
24.363636
103
0.645522
e01c04bebe60c8168ba57d9ca72f689aa3d50680
5,242
ino
Arduino
source_code/code.ino
m2i101/Garbagemonitoring
882aeb05dc2435be4df45ea6b8f2e1d76ecaa3b2
[ "MIT" ]
2
2019-10-07T12:00:21.000Z
2019-10-07T13:37:18.000Z
source_code/code.ino
m2i101/Garbagemonitoring
882aeb05dc2435be4df45ea6b8f2e1d76ecaa3b2
[ "MIT" ]
null
null
null
source_code/code.ino
m2i101/Garbagemonitoring
882aeb05dc2435be4df45ea6b8f2e1d76ecaa3b2
[ "MIT" ]
null
null
null
#include <TinyGPS++.h> #include <SoftwareSerial.h> #define BLYNK_PRINT Serial #include <ESP8266WiFi.h> #include <BlynkSimpleEsp8266.h> #include <ESP8266WiFi.h> #include <OneWire.h> #include <PubSubClient.h> static const int RXPin = 4, TXPin = 5; // GPIO 4=D2(conneect Tx of GPS) and GPIO 5=D1(Connect Rx of GPS static const uint32_t GPSBaud = 9600; //if Baud rate 9600 didn't work in your case then use 4800 const char *ssid = "ACT101014564385"; //Your Access Point or Personal Hotspot, cannot be longer than 32 characters! const char *pass = "44017881"; //Your Access Point or Personal Hotspot password const char* serverTS = "api.thingspeak.com"; char auth[] = "aa26238b0db54c69ae84a952d46d981c"; String apiKey = "HWP2ST3URKAB3QQE"; //Insert your Channel API Key here int TRIGGER = 2; //Pin D4 = TRIGGER int ECHO = 14; //Pin D5 = ECHO static const float bin=25; TinyGPSPlus gps; // The TinyGPS++ object WidgetMap myMap(V0); // V0 for virtual pin of Map Widget SoftwareSerial ss(RXPin, TXPin); // The serial connection to the GPS device BlynkTimer timer; float spd; //Variable to store the speed float sats; //Variable to store no. of satellites response String bearing; //Variable to store orientation or direction of GPS unsigned int move_index = 1; // fixed location for now void setup() { Serial.begin(115200); Serial.println(); ss.begin(GPSBaud); Blynk.begin(auth, ssid, pass); timer.setInterval(5000L, checkGPS); // every 5s check if GPS is connected, only really needs to be done once pinMode(0,OUTPUT); //LED connected to GPIO2 pinMode(TRIGGER,OUTPUT); pinMode(ECHO,INPUT); } void checkGPS(){ if (gps.charsProcessed() < 10) { Serial.println(F("No GPS detected: check wiring.")); Blynk.virtualWrite(V4, "GPS ERROR"); // Value Display widget on V4 if GPS not detected } } void loop() { while (ss.available() > 0) { // sketch displays information every time a new sentence is correctly encoded. if (gps.encode(ss.read())) displayInfo(); } Blynk.run(); timer.run(); // establish variables for duration of the ping, // and the distance result in inches and centimeters: long duration, inches, cm,percentage; // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: digitalWrite(TRIGGER, LOW); delayMicroseconds(2); digitalWrite(TRIGGER, HIGH); delayMicroseconds(10); digitalWrite(TRIGGER, LOW); // The same pin is used to read the signal from the PING))): a HIGH // pulse whose duration is the time (in microseconds) from the sending // of the ping to the reception of its echo off of an object. duration = pulseIn(ECHO, HIGH); // convert the time into a distance cm = microsecondsToCentimeters(duration); percentage=(1-(cm/bin))*100; Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100); digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(2, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second sendHeight(percentage); } void displayInfo() { if (gps.location.isValid() ) { float latitude = (gps.location.lat()); //Storing the Lat. and Lon. float longitude = (gps.location.lng()); Serial.print("LAT: "); Serial.println(latitude, 6); // float to x decimal places Serial.print("LONG: "); Serial.println(longitude, 6); Blynk.virtualWrite(V1, String(latitude, 6)); Blynk.virtualWrite(V2, String(longitude, 6)); myMap.location(move_index, latitude, longitude, "GPS_Location"); spd = gps.speed.kmph(); //get speed Blynk.virtualWrite(V3, spd); sats = gps.satellites.value(); //get number of satellites Blynk.virtualWrite(V4, sats); bearing = TinyGPSPlus::cardinal(gps.course.value()); // get the direction Blynk.virtualWrite(V5, bearing); } Serial.println(); } long microsecondsToCentimeters(long microseconds) { // The speed of sound is 340 m/s or 29 microseconds per centimeter. // The ping travels out and back, so to find the distance of the // object we take half of the distance travelled. return microseconds / 29 / 2; } void sendHeight(float cm) { WiFiClient tclient;//not to be confused with "client" in PubSub{}, and wclient for mqtt if (tclient.connect(serverTS, 80)) { // use ip 184.106.153.149 or api.thingspeak.com Serial.println("WiFi Client connected "); String postStr = apiKey; postStr += "&field1="; postStr += String(cm); postStr += "\r\n\r\n"; tclient.print("POST /update HTTP/1.1\n"); tclient.print("Host: api.thingspeak.com\n"); tclient.print("Connection: close\n"); tclient.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n"); tclient.print("Content-Type: application/x-www-form-urlencoded\n"); tclient.print("Content-Length: "); tclient.print(postStr.length()); tclient.print("\n\n"); tclient.print(postStr); delay(1000); }//end if tclient.stop(); }//end send to ts
31.389222
123
0.669973
51d7c773c5865ebb97b3e958c130adb5b8b97055
508
ino
Arduino
step1/External_pull_up_resistor/External_pull_up_resistor.ino
shilpasayura/arduino
b0ecf83d357183a6bb64f49c35186e3018c3ee98
[ "MIT" ]
null
null
null
step1/External_pull_up_resistor/External_pull_up_resistor.ino
shilpasayura/arduino
b0ecf83d357183a6bb64f49c35186e3018c3ee98
[ "MIT" ]
null
null
null
step1/External_pull_up_resistor/External_pull_up_resistor.ino
shilpasayura/arduino
b0ecf83d357183a6bb64f49c35186e3018c3ee98
[ "MIT" ]
null
null
null
// CODE TO LIGHT LED AND USAGE OF EXTERNAL PULL UP RESISTOR // LINK TO SIMULATOR // https://www.tinkercad.com/things/8Y2b6yyEed9-externalpullupresistor/editel const int btn_pin = 2; const int led_pin = 6; void setup() { pinMode(btn_pin, INPUT); pinMode(led_pin, OUTPUT); } void loop() { if( digitalRead(btn_pin) == LOW ){ // returns 0 for 0V Button Pressed // returns 1 for 5V Button Not Pressed digitalWrite(led_pin, HIGH); }else { digitalWrite(led_pin, LOW); } }
19.538462
77
0.67126
46a1625e48e5b6ab87a3f928a8de3921bbfc0f9c
7,798
ino
Arduino
version4_0/ESP32/MPPT/MPPT.ino
atmelino/MPPT
7db2eab8b8a8679aab2d99a2f4825a6efa0a102c
[ "MIT" ]
1
2020-03-24T00:40:14.000Z
2020-03-24T00:40:14.000Z
version4_0/ESP32/MPPT/MPPT.ino
atmelino/MPPT
7db2eab8b8a8679aab2d99a2f4825a6efa0a102c
[ "MIT" ]
1
2019-05-05T04:37:59.000Z
2019-05-05T07:25:30.000Z
version4_0/ESP32/MPPT/MPPT.ino
atmelino/MPPT
7db2eab8b8a8679aab2d99a2f4825a6efa0a102c
[ "MIT" ]
null
null
null
// Import required libraries #include "WiFi.h" #include "ESPAsyncWebServer.h" #include "SPIFFS.h" #include <Wire.h> #include <SDL_Arduino_INA3221.h> #include <ArduinoJson.h> #include "FS.h" #include "SD.h" #include "SPI.h" #include "RTClib.h" int debugLevel = 2; // 0=print nothing // pin assignment const int ledPin = 2; // on-board blue led (also internally pulled up) const int green_LED = 14; const int orange_LED = 27; const int red_LED = 26; const int PWM_OUT = 4; const int PWM_ENABLE_PIN = 15; const int RelayPin = 32; // PWM uint8_t PWM_actual = 100; // a value from 0 to 255 uint8_t PWM_requested = 130; //boolean PWMModeMPPT = true; boolean PWMModeMPPT = false; //uint32_t freq = 82000; uint32_t freq = 80000; uint8_t resolution_bits = 8; uint8_t channel = 1; // Replace with your network credentials const char* ssid = "NETGEAR53"; const char* password = ""; int count = 0; RTC_DS1307 rtc; char dateTime[20]; SDL_Arduino_INA3221 ina3221; #define CHB 0 // Battery INA channel 1 but 0 for array #define CHS 2// Solar INA channel 3 but 2 for array float sv[3], bv[3], cmA[3], lv[3], pw[3]; char headerLine[80]; # define maxLines 240 char dataLines[maxLines][80]; int linePointer = 0; boolean DataFilesYesNo = true; int keepMeasurement = 1; int DataFileLines = 10; AsyncWebServer server(80); AsyncWebSocket ws("/ws"); void setup(void) { Serial.begin(115200); debugPrintln("MPPT ESP32", 1); if (! rtc.begin()) { Serial.println("Couldn't find RTC"); } // Initialize SPIFFS if (!SPIFFS.begin(true)) { //Serial.println("An Error has occurred while mounting SPIFFS"); return; } else { getSettings(); //digitalWrite(ledPin, HIGH); //delay(300); } // Connect to Wi-Fi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { digitalWrite(ledPin, LOW); delay(1000); digitalWrite(ledPin, HIGH); //Serial.println("Connecting to WiFi.."); } // Print ESP32 Local IP Address Serial.println(WiFi.localIP()); // Start server ws.onEvent(onWsEvent); server.addHandler(&ws); // Route for root / web pages and javascript server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) { request->send(SPIFFS, "/index.html", "text/html"); }); server.on("/favicon.ico", HTTP_GET, [](AsyncWebServerRequest * request) { request->send(SPIFFS, "/favicon.png", "image/png"); }); server.on("/MPPT.css", HTTP_GET, [](AsyncWebServerRequest * request) { request->send(SPIFFS, "/MPPT.css", "text/css"); }); server.on("/MPPT.js", HTTP_GET, [](AsyncWebServerRequest * request) { request->send(SPIFFS, "/MPPT.js", "text/javascript"); }); server.begin(); makeHeaderLine(); Serial.println(headerLine); ina3221.begin(); pinMode(ledPin, OUTPUT); digitalWrite(ledPin, LOW);// Turn off on-board blue led //digitalWrite(ledPin, HIGH); pinMode(green_LED, OUTPUT); pinMode(orange_LED, OUTPUT); pinMode(red_LED, OUTPUT); if (!SD.begin()) { Serial.println("Card Mount Failed"); return; } else { Serial.println("Card Mount success"); //createDirSD(SD, "/mydir"); listDirSD(SD, "/", 2); } // PWM pinMode(PWM_ENABLE_PIN, OUTPUT); // GPIO as output digitalWrite(PWM_ENABLE_PIN, HIGH); ledcAttachPin(PWM_OUT, 1); // assign IR2104 PWM signal to channels // channels 0-15, resolution 1-16 bits, freq limits depend on resolution ledcSetup( channel, freq, resolution_bits); PWM_actual = 190; ledcWrite(1, PWM_actual); // // Relay to battery pinMode(RelayPin, OUTPUT); digitalWrite(RelayPin, HIGH); } void loop(void) { count++; // acquire voltages and currents for (int i = 0; i < 3; i++) { bv[i] = ina3221.getBusVoltage_V(i + 1); sv[i] = ina3221.getShuntVoltage_mV(i + 1); cmA[i] = ina3221.getCurrent_mA(i + 1); lv[i] = bv[i] + (sv[i] / 1000); pw[i] = bv[i] * cmA[i]; } float batteryVoltage = bv[CHB]; float solarVoltage = bv[CHS]; float batteryCurrent = cmA[CHB]; if (PWMModeMPPT) { if (batteryVoltage > 8.4) { // prevent battery overvoltage debugPrintln("battery over voltage, decrease PWM", 4); PWM_actual -= 5; setPWM(); } if (abs(batteryCurrent) > 1050) { //Serial.println("battery over current"); PWM_actual -= 5; setPWM(); } if (solarVoltage > 10.0 && batteryVoltage >= 8.2) { debugPrintln("increase PWM slow", 4); PWM_actual += 1; setPWM(); } if (solarVoltage > 10.0 && batteryVoltage < 8.2) { debugPrintln("increase PWM fast", 4); PWM_actual += 5; setPWM(); } if (solarVoltage <= 10.0 && batteryVoltage >= 7.6) { debugPrintln("solar under voltage, stop PWM", 4); stopPWM(); } if (solarVoltage <= 10.0 && batteryVoltage < 7.6) { // prevent battery over discharge //Serial.println("solar and battery under voltage"); debugPrintln("solar and battery under voltage, low battery shutdown", 4); //logEntry("low battery shutdown"); stopPWM(); //DataFilesYesNo = false; // if (true) { // LEDblink(); // clearInterval(loopTimer); // // give it a bit of time before turning off power // setInterval(function () { // rpio.write(relaypin, rpio.LOW);// disconnect battery // }, 10000); // } } } else { if (batteryVoltage > 8.4) // prevent battery overvoltage { Serial.println("battery over voltage"); PWM_actual -= 5; PWM_requested = PWM_actual; setPWM(); } else { //PWM_actual = PWM_requested; debugPrintln("manual mode set PWM", 4); setPWM(); } } makeDataLine(); debugPrint(dataLines[linePointer], 3); sendDataLine(); linePointer++; if (linePointer >= maxLines || linePointer >= DataFileLines) { linePointer = 0; // for (size_t i = 0; i < DataFileLines; i++) { // debugPrint(dataLines[i], 4); // } if (DataFilesYesNo) { writeDataFile(dateTime); } } //debugMsgln("Keep every " + keepMeasurement + " measurements", 0); //debugMsgln("count " + count + " remainder " + count % keepMeasurement, 0); // if (count % keepMeasurement == 0) { // bufferarray.push(line); // } delay(1000); } void setPWM() { //if (PWM_actual > 254) PWM_actual = 254; ledcWrite(1, PWM_actual); // } void startPWM() { PWM_actual = 100; digitalWrite(PWM_ENABLE_PIN, HIGH); // PWM on, enable IR2104 ledcWrite(1, PWM_actual); // } void stopPWM() { PWM_actual = 0; digitalWrite(PWM_ENABLE_PIN, LOW); // PWM off, disable IR2104 } void sendDataLine() { StaticJsonDocument<200> doc; char json_string[256]; doc["type"] = "livedata"; doc["data"] = dataLines[linePointer]; serializeJson(doc, json_string); //Serial.println(json_string); ws.printfAll(json_string); } void makeDataLine() { makeDateTime(); char* format = "%s %5d %.3f %.3f %.3f %.3f %.3f %.3f %4d\n"; sprintf(dataLines[linePointer], format, dateTime, count, bv[CHS], cmA[CHS], pw[CHS], bv[CHB], cmA[CHB], pw[CHB], PWM_actual); } void makeHeaderLine() { char* format = "%19s %5s %6s %6s %6s %5s %5s %5s %3s"; sprintf(headerLine, format, "Date", "no", "Volt", "mA", "mW", "Volt", "mA", "mW", "PWM"); } void makeDateTime() { DateTime now = rtc.now(); char* format = "%4d-%02d-%02d_%02d:%02d:%02d\0"; sprintf(dateTime, format, now.year(), now.month(), now.day(), now.hour(), now.minute(), now.second()); } void debugPrint(const char* message, int level) { //Serial.printf("level=%d debugLevel=%d\n", level, debugLevel); if (level <= debugLevel) Serial.print(message); } void debugPrintln(const char* message, int level) { if (level <= debugLevel) Serial.println(message); }
25.821192
127
0.629136
576bd43140fcc386f1331f511a9a3f67785e9bab
5,839
ino
Arduino
gameboy-spi/gameboy-spi.ino
ataulien/elm-gba-multiboot
c285d213624e6ee79fe3210a30a026c091c70640
[ "MIT" ]
7
2019-04-19T12:51:11.000Z
2020-01-16T19:55:35.000Z
gameboy-spi/gameboy-spi.ino
ataulien/elm-gba-multiboot
c285d213624e6ee79fe3210a30a026c091c70640
[ "MIT" ]
null
null
null
gameboy-spi/gameboy-spi.ino
ataulien/elm-gba-multiboot
c285d213624e6ee79fe3210a30a026c091c70640
[ "MIT" ]
null
null
null
/** * Multiboot-Loader for the GBA by Andre Taulien (2018) * * This was quickly thrown together for university (we've all been there, right?), so sorry for the lack of documentation. * Besides, this project was about using the "elm"-language, so who cares about c? */ #include <SPI.h> // http://problemkaputt.de/gbatek.htm (Multiboot Transfer Protocol) // // Pin SPI GBA // ----------------- // 12 miso SO // 11 mosi SI // 10 sck SC const uint8_t COMMAND_STARTUP = 0x01; const uint8_t COMMAND_WRITE_DONE = 0x03; uint16_t answers[512]; uint16_t numAnswers = 0; void setup() { uint32_t r; pinMode(LED_BUILTIN, OUTPUT); Serial.begin(57600); Serial.setTimeout(-1); SPI.begin(); SPI.beginTransaction (SPISettings (256000, MSBFIRST, SPI_MODE3)); Serial.write(COMMAND_STARTUP); upload(); while(1); } void loop() { } void receiveRomHeader(uint8_t* pTarget) { for (int i = 0; i < 0xC0; i++) { pTarget[i] = serial_read8(); } } void receiveRomLength(uint32_t* pTarget) { *pTarget = serial_read32(); } uint32_t serial_read32(void) { uint32_t rx1 = serial_read8(); uint32_t rx2 = serial_read8(); uint32_t rx3 = serial_read8(); uint32_t rx4 = serial_read8(); return rx1 | (rx2 << 8) | (rx3 << 16) | (rx4 << 24); } uint8_t serial_read8(void) { uint8_t rx; Serial.readBytes(&rx, 1); return (uint8_t)rx; } void serial_write16(uint16_t tx) { Serial.write(tx & 0xFF); Serial.write(tx >> 8); } void serial_write32(uint32_t tx) { serial_write16(tx & 0xFFFF); serial_write16(tx >> 16); } uint16_t spi_transmit_receive16(uint16_t tx16) { uint16_t rx = SPI.transfer16(tx16); delayMicroseconds(36); //delayMicroseconds(10); return rx; } void spi_transmit16(uint16_t tx16) { uint16_t rx = SPI.transfer16(tx16); delayMicroseconds(36); //delayMicroseconds(10); } uint32_t spi_transmit_receive32(uint32_t tx) { uint32_t rx[4]; rx[0] = SPI.transfer((tx >> 24) & 0xFF); rx[1] = SPI.transfer((tx >> 16) & 0xFF); rx[2] = SPI.transfer((tx >> 8) & 0xFF); rx[3] = SPI.transfer(tx & 0xFF); delayMicroseconds(36); //delayMicroseconds(10); return rx[3] | (rx[2] << 8) | (rx[1] << 16) | (rx[0] << 24); } void spi_transmit32(uint32_t tx) { SPI.transfer((tx >> 24) & 0xFF); SPI.transfer((tx >> 16) & 0xFF); SPI.transfer((tx >> 8) & 0xFF); SPI.transfer(tx & 0xFF); delayMicroseconds(36); //delayMicroseconds(10); } void setLedEnabled(bool enabled) { digitalWrite(LED_BUILTIN, enabled ? HIGH : LOW); } uint32_t WriteSPI32NoDebug(uint32_t w) { return spi_transmit_receive32(w); } uint32_t WriteSPI32(uint32_t w, const char* msg) { uint32_t r = WriteSPI32NoDebug(w); char buf[32]; sprintf(buf, "0x%08x 0x%08x ; ", r, w); Serial.print(buf); Serial.println(msg); return r; } void WaitSPI32(uint32_t w, uint32_t comp, const char* msg) { char buf[32]; sprintf(buf, " 0x%08x\n", comp); Serial.print(msg); Serial.print(buf); uint32_t r; do { r = WriteSPI32NoDebug(w); } while(r != comp); } /** * Mostly taken from https://github.com/akkera102/gba_01_multiboot * Honestly, it's the best implementation I could find. Straight to the point, no bullshit, no crappy code. */ void upload(void) { uint32_t fsize; receiveRomLength(&fsize); Serial.print("Received ROM-Size: "); Serial.println(fsize); uint8_t header[0xC0]; receiveRomHeader(header); if(fsize > 0x40000) { Serial.println("Romfile too large!"); return; } long fcnt = 0; uint32_t r, w, w2; uint32_t i, bit; WaitSPI32(0x00006202, 0x72026202, "Looking for GBA"); r = WriteSPI32(0x00006202, "Found GBA"); r = WriteSPI32(0x00006102, "Recognition OK"); Serial.println("Send Header(NoDebug)"); for(i=0; i<=0x5f; i++) { w = header[2*i]; w = header[2*i+1] << 8 | w; fcnt += 2; r = WriteSPI32NoDebug(w); } r = WriteSPI32(0x00006200, "Transfer of header data complete"); r = WriteSPI32(0x00006202, "Exchange master/slave info again"); r = WriteSPI32(0x000063d1, "Send palette data"); r = WriteSPI32(0x000063d1, "Send palette data, receive 0x73hh****"); uint32_t m = ((r & 0x00ff0000) >> 8) + 0xffff00d1; uint32_t h = ((r & 0x00ff0000) >> 16) + 0xf; r = WriteSPI32((((r >> 16) + 0xf) & 0xff) | 0x00006400, "Send handshake data"); r = WriteSPI32((fsize - 0x190) / 4, "Send length info, receive seed 0x**cc****"); uint32_t f = (((r & 0x00ff0000) >> 8) + h) | 0xffff0000; uint32_t c = 0x0000c387; //Serial.write(COMMAND_SUCCESS); Serial.println("Send encrypted data(NoDebug)"); Serial.write(COMMAND_WRITE_DONE); uint32_t bytes_received = 0; while(fcnt < fsize) { if(bytes_received == 32) { Serial.write(COMMAND_WRITE_DONE); bytes_received = 0; } w = serial_read32(); bytes_received += 4; if(fcnt % 0x800 == 0 || fcnt > 63488) { Serial.print(fcnt); Serial.print("/"); Serial.println(fsize); } w2 = w; for(bit=0; bit<32; bit++) { if((c ^ w) & 0x01) { c = (c >> 1) ^ 0x0000c37b; } else { c = c >> 1; } w = w >> 1; } m = (0x6f646573 * m) + 1; WriteSPI32NoDebug(w2 ^ ((~(0x02000000 + fcnt)) + 1) ^m ^0x43202f2f); fcnt = fcnt + 4; } Serial.println("ROM sent! Doing checksum now..."); for(bit=0; bit<32; bit++) { if((c ^ f) & 0x01) { c =( c >> 1) ^ 0x0000c37b; } else { c = c >> 1; } f = f >> 1; } WaitSPI32(0x00000065, 0x00750065, "Wait for GBA to respond with CRC"); Serial.print("CRC: "); Serial.println(c, HEX); r = WriteSPI32(0x00000066, "GBA ready with CRC"); r = WriteSPI32(c, "Let's exchange CRC!"); Serial.println("All done, let's hope this worked!"); }
18.13354
122
0.61329
d0e68ca48098b1e79bcdea365941b0bf34f07cf3
628
ino
Arduino
examples/Sensor/Otto_clapwalk/Otto_clapwalk.ino
ehippy/OttoDIYLib
7188ea030a3f3740425a11900692b5e1e8889efe
[ "BSD-3-Clause" ]
2
2021-12-12T11:45:09.000Z
2021-12-12T11:45:11.000Z
examples/soundsensor/OttoPLUS_clapwalk_V9/OttoPLUS_clapwalk_V9.ino
flyingAfish/OttoDIYLib
c9cdf49f52c5fc4e522c4ce9618e04284bf24774
[ "BSD-3-Clause" ]
null
null
null
examples/soundsensor/OttoPLUS_clapwalk_V9/OttoPLUS_clapwalk_V9.ino
flyingAfish/OttoDIYLib
c9cdf49f52c5fc4e522c4ce9618e04284bf24774
[ "BSD-3-Clause" ]
null
null
null
#include <Otto9.h> Otto9 Otto; //This is Otto!! #define PIN_YL 2 //servo[0] left leg #define PIN_YR 3 //servo[1] right leg #define PIN_RL 4 //servo[2] left foot #define PIN_RR 5 //servo[3] right foot #define PIN_Trigger 8 //TRIGGER pin (8) #define PIN_Echo 9 //ECHO pin (9) #define PIN_Buzzer 13 //BUZZER pin (13) void setup() { Otto.init(PIN_YL, PIN_YR, PIN_RL, PIN_RR, true, A6, PIN_Buzzer, PIN_Trigger, PIN_Echo); //Set the servo pins and ultrasonic pins and Buzzer pin Otto.playGesture(OttoHappy); Otto.home(); } void loop() { if (Otto.getNoise() >= 500) { Otto.walk(1); } }
27.304348
145
0.648089
95cbb2eee4d0602f725754018a5abfbd87b7dad4
2,381
ino
Arduino
src/esp8266/btn_demo/btn_demo.ino
codemercs-com/lw18
344d47dd1ce7ac9da594ae3b8a731b71e12650c9
[ "MIT" ]
1
2022-02-05T17:14:10.000Z
2022-02-05T17:14:10.000Z
src/esp8266/btn_demo/btn_demo.ino
codemercs-com/lw18
344d47dd1ce7ac9da594ae3b8a731b71e12650c9
[ "MIT" ]
null
null
null
src/esp8266/btn_demo/btn_demo.ino
codemercs-com/lw18
344d47dd1ce7ac9da594ae3b8a731b71e12650c9
[ "MIT" ]
null
null
null
/* Sample code for LED-Warrior18 controlled by an ESP8266 */ #define FLAG_NONE 0x0000 #define FLAG_BTN_1 0x0001 #define FLAG_BTN_2 0x0002 #include "CLedWarrior18.h" // Button struct struct BUTTON_STRUCT { uint8_t pin; uint8_t now_state; uint8_t last_state; }; BUTTON_STRUCT btn[2]; // the number of the pushbutton pin CLedWarrior18 lw18; // Dimming int dimm_pos = 0; // Position for dimming const uint8_t dimm_size = 11; // Max size of array dimm[] uint8_t dimm[11] = {0, 26, 52, 78, 104, 130, 156, 182, 208, 234, 254}; // Table for 10% dimming steps + off // Flag uint8_t flag = FLAG_NONE; // Debounce based on Arduino dokumentation long lastDebounceTime = 0; long debounceDelay = 50; void setup() { // Setup buttons btn[0].pin = 12; btn[0].now_state = LOW; btn[0].last_state = LOW; pinMode(btn[0].pin, INPUT); btn[1].pin = 14; btn[1].now_state = LOW; btn[1].last_state = LOW; pinMode(btn[1].pin, INPUT); // init LED-Warrior18 lw18.Init(); lw18.SetI2cAddress(LW18_I2C_DEFAULT); } void loop() { // Get button states btn[0].now_state = digitalRead(btn[0].pin); btn[1].now_state = digitalRead(btn[1].pin); // Debounce if ((millis() - lastDebounceTime) > debounceDelay) { // Only if button 2 not pressed if (btn[1].now_state == LOW) { // Button 1 if ((btn[0].now_state == HIGH) && (btn[0].last_state == LOW)) { dimm_pos++; if (dimm_pos > (dimm_size - 1)) dimm_pos = 10; flag |= FLAG_BTN_1; btn[0].last_state = HIGH; lastDebounceTime = millis(); } else if ((btn[0].now_state == LOW) && (btn[0].last_state == HIGH)) { btn[0].last_state = LOW; lastDebounceTime = millis(); } } // Only if button 1 not pressed if (btn[0].now_state == LOW) { // Button 2 if ((btn[1].now_state == HIGH) && (btn[1].last_state == LOW)) { dimm_pos--; if (dimm_pos < 0) dimm_pos = 0; flag |= FLAG_BTN_2; btn[1].last_state = HIGH; lastDebounceTime = millis(); } else if ((btn[1].now_state == LOW) && (btn[1].last_state == HIGH)) { btn[1].last_state = LOW; lastDebounceTime = millis(); } } } // Send data if any button bressed (flag check) if (((flag & (FLAG_BTN_1 | FLAG_BTN_2)) == FLAG_BTN_1) || ((flag & (FLAG_BTN_1 | FLAG_BTN_2)) == FLAG_BTN_2)) { lw18.WritePwm8(dimm[dimm_pos], 0); flag = FLAG_NONE; } }
20.885965
107
0.623268
f6eb0fdff4959f29e441268358d6e5b0514a13e9
2,566
ino
Arduino
arduino/CombinedNewTest/CombinedNewTest.ino
maifeeulasad/Mouse-3D
eea3c9ee0600f67494891386abd3ff2a94d878c9
[ "MIT" ]
6
2019-04-18T04:36:57.000Z
2021-06-28T21:15:50.000Z
arduino/CombinedNewTest/CombinedNewTest.ino
maifeeulasad/Mouse-3D
eea3c9ee0600f67494891386abd3ff2a94d878c9
[ "MIT" ]
null
null
null
arduino/CombinedNewTest/CombinedNewTest.ino
maifeeulasad/Mouse-3D
eea3c9ee0600f67494891386abd3ff2a94d878c9
[ "MIT" ]
1
2019-08-16T15:12:51.000Z
2019-08-16T15:12:51.000Z
#include<Wire.h> const int MPU = 0x68; int t = 0, dt = 1; int AcX, AcY, AcZ, GyX, GyY, GyZ, tmp; int AcXo, AcYo, AcZo, GyXo, GyYo, GyZo; float roll = 0, pitch = 0, rollgy = 0, pitchgy = 0, rollac = 0, pitchac = 0, Ax, Ay, Az, Gx, Gy, Gz, gain = 0.95; void MPUconfig(int Addr, int data) { Wire.beginTransmission(MPU); Wire.write(Addr); Wire.write(data); Wire.endTransmission(); } void MPUread() { Wire.beginTransmission(MPU); Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) Wire.endTransmission(); Wire.requestFrom(MPU, 14); // request a total of 14 registers AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L) AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L) AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L) tmp = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L) GyX = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L) GyY = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L) GyZ = Wire.read() << 8 | Wire.read(); } void offset() { MPUconfig(0x1A, 0b00000000); int ax = 0, ay = 0, az = 0, gx = 0, gy = 0, gz = 0, i; MPUread(); MPUread(); ax = AcX; ay = AcY; az = AcZ; gx = GyX; gy = GyY; gz = GyZ; for (i = 0; i < 1100; i++) { MPUread(); if (i > 100) { ax = (ax + AcX) / 2; ay = (ay + AcY) / 2; az = (az + AcZ) / 2; gx = (gx + GyX) / 2; gy = (gy + GyY) / 2; gz = (gz + GyZ) / 2; } delay(2); } AcXo = ax; AcYo = ay; AcZo = 16384 - az; GyXo = gx; GyYo = gy; GyZo = gz; MPUconfig(0x1A, 0b00000110); } void setup() { Serial.begin(115200); Wire.begin(); MPUconfig(0x1A, 0b00000110); MPUconfig(0x1B, 0b00000000); MPUconfig(0x1C, 0b00000000); MPUconfig(0x6B, 0b00000000); offset(); } void loop() { t = millis(); MPUread(); Ax = (float)(AcX - AcXo) / 16384; Ay = (float)(AcY - AcYo) / 16384; Az = (float)(AcZ - AcZo) / 16384; Gx = (float)(GyX - GyXo) / 131; Gy = (float)(GyY - GyYo) / 131; Gz = (float)(GyZ - GyZo) / 131; pitchgy = (Gy * ((float) dt / 1000)) + pitch; rollgy = (Gx * ((float) dt / 1000)) + roll; pitchac = atan2(Ax, Az) * (float)(180 / PI); rollac = atan2(Ay, Az) * (float) (180 / PI); roll = gain * rollgy + (1 - gain) * rollac; pitch = gain * pitchgy + (1 - gain) * pitchac; Serial.print(roll); Serial.print(" "); Serial.print(pitch); Serial.println(" "); dt = millis() - t; }
27.010526
113
0.564302
e73455d36a358610f6060bb0a3bf5aa8c29c7a9b
21,556
ino
Arduino
Archive/3D_Space_w_Robot_Hand.ino
FAR-Lab/RobotArmArduinoAnimation
51d5e39977eb74e31e1a2b259d0e135cb3b9ac2f
[ "MIT" ]
1
2020-11-18T16:43:55.000Z
2020-11-18T16:43:55.000Z
Archive/3D_Space_w_Robot_Hand.ino
KacperBazan/RobotArmArduinoAnimation
ce8367f761951a56244dbb002d1acf9af54138aa
[ "MIT" ]
null
null
null
Archive/3D_Space_w_Robot_Hand.ino
KacperBazan/RobotArmArduinoAnimation
ce8367f761951a56244dbb002d1acf9af54138aa
[ "MIT" ]
1
2020-11-18T16:39:16.000Z
2020-11-18T16:39:16.000Z
#include <Servo.h> //Library needed to inpute values to the servo. #include <math.h> //Math Library needed to do some angle meassurements (Sin/Cos/Tan) Servo myservo_5; //There are six servos on this particular robot arm. The bottom servo is labeled Servo_5. Servo myservo_4; //Servo_4 is the first arm structure from the mainframe of the robot body. Servo myservo_3; //Servo_3 is the second arm connected directly to the first one. Servo myservo_2; //Servo_2 is the servo following the second arm. Can be thought of like the "pitch" of the hand. Servo myservo_1; //Servo_1 is the servo below the hand that lets it control the "roll" of the hand. Servo myservo_0; //Servo_0 is the servo that dictates how much the hand opens and closes. float A = 10.5, //A is the length of the first arm. In this robot, it is 10.5cm. B = 8.85; //B is the length of the second arm. In this robot, it is 8.85cm. int potentvalue = 0, potent = A0; //An optional potentiometer variable is made here. Connect the potentiometer to A0. int button_1 = 4, buttonstate_1 = 0, lastbuttonstate_1=0, //Variables for an optional button. Variables include the pin location (4) and current/last states. button_2 = 2, buttonstate_2 = 0, lastbuttonstate_2=0; //Variables for a second optional button. Variables include the pin location (2) and current/last states. int buttoncount = 0; //Variable used to count how many times a button was pressed. String InString = "d"; float count; float currentAngles[6] = {75,90,90,90,90,90}; /* * The robot doesn't necessarily know where its moving parts are in 3D space. Therefore, we have an array that keeps track of the angles at each servo. * If we didn't keep track of the angles at every servo, there would be times where the robot wouldn't know where to go, how fast to go, and on occasion just move randomly. * There are six values in this array; one for each of the servos. They follow the following order. * * {Servo_4, Servo_3, Servo_5, Servo_2, Servo_1, Servo_0} * * The reason for the unusual order is because of the way the robot moves. We want our robot to move to points of 3D space. It is easier to visualize a 3D point that we want * the robot to move to rather than multiple angles of servos moving together to reach a specified point. Since we will be working with 3D points, they are written in the order * (X,Y,Z), with X being the distance from the origin on the X-Axis, Y being the distance from the origin on the Y-Axis, and Z being the distance from the origin on the Z-Axis. * The platform of the robot is set up in such a way where the Arduino and wire connections are off to the left on the metal stand, and the robot has free motion in the empty space * in front of it. Thinking from the perspective of the robot, the X-Axis would go forward and backward, the Y-Axis would go straight up, and the Z-Axis would travel from left to right. * Additionally, the negative X-Axis is behind the robot, the negative Y-Axis would go down under it, aand the negative Z-Axis would go to the left. The axeses are set up in a way where * the positive space is in the range of motion of the robot. * * Because of this 3D system, the servo labeled Servo_5 can only turn the robot hand left and right, or into the Z-Axis. Therefore, we associate Servo_4 and Servo_3 with the (X,Y) movement * and Servo_5 with the final Z movement. Servo_2, Servo_1 and Servo_0 are just additional angles used to manipulate the arm after the robot reaches the desired 3D point. The robot can move * to a point such as (10,9,-8), but Servo_2, Servo_1 and Servo_0 can make it point the hand downward, tilted or even open and close it. * * By having an array with the angles of each servo, it provides a bassis for many functions to calculate where each servo to move to. The current value of the array sets the robot in a * straight up, "default", position. * * NOTE: Servo_4 is set at a value of 75 degrees rather than 90. This servo doesn't go directly vertical at 90 degrees. The exact reason is unknown [EDIT NEEDED]. All references to this angle * need an adjustment of 15 degrees. At 0 degrees, this servo is about 15 degrees off of parallel. This means that at 180 degrees, the servo would caause the arm to over extend. Functions * here prevent that from happening. If a different servo is being used, this starting position in currentAngles[] and newAngles[] can be switched from 75 to 90. Additionally, any starting * position angles can be chosen, these are the angles that work for one particular robot. * */ float newAngles[6] = {75,90,90,90,90,90}; /* * Similar to currentAngles[], but this array is used to determine what angle each servo needs to move to. Currently, both arrays are the same and will change with functions altering the * movement of the robot. * * NOTE: Servo_4 is set at a value of 75 degrees rather than 90. This servo doesn't go directly vertical at 90 degrees. The exact reason is unknown [EDIT NEEDED]. All references to this angle * need an adjustment of 15 degrees. At 0 degrees, this servo is about 15 degrees off of parallel. This means that at 180 degrees, the servo would caause the arm to over extend. Functions * here prevent that from happening. If a different servo is being used, this starting position in currentAngles[] and newAngles[] can be switched from 75 to 90. Additionally, any starting * position angles can be chosen, these are the angles that work for one particular robot. */ void setup() { myservo_5.attach(3); // Attaches the myservo_5 on pin 3 to the servo object. myservo_4.attach(5); // Attaches the myservo_4 on pin 5 to the servo object. myservo_3.attach(6); // Attaches the myservo_3 on pin 6 to the servo object. myservo_2.attach(9); // Attaches the myservo_2 on pin 9 to the servo object. myservo_1.attach(10); // Attaches the myservo_1 on pin 10 to the servo object. myservo_0.attach(11); // Attaches the myservo_0 on pin 11 to the servo object. Serial.flush(); Serial.begin(9600); //Sets up the serial monitor in order to debug and see angle values. pinMode(potent,INPUT); //Optional Potentiometer is set as an input. pinMode(button_1,INPUT); //Optional Button_1 is set as an input. pinMode(button_2,INPUT); //Optional Button_2 is set as an input. } void Deg_5(float a) //This function moves Servo_5 to an angle between 0 and 180. { myservo_5.write(a); } void Deg_4(float a) //This function moves Servo_4 to an angle between 0 and 180. To keep the movement consistent, we reverse the values of the servo. Instead of moving right to left from 0 degrees to 180, it now moves left to right. { a = 180 - a; myservo_4.write(a); } void Deg_3(float a) //This function moves Servo_3 to an angle between 0 and 180. { myservo_3.write(a); } void Deg_2(float a) //This function moves Servo_2 to an angle between 0 and 180. This servo has an increased range of 270 degrees, but needs extra equations to understand angle measurements. { a = a + 67.5; a = a / 1.5; myservo_2.write(a); } void Deg_1(float a) //This function moves Servo_1 to an angle between 0 and 180. { myservo_1.write(a); } void Deg_0(float a) //This function moves Servo_0 to an angle between 0 and 180. { myservo_0.write(a); } void Button1Pressed() { buttonstate_1 = digitalRead(button_1); //Optional Button function that is called only when the button is pressed from off to on. In this case, pressing the button increments the buttoncount variable. if (buttonstate_1 != lastbuttonstate_1) { if (buttonstate_1 == 1) { buttoncount = buttoncount + 1; Serial.println(buttoncount); } } lastbuttonstate_1 = buttonstate_1; } void Button2Pressed() //Optional Button function that is called only when the button is pressed from off to on. In this case, pressing the button resets the buttoncount variable to 0. { buttonstate_2 = digitalRead(button_2); if (buttonstate_2 != lastbuttonstate_2) { if (buttonstate_2 == 1) { buttoncount = 0; Serial.println(buttoncount); } } lastbuttonstate_2 = buttonstate_2; } void Potentiometer() //Optional Potentiometer function that maps the analog values of (0 -> 1023) to (0 -> 180). { potentvalue = analogRead(potent); potentvalue = map(potentvalue,0,1023,0,180); } float Distance(float px1, float py1, float px2, float py2) //The distance function calculates the distance between two points in (X,Y) space only. { return sqrt(sq(px2-px1) + sq(py2-py1)); } void XY(float m, float n) { /* * This function takes a point in 2D space, (m,n), and then changes the angles on Servo_4 and Servo_3 to hit that point. It changes the angle in the array newAngles[] so * future servo moving functions can read from that list. This function doesn't alter Servo_5 at all as Servo_5 is what allows the robot to move left and right. * * This desmos link shows a side view visualization of the first two arms of the robot: https://www.desmos.com/calculator/zgmw47nks6 * * The calculations in that program show the following float values being calculated so that the Servo_4 and Servo_3 angles can be figured out. * * NOTE: This point is represented by the end of the second arm, or the connection of Servo_2. */ float C = sq(m) + sq(n) - sq(B) + sq(A); //A constant used to calculate the coordinates of the joint of the robot. float x1 = ((4*m*C - sqrt((64 * sq(m) * sq(A) * sq(n))+(64 * sq(n) * sq(n) * sq(A))-(16 * sq(n) * sq(C))))/((8*sq(m))+(8*sq(n)))); //The x coordinate of one point of one joint. float y1 = (((-2*m*x1) + C)/(2*n)); //The y coordinate of one point of one joint. if (Distance(0,0,m,n) < sqrt(sq(A) + sq(B)) || Distance(0,0,m,n) > (A + B) || n < 0 || y1 < 0) { /* * This if statement checks four different things. The first check is to see if the desired 2D point is too close to the origin. Due to each servo having * a specific length, and only being able to go to angles between 0 and 180, there are certain 2D coordinates close to the origin of the robot that can simply * not be touched. The second check is to see if the desired point is too far outside the maximum range of the robot. Even when fully exteneded, the robot can only * reach so far. Anything outside maximum extensions is physically impossible. The robot would have to have longer arms to reach this point. The third check is to see if * the desired point goes below the ground. This is again physically impossible. The final check is to see if one of the joints of the robot goes below the ground. y1 is the * y coordinate of one of the joints of the robot. If this goes into the ground, or below 0, one knows that desired point cannot be reached. If all these checks are false, * the "Out of Range" message isn't printed. * */ Serial.println("Out of Range"); return; } else { /* * Again, each of these floats are just variables needed to determine joint coordinates, slopes, and eventually the angles required for Servo_4 and Servo_3 to successfully * move to the point in question. * */ float s1 = y1/x1; //The slope the first arm makes. float x2 = ((4*m*C + sqrt((64 * sq(m) * sq(A) * sq(n))+(64 * sq(n) * sq(n) * sq(A))-(16 * sq(n) * sq(C))))/((8*sq(m))+(8*sq(n)))); //The x coordinate of one point of an alternate joint. float y2 = (((-2*m*x2) + C)/(2*n)); //The y coordinate of one point of an alternate joint. float s2 = y2/x2; //The slope the first arm would make if another path to the point was taken. float o1 = (n-y1)/(m-x1); //The slope the second arm makes. float o2 = (n-y2)/(m-x2); //The slope the second arm makes if another path to the point was taken. float p1 = -1/s1; //The perpendicular slope at the connection between the first and second arm. float p2 = -1/s2; //The perpendicular slope at the connection between the first and second arm if another path to the point was taken. float a1 = atan(s1) * (180/PI); //Servo_4 angle. float a2 = atan(s2)* (180/PI); //Servo_4 angle if another path to the point was taken. float b1 = atan(((o1-p1)/(1+(o1*p1))))* (180/PI); //Servo_3 angle. float b2 = atan(((o2-p2)/(1+(o2*p2))))* (180/PI); //Servo_3 angle if another path to the point was taken. if (a1<15 && a1>0) { /* * * Using the triginometry functions here, as well as the previous check, the only time the Servo_4 angle would go between 0 and 15 is if it was trying to go beyond the limitations described * before in the currentAngles[] NOTE. Therefore, we use a check here to see if an impossible angle is achieved. If so, the Serial prints an error message. * */ Serial.println("a1 is below 15 degrees"); return; } else { if(a1<=0) { /* * The trigonometric functions work in such a way that they give angles in a range of -90 to 90 rather than 0 to 180. The negative values simply represent angles greater than 90. So, if the angle * does come back negative, we simply subtract it from 180 to give the corrected angle. */ a1 = 180 + a1; } a1 = a1-15; //15 is subtracted from the angle to correct it to the actual value. newAngles[0] = a1; //Servo_4's angle gets input into the matrix to be read later. newAngles[1] = b1; //Servo_3's angle gets input into the matrix to be read later. } } } float AngleTopView(float j, float m) { /* * This function determines what angle Servo_5 has to move to in order to match the Z coordinate. Since the entire arm would rotate, the X coordinate is also needed to determine the angle needed to rotate. * j is the Z coordinate, and m is the X coordinate. */ float t = m/j; float theta = atan(t) * (180/PI); if (theta < 0) { theta = 180 + theta; } return theta; } void XYZ(float m, float n, float j) { /* * The main function. It takes three values (m,n,j) in reference to the (x,y,z) coordinates. */ if((sq(m) + sq(n) + sq(j)) > sq(A+B) || n < 0 || Distance(0,0,sqrt((sq(m)+sq(j))),n) < sqrt(sq(A) + sq(B))) { /* * This if statement checks three things. The first check is to see whether the point in question is too far outside the possible range of the robot. The second check * is to see whether the y coordinate is less than 0. In this case, the robot arm would have to go into the ground which is not possible. The third check is to see * whether the point in question is too close to the origin of the robot. The equation checks if the distance from thhe origin to the point in quesstion is less than the * minimum range possible. * */ Serial.println("Out of Range"); return; } else { newAngles[2] = AngleTopView(j,m); /* * If none of those checks return true, that means that the point is possible in the robot's operable range. Servo_5 can now move to meet the Z value, and AngleTopView() * determines the value of that angle. */ int sign_converter = 1; if(m<0) { sign_converter = -1; } m = sign_converter * sqrt((sq(m)+sq(j))); /* * This distance function determines the new value for m. If it was negative beforehand, it is important to make it negative after the square and square root functions. */ XY(m,n); //Finally, after Servo_5 gets its angle, and m is converted, the XY() function solves the angle for Servo_4 and Servo_3. } } void ServoMove(float a1, float a2, float a3,float a4,float a5, float a6,int steps) { /* * This ServoMove function takes seven parameters. The first six represent Servo_4, Servo_3, Servo_5, Servo_2, Servo_1, and Servo_0. The last is steps, which determines how fluid * the actual servo movement will be. Each of these floats is an angle the respective servo will move to. * * a1 = Servo_4 - Combined with Servo_3 to make up the XY movement to the point. * a2 = Servo_3 - Combined with Servo_4 to make up the XY movement to the point. * a3 = Servo_5 - Moves the robot into the plane of the Z coordinate of the point. * a4 = Servo_2 - Dictates angle of hand (PITCH) * a5 = Servo_1 - Dictates angle of wrist (ROLL) * a6 = Servo_0 - Dictates how open the hand is. */ float diff_1 = a1 - currentAngles[0]; float diff_2 = a2 - currentAngles[1]; float diff_3 = a3 - currentAngles[2]; float diff_4 = a4 - currentAngles[3]; float diff_5 = a5 - currentAngles[4]; float diff_6 = a6 - currentAngles[5]; /* * Each of these floats shows the difference between each angle in each servo. currentAngles[] are the angles where the servos are already at. The a1 through a6 floats show where the * servos have to move to. * */ for(int i=1; i<=steps; i++) { Deg_4(currentAngles[0] + (i*(diff_1/steps))); Deg_3(currentAngles[1] + (i*(diff_2/steps))); Deg_5(currentAngles[2] + (i*(diff_3/steps))); Deg_2(currentAngles[3] + (i*(diff_4/steps))); Deg_1(currentAngles[4] + (i*(diff_5/steps))); Deg_0(currentAngles[5] + (i*(diff_6/steps))); Button1Pressed(); Button2Pressed(); /* * This for function runs "steps" amount of times. The larger the number of steps determined by the user, the less jarring each step of the servo. We need to alternate between each of the * servos for each step to produce a fluid movement. Otherwise it would be one servo at a time reaching the required position. The steps allow a fluid motion in increments. */ } currentAngles[0] = a1; currentAngles[1] = a2; currentAngles[2] = a3; currentAngles[3] = a4; currentAngles[4] = a5; currentAngles[5] = a6; /* * After completing the motion, the currentAngles[] of the robot need to be reset as they are now different. */ } void PointMove(float x, float y, float z, float head, float head_tilt, float open_head, int steps) { /* * Similar to ServoMove() but it is more user friendly. This function allows the user to input the 3D point they * want the robot to move to, as well as the head position, the head tilt, and how open the hand is. */ XYZ(x,y,z); newAngles[3] = head; newAngles[4] = head_tilt; newAngles[5] = open_head; ServoMove(newAngles[0],newAngles[1],newAngles[2],newAngles[3],newAngles[4],newAngles[5],steps); } float FuncX_1(float t) //Parametric function for the x coordinate of the funtion_1. { return -3*cos(t)+12; } float FuncY_1(float t) //Parametric function for the y coordinate of the funtion_1. { return 3*cos(t)+12; } float FuncZ_1(float t) //Parametric function for the z coordinate of the funtion_1. { return 3*sin(t); } void Parent_Function_1(float tmin, float tmax, int samples, int steps) /* * The way this function works is by calculating multiple points /* in space between a range determined by the variable "t". /* Points are determined between t_min and t_max, and there /* are "sample" amount of points between those two values. /* x is a_0, y is a_1, and z is a_2. XYZ then converts those points /* to angles the robot has to reach, and then moves the servos to /* those angles. */ { float inc = (tmax-tmin)/(samples-1); for (int i = 0; i<samples; i++) { float a_0 = FuncX_1(tmin + (i * inc)); float a_1 = FuncY_1(tmin + (i * inc)); float a_2 = FuncZ_1(tmin + (i * inc)); float array_points[4] = {a_0,a_1,a_2,steps}; //A new array is made to store the updated points the robot needs to move to. XYZ(array_points[0],array_points[1],array_points[2]); if (i == 0) //If the robot is doing the first increment, we make sure the amount of steps is 2000 to prevent sudden jerking. { ServoMove(newAngles[0],newAngles[1],newAngles[2],newAngles[3],newAngles[4],newAngles[5],2000); } else { ServoMove(newAngles[0],newAngles[1],newAngles[2],newAngles[3],newAngles[4],newAngles[5],array_points[3]); } } } void KeyboardRead() { if (Serial.available()) { InString = Serial.readString(); } } void Sad() { PointMove(2.1,15.1,0,0,90,90,1000); PointMove(2.1,15.1,0,0,45,90,1000); PointMove(2.1,15.1,0,0,90,90,1000); PointMove(2.1,15.1,0,0,135,90,1000); } void Excited() { PointMove(0.1,19,0,102.19,90,0,1000); PointMove(0.1,14,0,138.95,45,0,1000); PointMove(0.1,19,0,102.19,90,0,1000); PointMove(0.1,14,0,138.95,135,0,1000); } void loop() { KeyboardRead(); if(InString == "a") { Excited(); } if(InString == "s") { Sad(); } if(InString == "d") { ServoMove(75.00,90.00,90.00,90.00,90.00,90.00,3000); } }
50.839623
256
0.666589
48b92d9aedc59941f9cc2ab2b08263aa521013ff
3,218
ino
Arduino
leds2/leds2.ino
tiferrei/CJP2.0
28f59c4abe369a8fc8d74d6a48f2357800c73c3b
[ "MIT" ]
null
null
null
leds2/leds2.ino
tiferrei/CJP2.0
28f59c4abe369a8fc8d74d6a48f2357800c73c3b
[ "MIT" ]
null
null
null
leds2/leds2.ino
tiferrei/CJP2.0
28f59c4abe369a8fc8d74d6a48f2357800c73c3b
[ "MIT" ]
null
null
null
// Copyright (c) 2014 The CJP2.0 Team // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. int r = 9; //porta vermelha int g = 10; //porta verde int b = 11; //porta azul int t = 1000; int fadetime=10; int f; int contagem; void setup() { pinMode(r, OUTPUT);// vermelho como saida pinMode(g, OUTPUT);// verde como saida pinMode(b, OUTPUT);// azul como saida } void loop(){ digitalWrite(r, HIGH); // turn the LED on (HIGH is the voltage level) delay(t); // wait for a second digitalWrite(r, LOW); // turn the LED off by making the voltage LOW digitalWrite(g, HIGH); // turn the LED on (HIGH is the voltage level) delay(t); // wait for a second digitalWrite(g, LOW); // turn the LED off by making the voltage LOW digitalWrite(b, HIGH); // turn the LED on (HIGH is the voltage level) delay(t); digitalWrite(b, LOW); digitalWrite(r, HIGH); // turn the LED on (HIGH is the voltage level) digitalWrite(g, HIGH); // turn the LED on (HIGH is the voltage level) delay(t); // wait for a second digitalWrite(r, LOW); digitalWrite(g, LOW); digitalWrite(g, HIGH); // turn the LED on (HIGH is the voltage level) digitalWrite(b, HIGH); // turn the LED on (HIGH is the voltage level) delay(t); // wait for a second digitalWrite(g, LOW); digitalWrite(b, LOW); digitalWrite(r, HIGH); // turn the LED on (HIGH is the voltage level) digitalWrite(b, HIGH); // turn the LED on (HIGH is the voltage level) delay(t); // wait for a second digitalWrite(r, LOW); digitalWrite(b, LOW); digitalWrite(r, HIGH); // turn the LED on (HIGH is the voltage level) digitalWrite(g, HIGH); // turn the LED on (HIGH is the voltage level) digitalWrite(b, HIGH); // turn the LED on (HIGH is the voltage level) delay(t); // wait for a second digitalWrite(r, LOW); digitalWrite(g, LOW); digitalWrite(b, LOW); delay(5000); f_r(); } void f_r() { // fade from vermelho for (f = 0; f < 255; f++) { analogWrite(r, f); delay (fadetime); } for (f = 255; f > 0; f--) { analogWrite(r, f); delay (fadetime); } analogWrite(r, 0); } //__________________________ void f_g(){ // fade from verde for (f = 0; f < 255; f++) { analogWrite(g, f); delay (fadetime); } // fade from verde for (f = 255; f >0; f--) { analogWrite(g, f); delay (fadetime); } } //----------------------- void f_b() { // fade from azul for (f = 0; f < 255; f++) { analogWrite(b, f); delay (fadetime); } // fade from azul for (f = 255; f > 0; f--) { analogWrite(b, f); delay (fadetime); } }
23.837037
80
0.598508
252201220dcbb0eb92636daaf6722c71c74b319e
4,438
ino
Arduino
mySensors-Rs485AmpMeterSensor.ino
tomarc3/mySensors-Rs485AmpMeterSensor
c15b8aa76e60942eeea3cca8ae07fb8f01c66d01
[ "MIT" ]
null
null
null
mySensors-Rs485AmpMeterSensor.ino
tomarc3/mySensors-Rs485AmpMeterSensor
c15b8aa76e60942eeea3cca8ae07fb8f01c66d01
[ "MIT" ]
null
null
null
mySensors-Rs485AmpMeterSensor.ino
tomarc3/mySensors-Rs485AmpMeterSensor
c15b8aa76e60942eeea3cca8ae07fb8f01c66d01
[ "MIT" ]
1
2019-11-26T11:25:46.000Z
2019-11-26T11:25:46.000Z
/** * The MySensors Arduino library handles the wireless radio link and protocol * between your home built sensors/actuators and HA controller of choice. * The sensors forms a self healing radio network with optional repeaters. Each * repeater and gateway builds a routing tables in EEPROM which keeps track of the * network topology allowing messages to be routed to nodes. * * Created by Henrik Ekblad <henrik.ekblad@mysensors.org> * Copyright (C) 2013-2015 Sensnology AB * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors * * Documentation: http://www.mysensors.org * Support Forum: http://forum.mysensors.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * ******************************* * * REVISION HISTORY * Version 1.0 - Thomas Kocher * * DESCRIPTION * This sketch implements a MySensors 4 channel ampere meter sensor. * It uses the OpenEnergyMonitor libraries: https://openenergymonitor.org * The communication is RS485 based. */ // Enable debug prints to serial monitor #define MY_DEBUG /** * Configure RS485 transport */ // Enable RS485 transport layer #define MY_RS485 // Incontrast to radio based transport, we have to explicitely assigen a MY_NODE_ID whe using RS485 transport. #define MY_NODE_ID 46 // Define this to enables DE-pin management on defined pin #define MY_RS485_DE_PIN 2 // Set RS485 baud rate to use #define MY_RS485_BAUD_RATE 9600 /** * Configure sensor */ #define SENSOR_NAME "4Chan Ampere Meter" #define SENSOR_VERSION "1.0" // Analog pin assignment for all channels of ampere meter #define AMP_METER_CH1_PIN A0 #define AMP_METER_CH2_PIN A1 #define AMP_METER_CH3_PIN A2 #define AMP_METER_CH4_PIN A3 // Digital I/O pin number for status led #define STATUS_PIN 13 #define STATUS_BLINK_INTERVAL 200 // The sketch reads approximately 106 samples of current in each cycle of mains at 50 Hz. // 1480 samples therefore works out at 14 cycles of mains. That will give you a good average reading. // You can change the number, but you should get as close as possible to having a whole number of mains cycles, // otherwise if you have only part of a cycle on the end, you will introduce an error. #define NUM_OF_SAMPLES 1480 #define NUM_OF_CHANNELS 4 /** * Include libraries */ #include <MySensors.h> #include "EmonLib.h" /** * Sensor code */ MyMessage msgAmp[NUM_OF_CHANNELS]; EnergyMonitor emon[NUM_OF_CHANNELS]; // measure current on each channel and send values every 5secs static const uint64_t UPDATE_INTERVAL = 5000; /** * Initialize Ampere meters. */ void before() { Serial.print("Initializing "); Serial.print(SENSOR_NAME); Serial.print(" v"); Serial.print(SENSOR_VERSION); Serial.println("..."); pinMode(STATUS_PIN, OUTPUT); digitalWrite(STATUS_PIN, LOW); for (int i = 0; i < NUM_OF_CHANNELS; i++) { msgAmp[i].sensor = i; msgAmp[i].type = V_CURRENT; } // initialize apere meter with pin and calibration current constant // see https://learn.openenergymonitor.org/electricity-monitoring/ctac/ct-and-ac-power-adaptor-installation-and-calibration-theory // calculation: current constant = (ratio of current transformer) / (burden resistor) // (100 / 0.050) / 33 = 60.6 emon[0].current(AMP_METER_CH1_PIN, 60.6); emon[1].current(AMP_METER_CH2_PIN, 61.6); emon[2].current(AMP_METER_CH3_PIN, 60.0); emon[3].current(AMP_METER_CH4_PIN, 60.6); } /** * Present the sonsor the contrller. */ void presentation () { // Send the sketch version information to the gateway sendSketchInfo(SENSOR_NAME, SENSOR_VERSION); // Register all sensors to gw (they will be created as child devices) for (int i = 0; i < NUM_OF_CHANNELS; i++) present(i, S_MULTIMETER); } /** * Setup */ void setup() { // everthing was initialized in before(). hence do nothing } /** * Loop */ void loop() { // put your main code here, to run repeatedly: for (int i = 0; i < NUM_OF_CHANNELS; i++) { // Calculate RMS currernt with defined number of samples float Irms = (float)emon[i].calcIrms(NUM_OF_SAMPLES); send(msgAmp[i].set(Irms, 3)); blinkStatus(); } sleep(UPDATE_INTERVAL); } /** * Blink status LED once. */ void blinkStatus() { digitalWrite(STATUS_PIN, HIGH); wait(STATUS_BLINK_INTERVAL); digitalWrite(STATUS_PIN, LOW); }
27.395062
132
0.727355
feae94083cc2c9259f0f5b2c5081ee5dc451fac5
1,675
ino
Arduino
neopixels_firmware/neopixels_firmware.ino
ebezzam/melody-detection
8e1637755895fc92fb5ec0ce703eff8772c7a234
[ "MIT" ]
4
2019-05-09T16:38:00.000Z
2020-08-14T15:43:08.000Z
neopixels_firmware/neopixels_firmware.ino
ebezzam/melody-detection
8e1637755895fc92fb5ec0ce703eff8772c7a234
[ "MIT" ]
null
null
null
neopixels_firmware/neopixels_firmware.ino
ebezzam/melody-detection
8e1637755895fc92fb5ec0ce703eff8772c7a234
[ "MIT" ]
1
2021-07-30T07:22:11.000Z
2021-07-30T07:22:11.000Z
// http://arduino.stackexchange.com/questions/1013/how-do-i-split-an-incoming-string // http://internetofhomethings.com/homethings/?p=927 // http://www.hobbytronics.co.uk/arduino-serial-buffer-size--> increase buffer size? #include <Adafruit_NeoPixel.h> #ifdef __AVR__ #include <avr/power.h> #endif #include <limits.h> // Turn off the LEDs after a timeout #define TIMEOUT 2000 unsigned long last_update = 0; char is_on = 0; #define PIN 6 #define INPUT_SIZE 180 #define NUM_LEDS 60 char input[INPUT_SIZE + 1]; Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800); void reset_leds() { // Turn off all the LEDs uint8_t i; for (i = 0 ; i < NUM_LEDS ; i++) strip.setPixelColor(i, strip.Color(0, 0, 0)); strip.show(); is_on = 0; } unsigned long time_since_last_update() { unsigned long now = millis(); if (now < last_update) return ULONG_MAX - last_update + now; else return now - last_update; } void setup() { Serial.begin(115200); strip.begin(); reset_leds(); // Initialize all pixels to 'off' } void loop() { if (Serial.available() > 0) { last_update = millis(); is_on = 1; byte size = Serial.readBytes(input, INPUT_SIZE); input[size] = 0; uint8_t pixelIdx, red, green, blue; for ( pixelIdx = 0; pixelIdx < NUM_LEDS; pixelIdx++) { red = uint8_t(input[pixelIdx * 3]); green = uint8_t(input[pixelIdx * 3 + 1]); blue = uint8_t(input[pixelIdx * 3 + 2]); strip.setPixelColor(pixelIdx, strip.Color(red, green, blue)); } strip.show(); } // Turn off LEDs on timeout if (is_on && time_since_last_update() > TIMEOUT) reset_leds(); }
21.202532
84
0.66209
e17782c8c74d6ec90ae3e5dce903e919ffc1da98
10,393
ino
Arduino
src/arduino/Arduino.ino
grey-gray/Human-following-robot-using-Xbox-Kinect-
7f5c8961295d0d0cadb1b9e0d26d75e6ee6fe452
[ "MIT" ]
3
2020-01-09T13:19:19.000Z
2020-12-14T23:05:09.000Z
src/arduino/Arduino.ino
grey-gray/Human-following-robot-using-Xbox-Kinect-
7f5c8961295d0d0cadb1b9e0d26d75e6ee6fe452
[ "MIT" ]
null
null
null
src/arduino/Arduino.ino
grey-gray/Human-following-robot-using-Xbox-Kinect-
7f5c8961295d0d0cadb1b9e0d26d75e6ee6fe452
[ "MIT" ]
null
null
null
<<<<<<< HEAD /*By Nator Verinumbe and Solomon University of Ibadan 10/October/2019 */ const int trigPin = 7; const int echoPin = 8; //#include <LiquidCrystal.h> // includes the LiquidCrystal Library //LiquidCrystal lcd(1, 2, 3, 4, 5, 6); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7) #define enA 9 #define in1 11 #define in2 12 #define enB 10 #define in3 13 #define in4 22 int motorSpeedA = 0; int motorSpeedB = 0; int val, xVal, zVal; int xMin = 80; int xMax = 160; int zMin = 10; int zMax = 50; int distance; int read_dist_ultra_sensor(); //function prototyping for distance measuring (ultrasonic sensors) void setup(){ Serial.begin(9600); //lcd.begin(16,2); pinMode(enA, OUTPUT); pinMode(enB, OUTPUT); pinMode(in1, OUTPUT); pinMode(in2, OUTPUT); pinMode(in3, OUTPUT); pinMode(in4, OUTPUT); pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input } void loop() { distance = read_dist_ultra_sensor(); if (Serial.available()>2) { // If data is available to read, val = Serial.read(); if(val == 'S'){ // read the most recent byte (which will be from 0 to 255): //int a = Serial.read(); //if (a =1) //lcd.print("stand for kindly stand upright for scanning)"); //int b = Serial.read(); //if (b =1) //lcd.print("scanning completed"); //delay (5000); //lcd.print("Please proceed to shopping"); xVal = Serial.read(); zVal = Serial.read(); //backward while ( distance < 40){ //caution from ultrasonic sensors if (zVal < zMin) { // Set Motor A backward digitalWrite(in2, HIGH); digitalWrite(in1, LOW); // Set Motor B backward digitalWrite(in3, HIGH); digitalWrite(in4, LOW); // Convert the declining Y-axis readings for going backward from 470 to 0 into 0 to 255 value for the PWM signal for increasing the motor speed motorSpeedA = map(zVal, zMin, 0, 200, 255); motorSpeedB = map(zVal, zMin, 0, 200, 255); //backward right, A is higher if (xVal <= xMin) { int xMapped = map(xVal, xMin, 0, 200, 255); // Move to left - decrease left motor speed, increase right motor speed motorSpeedA = motorSpeedA + xMapped; motorSpeedB = motorSpeedB - xMapped; } //backward left, B is higher else if (xVal >= xMax) { int xMapped = map(xVal, 225, xMax, 255, 200); // Move to left - decrease left motor speed, increase right motor speed motorSpeedA = motorSpeedA - xMapped; motorSpeedB = motorSpeedB + xMapped; } } //forward else if (zVal >= zMin) { // Set Motor A forward digitalWrite(in2, LOW); digitalWrite(in1, HIGH); // Set Motor B forward digitalWrite(in4, HIGH); digitalWrite(in3, LOW); motorSpeedA = map(zVal, zMax,255, 200, 255); motorSpeedB = map(zVal, zMax,255, 170, 255); //forward right, b is higher if (xVal <= xMin) { int xMapped = map(xVal, xMin, 0, 200, 255); // Move to left - decrease left motor speed, increase right motor speed motorSpeedA = motorSpeedA - xMapped; motorSpeedB = motorSpeedB + xMapped; } //forward left, A is higher else if (xVal >= xMax) { int xMapped = map(xVal, 225, xMax, 255, 200); // Move to left - decrease left motor speed, increase right motor speed motorSpeedA = motorSpeedA + xMapped; motorSpeedB = motorSpeedB - xMapped; } // stop else if (xVal > xMin && xVal < xMax) { if (zVal <= zMax){ motorSpeedA = 0; motorSpeedB = 0; } } } if (motorSpeedA < 0) { motorSpeedA = 0; } if (motorSpeedB > 255) { motorSpeedB = 255; } if (motorSpeedB < 0) { motorSpeedB = 0; } if (motorSpeedA > 255) { motorSpeedA = 255; //max speed } analogWrite(enA, motorSpeedA); // Send PWM signal to motor A analogWrite(enB, motorSpeedB); // Send PWM signal to motor B } } } } int read_dist_ultra_sensor(){ long duration; digitalWrite(trigPin, LOW);//to clear it of stray current delayMicroseconds(2); //Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, HIGH); delayMicroseconds(10); //this tells the sensor to send out a sound wave digitalWrite(trigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds duration = pulseIn(echoPin, HIGH); // Calculating the distance return (duration*0.034/2); } //sdfasd ======= /*By Nator Verinumbe and Solomon University of Ibadan 10/October/2019 */ const int trigPin = 7; const int echoPin = 8; //#include <LiquidCrystal.h> // includes the LiquidCrystal Library //LiquidCrystal lcd(1, 2, 3, 4, 5, 6); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7) #define enA 9 #define in1 11 #define in2 12 #define enB 10 #define in3 13 #define in4 22 int motorSpeedA = 0; int motorSpeedB = 0; int val, xVal, zVal; int xMin = 80; int xMax = 160; int zMin = 10; int zMax = 50; int distance; int read_dist_ultra_sensor(); //function prototyping for distance measuring (ultrasonic sensors) void setup(){ Serial.begin(9600); //lcd.begin(16,2); pinMode(enA, OUTPUT); pinMode(enB, OUTPUT); pinMode(in1, OUTPUT); pinMode(in2, OUTPUT); pinMode(in3, OUTPUT); pinMode(in4, OUTPUT); pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input } void loop() { distance = read_dist_ultra_sensor(); if (Serial.available()>2) { // If data is available to read, val = Serial.read(); if(val == 'S'){ // read the most recent byte (which will be from 0 to 255): //int a = Serial.read(); //if (a =1) //lcd.print("stand for kindly stand upright for scanning)"); //int b = Serial.read(); //if (b =1) //lcd.print("scanning completed"); //delay (5000); //lcd.print("Please proceed to shopping"); xVal = Serial.read(); zVal = Serial.read(); //backward while ( distance < 40){ //caution from ultrasonic sensors if (zVal < zMin) { // Set Motor A backward digitalWrite(in2, HIGH); digitalWrite(in1, LOW); // Set Motor B backward digitalWrite(in3, HIGH); digitalWrite(in4, LOW); // Convert the declining Y-axis readings for going backward from 470 to 0 into 0 to 255 value for the PWM signal for increasing the motor speed motorSpeedA = map(zVal, zMin, 0, 200, 255); motorSpeedB = map(zVal, zMin, 0, 200, 255); //backward right, A is higher if (xVal <= xMin) { int xMapped = map(xVal, xMin, 0, 200, 255); // Move to left - decrease left motor speed, increase right motor speed motorSpeedA = motorSpeedA + xMapped; motorSpeedB = motorSpeedB - xMapped; } //backward left, B is higher else if (xVal >= xMax) { int xMapped = map(xVal, 225, xMax, 255, 200); // Move to left - decrease left motor speed, increase right motor speed motorSpeedA = motorSpeedA - xMapped; motorSpeedB = motorSpeedB + xMapped; } } //forward else if (zVal >= zMin) { // Set Motor A forward digitalWrite(in2, LOW); digitalWrite(in1, HIGH); // Set Motor B forward digitalWrite(in4, HIGH); digitalWrite(in3, LOW); motorSpeedA = map(zVal, zMax,255, 200, 255); motorSpeedB = map(zVal, zMax,255, 170, 255); //forward right, b is higher if (xVal <= xMin) { int xMapped = map(xVal, xMin, 0, 200, 255); // Move to left - decrease left motor speed, increase right motor speed motorSpeedA = motorSpeedA - xMapped; motorSpeedB = motorSpeedB + xMapped; } //forward left, A is higher else if (xVal >= xMax) { int xMapped = map(xVal, 225, xMax, 255, 200); // Move to left - decrease left motor speed, increase right motor speed motorSpeedA = motorSpeedA + xMapped; motorSpeedB = motorSpeedB - xMapped; } // stop else if (xVal > xMin && xVal < xMax) { if (zVal <= zMax){ motorSpeedA = 0; motorSpeedB = 0; } } } if (motorSpeedA < 0) { motorSpeedA = 0; } if (motorSpeedB > 255) { motorSpeedB = 255; } if (motorSpeedB < 0) { motorSpeedB = 0; } if (motorSpeedA > 255) { motorSpeedA = 255; //max speed } analogWrite(enA, motorSpeedA); // Send PWM signal to motor A analogWrite(enB, motorSpeedB); // Send PWM signal to motor B } } } } int read_dist_ultra_sensor(){ long duration; digitalWrite(trigPin, LOW);//to clear it of stray current delayMicroseconds(2); //Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, HIGH); delayMicroseconds(10); //this tells the sensor to send out a sound wave digitalWrite(trigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds duration = pulseIn(echoPin, HIGH); // Calculating the distance return (duration*0.034/2); } //sdfasd >>>>>>> updates
27.206806
155
0.549697
e3690c9b240681cc383d24387f58f84a1da2d8a5
14,210
ino
Arduino
photoresist/photoresist.ino
braserlaky/ams_laky
51aa2c788dd994c97ba0ce8043ff46e3fa2f3ad8
[ "W3C" ]
null
null
null
photoresist/photoresist.ino
braserlaky/ams_laky
51aa2c788dd994c97ba0ce8043ff46e3fa2f3ad8
[ "W3C" ]
null
null
null
photoresist/photoresist.ino
braserlaky/ams_laky
51aa2c788dd994c97ba0ce8043ff46e3fa2f3ad8
[ "W3C" ]
null
null
null
#include <EEPROM.h> //библиотека работы с постоянной памятью для записи настроек. #include <Adafruit_GFX.h> //библиотека работы с примитивами и текстом #include <Adafruit_PCD8544.h> //библиотека работы с жк экраном от nokia3310 #include "DHT.h" //библиотека работы с датчиком DHT11 // const int relayLight = 8; //переменная с номером пина реле const byte relayLight = 8; //переменная с номером пина реле const byte ldr1 = 0; //аналоговый пин фоторезистора const byte ldr2 = 1; //второй аналоговый пин фоторезистора для исключения ложных срабатываний int level1 = 0; //уровень освещенности с первого фоторезистора int level2 = 0; //уровень освещенности со второго фоторезистора // const int buttonPlus = 9; //цифровой пин первой кнопки "+" // const int buttonMinus = 10; //цифровой пин второй кнопки "-" // const int buttonLight = 11; //цифровой пин кнопки включения освещения экрана const byte buttonPlus = 9; //цифровой пин первой кнопки "+" const byte buttonMinus = 10; //цифровой пин второй кнопки "-" const byte buttonLight = 11; //цифровой пин кнопки включения освещения экрана const int delayButtonRequest = 100; //длительность периодичности опроса кнопок //const int delayScreenLight = delayButtonRequest * 10; //длительность подсветки. на будущее для сохранения настроек в памяти //const int delaySensorsWait = delayButtonRequest * 20; //длительность периодичности опроса датчиков // const int screenLightPin = 12; //цифровой пин подсветки (на выход) const byte screenLightPin = 12; //цифровой пин подсветки (на выход) byte buttonPlusState = 0; //состояние кнопки "плюс" byte buttonMinusState = 0; //изначальное состояние кнопки const int step_level = 1; //переменная шага изменения уровня освещенности const int serialSpeed = 9600; //скорость подключения по сериалу const byte contrast = 60; //указываем контраст экрана. 60 вроде как самое то String strStateRelay = "empty str"; unsigned long currentTime; //------текущее время unsigned long loopTime; //------время для обновления unsigned long timeToRelay; // переменная для управления задержкой включения/выключения освещения bool lightOn; // состояние света true - включен, false - выключен const unsigned long delayRelay = 300000; // задержка времени при переключении реле. чтобы избежать дребезга. #define DHTPIN 2 // номер пина, к которому подсоединен датчик DHT dht(DHTPIN, DHT11); // // pin 7 - Serial clock out (SCLK) // pin 6 - Serial data out (DIN) // pin 5 - Data/Command select (D/C) // pin 4 - LCD chip select (CS) // pin 3 - LCD reset (RST) Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3);// #define NUMFLAKES 10 #define XPOS 0 #define YPOS 1 #define DELTAY 2 #define LOGO16_GLCD_HEIGHT 16 #define LOGO16_GLCD_WIDTH 16 const static unsigned char PROGMEM logo16_glcd_bmp[] = //массив цветочка (бантики) { B00000000, B11000000, B00000001, B11000000, B00000001, B11000000, B00000011, B11100000, B11110011, B11100000, B11111110, B11111000, B01111110, B11111111, B00110011, B10011111, B00011111, B11111100, B00001101, B01110000, B00011011, B10100000, B00111111, B11100000, B00111111, B11110000, B01111100, B11110000, B01110000, B01110000, B00000000, B00110000 }; int delay_sleep = 1000; //время задержки в системе (обновления экрана и измерений) // int porog = 800; //пороговое значение уровня освещенности, когда включается освещение uint8_t porog = 80; //в будущем читать из EEPROM (чтобы настройки запоминались) void setup() //процедура первичной инициализации { lightOn = false; porog = EEPROM.read(0); currentTime = millis(); //считываем время, прошедшее с момента запуска программы loopTime = currentTime; //выравниваем показания Serial.begin(serialSpeed); //инициализируем сериал на скорости 9600 dht.begin(); //инициализируем датчик влажности и температуры display.begin(); //инициализируем экран display.setContrast(contrast); //указываем контраст экрана. 60 вроде как самое то display.display(); //show splashscreen -- используется несколько раз. кажется для отображения заготовленных изменнений. проверить. если что удалить. delay(delay_sleep); //задержка. кажется нужна. связано с ком.выше, чтобы успел отобразиться (?) display.clearDisplay(); //clears the screen and buffer display.drawPixel(10, 10, BLACK); //draw a single pixel. было, тупо тупая фишка. можно будет удалить. display.display(); delay(delay_sleep); // display.clearDisplay(); display.setTextSize(1); //выбираем размер шрифта 1 (мелкий, кажется самый) display.setTextColor(BLACK); //выбираем цвет шрифта (??) pinMode(buttonPlus, INPUT); //настроить пин первой кнопки на ввод данных pinMode(buttonMinus, INPUT); //настроить пин второй кнопки на ввод данных pinMode(buttonLight, INPUT); //настроить пин кнопки подсветки на ввод данных pinMode(relayLight, OUTPUT); //указываем, что пин реле - выход. в последующем переименовать это в понятное реле. pinMode(screenLightPin, OUTPUT); //настроить пин подсветки на вывод, им запускать транзистор подсветки } void loop() //процедура бесконечного цикла { float h = 0; //объявляем переменную типа float влажности float t = 0; //объявляем переменную типа float температуры int prom = 14; //длительность периода работы лампы (пока тупо рисуем 14 часов на экране. потом будем измерять) bool b_updateScreen = false; //флаг обновления содержимого экрана. если true, то обновить экран bool b_updateSensorValue = false; //флаг обновления значений сенсоров влажности и температуры, если true, то запросить новые значения bool b_updateButtons = false; //флаг обновления значений кнопок int i_prom = 0; //счетчик повторов для опроса датчиков currentTime = millis(); // считываем заново время, прошедшее с момента запуска программы if(currentTime >= (loopTime + delayButtonRequest)) { // сравниваем текущий таймер с переменной loopTime + 0,1 секунда для задержки в 0,1 секунду i_prom++; if(i_prom = 10) { //будет выполняться в 20 раза реже delayScreenLight (2 секунды) чтобы датчики успевали отработать b_updateScreen = true; //ставим флаг обновить экран раз в секунду b_updateButtons = true; //ставим флаг "время обновить значение кнопок" } if(i_prom = 20) { //будет выполняться в 20 раза реже delayScreenLight (2 секунды) чтобы датчики успевали отработать b_updateSensorValue = true; //ставим флаг обновить значения сенсоров в true i_prom = 0; //зануляем счетчик для следующего цикла } loopTime = currentTime; //в loopTime записываем новое текущее значение } // определяем нажатие кнопок и изменение порогового уровня освещенности // переопределить поведение. кажется все окей. if(b_updateButtons) { //время выяснить значение кнопок buttonPlusState = digitalRead(buttonPlus); //считать в переменную состояние кнопки1 на увеличение порога (есть проблема, что надо держать долго кнопку) buttonMinusState = digitalRead(buttonMinus); //считать в переменную состояние кнопки2 на уменьшение порога (есть проблема, что надо держать долго кнопку) if (buttonPlusState == HIGH) { //если нажата кнопка1 ("+"), то увеличить porog = porog + step_level; //пороговое значение на step_level EEPROM.write(0, porog); Serial.println(" + "); //отладочная } else { // Serial.println(" 0"); //конструкцию с двумя if сократить! if (buttonMinusState == HIGH) { //если нажата кнопка2 ("-"), то уменьшить porog = porog - step_level; //пороговое значение на step_level EEPROM.write(0, porog); Serial.println(" - "); //отладочная } } b_updateButtons = false; //сбрасываем флаг для следующего цикла } if(b_updateSensorValue) { //время обновить значения сенсоров level1 = int(analogRead(ldr1)/10); // выясняем уровень освещенности на фоторезисторе1 level2 = int(analogRead(ldr2)/10); // выясняем уровень освещенности на фоторезисторе2 h = dht.readHumidity(); //Считываем влажность с датчика DHT11 t = dht.readTemperature(); //Считываем температуру с датчика DHT11 if (isnan(h) || isnan(t)) { // Проверка удачно прошло ли считывание. Serial.println(" ERROR t or h "); // в сериал display.print (" ERROR t or h "); // на дисплей } b_updateSensorValue = false; //сбрасываем флаг обновления данных с сенсоров } if(b_updateScreen) { //время обновить экран display.clearDisplay(); display.setCursor(0,0); //ставим курсор на начальную позицию display.setTextSize(0); //задаем размер шрифта 0 (кажется не работает) display.print("sens "); //форматируем вывод. выводим текст на экран display.print(level1); display.print("/"); display.println(level2); display.setTextColor(BLACK); display.setTextSize(2); //выводим большими буквами display.print(int(h)); display.println("% H"); display.setTextSize(2); display.print(int(t)); display.print(char(0)); //печатаем знак градуса (проверить!) display.println(" C"); display.setTextSize(1); display.print(porog); display.print(strStateRelay); // добавить печать строки со значением статуса реле display.display(); // delay(delay_sleep); b_updateScreen = false; //сбрасываем флаг обновления дисплея } if ((level1 < porog)&(level2 < porog)&(!lightOn)){ lightOn = true; timeToRelay = currentTime; } if ((level1 < porog)&(level2 < porog)) { //сама логика включения реле. если оба датчика показывают уровень освещенности ниже порогового if (currentTime >= timeToRelay + delayRelay) { digitalWrite(relayLight, HIGH); // добавить строку и в нее записывать статус реле. а строку в дисплей печатать во время обновления strStateRelay = String(" ON (" + String(prom) + "h)"); timeToRelay = currentTime; } } else { if(currentTime >= timeToRelay + delayRelay){ digitalWrite(relayLight, LOW); //иначе выключаем реле освещения strStateRelay = String(" OFF"); timeToRelay = currentTime; // display.print(" OFF"); } } } void testdrawbitmap(const uint8_t *bitmap, uint8_t w, uint8_t h) { //в будущем можно сделать экранную заставку, если температура не трогалась более 5 минут uint8_t icons[NUMFLAKES][3]; srandom(666); // whatever seed // initialize for (uint8_t f=0; f< NUMFLAKES; f++) { icons[f][XPOS] = random() % display.width(); icons[f][YPOS] = 0; icons[f][DELTAY] = random() % 5 + 1; Serial.print("x: "); Serial.print(icons[f][XPOS], DEC); Serial.print(" y: "); Serial.print(icons[f][YPOS], DEC); Serial.print(" dy: "); Serial.println(icons[f][DELTAY], DEC); } while (1) { // draw each icon for (uint8_t f=0; f< NUMFLAKES; f++) { display.drawBitmap(icons[f][XPOS], icons[f][YPOS], logo16_glcd_bmp, w, h, BLACK); } display.display(); delay(200); // then erase it + move it for (uint8_t f=0; f< NUMFLAKES; f++) { display.drawBitmap(icons[f][XPOS], icons[f][YPOS], logo16_glcd_bmp, w, h, WHITE); // move it icons[f][YPOS] += icons[f][DELTAY]; // if its gone, reinit if (icons[f][YPOS] > display.height()) { icons[f][XPOS] = random() % display.width(); icons[f][YPOS] = 0; icons[f][DELTAY] = random() % 5 + 1; } } } }
55.507813
190
0.564673
bfd5a7070630dfa49e3a36fd4b28dbe659c87572
351
ino
Arduino
sketch_oct15a.ino
Samhithgb/ArduinoControl
9b83f7a236dc357ec96b677668776c080f305e5f
[ "Apache-2.0" ]
null
null
null
sketch_oct15a.ino
Samhithgb/ArduinoControl
9b83f7a236dc357ec96b677668776c080f305e5f
[ "Apache-2.0" ]
null
null
null
sketch_oct15a.ino
Samhithgb/ArduinoControl
9b83f7a236dc357ec96b677668776c080f305e5f
[ "Apache-2.0" ]
null
null
null
int ledPin=13; int state=0; int data=0; void setup() { pinMode(ledPin,OUTPUT); digitalWrite(ledPin,state); Serial.begin(9600); } void loop() { Serial.println(data); if(Serial.available()>0) { state=!state; data=Serial.read(); switch(data) { case 177: digitalWrite(ledPin,state); break; } } }
13
35
0.586895
79494a0df63055250a0eb65cbbf696cc12cb3dad
7,198
ino
Arduino
sensortest/sensortest.ino
deton/heatmapdrone
1867b0acaa927e3387e208710be52bc2252a42a0
[ "MIT" ]
null
null
null
sensortest/sensortest.ino
deton/heatmapdrone
1867b0acaa927e3387e208710be52bc2252a42a0
[ "MIT" ]
null
null
null
sensortest/sensortest.ino
deton/heatmapdrone
1867b0acaa927e3387e208710be52bc2252a42a0
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016 RedBear * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ /** * @note This demo is Nordic HRM example. * You could use nRF toolbox tool to test it. */ #define SENSOR_VCNL4010 0 #define SENSOR_TOF 1 #define SENSOR_TEMPERATURE 1 #include <nRF5x_BLE_API.h> #include <Wire.h> #if SENSOR_VCNL4010 #include "Adafruit_VCNL4010.h" #endif #if SENSOR_TOF // https://github.com/pololu/vl53l0x-arduino #include <VL53L0X.h> #endif #if SENSOR_TEMPERATURE #include <FaBoTemperature_ADT7410.h> #endif const uint8_t PIN_LIGHT1 = A5; const uint8_t PIN_LIGHT2 = A4; #if SENSOR_TOF const uint8_t XSHUT_PIN = D6; const uint8_t TOF_FRONT_NEWADDR = 42; // TOF_UP = 41 (default) #endif #if SENSOR_VCNL4010 Adafruit_VCNL4010 vcnl; #endif #if SENSOR_TOF VL53L0X tof_up; VL53L0X tof_front; #endif #if SENSOR_TEMPERATURE FaBoTemperature adt7410; #endif #define DEVICE_NAME "Nordic_HRM" BLE ble; Ticker ticker_task1; static uint32_t prevMillis = 0; static uint8_t hrmCounter = 100; static uint8_t bpm[2] = {0x00, hrmCounter}; static const uint8_t location = 0x03; static const uint16_t uuid16_list[] = {GattService::UUID_HEART_RATE_SERVICE}; // Create characteristic and service GattCharacteristic hrmRate(GattCharacteristic::UUID_HEART_RATE_MEASUREMENT_CHAR, bpm, sizeof(bpm), sizeof(bpm), GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY); GattCharacteristic hrmLocation(GattCharacteristic::UUID_BODY_SENSOR_LOCATION_CHAR,(uint8_t *)&location, sizeof(location), sizeof(location),GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ); GattCharacteristic *hrmChars[] = {&hrmRate, &hrmLocation, }; GattService hrmService(GattService::UUID_HEART_RATE_SERVICE, hrmChars, sizeof(hrmChars) / sizeof(GattCharacteristic *)); void disconnectionCallBack(const Gap::DisconnectionCallbackParams_t *params) { Serial.println("Disconnected!"); Serial.println("Restarting the advertising process"); ble.startAdvertising(); } void periodicCallback() { if (ble.getGapState().connected) { // Update the HRM measurement // First byte = 8-bit values, no extra info, Second byte = uint8_t HRM value // See --> https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml /* hrmCounter++; if (hrmCounter == 175) hrmCounter = 100; */ bpm[1] = hrmCounter; ble.updateCharacteristicValue(hrmRate.getValueAttribute().getHandle(), bpm, sizeof(bpm)); } } void setup() { #if SENSOR_TOF // https://forum.pololu.com/t/vl53l0x-maximum-sensors-on-i2c-arduino-bus/10845/7 pinMode(XSHUT_PIN, OUTPUT); // LOW: shutdown tof_up #endif Serial.begin(9600); Serial.println("Nordic_HRM Demo "); Wire.begin(); #if SENSOR_VCNL4010 if (! vcnl.begin()){ Serial.println("Sensor not found :("); while (1); } // disable proximity sensing. use ambient sensing only vcnl.setLEDcurrent(0); vcnl.setFrequency(VCNL4010_1_95); #endif #if SENSOR_TOF // change address to use multiple VL53L0X tof_front.setAddress(TOF_FRONT_NEWADDR); pinMode(XSHUT_PIN, INPUT); // HIGH: boot tof_up. default addr delay(50); tof_up.init(); tof_up.setTimeout(300); tof_up.setMeasurementTimingBudget(20000); tof_front.init(); tof_front.setTimeout(300); tof_front.setMeasurementTimingBudget(20000); #endif #if SENSOR_TEMPERATURE adt7410.begin(); #endif ticker_task1.attach(periodicCallback, 1); ble.init(); ble.onDisconnection(disconnectionCallBack); // setup adv_data and srp_data ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t*)uuid16_list, sizeof(uuid16_list)); ble.accumulateAdvertisingPayload(GapAdvertisingData::HEART_RATE_SENSOR_HEART_RATE_BELT); ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME)); ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); ble.addService(hrmService); ble.setDeviceName((const uint8_t *)DEVICE_NAME); // set tx power,valid values are -40, -20, -16, -12, -8, -4, 0, 4 ble.setTxPower(4); // set adv_interval, 100ms in multiples of 0.625ms. ble.setAdvertisingInterval(160); // set adv_timeout, in seconds ble.setAdvertisingTimeout(0); ble.startAdvertising(); } void loop() { ble.waitForEvent(); if (millis() - prevMillis > 1000) { prevMillis = millis(); int light1 = analogRead(PIN_LIGHT1); int light2 = analogRead(PIN_LIGHT2); Serial.print("sensing ms: "); Serial.println(millis() - prevMillis); // ex. 11ms Serial.print("Light1: "); Serial.println(light1); Serial.print("Light2: "); Serial.println(light2); #if SENSOR_VCNL4010 uint16_t ambient = vcnl.readAmbient(); //Serial.print("sensing ms: "); Serial.println(millis() - prevMillis); // ex. 117 ms Serial.print("Ambient: "); Serial.println(ambient); //Serial.print("Proximity: "); Serial.println(vcnl.readProximity()); // 75:65535 = hrm:ambient hrmCounter = ambient * 75.0 / 65535.0 + 100; //Serial.print("hrm value: "); Serial.println(hrmCounter); #endif #if SENSOR_TOF uint16_t mm_up = tof_up.readRangeSingleMillimeters(); if (!tof_up.timeoutOccurred()) { Serial.print("up ToF mm: "); Serial.println(mm_up); //hrmCounter = mm_up * 75.0 / 8192.0 + 100; //Serial.print("hrm value: "); Serial.println(hrmCounter); } uint16_t mm_front = tof_front.readRangeSingleMillimeters(); if (!tof_front.timeoutOccurred()) { const uint16_t FRONT_MIN = 600; if (mm_front < FRONT_MIN) { Serial.print("XXX "); } Serial.print("front ToF mm: "); Serial.println(mm_front); } #endif #if SENSOR_TEMPERATURE float temp = adt7410.readTemperature(); Serial.print("temperature: "); Serial.println(temp, 1); // 75:255 = hrm:(temp+55) // temp:[-55, 150] hrmCounter = (temp + 55) * 75.0 / 255.0 + 100; Serial.print("hrm value: "); Serial.println(hrmCounter); #endif } }
34.941748
192
0.730064
76601f7c1ae3cf83034212977d92458402e9d5d1
8,239
ino
Arduino
_sketches/LoconetLayoutControlPanel/LoconetLayoutControlPanel.ino
plocher/plocher.github.io
bb85e07759c912167e656051e2372be559247ab9
[ "BSD-3-Clause" ]
null
null
null
_sketches/LoconetLayoutControlPanel/LoconetLayoutControlPanel.ino
plocher/plocher.github.io
bb85e07759c912167e656051e2372be559247ab9
[ "BSD-3-Clause" ]
null
null
null
_sketches/LoconetLayoutControlPanel/LoconetLayoutControlPanel.ino
plocher/plocher.github.io
bb85e07759c912167e656051e2372be559247ab9
[ "BSD-3-Clause" ]
null
null
null
/* * LocoNet Layout Commander * * A standalone controller which will generate LocoNet commands when a button is pressed to: * Turn track power on and off, with a LED to indicate state. * Generate a master E-Stop, with a LED to indicate state. * Clear all slots in a command station * * RX and TX Loconet * Hardcoded to use ICP pin 8 (port PINB bit PB0) for LocoNet input and a user define'd pin for output/transmit * * 3 pushbuttons and associated LEDs plus a Loconet Shield * * Copyright (c) 2012, 2014 John Plocher, released under the terms of the MIT License (MIT) */ #include <LocoNet.h> #define PowerOnPort 2 // Buttons connected to these pins #define PowerOffPort 3 // GPON GPOFF and ESTOP as well as Clear All Slots #define EStopPort 4 #define SlotClearPort 5 #define LNtxPort 6 // LocoNet Transmit pin (LocoShield uses pin7) #define PowerOnLEDPort 11 // Assume this pin has a LED+resistor attached... #define PowerOffLEDPort 12 // Assume this pin has a LED+resistor attached... #define EStopLEDPort 13 // Assume this pin has a LED+resistor attached... // Button press state // Current int GPonButton, GPonButton1, GPonButton2; int GPoffButton, GPoffButton1, GPoffButton2; int EStopButton, EStopButton1, EStopButton2; int ClearButton, ClearButton1, ClearButton2; // Last state processed - helps us ensure we don't repeat commands while a button is held down int lastGPon = -1; int lastGPoff = -1; int lastEStop = -1; int lastClear = -1; int ClearIt = 0; // Should we clear slots when we get a slot status packet? void setup(){ pinMode(PowerOnPort, INPUT); pinMode(PowerOffPort, INPUT); pinMode(SlotClearPort, INPUT); pinMode(EStopPort, INPUT); pinMode(EStopLEDPort, OUTPUT); pinMode(PowerOnLEDPort, OUTPUT); pinMode(PowerOffLEDPort, OUTPUT); digitalWrite(PowerOnLEDPort, 0); // Power is in an unknown state digitalWrite(PowerOffLEDPort, 0); // digitalWrite(EStopLEDPort, 0); // and not estopped // Configure the serial port for 57600 baud Serial.begin(57600); Serial.println("LocoNet Controller"); // initialize the LocoNet interface LocoNet.init(LNtxPort); } void setLNTurnout(int address, byte dir) { sendOPC_SW_REQ( address - 1, dir, 1 ); sendOPC_SW_REQ( address - 1, dir, 0 ); } void sendOPC_SW_REQ(int address, byte dir, byte on) { lnMsg SendPacket ; int sw2 = 0x00; if (dir) sw2 |= B00100000; if (on) sw2 |= B00010000; sw2 |= (address >> 7) & 0x0F; SendPacket.data[ 0 ] = OPC_SW_REQ ; SendPacket.data[ 1 ] = address & 0x7F ; SendPacket.data[ 2 ] = sw2 ; LocoNet.send( &SendPacket ); } void sendOPC_INPUT_REP(int address, byte on) { lnMsg SendPacket; SendPacket.data[ 0 ] = OPC_INPUT_REP; SendPacket.data[ 1 ] = address & 0x7F; // turnout address int in2 = B01000000; if (on) in2 |= B00010000; in2 |= (address >> 7) & 0x0F; SendPacket.data[ 2 ] = in2; // sw2 contains direction, on/off and hi nibble of address LocoNet.send( &SendPacket ) ; } void sendOPC_GP(byte on) { lnMsg SendPacket; if (on) { SendPacket.data[ 0 ] = OPC_GPON; } else { SendPacket.data[ 0 ] = OPC_GPOFF; } LocoNet.send( &SendPacket ) ; } void sendOPC_IDLE() { lnMsg SendPacket; SendPacket.data[ 0 ] = OPC_IDLE; LocoNet.send( &SendPacket ) ; } void send3bytePacket(int opcode, int slot, int spd) { lnMsg SendPacket; SendPacket.data[ 0 ] = opcode; SendPacket.data[ 1 ] = slot; SendPacket.data[ 2 ] = spd; LocoNet.send( &SendPacket ); } void sendOPC_LOCO_SPD(int slot, int spd) { send3bytePacket(OPC_LOCO_SPD,slot,spd); } void sendOPC_LOCO_DIRF(int slot, int dirf) { send3bytePacket(OPC_LOCO_DIRF,slot,dirf); } void sendOPC_LOCO_SND(int slot, int snd) { send3bytePacket(OPC_LOCO_SND,slot,snd); } void sendOPC_SLOT_STAT1(int slot, int stat) { send3bytePacket(OPC_SLOT_STAT1,slot,stat); } void sendOPC_RQ_SL_DATA(int slot) { send3bytePacket(OPC_RQ_SL_DATA,slot,0); } void processIncomingLoconetCommand(lnMsg* LnPacket) { if( LnPacket ) { //LocoNet.processSwitchSensorMessage(LnPacket); unsigned char opcode = (int)LnPacket->sz.command; if (opcode == OPC_GPON) { Serial.println("Power ON"); digitalWrite(PowerOnLEDPort, 1); digitalWrite(PowerOffLEDPort, 0); digitalWrite(EStopLEDPort, 0); } else if (opcode == OPC_GPOFF) { Serial.println("Power OFF"); digitalWrite(PowerOnLEDPort, 0); digitalWrite(PowerOffLEDPort, 1); } else if (opcode == OPC_IDLE) { digitalWrite(EStopLEDPort, 1); Serial.println("EStop!"); } else if (opcode == OPC_SL_RD_DATA) { if (ClearIt) { int slot = LnPacket->sd.slot; int stat = LnPacket->sd.stat; Serial.print("Clear Slot:"); Serial.print(slot); Serial.print(":"); Serial.println(stat); if (stat != 0) { sendOPC_LOCO_SPD(slot, 0); // speed 0 sendOPC_LOCO_DIRF(slot, 0); // F0-4 off, Fwd sendOPC_LOCO_SND(slot, 0); // F5-8 off // Don't need to turn off F9 and above because they should go away when track power is turned off... sendOPC_SLOT_STAT1(slot, 0); } } } else { // ignore the message... } } } void loop() { // Check for any received LocoNet packets while (lnMsg *LnPacket = LocoNet.receive() ) { processIncomingLoconetCommand( LnPacket ); } // Debounce logic: // ...Check for any buttons pushed, delay, read again... GPonButton1 = digitalRead(PowerOnPort); GPoffButton1 = digitalRead(PowerOffPort); EStopButton1 = digitalRead(EStopPort); ClearButton1 = digitalRead(SlotClearPort); delay(5); GPonButton2 = digitalRead(PowerOnPort); GPoffButton2 = digitalRead(PowerOffPort); EStopButton2 = digitalRead(EStopPort); ClearButton2 = digitalRead(SlotClearPort); // ...identical readings mean we have a good result if (GPonButton1 == GPonButton2) { GPonButton = GPonButton1 ? 0 : 1; } if (GPoffButton1 == GPoffButton2) { GPoffButton = GPoffButton1 ? 0 : 1; } if (EStopButton1 == EStopButton2) { EStopButton = EStopButton1 ? 0 : 1; } if (ClearButton1 == ClearButton2) { ClearButton = ClearButton1 ? 0 : 1; } if (lastGPon == -1) { // need to initialize things the first time thru to ensure buttons don't all fire... lastGPon = GPonButton; lastGPoff = GPoffButton; lastEStop = EStopButton; lastClear = ClearButton; } else { // See if anything has changed since last time thru... if (GPonButton != lastGPon) { // GP_ON lastGPon = GPonButton; if (GPonButton) { sendOPC_GP(1); } ClearIt = 0; } if (GPoffButton != lastGPoff) { // GP_OFF lastGPoff = GPoffButton; if (GPoffButton) { sendOPC_GP(0); } ClearIt = 0; } if (EStopButton != lastEStop) { // E_STOP lastEStop = EStopButton; if (EStopButton) { sendOPC_IDLE(); } ClearIt = 0; } if (ClearButton != lastClear) { // Clear all Slots lastClear = ClearButton; if (ClearButton) { ClearIt = 1; // query all the slots, let the handler clear things for (int slot = 0; slot < 120; slot++) { sendOPC_RQ_SL_DATA(slot); } ClearIt = 0; } } } }
33.356275
120
0.585387
2ec3da251734c869e4c96c2160193149d6e285aa
2,343
ino
Arduino
duoduo_steering_sr518d/duoduo_steering_sr518d.ino
tianb03/RabbitArduino
19cfbc71f7e17e216e624a493268498c86078585
[ "MIT" ]
3
2017-07-24T03:25:30.000Z
2019-08-15T17:27:03.000Z
duoduo_steering_sr518d/duoduo_steering_sr518d.ino
tianb03/RabbitArduino
19cfbc71f7e17e216e624a493268498c86078585
[ "MIT" ]
null
null
null
duoduo_steering_sr518d/duoduo_steering_sr518d.ino
tianb03/RabbitArduino
19cfbc71f7e17e216e624a493268498c86078585
[ "MIT" ]
1
2019-08-15T17:27:04.000Z
2019-08-15T17:27:04.000Z
#include <ros.h> #include <dependant_api/robotcmd_motor.h> #include <dependant_api/arduino_motor.h> #include "SpringRC.h" ros::NodeHandle nh; dependant_api::arduino_motor motor_feedback; ros::Publisher feedback("/arduino/motor", &motor_feedback); int vertical = 150; int horizontal = 90; long int pos_vertical = 150; long int pos_horizontal = 90; void servoCallback(const dependant_api::robotcmd_motor& cloud_terrace) { motor_feedback.id = cloud_terrace.id; vertical = cloud_terrace.ver_angle; horizontal = cloud_terrace.hor_angle; if (vertical >= 130) vertical = 130; vertical = 180 - vertical; horizontal = 180 - horizontal; } ros::Subscriber<dependant_api::robotcmd_motor> servo("/robotcmd/motor", servoCallback); void setup() { nh.initNode(); nh.subscribe(servo); nh.advertise(feedback); SR518.begin(57000, 2, 3); //配置串口速率为1mbps,设数字引脚2,3为收发和使能端口,2,3电平始终相等 //设置柔性边界和斜率 SR518.setCompliance(0, 1, 1, 8, 8); SR518.setCompliance(1, 1, 1, 8, 8); //设置运动范围 SR518.setLimit(0, translateAnalog(-15), translateAnalog(195)); //一级保险 SR518.setLimit(1, translateAnalog(50), translateAnalog(180)); } void loop() { nh.spinOnce(); if (horizontal >= 195) //二级保险 horizontal = 195; if (horizontal <= -15) horizontal = -15; if (vertical >= 170) vertical = 170; if (vertical <= 50) vertical = 50; SR518.moveSpeed(0, translateAnalog(horizontal), 300); SR518.moveSpeed(1, translateAnalog(vertical), 300); Serial.print(translateAnalog(horizontal)); Serial.print(","); Serial.print(translateAnalog(vertical)); Serial.print("; "); pos_horizontal = translateAngle(SR518.readPosition(0)); pos_vertical = translateAngle(SR518.readPosition(1)); Serial.print(pos_horizontal); Serial.print(","); Serial.println(pos_vertical); if (horizontal + 2 >= pos_horizontal && horizontal - 2 <= pos_horizontal) motor_feedback.ret_hor = 0; else motor_feedback.ret_hor = 1; if (vertical + 10 >= pos_vertical && vertical - 2 <= pos_vertical) //此处的数字10不通用 motor_feedback.ret_ver = 0; else motor_feedback.ret_ver = 1; feedback.publish(&motor_feedback); } long int translateAnalog(long int angle) //将舵机的控制范围由0~300度换算成-60~240度 { return (angle + 60) * 1023 / 300; } long int translateAngle(long int analog) //将舵机反馈值转为角度 { return analog * 300 / 1023 - 60; }
25.467391
87
0.706359
a9f2185ab76fd218c161caaa0ac30c8843add4cf
2,318
ino
Arduino
src/paceclock.ino
xcijimv/arduino-paceclock
40aaef4ae81aa06bae71f62e4214ba990a3f2a65
[ "MIT" ]
null
null
null
src/paceclock.ino
xcijimv/arduino-paceclock
40aaef4ae81aa06bae71f62e4214ba990a3f2a65
[ "MIT" ]
null
null
null
src/paceclock.ino
xcijimv/arduino-paceclock
40aaef4ae81aa06bae71f62e4214ba990a3f2a65
[ "MIT" ]
null
null
null
/*! * arduino-paceclock */ /** * ATmega pins. */ int latchPin = 8; int clockPin = 12; int dataPin = 11; /** * Digits of the paceclock. * * 00:00 */ int m1 = 0; int m2 = 0; int s1 = 0; int s2 = 0; /** * Number of seconds to count down, must be <= 9. */ int countDownFrom = 9; /** * On/off state of shift register registers (segments) for all digits in a * common-anode LED array. * * 0 * 5 1 * 6 * 4 2 * 3 */ int digits[11] = { 0b00000011, // 0 0b10011111, // 1 0b00100101, // 2 0b00001101, // 3 0b10011001, // 4 0b01001001, // 5 0b01000001, // 6 0b00011111, // 7 0b00000001, // 8 0b00001001, // 9 0b11111111, // blank }; /** * Arduino setup function that is run once, at power-on. The clock is cleared, * displays 88:88 to show that all segments work, is cleared again, then counts * down to 00:00. * * @api public */ void setup() { pinMode(latchPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(dataPin, OUTPUT); // show that all segments work display(8, 8, 8, 8); delay(1000); // clear the clock display(10, 10, 10, 10); delay(1000); // count down to 00:00 for (int i = countDownFrom; i >= 0; i--) { display(0, 0, 0, i); delay(1000); } } /** * Arduino loop function that is run over and over. This function counts from * 00:00 to 59:59 (then back to 00:00) and displays the digits. * * @api public */ void loop() { // count from 00:00 to 59:59 if (s2 == 9) { if (s1 == 5) { if (m2 == 9) { if (m1 == 5) { m1 = 0; } else { m1 += 1; } m2 = 0; } else { m2 += 1; } s1 = 0; } else { s1 += 1; } s2 = 0; } else { s2 += 1; } // display the digits display(m1, m2, s1, s2); delay(1000); } /** * Display the digits by changing the states of the shift register registers * (for the segments). * * @api public */ void display(int minute1, int minute2, int second1, int second2) { digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, LSBFIRST, digits[minute1]); shiftOut(dataPin, clockPin, LSBFIRST, digits[minute2]); shiftOut(dataPin, clockPin, LSBFIRST, digits[second1]); shiftOut(dataPin, clockPin, LSBFIRST, digits[second2]); digitalWrite(latchPin, HIGH); }
16.097222
79
0.572908
e079eb4521b49bb0b0c6f7e47db4634b1d3ca80a
494
ino
Arduino
sketch_sep10a.ino
rahitnath/light-intensity-and-angle-detection
f6d9ef23c5b8c28551e27bb446979c2f9d09af24
[ "Apache-2.0" ]
null
null
null
sketch_sep10a.ino
rahitnath/light-intensity-and-angle-detection
f6d9ef23c5b8c28551e27bb446979c2f9d09af24
[ "Apache-2.0" ]
null
null
null
sketch_sep10a.ino
rahitnath/light-intensity-and-angle-detection
f6d9ef23c5b8c28551e27bb446979c2f9d09af24
[ "Apache-2.0" ]
null
null
null
#include <SoftwareSerial.h> SoftwareSerial MyBlue(0, 1); // RX | TX #define LDRpin A0 // pin where we connected the LDR and the resistor int LDRValue = 0; // result of reading the analog pin void setup() { Serial.begin(38400); // sets serial port for communication } void loop() { LDRValue = analogRead(LDRpin); // read the value from the LDR Serial.println(LDRValue); // print the value to the serial port delay(100); // wait a little }
30.875
71
0.6417
7b033eb25e2a34155449bb947a678558e75a860d
163
ino
Arduino
linde_test/Speed/Speed.ino
Technariumas/smalsiukas
57e988ad460125b91edbf1e5edec164f901eb28c
[ "Apache-2.0" ]
null
null
null
linde_test/Speed/Speed.ino
Technariumas/smalsiukas
57e988ad460125b91edbf1e5edec164f901eb28c
[ "Apache-2.0" ]
null
null
null
linde_test/Speed/Speed.ino
Technariumas/smalsiukas
57e988ad460125b91edbf1e5edec164f901eb28c
[ "Apache-2.0" ]
null
null
null
#include "Speed.h" void setup() { // put your setup code here, to run once: Speed speed; } void loop() { // put your main code here, to run repeatedly: }
11.642857
48
0.631902
af039fa692b609ecd6235b10708bf1a1453ed076
1,855
ino
Arduino
module_IoT/sub_client_module/example code/sketch_nov27a/sketch_nov27a.ino
ngthuc/TSV2017-12
0dac9292d7c889772b500098b7694abdf81851db
[ "MIT" ]
null
null
null
module_IoT/sub_client_module/example code/sketch_nov27a/sketch_nov27a.ino
ngthuc/TSV2017-12
0dac9292d7c889772b500098b7694abdf81851db
[ "MIT" ]
null
null
null
module_IoT/sub_client_module/example code/sketch_nov27a/sketch_nov27a.ino
ngthuc/TSV2017-12
0dac9292d7c889772b500098b7694abdf81851db
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> #include <ESP8266HTTPClient.h> #include <LiquidCrystal.h> //Khởi tạo với các chân LiquidCrystal lcd(D5, D0, D4, D3, D2, D1); const char* ssid = "68C/10a"; const char* password = "Khuvuc6@2017"; int count; void setup() { pinMode(A0, INPUT); //Thông báo đây là LCD 1602 lcd.begin(16, 2); Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi.."); printLCD("Connecting..", 0, 0); } Serial.println("Connected to the WiFi network"); printLCD("Connected", 0, 0); count = 0; } void loop() { while (Serial.available()) { String id = Serial.readStringUntil(':'); Serial.print(id+":"); id = Serial.readStringUntil(';'); Serial.println(id); Serial.println("Send data."); sendData(id); Serial.println("Send done."); } } boolean sendData(String ID) { if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status HTTPClient http; http.begin("http://192.168.1.7:80/post.php?ID=1&key=1"); //Specify the URL and certificate int httpCode = http.GET(); //Make the request if (httpCode > 0) { //Check for the returning code Serial.print(count + " - "); count++; String payload = http.getString(); // Serial.println(httpCode); Serial.println(payload); printLCD(payload, 0, 1); } else { Serial.println("Error on HTTP request"); } http.end(); //Free the resources } } void printLCD(String str, int x, int line) { clearLCD(line); lcd.setCursor(x, line); // In ra dong chu lcd.print(str); } void clearLCD(int line) { lcd.setCursor(0, line); lcd.print(" "); }
21.823529
98
0.602156
1f8a098a62d2e9ae84fc8554b8ad6474a10e9901
1,275
ino
Arduino
portenta-breakout-board/pwm-pin-test.ino
hpssjellis/my-examples-for-the-arduino-portentaH7
3748fe1f843adeb2b5f0677cf47d46038208ef03
[ "MIT" ]
48
2020-08-09T01:55:15.000Z
2022-03-26T20:13:01.000Z
portenta-breakout-board/pwm-pin-test.ino
khoih-prog/my-examples-for-the-arduino-portentaH7
e8f673b1fe55de09c3b69d936a4be70c658026b6
[ "MIT" ]
3
2021-02-15T12:45:34.000Z
2022-03-29T21:52:24.000Z
portenta-breakout-board/pwm-pin-test.ino
khoih-prog/my-examples-for-the-arduino-portentaH7
e8f673b1fe55de09c3b69d936a4be70c658026b6
[ "MIT" ]
9
2020-08-30T00:41:51.000Z
2022-01-28T10:02:50.000Z
// Testing the PWM pins void myPwm(int myGPIO, int myDelay){ //pinMode(myGPIO, OUTPUT); for (int x=0; x<=255; x++){ analogWrite(myGPIO, x); delay(myDelay); } delay(myDelay); for (int x=255; x>=0; x--){ analogWrite(myGPIO, x); delay(myDelay); } delay(myDelay); //pinMode(myGPIO, INPUT); } void setup() { pinMode(0, OUTPUT); //PWM6 pinMode(PWM_2, OUTPUT); //PWM5 pinMode(2, OUTPUT); //PWM4 //pinMode(3, OUTPUT); //Broken pinMode(4, OUTPUT); //PWM2 pinMode(5, OUTPUT); //PWM1 pinMode(6, OUTPUT); //PWM0 //pinMode(7, OUTPUT); //Broken //pinMode(PWM_8, OUTPUT); //PWM6 //pinMode(PWM_3, OUTPUT); //PWM6 //pinMode(PH_15, OUTPUT); //Broken pinMode(LEDB, OUTPUT); digitalWrite(LEDB, LOW); //Portenta LED on delay(2000); digitalWrite(LEDB, HIGH); delay(2000); } void loop() { myPwm(0, 1); myPwm(1, 1); myPwm(2, 1); // myPwm(3, 1); // broken myPwm(4, 1); myPwm(5, 1); myPwm(6, 1); // myPwm(7, 1); //Broken // myPwm(PWM_3, 1); //nope // myPwm(PH_15, 1); //nope digitalWrite(LEDB, LOW); //Portenta LED on delay(1000); digitalWrite(LEDB, HIGH); delay(1000); }
20.238095
45
0.536471