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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
973d4b225e7892831ff2a7679c0e902243d0eefd
| 3,017
|
ino
|
Arduino
|
Arduino Stuff/RFID RC522/RC522 Test 2/Test.ino
|
Karna-A/Sys-Engineering
|
90cef9f6f6d50ac63a6c6cb716973bfff0209bbc
|
[
"MIT"
] | 1
|
2020-11-10T02:45:57.000Z
|
2020-11-10T02:45:57.000Z
|
Arduino Stuff/RFID RC522/RC522 Test 2/Test.ino
|
Karna-A/Sys-Engineering
|
90cef9f6f6d50ac63a6c6cb716973bfff0209bbc
|
[
"MIT"
] | null | null | null |
Arduino Stuff/RFID RC522/RC522 Test 2/Test.ino
|
Karna-A/Sys-Engineering
|
90cef9f6f6d50ac63a6c6cb716973bfff0209bbc
|
[
"MIT"
] | null | null | null |
#include <MFRC522.h> //library responsible for communicating with the module RFID-RC522
#include <SPI.h> //library responsible for communicating of SPI bus
#define SS_PIN 21
#define RST_PIN 22
#define SIZE_BUFFER 18
#define MAX_SIZE_BLOCK 16
#define greenPin 12
#define redPin 32
//used in authentication
MFRC522::MIFARE_Key key;
//authentication return status code
MFRC522::StatusCode status;
// Defined pins to module RC522
MFRC522 mfrc522(SS_PIN, RST_PIN);
void setup()
{
Serial.begin(9600);
SPI.begin(); // Init SPI bus
pinMode(greenPin, OUTPUT);
pinMode(redPin, OUTPUT);
// Init MFRC522
mfrc522.PCD_Init();
Serial.println("Approach your reader card...");
Serial.println();
}
void loop()
{
// Aguarda a aproximacao do cartao
//waiting the card approach
if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
// Select a card
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
// Dump debug info about the card; PICC_HaltA() is automatically called
// mfrc522.PICC_DumpToSerial(&(mfrc522.uid));</p><p> //call menu function and retrieve the desired option
int op = menu();
if(op == 0)
readingData();
else if(op == 1)
writingData();
else {
Serial.println(F("Incorrect Option!"));
return;
}
//instructs the PICC when in the ACTIVE state to go to a "STOP" state
mfrc522.PICC_HaltA();
// "stop" the encryption of the PCD, it must be called after communication with authentication, otherwise new communications can not be initiated
mfrc522.PCD_StopCrypto1();
}
//reads data from card/tag
void readingData()
{
//prints the technical details of the card/tag
mfrc522.PICC_DumpDetailsToSerial(&(mfrc522.uid));
//prepare the key - all keys are set to FFFFFFFFFFFFh
for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;
//buffer for read data
byte buffer[SIZE_BUFFER] = {0};
//the block to operate
byte block = 1;
byte size = SIZE_BUFFER;</p><p> //authenticates the block to operate
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
if (status != MFRC522::STATUS_OK) {
Serial.print(F("Authentication failed: "));
Serial.println(mfrc522.GetStatusCodeName(status));
digitalWrite(redPin, HIGH);
delay(1000);
digitalWrite(redPin, LOW);
return;
}
//read data from block
status = mfrc522.MIFARE_Read(block, buffer, &size);
if (status != MFRC522::STATUS_OK) {
Serial.print(F("Reading failed: "));
Serial.println(mfrc522.GetStatusCodeName(status));
digitalWrite(redPin, HIGH);
delay(1000);
digitalWrite(redPin, LOW);
return;
}
else{
digitalWrite(greenPin, HIGH);
delay(1000);
digitalWrite(greenPin, LOW);
}
Serial.print(F("\nData from block ["));
Serial.print(block);Serial.print(F("]: "));
//prints read data
for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
{
Serial.write(buffer[i]);
}
Serial.println(" ");
}
| 27.427273
| 147
| 0.675174
|
e269074260ad16fdbe0fd512935d0f80197900d3
| 9,701
|
ino
|
Arduino
|
SplHAsh/SplHAsh.ino
|
cplagz/SplHAsh
|
d9fd564ca5317584a78ed54e92aebd253ec22c91
|
[
"MIT"
] | 12
|
2019-09-15T21:21:20.000Z
|
2021-09-04T19:41:24.000Z
|
SplHAsh/SplHAsh.ino
|
cplagz/SplHAsh
|
d9fd564ca5317584a78ed54e92aebd253ec22c91
|
[
"MIT"
] | 3
|
2019-09-05T04:28:18.000Z
|
2021-04-13T12:37:26.000Z
|
SplHAsh/SplHAsh.ino
|
cplagz/SplHAsh
|
d9fd564ca5317584a78ed54e92aebd253ec22c91
|
[
"MIT"
] | 8
|
2020-04-17T06:27:11.000Z
|
2021-06-18T11:04:45.000Z
|
/*
* SplHAsh
* An MQTT based sprinkler controller running on ESP3266
* Licensed under the MIT License, Copyright (c) 2019 TJPoorman
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "config.h"
// Mapping NodeMCU Ports to Arduino GPIO Pins
// Allows use of NodeMCU Port nomenclature in config.h
#define D0 16
#define D1 5
#define D2 4
#define D3 0
#define D4 2
#define D5 14
#define D6 12
#define D7 13
#define D8 15
const char* ssid = WIFI_SSID;
const char* password = WIFI_PASSWORD;
const boolean static_ip = STATIC_IP;
IPAddress ip(IP);
IPAddress gateway(GATEWAY);
IPAddress subnet(SUBNET);
const char* mqtt_broker = MQTT_BROKER;
const char* mqtt_clientId = MQTT_CLIENTID;
const char* mqtt_username = MQTT_USERNAME;
const char* mqtt_password = MQTT_PASSWORD;
const char* mqtt_topic_base = MQTT_TOPIC_BASE;
String clientBase = MQTT_CLIENTID;
String availabilitySuffix = "/availability";
String availabilityTopicStr = clientBase + availabilitySuffix;
const char* availabilityTopic = availabilityTopicStr.c_str();
const char* birthMessage = "online";
const char* lwtMessage = "offline";
const int relayActive = RELAY_ACTIVE;
const int dataPin = SR_DATA_PIN; //Outputs the byte to transfer
const int loadPin = SR_LATCH_PIN; //Controls the internal transference of data in SN74HC595 internal registers
const int clockPin = SR_CLOCK_PIN; //Generates the clock signal to control the transference of data
const int maxZone = MAX_ZONE;
const int pumpZone = PUMP_ZONE;
const int shiftRegisterCount = floor(maxZone / 8.0001) + 1;
int pumpSR = 0;
int pumpSRPin = 0;
WiFiClient espClient;
PubSubClient client(espClient);
/***************************************************
* Setup/Loop Functions
****************************************************/
void setup() {
pinMode(dataPin, OUTPUT);
pinMode(loadPin, OUTPUT);
pinMode(clockPin, OUTPUT);
// Set the Shift Register for pump if defined
if (pumpZone != -1) {
pumpSR = floor(pumpZone / 8.0001) + 1;
pumpSRPin = (pumpZone % 8 == 0) ? 8 : pumpZone % 8;
}
// Setup serial output, connect to wifi, connect to MQTT broker, set MQTT message callback
Serial.begin(115200);
Serial.println("Starting SplHAsh...");
if (relayActive == HIGH) {
Serial.println("Relay mode: Active-High");
}
else {
Serial.println("Relay mode: Active-Low");
}
// Set all zones off to start
ActivateZone(0);
setup_wifi();
client.setServer(mqtt_broker, 1883);
client.setCallback(callback);
}
void loop() {
// Connect/reconnect to the MQTT broker and listen for messages
if (!client.connected()) {
reconnect();
}
client.loop();
}
// Wifi setup function
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.print(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
if (static_ip) {
WiFi.config(ip, gateway, subnet);
}
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print(" WiFi connected - IP address: ");
Serial.println(WiFi.localIP());
}
/***************************************************
* MQTT Functions
****************************************************/
// Callback when MQTT message is received; calls triggerZoneAction(), passing topic and payload as parameters
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
String topicToProcess = topic;
payload[length] = '\0';
String payloadToProcess = (char*)payload;
triggerZoneAction(topicToProcess, payloadToProcess);
}
// Function that publishes birthMessage
void publish_birth_message() {
Serial.print("Publishing birth message \"");
Serial.print(birthMessage);
Serial.print("\" to ");
Serial.print(availabilityTopic);
Serial.println("...");
client.publish(availabilityTopic, birthMessage, true);
}
// Function that runs in loop() to connect/reconnect to the MQTT broker, and publish the current zone statuses on connect
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(mqtt_clientId, mqtt_username, mqtt_password, availabilityTopic, 0, true, lwtMessage)) {
Serial.println("Connected!");
// Publish the birth message on connect/reconnect
publish_birth_message();
for (int j = 0; j <= maxZone; j++) {
// Subscribe to the action topics to listen for action messages
String topic = mqtt_topic_base + String(j) + "/action";
Serial.print("Subscribing to ");
Serial.print(topic);
Serial.println("...");
client.subscribe(topic.c_str());
}
// Publish the current zone status(s) on connect/reconnect to ensure status is synced with whatever happened while disconnected
for (int j = 0; j <= maxZone; j++) {
publish_zone_status(j, "OFF");
}
}
else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
/***************************************************
* Zone Functions
****************************************************/
// Function called by callback() when a message is received
// Passes the message topic as the "topic" parameter and the message payload as the "requestedAction" parameter
void triggerZoneAction(String topic, String requestedAction) {
bool zoneFound = false;
int zoneActivated;
// Loop through all zones until the called topic matches the zones
for (int i = 0; i <= maxZone; i++) {
if (topic == mqtt_topic_base + String(i) + "/action") {
zoneFound = true;
zoneActivated = i;
break;
}
}
if (zoneFound) {
if (zoneActivated == 0) { // If zone0 is called turn all zones off
ActivateZone(0);
for (int i = 0; i <= maxZone; i++) {
publish_zone_status(i, "OFF");
}
}
else {
if (requestedAction == "ON") {
Serial.print("Triggering ");
Serial.print(topic);
Serial.println(" ON!");
ActivateZone(zoneActivated);
for (int i = 0; i <= maxZone; i++) {
if (i == zoneActivated) {
publish_zone_status(i, "ON");
}
else { publish_zone_status(i, "OFF"); }
}
}
else if (requestedAction == "OFF") {
Serial.print("Triggering ");
Serial.print(topic);
Serial.println(" OFF!");
ActivateZone(0);
for (int i = 0; i <= maxZone; i++) {
publish_zone_status(i, "OFF");
}
}
else { Serial.println("Unrecognized action payload... taking no action!"); }
}
}
else { Serial.println("Unrecognized action topic... taking no action!"); }
}
// Function that checks zone status and publishes an update when called
void publish_zone_status(int zoneNum, String state) {
client.publish(String(mqtt_topic_base + String(zoneNum) + "/status").c_str(), state.c_str(), true);
}
// Function to activate a specific zone.
// Works by getting the byte needed for each
// shift register and shifting them out.
void ActivateZone(int zoneNum) {
byte data;
digitalWrite(loadPin, LOW);
for(int i = 1; i <= shiftRegisterCount; i++) {
if (zoneNum > 0) {
data = getByteForShiftRegister(i, (floor(zoneNum / 8.0001) + 1 == i) ? ((zoneNum % 8 == 0) ? 8 : zoneNum % 8) : 0);
}
else {
data = (relayActive == LOW) ? 255 : 0;
}
shiftOut(dataPin, clockPin, data);
}
digitalWrite(loadPin, HIGH);
}
/***************************************************
* Shift Register Functions
****************************************************/
// Function to determine they byte needed for the given shift register
byte getByteForShiftRegister(int shiftRegister, int shiftRegisterPin) {
byte result = 0;
if(shiftRegisterPin > 0 || pumpSR == shiftRegister) {
for(int i=7; i>=0; i--){
if (i + 1 == shiftRegisterPin || (shiftRegister == pumpSR && i + 1 == pumpSRPin)){
result |= relayActive << i;
}
else {
result |= !relayActive << i;
}
}
}
return result;
}
// Function to send the byte data to they shift register
void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
// This shifts 8 bits out MSB first,
//on the rising edge of the clock,
//clock idles low
//internal function setup
int i=0;
int pinState;
//clear everything out just in case to
//prepare shift register for bit shifting
digitalWrite(myDataPin, 0);
digitalWrite(myClockPin, 0);
//for each bit in the byte myDataOut�
//NOTICE THAT WE ARE COUNTING DOWN in our for loop
//This means that %00000001 or "1" will go through such
//that it will be pin Q0 that lights.
for (i=7; i>=0; i--) {
digitalWrite(myClockPin, 0);
//if the value passed to myDataOut and a bitmask result
// true then... so if we are at i=6 and our value is
// %11010100 it would the code compares it to %01000000
// and proceeds to set pinState to 1.
if ( myDataOut & (1<<i) ) {
pinState= 1;
}
else {
pinState= 0;
}
//Sets the pin to HIGH or LOW depending on pinState
digitalWrite(myDataPin, pinState);
//register shifts bits on upstroke of clock pin
digitalWrite(myClockPin, 1);
//zero the data pin after shift to prevent bleed through
digitalWrite(myDataPin, 0);
}
//stop shifting
digitalWrite(myClockPin, 0);
}
| 28.78635
| 133
| 0.630657
|
414631e2be3414dc312c2703bdf153090e36bbf6
| 778
|
ino
|
Arduino
|
espaudio/sn3218_leds.ino
|
hmax42/home-automation-arduino
|
9dc4956f3a911fd9e604b6a16e9942bec46a4c8b
|
[
"MIT"
] | null | null | null |
espaudio/sn3218_leds.ino
|
hmax42/home-automation-arduino
|
9dc4956f3a911fd9e604b6a16e9942bec46a4c8b
|
[
"MIT"
] | null | null | null |
espaudio/sn3218_leds.ino
|
hmax42/home-automation-arduino
|
9dc4956f3a911fd9e604b6a16e9942bec46a4c8b
|
[
"MIT"
] | null | null | null |
#define WI2C 0x54
void wireWrite(uint8_t reg, uint8_t val) {
Wire.write((uint8_t)reg);
Wire.write((uint8_t)val);
}
void beginI2c() {
Wire.beginTransmission((uint8_t)WI2C);
}
void endI2c() {
Wire.endTransmission();
}
void initI2c() {
beginI2c();
uint8_t d[] = {0x01};
Wire.write(0x00);
Wire.write(d, 1);
endI2c();
beginI2c();
wireWrite(0x13, 0xFF);
endI2c();
beginI2c();
wireWrite(0x14, 0xFF);
endI2c();
beginI2c();
wireWrite(0x15, 0xFF);
endI2c();
}
void updateI2c() {
beginI2c();
wireWrite(0x16, 0xFF);
endI2c();
}
void cleanupI2c() {
beginI2c();
uint8_t d[] = {0x00};
Wire.write(0x00);
Wire.write(d, 1);
endI2c();
}
void ledI2c(uint8_t addr, uint8_t i) {
beginI2c();
wireWrite(addr, (byte) i);
endI2c();
}
| 13.649123
| 42
| 0.618252
|
c5d9bbbe91c3f0f23d88ffa19bd97f1458d93607
| 8,591
|
ino
|
Arduino
|
meteo-station/microcontroller/arduinoyun_ema_v2.ino
|
jordidh/environmental-data-collector-system
|
3d7283ae8691c5260d3c4afb8b67cad9dc673e99
|
[
"MIT"
] | null | null | null |
meteo-station/microcontroller/arduinoyun_ema_v2.ino
|
jordidh/environmental-data-collector-system
|
3d7283ae8691c5260d3c4afb8b67cad9dc673e99
|
[
"MIT"
] | null | null | null |
meteo-station/microcontroller/arduinoyun_ema_v2.ino
|
jordidh/environmental-data-collector-system
|
3d7283ae8691c5260d3c4afb8b67cad9dc673e99
|
[
"MIT"
] | null | null | null |
/*
Running shell commands using Process class.
This sketch demonstrate how to run linux shell commands
using a YunShield/Yún. It runs the wifiCheck script on the Linux side
of the Yún, then uses grep to get just the signal strength line.
Then it uses parseInt() to read the wifi signal strength as an integer,
and finally uses that number to fade an LED using analogWrite().
The circuit:
* YunShield/Yún with LED connected to pin 9
created 12 Jun 2013
by Cristian Maglie
modified 25 June 2013
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/ShellCommands
*/
/**
* To see the Console, select your Yún's name and IP address in the Port menu.
* The Yún will only show up in the Ports menu if your computer is on the same LAN as the Yún.
* If your board is on a different network, you won't see it in the Ports menu. Open the Port Monitor.
* You'll be prompted for the Yún's password.
* You can also see the Console by opening a terminal window and typing ssh root@yourYunsName.local (root@seeed.local,
* password seeeduino) 'telnet localhost 6571' then pressing enter.
* Type H or L to turn on or off the LED
*/
/*
* ArduinoYun EMA (Eastació Monitorització Aire)
*
* Solució basada en un Arduino Yun
* Funcionament:
* 1 - L'arduino monitoritza els sensors
* 2 - L'arduino envia els valors al Linux mitjançant el mailBox
* 3 - El Mailbox envia les lectures a un servidor web
*
*
#Mailbox.py
import socket
import json
def sendMailbox(msg):
m = {'command':'raw'}
m['data'] = str(msg)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 5700))
s.sendall(json.dumps(m))
s.close()
def recvMailbox():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 5700))
result = json.loads(s.recv(1024))
s.close()
return result
*
*
*
*/
#include <Process.h>
#include <Bridge.h>
#include <Mailbox.h>
//#include <Console.h>
#include <Barometer.h>
const int LED_PIN = 13; // the pin that the LED is attached to
const int DUST_PIN = 8; // the dust sensor used pin
//***** Grove - Barometer BMP180 *************************
float temperature = 0;
float pressurePa = 0;
float pressureHPa = 0; //100Pa = 1HPa = 1mbar
float atm;
float altitude;
Barometer myBarometer;
//********************************************************
//***** Grove - Gas Sensor MQ9 ***************************
int mq9_pin = A1;
float mq9_sensor_volt;
float mq9_RS_air; // Get the value of RS via in a clear air
float mq9_R0; // Get the value of R0 via in LPG
float mq9_sensorValue;
float mq9_RS_gas; // Get value of RS in a GAS
float mq9_ratio; // Get ratio RS_GAS/RS_air
//********************************************************
//***** Grove - Dust Sensor ******************************
int dust_pin = 8;
unsigned long dust_duration;
unsigned long dust_starttime;
unsigned long dust_sampletime_ms = 30000;//sampe 30s ;
unsigned long dust_lowpulseoccupancy = 0;
float dust_ratio;
float dust_concentration = 0;
//********************************************************
void setup() {
// initialize the LED pin as an output:
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
Bridge.begin(); // Initialize the Bridge
Mailbox.begin(); // Initialize the Mailbox
/*
Console.begin(); // Initialize the Console
while (!Console){
; // wait for Console port to connect.
}
Console.println("You're connected to the Console!!!!");
*/
// Grove - Barometer Sensor Initialization -------------
//Console.print("Initializating barometer");
myBarometer.init();
//Console.println("...OK");
// -----------------------------------------------------
// Grove - Gas Sensor MQ9 ------------------------------
//Console.print("Initializating Gas Sensor");
//Console.println("...OK");
// -----------------------------------------------------
// Grove - Gas Sensor MQ9 Calibration (Read R0 when stable) -------
mq9_sensorValue = 0;
/*--- Get a average data by testing 100 times ---*/
for(int x = 0 ; x < 100 ; x++)
{
mq9_sensorValue = mq9_sensorValue + analogRead(mq9_pin);
}
mq9_sensorValue = mq9_sensorValue/100.0;
/*-----------------------------------------------*/
mq9_sensor_volt = mq9_sensorValue/1024*5.0;
mq9_RS_air = (5.0-mq9_sensor_volt)/mq9_sensor_volt; // omit *RL
mq9_R0 = mq9_RS_air/9.9; // The ratio of RS/R0 is 9.9 in LPG gas from Graph (Found using WebPlotDigitizer)
//Please node down the mq9_R0 after the reading stabilizes
//Console.print("GAS SENSOR Calibration: sensor_volt = ");
//Console.print(mq9_sensor_volt);
//Console.print("V ");
//Console.print("R0 = ");
//Console.println(mq9_R0);
//***************************************************************************
//Start PYTHON script
//Run a process asynchronously
//Please note that since Process.begin(). calls close the running process is terminated. This is the reason why you can not run 2 processes the same time with the same Process instance.
//p.runShellCommandAsynchronously("cmd")
// Grove - Dust Sensor Initialization -------------
//Console.print("Initializating dust sensor");
pinMode(dust_pin,INPUT);
dust_starttime = millis();//get the current time;
//Console.println("...OK");
// -----------------------------------------------------
digitalWrite(LED_PIN, LOW);
}
void loop() {
//***** Grove - Dust Sensor Measurement *************************************
dust_duration = pulseIn(dust_pin, LOW);
dust_lowpulseoccupancy = dust_lowpulseoccupancy + dust_duration;
//***************************************************************************
if ((millis()-dust_starttime) >= dust_sampletime_ms)//if the sampel time = = 30s
{
//Switch on led => Communicating
digitalWrite(LED_PIN, HIGH);
//***** Grove - Barometer BMP180 Sensor Measurement *************************
temperature = myBarometer.bmp085GetTemperature(myBarometer.bmp085ReadUT()); //Get the temperature, bmp085ReadUT MUST be called first
pressurePa = myBarometer.bmp085GetPressure(myBarometer.bmp085ReadUP());//Get the temperature
pressureHPa = pressurePa / 100;
altitude = myBarometer.calcAltitude(pressurePa); //Uncompensated calculation - in Meters
atm = pressurePa / 101325;
// -----------------------------------------------------
//***** Grove - Gas Sensor MQ9 Measurement **********************************
mq9_sensorValue = analogRead(mq9_pin);
mq9_sensor_volt=(float)mq9_sensorValue/1024*5.0;
mq9_RS_gas = (5.0-mq9_sensor_volt)/mq9_sensor_volt; // omit *RL
/*-Replace the name "R0" with the value of R0 in the demo of First Test -*/
mq9_ratio = mq9_RS_gas/mq9_R0; // ratio = RS/R0
/*-----------------------------------------------------------------------*/
//Console.print("GAS SENSOR Measurement: sensor_volt = ");
//Console.print(mq9_sensor_volt);
//Console.print(" RS_ratio = ");
//Console.print(mq9_RS_gas);
//Console.print(" Rs/R0 = ");
//Console.println(mq9_ratio);
//***************************************************************************
//***** Grove - Dust Sensor Measurement *************************************
//Detecta partícules mes grans de 1micrometre
dust_ratio = dust_lowpulseoccupancy/(dust_sampletime_ms*10.0); // Integer percentage 0=>100
dust_concentration = 1.1*pow(dust_ratio,3)-3.8*pow(dust_ratio,2)+520*dust_ratio+0.62; // using spec sheet curve
//Serial.print("concentration = ");
//Serial.print(dust_concentration);
//Serial.println(" pcs/0.01cf"); //concentració de partícules mes grans d'1 micrometre per peu cúbic.
//cf = cubic foot, 1 cf = 283 ml
//1 metre cúbic = 1000 litres
//Serial.println("\n");
//TODO: passar-ho a ug/m3 (micrograms per metre cúbic)
dust_lowpulseoccupancy = 0;
dust_starttime = millis();
//***************************************************************************
//Send values to linino with Mailbox
Mailbox.writeJSON("[ {\"key\": \"temperature\", \"value\": \"" + String(temperature, 2) + "\"} , {\"key\": \"pressure\", \"value\": \"" + String(pressureHPa, 2) + "\"} , {\"key\": \"dust\", \"value\": \"" + String(dust_concentration, 2) + "\"} ]");
//Switch off led
digitalWrite(LED_PIN, LOW);
}
//delay(10000); // wait 10 seconds before you do it again
//delay(30000); // wait 30 seconds before you do it again
}
| 37.515284
| 253
| 0.591549
|
acd25e08f7973784fd9c7c7de70474b3e6aaae0f
| 2,704
|
ino
|
Arduino
|
Arduino/Arduino.ino
|
lxkarthi/SHARP
|
60a547966f7d6475ba44346116065f190c9abbb8
|
[
"Apache-2.0"
] | null | null | null |
Arduino/Arduino.ino
|
lxkarthi/SHARP
|
60a547966f7d6475ba44346116065f190c9abbb8
|
[
"Apache-2.0"
] | null | null | null |
Arduino/Arduino.ino
|
lxkarthi/SHARP
|
60a547966f7d6475ba44346116065f190c9abbb8
|
[
"Apache-2.0"
] | null | null | null |
const int R_pins[4] = {5, 6, 7, 8};
boolean R_value[4];
void setup() {
// initialize digital pin R_0 as an output.
Serial.begin(115200);
for(int i=0;i<4;i++) {
pinMode(R_pins[i], OUTPUT);
digitalWrite(R_pins[i],LOW);
R_value[i] = LOW;
}
Serial.println("RDY");
}
// COMMAND SHEET
// 1 byte. 4 MSB command 4 LSB pin no.
// MSB commands
// 0 -> OFF
// 1 -> ON
// 2 -> TOGGLE
// 3 -> STATUS
// extra commands
// 4 -> ALL commands
// 0x40 -> OFF ALL
// 0x41 -> ON ALL
// 0x42 -> TOGGLE ALL
// 0x43 -> STATUS ALL
// 0x81 -> PING
// 0x82 -> RESET
// Serial reponses.
// OK, ER, ####
// the loop function runs over and over again forever
void loop() {
if (Serial.available() > 0) {
String request = Serial.readStringUntil('\n');
if(request.length()!=1) {
Serial.println("ER");
}
char code = request.charAt(0);
char command = code & 0xF0;
int pin = code & 0x0F;
//PING
if (code == 0x00) {
Serial.println("OK");
}
// Wrong pin no.
else if ( (code<4) && (pin==0 || pin>4) ) {
Serial.println("ER");
}
//OFF
else if (command == 0x00) {
R_value[pin-1]=LOW;
digitalWrite(R_pins[pin-1],LOW);
Serial.println("OK");
}
//ON
else if (command == 0x10) {
R_value[pin-1]=HIGH;
digitalWrite(R_pins[pin-1],HIGH);
Serial.println("OK");
}
//TOGGLE
else if (command == 0x20) {
R_value[pin-1]=!R_value[pin-1];
digitalWrite(R_pins[pin-1],R_value[pin-1]);
Serial.println("OK");
}
//STATUS
else if (command == 0x30) {
if(R_value[pin-1]==HIGH)
Serial.println("01");
else if (R_value[pin-1]==LOW)
Serial.println("00");
else
Serial.println("UN");
Serial.println("OK");
}
// ALL commands
else if (command == 0x40) {
char sub_cmd=pin;
for(int i=0;i<4;i++) {
if(sub_cmd==0) {
R_value[i]=LOW;
digitalWrite(R_pins[i],LOW);
} else if (sub_cmd==1) {
R_value[i]=HIGH;
digitalWrite(R_pins[i],HIGH);
} else if (sub_cmd==2) {
R_value[i]=!R_value[i];
digitalWrite(R_pins[i],R_value[i]);
} else if (sub_cmd==3) {
Serial.print(String(R_value[i]));
}
}
if(sub_cmd==3)
Serial.println("");
else
Serial.println("OK");
}
//PING, RESET.
else if (command == 0x80) {
if(code==0x81)
Serial.println("OK");
else if(code==0x82) {
Serial.println("OK");
}
}
else {
Serial.print("Unknown command:");
Serial.println(request);
}
}
delay(10); // wait for a second
}
| 23.513043
| 53
| 0.52071
|
862558c37fbe92ee93d22a709a3236356fc82c55
| 3,790
|
ino
|
Arduino
|
arduino_code.ino
|
lucascassiano/lego-api-mit
|
d521020f204085a30114b14893531e61b72c559c
|
[
"CC-BY-3.0"
] | null | null | null |
arduino_code.ino
|
lucascassiano/lego-api-mit
|
d521020f204085a30114b14893531e61b72c559c
|
[
"CC-BY-3.0"
] | null | null | null |
arduino_code.ino
|
lucascassiano/lego-api-mit
|
d521020f204085a30114b14893531e61b72c559c
|
[
"CC-BY-3.0"
] | null | null | null |
//Positive Connectors
int p0 = 8;
int p1 = 9;
int p2 = 10;
int p3 = 11;
//Negative Connectors
int n0 = 5;
int n1 = 4;
int n2 = 3;
int n3 = 2;
//Input Pins
int i0 = A0;
int i1 = A1;
int i2 = A2;
int i3 = A3;
//input grid values
int inputGrid[4][4] = {
{0,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,0}
};
void setup() {
// put your setup code here, to run once:
pinMode(p0, OUTPUT);
pinMode(p1, OUTPUT);
pinMode(p2, OUTPUT);
pinMode(p3, OUTPUT);
pinMode(n0, OUTPUT);
pinMode(n1, OUTPUT);
pinMode(n2, OUTPUT);
pinMode(n3, OUTPUT);
pinMode(i3, INPUT);
pinMode(i2, INPUT);
pinMode(i1, INPUT);
pinMode(i0, INPUT);
Serial.begin(9600);
//Setting all pins
digitalWrite(n0,LOW);
digitalWrite(n1,LOW);
digitalWrite(n2,LOW);
digitalWrite(n3,LOW);
digitalWrite(p0,HIGH);
digitalWrite(p1,HIGH);
digitalWrite(p2,HIGH);
digitalWrite(p3,HIGH);
//Populating the matrix
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
inputGrid[i][j] = 0;
}
}
}
void loop() {
//Reading Each Point
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
inputGrid[i][j] = ReadPosition(i,j);
delay(10);
}
}
Serial.println("-#-"); //Represents a new reading
Serial.println(String(inputGrid[0][0])+","+String(inputGrid[1][0])+","+String(inputGrid[2][0])+","+String(inputGrid[3][0]));
Serial.println(String(inputGrid[0][1])+","+String(inputGrid[1][1])+","+String(inputGrid[2][1])+","+String(inputGrid[3][1]));
Serial.println(String(inputGrid[0][2])+","+String(inputGrid[1][2])+","+String(inputGrid[2][2])+","+String(inputGrid[3][2]));
Serial.println(String(inputGrid[0][3])+","+String(inputGrid[1][3])+","+String(inputGrid[2][3])+","+String(inputGrid[3][3]));
Serial.flush();
//delay(100);
digitalWrite(13,HIGH);
//delay(400);
//digitalWrite(13,LOW);
}
int GetResistenceFromValue(int value){
if(value>10)
{
float Vin= 5;
float Vout= 0;
float R1= 1000; //1k ohm
int R2= 0;
float buffer= 0;
buffer = value * Vin;
Vout = (buffer)/1024.0;
buffer= (Vin/Vout) -1;
R2= R1 * buffer;
if(R2>0)
return (int)R2;
else return 0;
}
else
return 0;
}
int ReadPosition(int i, int j){
if(i ==0){
pinMode(n0,OUTPUT);
digitalWrite(n0,LOW);
pinMode(n1,INPUT);//this goes to high-impedance
pinMode(n2,INPUT);
pinMode(n3,INPUT);
}
else if(i ==1){
pinMode(n0,INPUT);
pinMode(n1,OUTPUT);
digitalWrite(n1,LOW);
pinMode(n2,INPUT);
pinMode(n3,INPUT);
}
else if(i==2){
pinMode(n0,INPUT);
pinMode(n1,INPUT);
pinMode(n2,OUTPUT);
digitalWrite(n2,LOW);
pinMode(n3,INPUT);
}
else if(i==3){
pinMode(n0,INPUT);
pinMode(n1,INPUT);
pinMode(n2,INPUT);
pinMode(n3,OUTPUT);
digitalWrite(n3,LOW);
}
//Positive connectors
if(j ==0){
pinMode(p0,OUTPUT);
digitalWrite(p0,HIGH);
pinMode(p1,INPUT);
pinMode(p2,INPUT);
pinMode(p3,INPUT);
}
else if(j ==1){
pinMode(p0,INPUT);
pinMode(p1,OUTPUT);
digitalWrite(p1,HIGH);
pinMode(p2,INPUT);
pinMode(p3,INPUT);
}
else if(j==2){
pinMode(p0,INPUT);
pinMode(p1,INPUT);
pinMode(p2,OUTPUT);
digitalWrite(p2,HIGH);
pinMode(p3,INPUT);
}
else if(j==3){
pinMode(p0,INPUT);
pinMode(p1,INPUT);
pinMode(p2,INPUT);
pinMode(p3,OUTPUT);
digitalWrite(p3,HIGH);
}
int value = 0;
if(i ==0){
value = GetResistenceFromValue(analogRead(i0));
}
else if(i ==1){
value = GetResistenceFromValue(analogRead(i1));
}
else if(i==2){
value = GetResistenceFromValue(analogRead(i2));
}
else if(i==3){
value = GetResistenceFromValue(analogRead(i3));
}
return value;
}
| 19.238579
| 126
| 0.582586
|
294785a05c1f8c0035c82884beef9941f5244a8c
| 2,799
|
ino
|
Arduino
|
Arduino/Sensors/Accelerometer/LSM303_tilt_test/LSM303_tilt_test.ino
|
jzimmer5/470Repository
|
8d653a7a815553b591a295f8fb26768029e66dae
|
[
"MIT"
] | 1
|
2017-03-17T13:50:24.000Z
|
2017-03-17T13:50:24.000Z
|
Arduino/Sensors/Accelerometer/LSM303_tilt_test/LSM303_tilt_test.ino
|
jzimmer5/470Repository
|
8d653a7a815553b591a295f8fb26768029e66dae
|
[
"MIT"
] | null | null | null |
Arduino/Sensors/Accelerometer/LSM303_tilt_test/LSM303_tilt_test.ino
|
jzimmer5/470Repository
|
8d653a7a815553b591a295f8fb26768029e66dae
|
[
"MIT"
] | 9
|
2019-09-05T18:06:18.000Z
|
2021-11-04T03:57:30.000Z
|
/*
* Example of using Arduino and Adafruit LSM303 Accelerometer to determine tilt
*
*
* Carlos Castellanos
* August 24, 2020
*
*/
#include <Adafruit_LSM303_Accel.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
/* Assign a unique ID to this sensor at the same time */
Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(54321);
void setup(void) {
#ifndef ESP8266
while (!Serial)
; // will pause Zero, Leonardo, etc until serial console opens
#endif
Serial.begin(9600);
Serial.println("Adafruit LSM303 Accelerometer Test");
Serial.println("");
/* Initialise the sensor */
if (!accel.begin()) {
/* There was a problem detecting the ADXL345 ... check your connections */
Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
while (1)
;
}
/* Display some basic information on this sensor */
displaySensorDetails();
accel.setRange(LSM303_RANGE_4G);
Serial.print("Range set to: ");
lsm303_accel_range_t new_range = accel.getRange();
switch (new_range) {
case LSM303_RANGE_2G:
Serial.println("+- 2G");
break;
case LSM303_RANGE_4G:
Serial.println("+- 4G");
break;
case LSM303_RANGE_8G:
Serial.println("+- 8G");
break;
case LSM303_RANGE_16G:
Serial.println("+- 16G");
break;
}
accel.setMode(LSM303_MODE_NORMAL);
Serial.print("Mode set to: ");
lsm303_accel_mode_t new_mode = accel.getMode();
switch (new_mode) {
case LSM303_MODE_NORMAL:
Serial.println("Normal");
break;
case LSM303_MODE_LOW_POWER:
Serial.println("Low Power");
break;
case LSM303_MODE_HIGH_RESOLUTION:
Serial.println("High Resolution");
break;
}
}
void loop(void) {
/* Get a new sensor event */
sensors_event_t event;
accel.getEvent(&event);
/* send the results for orientation over the serial port */
Serial.print(event.orientation.roll);
Serial.print(",");
Serial.print(event.orientation.pitch);
Serial.print(",");
Serial.println(event.orientation.heading);
/* short delay to keep things stable */
delay(1);
}
void displaySensorDetails(void) {
sensor_t sensor;
accel.getSensor(&sensor);
Serial.println("------------------------------------");
Serial.print("Sensor: ");
Serial.println(sensor.name);
Serial.print("Driver Ver: ");
Serial.println(sensor.version);
Serial.print("Unique ID: ");
Serial.println(sensor.sensor_id);
Serial.print("Max Value: ");
Serial.print(sensor.max_value);
Serial.println(" m/s^2");
Serial.print("Min Value: ");
Serial.print(sensor.min_value);
Serial.println(" m/s^2");
Serial.print("Resolution: ");
Serial.print(sensor.resolution);
Serial.println(" m/s^2");
Serial.println("------------------------------------");
Serial.println("");
delay(500);
}
| 24.991071
| 79
| 0.661308
|
a88c63f476304ea8e88f9b2428a6d81490f1db3f
| 28,914
|
ino
|
Arduino
|
M847_bootloader/M847_bootloader.ino
|
MattisLind/M847-extended-version-V1.1
|
0729b8f68d7c2c376ca3867050146e21a6eac065
|
[
"MIT"
] | null | null | null |
M847_bootloader/M847_bootloader.ino
|
MattisLind/M847-extended-version-V1.1
|
0729b8f68d7c2c376ca3867050146e21a6eac065
|
[
"MIT"
] | null | null | null |
M847_bootloader/M847_bootloader.ino
|
MattisLind/M847-extended-version-V1.1
|
0729b8f68d7c2c376ca3867050146e21a6eac065
|
[
"MIT"
] | null | null | null |
// =============================================================================================================
// Bootloader for Digital PDP8/e PDP8/f PDP8/m computers by Roland Huisman. MIT license
// V1.1 fixed false run state message
// V1.2 changed RX(2)8 boot address for RX(2)8 (RX01/RX02) bootloader
// V1.3 Expanded to currently maximum possible 63 programs, so users can just replace the line with their own boot code
// V1.4 - Added Kaleidoscope.
// - Removed delays and Added variable "SlowDown". So you can determine your own loading speed.
// It's set to a quite fast but still blinky rate. Search for unsigned long SlowDown which is currently set at 35 milliseconds.
// You can change it if you want to speed up or slow down the loading. 0 gives the maximum load speed 200 gives a real slow loading.
// V1.5 Added TA8E TU60 bootstrap for Caps-8 and OS/8 setup cassettes
// V1.6 Added program 37, receive charachters on 03/04 serial port and place them into AC
// V1.7 - Updated BIN loader. You don't need to set the switches to 7777 when you want to use the serial port.
// It is now permanent set to use the 'low speed reader'. Which actually means that you can use the serial port at high speed.
// - Besides the BIN loader at 03/04 there is now also a secondary BIN loader at 40/41. So if you have a slow dumb terminal at
// 03/04 you can upload BIN images trough the second serial port at high speed. When you start your program it wil
// show up on your dumb terminal or TTY.
// - Changed the order of the bootstraps to a more logical structure
// =============================================================================================================
// =============================================================================================================
// Bootload programs
//
// Please note the data format. You can use the octal numbers after 0x....
// Please fill in all the numbers even if they are zero
//
// The first number is the initial address to deposit from
// The second number is the EMA address (IF and DF)
// Then the complete program can be written
// The last number is the start address of the program
//
// Example:
// We want a program located at address 200
// The EMA address is 0
// The data to deposit in memory is: 7001, 2300, 5201, 5200
// The startaddress is 200
//
// Should look like this:
// const PROGMEM word Program_01[] = {0x0200, 0x0000, 0x7001, 0x2300, 0x5201, 0x5200, 0x0200}; //AC increment program
//
//
// All Octal values are repesented as HEX numbers, and put as HEX into the MCP23017.
// Due hardware the bits 15, 11, 7 and 3 are zero and just not used.
// Programnumbers are shown in Octal as well... The highest program number is currently 77 oct (so max 63 programs)
// Program_00 does not exist, this is used to load the selected default
//
//
// =============================================================================================================
#include "programs.h"
// =============================================================================================================
// Includes
#include <Wire.h> // I2C handler
// =============================================================================================================
// Variables
const byte GPIOA = 0x12; // GPIOA adres in 16-bit mode, 2x 8 I/O ports.
const byte IOCON = 0x0A; // IOCON adres in 16-bit mode, I/O Expander Configuration Register.
const byte IODIRA = 0x00; // IODIRA adres in 16-bit mode, is het I/O Direction Register voor PortA.
volatile byte ProgramNumber = 0x00; // program to run
volatile byte pulseState = 0x00; // Previous state of switch
volatile unsigned long SwitchTimeOut = 3000; // This is the wait time (ms) after the last toggle. Then the program loads.
volatile word ProgramLength = 0x0000;// To calculate the amount of words in the programs
volatile byte RunOnce = 0x00; // just run Kitt once at turn on
unsigned long SlowDown = 5; // Blink delay in milli seconds. This slows down the loading of a bootstrap to give it a nice blinking effect.
// Placing a 0 loads the program at full speed, you can't really see a program to be loaded.
// Placing 50 will give a nice blinking effect but it slows down the program loading.
void setup ()
{
// =============================================================================================================
// Pin definitions
#define r_RUN 8 // PB0
#define r_SW 9 // PB1
#define Dip_1 10 // PB2
#define Dip_2 11 // PB3
#define Dip_3 12 // PB4
#define Dip_4 13 // PB5
#define BRK_DATA 10 // PB2
#define w_INITIALIZE_H A0 // PC0 for 400nS pulse
#define w_PULSE_LA_H A1 // PC1 for 400nS pulse
#define w_MEM_START A2 // PC2 for 400nS pulse
#define w_STOP A3 // PC3
#define Set_Flip_Flop 2 // PD2
#define Show_Data 3 // PD3
#define Exam 4 // PD4
#define w_LA_ENABLE 5 // PD5
#define w_MS_IR_DISABLE 6 // PD6
#define w_KEY_CONTROL 7 // PD7
pinMode (r_RUN , INPUT) ; // read RUN signal from Omnibus
pinMode (r_SW , INPUT) ; // read SW signal from Omnibus
//pinMode (Dip_1 , INPUT) ; // Default bootprogam select for one time toggeling SW
pinMode (Dip_2 , INPUT) ; // Default bootprogam select for one time toggeling SW
pinMode (Dip_3 , INPUT) ; // Default bootprogam select for one time toggeling SW
pinMode (Dip_4 , INPUT) ; // Default bootprogam select for one time toggeling SW
digitalWrite (r_RUN , HIGH) ; // turn on pull up
digitalWrite (r_SW , HIGH) ; // turn on pull up
digitalWrite (Dip_1 , HIGH) ; // turn on pull up
digitalWrite (Dip_2 , HIGH) ; // turn on pull up
digitalWrite (Dip_3 , HIGH) ; // turn on pull up
digitalWrite (Dip_4 , HIGH) ; // turn on pull up
digitalWrite (w_INITIALIZE_H , LOW) ; // Write zero before initializing output
digitalWrite (w_PULSE_LA_H , LOW) ; // Write zero before initializing output
digitalWrite (w_MEM_START , LOW) ; // Write zero before initializing output
digitalWrite (w_STOP , LOW) ; // Write zero before initializing output
pinMode (w_INITIALIZE_H , OUTPUT) ; // Set to output mode
pinMode (w_PULSE_LA_H , OUTPUT) ; // Set to output mode
pinMode (w_MEM_START , OUTPUT) ; // Set to output mode
pinMode (w_STOP , OUTPUT) ; // Set to output mode
digitalWrite (Set_Flip_Flop , LOW) ; // Write zero before initializing output
digitalWrite (Show_Data , LOW) ; // Write zero before initializing output
digitalWrite (Exam , LOW) ; // Write zero before initializing output
digitalWrite (w_LA_ENABLE , LOW) ; // Write zero before initializing output
digitalWrite (w_MS_IR_DISABLE , LOW) ; // Write zero before initializing output
digitalWrite (w_KEY_CONTROL , LOW) ; // Write zero before initializing output
pinMode (Set_Flip_Flop , OUTPUT) ; // Set to output mode
pinMode (Show_Data , OUTPUT) ; // Set to output mode
pinMode (Exam , OUTPUT) ; // Set to output mode
pinMode (w_LA_ENABLE , OUTPUT) ; // Set to output mode
pinMode (w_MS_IR_DISABLE , OUTPUT) ; // Set to output mode
pinMode (w_KEY_CONTROL , OUTPUT) ; // Set to output mode
// =============================================================================================================
// Start I2C bus
Wire.begin(); // start Wire library as I2C-Bus Master
Wire.beginTransmission(0x20); // MCP23017 Address
Wire.write(IOCON); // IOCON register
Wire.write(byte(B01000000)); // Enable sequential addresses
Wire.endTransmission();
Wire.beginTransmission(0x20);
Wire.write(IODIRA); // IODIRA register
Wire.write(byte(0x00)); // Write zeto's to outputs A
Wire.write(byte(0x00)); // Write zeto's to outputs B
Wire.endTransmission();
// =============================================================================================================
// Setup serial port for debugging
Serial.begin (115200);
digitalWrite (0 , HIGH) ; // turn on pull up on RX line
}
// End setup
// =============================================================================================================
// =============================================================================================================
// Main loop
void loop ()
{
if (RunOnce==0x00){Kitt();}
Serial.println ("PDP8/E, PDP8/F, PDP8/M bootloader by Roland Huisman V1.6");
Serial.println ();
Serial.print ("Default program number by dipswitch ");
Serial.println (ReadDefaultProgramNumber(),HEX);
Serial.print ("Use SW switch to select program number please... ");
ProgramNumber=(GetProgramNumber());
Serial.println (ProgramNumber,HEX);
Serial.println();
if (ProgramNumber==0x00)
{
ProgramNumber = ReadDefaultProgramNumber();
if (ProgramNumber == 0x00)
{
Serial.print("No default selected, no program will be loaded !");
Serial.println();
}
if (ProgramNumber != 0x00)
{
Serial.print("Default program ");
Serial.print(ProgramNumber,HEX);
Serial.println(" will be loaded !");
Serial.println();
}
}
if (ProgramNumber==0x01) {LoadProgram(Program_01, sizeof(Program_01));}
if (ProgramNumber==0x02) {LoadProgram(Program_02, sizeof(Program_02));}
if (ProgramNumber==0x03) {LoadProgram(Program_03, sizeof(Program_03));}
if (ProgramNumber==0x04) {LoadProgram(Program_04, sizeof(Program_04));}
if (ProgramNumber==0x05) {LoadProgram(Program_05, sizeof(Program_05));}
if (ProgramNumber==0x06) {LoadProgram(Program_06, sizeof(Program_06));}
if (ProgramNumber==0x07) {LoadProgram(Program_07, sizeof(Program_07));}
if (ProgramNumber==0x10) {LoadProgram(Program_10, sizeof(Program_10));}
if (ProgramNumber==0x11) {LoadProgram(Program_11, sizeof(Program_11));}
if (ProgramNumber==0x12) {LoadProgram(Program_12, sizeof(Program_12));}
if (ProgramNumber==0x13) {LoadProgram(Program_13, sizeof(Program_13));}
if (ProgramNumber==0x14) {LoadProgram(Program_14, sizeof(Program_14));}
if (ProgramNumber==0x15) {LoadProgram(Program_15, sizeof(Program_15));}
if (ProgramNumber==0x16) {LoadProgram(Program_16, sizeof(Program_16));}
if (ProgramNumber==0x17) {LoadProgram(Program_17, sizeof(Program_17));}
if (ProgramNumber==0x20) {LoadProgram(Program_20, sizeof(Program_20));}
if (ProgramNumber==0x21) {LoadProgram(Program_21, sizeof(Program_21));}
if (ProgramNumber==0x22) {LoadProgram(Program_22, sizeof(Program_22));}
if (ProgramNumber==0x23) {LoadProgram(Program_23, sizeof(Program_23));}
if (ProgramNumber==0x24) {LoadProgram(Program_24, sizeof(Program_24));}
if (ProgramNumber==0x25) {LoadProgram(Program_25, sizeof(Program_25));}
if (ProgramNumber==0x26) {LoadProgram(Program_26, sizeof(Program_26));}
if (ProgramNumber==0x27) {LoadProgram(Program_27, sizeof(Program_27));}
if (ProgramNumber==0x30) {LoadProgram(Program_30, sizeof(Program_30));}
if (ProgramNumber==0x31) {LoadProgram(Program_31, sizeof(Program_31));}
if (ProgramNumber==0x32) {LoadProgram(Program_32, sizeof(Program_32));}
if (ProgramNumber==0x33) {LoadProgram(Program_33, sizeof(Program_33));}
if (ProgramNumber==0x34) {LoadProgram(Program_34, sizeof(Program_34));}
if (ProgramNumber==0x35) {LoadProgram(Program_35, sizeof(Program_35));}
if (ProgramNumber==0x36) {LoadProgram(Program_36, sizeof(Program_36));}
if (ProgramNumber==0x37) {LoadProgram(Program_37, sizeof(Program_37));}
if (ProgramNumber==0x40) {LoadProgram(Program_40, sizeof(Program_40));}
if (ProgramNumber==0x41) {LoadProgram(Program_41, sizeof(Program_41));}
if (ProgramNumber==0x42) {LoadProgram(Program_42, sizeof(Program_42));}
if (ProgramNumber==0x43) {LoadProgram(Program_43, sizeof(Program_43));}
if (ProgramNumber==0x44) {LoadProgram(Program_44, sizeof(Program_44));}
if (ProgramNumber==0x45) {LoadProgram(Program_45, sizeof(Program_45));}
if (ProgramNumber==0x46) {LoadProgram(Program_46, sizeof(Program_46));}
if (ProgramNumber==0x47) {LoadProgram(Program_47, sizeof(Program_47));}
if (ProgramNumber==0x50) {LoadProgram(Program_50, sizeof(Program_50));}
if (ProgramNumber==0x51) {LoadProgram(Program_51, sizeof(Program_51));}
if (ProgramNumber==0x52) {LoadProgram(Program_52, sizeof(Program_52));}
if (ProgramNumber==0x53) {LoadProgram(Program_53, sizeof(Program_53));}
if (ProgramNumber==0x54) {LoadProgram(Program_54, sizeof(Program_54));}
if (ProgramNumber==0x55) {LoadProgram(Program_55, sizeof(Program_55));}
if (ProgramNumber==0x56) {LoadProgram(Program_56, sizeof(Program_56));}
if (ProgramNumber==0x57) {LoadProgram(Program_57, sizeof(Program_57));}
if (ProgramNumber==0x60) {LoadProgram(Program_60, sizeof(Program_60));}
if (ProgramNumber==0x61) {LoadProgram(Program_61, sizeof(Program_61));}
if (ProgramNumber==0x62) {LoadProgram(Program_62, sizeof(Program_62));}
if (ProgramNumber==0x63) {LoadProgram(Program_63, sizeof(Program_63));}
if (ProgramNumber==0x64) {LoadProgram(Program_64, sizeof(Program_64));}
if (ProgramNumber==0x65) {LoadProgram(Program_65, sizeof(Program_65));}
if (ProgramNumber==0x66) {LoadProgram(Program_66, sizeof(Program_66));}
if (ProgramNumber==0x67) {LoadProgram(Program_67, sizeof(Program_67));}
if (ProgramNumber==0x70) {LoadProgram(Program_70, sizeof(Program_70));}
if (ProgramNumber==0x71) {LoadProgram(Program_71, sizeof(Program_71));}
if (ProgramNumber==0x72) {LoadProgram(Program_72, sizeof(Program_72));}
if (ProgramNumber==0x73) {LoadProgram(Program_73, sizeof(Program_73));}
if (ProgramNumber==0x74) {LoadProgram(Program_74, sizeof(Program_74));}
if (ProgramNumber==0x75) {LoadProgram(Program_75, sizeof(Program_75));}
if (ProgramNumber==0x76) {LoadProgram(Program_76, sizeof(Program_76));}
if (ProgramNumber==0x77) {LoadProgram(Program_77, sizeof(Program_77));}
// etc...
Serial.println();
}
// End of main loop
// =============================================================================================================
// =============================================================================================================
// Count amount of switch pulses for program number and show in address LEDs
byte GetProgramNumber()
{
byte ToggledProgramNumber = 0x00;
byte OctalProgramNumber = 0x00; // highest valid program number is 0x77
unsigned long currentMillis = millis();
unsigned long previousMillis = millis();
while( (ToggledProgramNumber==0) | (currentMillis-previousMillis<SwitchTimeOut) )
{
if ((digitalRead(r_SW) == LOW) && (pulseState == false))
{
pulseState = true;
ToggledProgramNumber++;
currentMillis = millis();
previousMillis = millis();
if(ToggledProgramNumber>1)
{
OctalProgramNumber = ToggledProgramNumber-1;
OctalProgramNumber = ((OctalProgramNumber<<1)&0x70) | (OctalProgramNumber & 0x07); // ToggledProgramNumber transfer to octal
SingleStep();
SwitchRegister(OctalProgramNumber);
AddresLoad();
}
}
else if (digitalRead(r_SW) == HIGH)
{
pulseState = false;
currentMillis = millis();
}
delay(20);
}
SwitchRegister(0x0000);
Serial.println();
UndoSingleStep();
Serial.println();
return (OctalProgramNumber);
}
// =============================================================================================================
// Read dipswitches for the default boot loader to load
byte ReadDefaultProgramNumber ()
{
byte DefaultProgramNumber = PINB;
DefaultProgramNumber = DefaultProgramNumber >> 2; // move bits to the right
DefaultProgramNumber = ~DefaultProgramNumber & 0x0F; // invert reading and wipe out extra bits
DefaultProgramNumber = ((DefaultProgramNumber<<1)&0x70) | (DefaultProgramNumber & 0x07); // dipswitch transfer to octal
return DefaultProgramNumber;
}
// =============================================================================================================
// Load program
void LoadProgram(const word TheProgram[], int ProgramLength)
{
SingleStep();
Serial.println();
int i=0;
ProgramLength = ProgramLength/2; // calculate programlength in words
for (i = 0; i < ProgramLength; i = i + 1)
{
//Serial.println(pgm_read_word_near(TheProgram+i),HEX);
SwitchRegister(pgm_read_word_near(TheProgram+i));
if (i==0){AddresLoad();}
if (i==1){ExtendedAddressLoad();}
if (i==ProgramLength-1) {AddresLoad();}
if ((i!=0)&(i!=1)&(i!=ProgramLength-1)) {Deposit();}
delay(SlowDown);
}
SwitchRegister(0x0000);
Serial.println();
Serial.println();
UndoSingleStep();
Clear();
Continue();
}
// =============================================================================================================
// Transfer the switchregisterdata to the MC23017 to deposit or load address
void SwitchRegister(word LoadData)
{
Serial.print ("Set Switch Register to ");
Serial.print (LoadData,HEX);
Serial.print (" ");
word WordA = (LoadData) & 0x00FF;
word WordB = (LoadData >> 8) & 0x00FF;
//Serial.println (WordA, HEX);
//Serial.println (WordB, HEX);
Wire.beginTransmission(0x20);
Wire.write(GPIOA); // gpioa
Wire.write(byte(WordA)& 0xFF); // set A outputs to WordA
Wire.write(byte(WordB)& 0xFF); // set B outputs to WordA
Wire.endTransmission();
}
// =============================================================================================================
// Put PDP into Single Step mode
void SingleStep()
{
Serial.println("Go into Single Step mode");
digitalWrite (w_STOP , HIGH); // Places the machine in Single step mode
}
// =============================================================================================================
// Get PDP out of Single Step mode
void UndoSingleStep()
{
Serial.println("Undo Single Step mode");
digitalWrite (w_STOP , LOW); // Get the machine out of Single step mode
}
// =============================================================================================================
// Deposit
void Deposit()
{
Serial.println("Deposit");
pinMode (BRK_DATA , OUTPUT) ; // Set to output mode
digitalWrite (BRK_DATA , HIGH) ;
digitalWrite (Set_Flip_Flop , HIGH) ;
digitalWrite (w_KEY_CONTROL , HIGH) ;
digitalWrite (Show_Data , HIGH) ;
digitalWrite (w_MS_IR_DISABLE , HIGH) ;
Trigger_Mem_Start ();
digitalWrite (Set_Flip_Flop , LOW) ;
digitalWrite (w_KEY_CONTROL , LOW) ;
digitalWrite (Show_Data , LOW) ;
digitalWrite (w_MS_IR_DISABLE , LOW) ;
digitalWrite (BRK_DATA , LOW) ;
pinMode (BRK_DATA , INPUT) ; // Set to output mode
}
// =============================================================================================================
// Address Load
void AddresLoad()
{
Serial.println("Addres Load");
pinMode (BRK_DATA , OUTPUT) ; // Set to output mode
digitalWrite (BRK_DATA , LOW) ;
digitalWrite (w_LA_ENABLE , HIGH) ; // get machine ready to receive an address
digitalWrite (w_MS_IR_DISABLE , HIGH) ; // get machine ready to receive an address
digitalWrite (Set_Flip_Flop , HIGH) ; // get machine ready to receive an address
digitalWrite (Show_Data , HIGH) ;
digitalWrite (Exam , HIGH) ;
Trigger_Adres_Latch ();
digitalWrite (w_LA_ENABLE , LOW) ; // get machine out of address latch mode
digitalWrite (w_MS_IR_DISABLE , LOW) ; // get machine out of address latch mode
digitalWrite (Set_Flip_Flop , LOW) ; // get machine out of address latch mode
digitalWrite (Show_Data , LOW) ;
digitalWrite (Exam , LOW) ;
digitalWrite (BRK_DATA , HIGH) ;
pinMode (BRK_DATA , INPUT) ; // Set to output mode
}
// =============================================================================================================
// Extended Memory Address Load
void ExtendedAddressLoad()
{
Serial.println("Extended Memory Address Load");
pinMode (BRK_DATA , OUTPUT) ; // Set to output mode
digitalWrite (BRK_DATA , HIGH) ;
digitalWrite (w_LA_ENABLE , HIGH) ; // get machine ready to receive an extended address
digitalWrite (w_KEY_CONTROL , HIGH) ; // get machine ready to receive an extended address
digitalWrite (Set_Flip_Flop , HIGH) ; // get machine ready to receive an extended address
digitalWrite (Show_Data , HIGH) ;
Trigger_Adres_Latch ();
digitalWrite (w_LA_ENABLE , LOW) ; // get machine out of extended address latch mode
digitalWrite (w_KEY_CONTROL , LOW) ; // get machine out of extended address latch mode
digitalWrite (Set_Flip_Flop , LOW) ; // get machine out of extended address latch mode
digitalWrite (Show_Data , LOW) ;
digitalWrite (BRK_DATA , LOW) ;
pinMode (BRK_DATA , INPUT) ; // Set to output mode
}
// =============================================================================================================
// Clear
void Clear()
{
Serial.print("Clear machine");
if (digitalRead(r_RUN) == HIGH) // check if machine is not running
{
Trigger_Initialize (); // give 400ns positive pulse on Initialize_H
Serial.print(" >> Machine cleared");
}
if (digitalRead(r_RUN) == LOW) // Warning, machine seems to run ! Not cleared
{
Serial.print(" >> ERROR !! Machine not cleared due RUN state !");
}
Serial.println();
}
// =============================================================================================================
// Continue, set machine in RUN mode
void Continue()
{
Serial.print("Continue, set machine in RUN mode");
if (digitalRead(r_RUN) == LOW) // Warning, machine seems to run ! Not started
{
Serial.print(" >> ERROR !! Machine not started due RUN state !");
}
if (digitalRead(r_RUN) == HIGH) // check if machine is not running
{
Trigger_Mem_Start (); // give 400ns positive pulse on Initialize_H
Serial.print(" >> Running");
}
Serial.println();
}
// =============================================================================================================
// 400nS pulse to Initialize
void Trigger_Initialize ()
{
PORTC |= B00000001 ; // Turn on PC0
__asm__("nop\n\t"); //
__asm__("nop\n\t"); //
__asm__("nop\n\t"); // Wait for 400nS
__asm__("nop\n\t"); //
__asm__("nop\n\t"); //
__asm__("nop\n\t"); //
PORTC &= B11111110 ; // Turn off PC0
}
// =============================================================================================================
// 400nS pulse to Latch in address
void Trigger_Adres_Latch ()
{
PORTC |= B00000010 ; // Turn on PC1
__asm__("nop\n\t"); //
__asm__("nop\n\t"); //
__asm__("nop\n\t"); // Wait for 400ns
__asm__("nop\n\t"); //
__asm__("nop\n\t"); //
__asm__("nop\n\t"); //
PORTC &= B11111101 ; // Turn off PC1
}
// =============================================================================================================
// 400nS pulse to start memorycycle
void Trigger_Mem_Start ()
{
PORTC |= B00000100; // Turn on PC2
__asm__("nop\n\t"); //
__asm__("nop\n\t"); //
__asm__("nop\n\t"); // Wait for 400ns
__asm__("nop\n\t"); //
__asm__("nop\n\t"); //
__asm__("nop\n\t"); //
PORTC &= B11111011; // Turn on PC2
}
// =============================================================================================================
// Kitt scanner at turn on PDP
void Kitt()
{
SingleStep();
RunOnce++;
unsigned long scanspeed = 35;
SwitchRegister(0x0001);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0003);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0007);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0016);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0034);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0070);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0160);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0340);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0700);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x1600);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x3400);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x7000);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x6000);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x4000);
AddresLoad();
delay(scanspeed);
// and back
SwitchRegister(0x6000);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x7000);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x3400);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x1600);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0700);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0340);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0160);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0070);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0034);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0016);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0007);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0003);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0001);
AddresLoad();
delay(scanspeed);
SwitchRegister(0x0000);
AddresLoad();
delay(scanspeed);
UndoSingleStep();
}
| 42.646018
| 161
| 0.532406
|
fb22d719d24e732b2e5d585cd1a5f62033274d05
| 1,598
|
ino
|
Arduino
|
LCD_03.ino
|
Ghiordy/Curso-Microcontroladores
|
4025fc52e896a880e24bad4b065000eedef5210d
|
[
"MIT"
] | 1
|
2019-08-20T17:08:22.000Z
|
2019-08-20T17:08:22.000Z
|
LCD_03.ino
|
Ghiordy/Curso-Microcontroladores
|
4025fc52e896a880e24bad4b065000eedef5210d
|
[
"MIT"
] | null | null | null |
LCD_03.ino
|
Ghiordy/Curso-Microcontroladores
|
4025fc52e896a880e24bad4b065000eedef5210d
|
[
"MIT"
] | 1
|
2019-04-03T15:27:18.000Z
|
2019-04-03T15:27:18.000Z
|
/* The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2
* LCD R/W pin to ground
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3) */
// include the library code:
#include <LiquidCrystal.h>
int button = A0;
int select = A1;
int pos = 1;
int attem = 3;
int number = 0;
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {
pinMode(button,INPUT);
pinMode(select,INPUT);
lcd.begin(16, 2);
lcd.display();
AsigNumber();
}
int AsigNumber(){
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Guess! ");
attem = 3;
lcd.setCursor(0,1);
lcd.print(String(attem)+" attempts left.");
number = random(1,10);
return number;}
void loop() {
lcd.setCursor(15,0);
lcd.print(String(number));
delay(10);
if(digitalRead(button)==1){
delay(250);
if(pos==10){pos=0;}
else{pos++;}}
lcd.setCursor(10,0);
lcd.print(" ");
lcd.setCursor(10,0);
lcd.print(String(pos));
if(digitalRead(select)==1){
attem = attem-1;
delay(250);
check(number, pos);}
}
void check(int number, int pos){
lcd.setCursor(0,1);
if(pos==number){
lcd.print("You've winned. ");
delay(5000);
AsigNumber();}
else{if(attem==0){
lcd.print("You've losed. ");
delay(3000);
AsigNumber();}
else{lcd.print(String(attem)+" attempts left.");}}}
| 22.507042
| 60
| 0.580726
|
80facc94e2543a105235d08c120338baeb107a6f
| 7,599
|
ino
|
Arduino
|
examples/ESP32-LGFX-SDCard-GifPlayer/ESP32-LGFX-SDCard-GifPlayer.ino
|
Hades32/AnimatedGIF
|
ed58028768a7a9afdbc80c9b438c808c5aaa30f8
|
[
"Apache-2.0"
] | 171
|
2020-07-27T07:25:41.000Z
|
2022-03-29T20:15:21.000Z
|
examples/ESP32-LGFX-SDCard-GifPlayer/ESP32-LGFX-SDCard-GifPlayer.ino
|
Hades32/AnimatedGIF
|
ed58028768a7a9afdbc80c9b438c808c5aaa30f8
|
[
"Apache-2.0"
] | 48
|
2020-07-28T01:13:55.000Z
|
2022-03-18T23:18:46.000Z
|
examples/ESP32-LGFX-SDCard-GifPlayer/ESP32-LGFX-SDCard-GifPlayer.ino
|
Hades32/AnimatedGIF
|
ed58028768a7a9afdbc80c9b438c808c5aaa30f8
|
[
"Apache-2.0"
] | 22
|
2020-07-28T04:14:24.000Z
|
2022-02-21T09:52:34.000Z
|
#include <ESP32-Chimera-Core.h> // https://github.com/tobozo/ESP32-Chimera-Core or regular M5Stack Core
#define tft M5.Lcd // syntax sugar
#define DISPLAY_WIDTH tft.width()
#ifndef M5STACK_SD
// for custom ESP32 builds
#define M5STACK_SD SD
#endif
#include "AnimatedGIF.h"
AnimatedGIF gif;
// rule: loop GIF at least during 3s, maximum 5 times, and don't loop/animate longer than 30s per GIF
const int maxLoopIterations = 5; // stop after this amount of loops
const int maxLoopsDuration = 3000; // ms, max cumulated time after the GIF will break loop
const int maxGifDuration = 30000; // ms, max GIF duration
// used to center image based on GIF dimensions
static int xOffset = 0;
static int yOffset = 0;
static int totalFiles = 0; // GIF files count
static int currentFile = 0;
static int lastFile = -1;
char GifComment[256];
static File FSGifFile; // temp gif file holder
static File GifRootFolder; // directory listing
std::vector<std::string> GifFiles; // GIF files path
static void MyCustomDelay( unsigned long ms ) {
delay( ms );
//log_d("delay %d\n", ms);
}
static void * GIFOpenFile(const char *fname, int32_t *pSize)
{
//log_d("GIFOpenFile( %s )\n", fname );
FSGifFile = M5STACK_SD.open(fname);
if (FSGifFile) {
*pSize = FSGifFile.size();
return (void *)&FSGifFile;
}
return NULL;
}
static void GIFCloseFile(void *pHandle)
{
File *f = static_cast<File *>(pHandle);
if (f != NULL)
f->close();
}
static int32_t GIFReadFile(GIFFILE *pFile, uint8_t *pBuf, int32_t iLen)
{
int32_t iBytesRead;
iBytesRead = iLen;
File *f = static_cast<File *>(pFile->fHandle);
// Note: If you read a file all the way to the last byte, seek() stops working
if ((pFile->iSize - pFile->iPos) < iLen)
iBytesRead = pFile->iSize - pFile->iPos - 1; // <-- ugly work-around
if (iBytesRead <= 0)
return 0;
iBytesRead = (int32_t)f->read(pBuf, iBytesRead);
pFile->iPos = f->position();
return iBytesRead;
}
static int32_t GIFSeekFile(GIFFILE *pFile, int32_t iPosition)
{
int i = micros();
File *f = static_cast<File *>(pFile->fHandle);
f->seek(iPosition);
pFile->iPos = (int32_t)f->position();
i = micros() - i;
//log_d("Seek time = %d us\n", i);
return pFile->iPos;
}
static void TFTDraw(int x, int y, int w, int h, uint16_t* lBuf )
{
tft.pushRect( x+xOffset, y+yOffset, w, h, lBuf );
}
// Draw a line of image directly on the LCD
void GIFDraw(GIFDRAW *pDraw)
{
uint8_t *s;
uint16_t *d, *usPalette, usTemp[320];
int x, y, iWidth;
iWidth = pDraw->iWidth;
if (iWidth > DISPLAY_WIDTH)
iWidth = DISPLAY_WIDTH;
usPalette = pDraw->pPalette;
y = pDraw->iY + pDraw->y; // current line
s = pDraw->pPixels;
if (pDraw->ucDisposalMethod == 2) {// restore to background color
for (x=0; x<iWidth; x++) {
if (s[x] == pDraw->ucTransparent)
s[x] = pDraw->ucBackground;
}
pDraw->ucHasTransparency = 0;
}
// Apply the new pixels to the main image
if (pDraw->ucHasTransparency) { // if transparency used
uint8_t *pEnd, c, ucTransparent = pDraw->ucTransparent;
int x, iCount;
pEnd = s + iWidth;
x = 0;
iCount = 0; // count non-transparent pixels
while(x < iWidth) {
c = ucTransparent-1;
d = usTemp;
while (c != ucTransparent && s < pEnd) {
c = *s++;
if (c == ucTransparent) { // done, stop
s--; // back up to treat it like transparent
} else { // opaque
*d++ = usPalette[c];
iCount++;
}
} // while looking for opaque pixels
if (iCount) { // any opaque pixels?
TFTDraw( pDraw->iX+x, y, iCount, 1, (uint16_t*)usTemp );
x += iCount;
iCount = 0;
}
// no, look for a run of transparent pixels
c = ucTransparent;
while (c == ucTransparent && s < pEnd) {
c = *s++;
if (c == ucTransparent)
iCount++;
else
s--;
}
if (iCount) {
x += iCount; // skip these
iCount = 0;
}
}
} else {
s = pDraw->pPixels;
// Translate the 8-bit pixels through the RGB565 palette (already byte reversed)
for (x=0; x<iWidth; x++)
usTemp[x] = usPalette[*s++];
TFTDraw( pDraw->iX, y, iWidth, 1, (uint16_t*)usTemp );
}
} /* GIFDraw() */
int gifPlay( char* gifPath )
{ // 0=infinite
gif.begin(BIG_ENDIAN_PIXELS);
if( ! gif.open( gifPath, GIFOpenFile, GIFCloseFile, GIFReadFile, GIFSeekFile, GIFDraw ) ) {
log_n("Could not open gif %s", gifPath );
return maxLoopsDuration;
}
int frameDelay = 0; // store delay for the last frame
int then = 0; // store overall delay
bool showcomment = false;
// center the GIF !!
int w = gif.getCanvasWidth();
int h = gif.getCanvasHeight();
xOffset = ( tft.width() - w ) /2;
yOffset = ( tft.height() - h ) /2;
if( lastFile != currentFile ) {
log_n("Playing %s [%d,%d] with offset [%d,%d]", gifPath, w, h, xOffset, yOffset );
lastFile = currentFile;
showcomment = true;
}
while (gif.playFrame(true, &frameDelay)) {
if( showcomment )
if (gif.getComment(GifComment))
log_n("GIF Comment: %s", GifComment);
then += frameDelay;
if( then > maxGifDuration ) { // avoid being trapped in infinite GIF's
//log_w("Broke the GIF loop, max duration exceeded");
break;
}
}
gif.close();
return then;
}
int getGifInventory( const char* basePath )
{
int amount = 0;
GifRootFolder = M5STACK_SD.open(basePath);
if(!GifRootFolder){
log_n("Failed to open directory");
return 0;
}
if(!GifRootFolder.isDirectory()){
log_n("Not a directory");
return 0;
}
File file = GifRootFolder.openNextFile();
tft.setTextColor( TFT_WHITE, TFT_BLACK );
tft.setTextSize( 2 );
int textPosX = tft.width()/2 - 16;
int textPosY = tft.height()/2 - 10;
tft.drawString("GIF Files:", textPosX-40, textPosY-20 );
while( file ) {
if(!file.isDirectory()) {
GifFiles.push_back( file.name() );
amount++;
tft.drawString(String(amount), textPosX, textPosY );
file.close();
}
file = GifRootFolder.openNextFile();
}
GifRootFolder.close();
log_n("Found %d GIF files", amount);
return amount;
}
void setup()
{
M5.begin();
int attempts = 0;
int maxAttempts = 50;
int delayBetweenAttempts = 300;
bool isblinked = false;
while(! M5STACK_SD.begin() ) {
log_n("SD Card mount failed! (attempt %d of %d)", attempts, maxAttempts );
isblinked = !isblinked;
attempts++;
if( isblinked ) {
tft.setTextColor( TFT_WHITE, TFT_BLACK );
} else {
tft.setTextColor( TFT_BLACK, TFT_WHITE );
}
tft.drawString( "INSERT SD", tft.width()/2, tft.height()/2 );
if( attempts > maxAttempts ) {
log_n("Giving up");
#if defined( ARDUINO_M5Stack_Core_ESP32 ) || defined( ARDUINO_M5STACK_FIRE ) || defined( ARDUINO_ODROID_ESP32 )// || defined( ARDUINO_M5STACK_Core2 )
M5.setWakeupButton( BUTTON_B_PIN );
M5.powerOFF();
#endif
}
delay( delayBetweenAttempts );
M5.sd_begin();
}
log_n("SD Card mounted!");
tft.begin();
tft.fillScreen(TFT_BLACK);
totalFiles = getGifInventory( "/gif" ); // scan the SD card GIF folder
}
void loop()
{
tft.clear();
const char * fileName = GifFiles[currentFile++%totalFiles].c_str();
int loops = maxLoopIterations; // max loops
int durationControl = maxLoopsDuration; // force break loop after xxx ms
while(loops-->0 && durationControl > 0 ) {
durationControl -= gifPlay( (char*)fileName );
gif.reset();
}
}
| 24.672078
| 155
| 0.622056
|
f2c78905e4cdf8251a4945dc62875bbecbc0c41a
| 8,789
|
ino
|
Arduino
|
baton_BNO055/baton_BNO055.ino
|
dreeves4321/Arduino
|
04a7a206fa1ae96dcc4c7ba77e93614d0d60d0b8
|
[
"MIT"
] | null | null | null |
baton_BNO055/baton_BNO055.ino
|
dreeves4321/Arduino
|
04a7a206fa1ae96dcc4c7ba77e93614d0d60d0b8
|
[
"MIT"
] | null | null | null |
baton_BNO055/baton_BNO055.ino
|
dreeves4321/Arduino
|
04a7a206fa1ae96dcc4c7ba77e93614d0d60d0b8
|
[
"MIT"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////
//
// Arduino Code for 9DOF based pointer (baton)
// For the Bosch BNO055 fusion board
//
//
//
// Copyright (c) 2014-2015, Small Design Firm
//
// This sketch reads raw data from the BNO055, does a little processing, and sends it over UDP
//
// Connections
// ===========
// Connect SCL to analog 5
// Connect SDA to analog 4
// Connect VDD to 3.3V DC
// Connect GROUND to common ground
//
////--- Libraries ----////
/// Custom settings
#include "baton_base.h" // sets critical network and sensor toggles and options
#include "SD_Network.h" // class for setting and storing network settings on an SD card (or EEProm)
// Note that some of the accessible functionality has been commented out in this sketch to save space.
/// Storage Libraries
#include <EEPROM.h>
#include <SD.h>
/// Sensor Libraries
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>
/// Communication Libraries
#include <Wire.h> // probably want to use my wire_custom!!!
#include <SPI.h> // needed for Arduino versions later than 0018
#include "Ethernet-NODNS.h"
#include "EthernetUdp-NODNS.h"
//// ---- Variable And Object Definitions and Initializations ---- /////
/// Create the Fusion Sensor Object
int32_t id = 101;
Adafruit_BNO055 bno = Adafruit_BNO055(id);
bool sensorSucceed = false;
//// Ethernet Setup
// global setting object
SD_Network* SDNetwork = NULL;
networkSettings* netSettings;
#ifdef EXPORT_TO_ETHERNET
// IP address objects
IPAddress ip;
IPAddress remoteIp; // IP of remote computer
// default gateway and dns
byte dnsdefault[] = {8,8,8,8};
// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
char SendBuffer[UDP_OUT_PACKET_SIZE]; //buffer for outgoing data
char CalDataBuffer[UDP_OUT_PACKET_SIZE]; //buffer for outgoing data
//char calibrationMessage[] = "calibration";
char pingMessageGood[] = "baton okay";
char pingMessageBad[] = "baton bad";
// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;
#endif
/// Other Variables
imu::Vector<3> euler;
imu::Vector<3> acc;
imu::Quaternion quat;
String inStr;
String outStr;
unsigned long dataT;
float accMag;
bool printUDP = false;
//// ----- Methods ---- ////
/////// ------- SETUP
void setup() {
//// First start Serial and Ethernet
#ifdef SERIAL_OUTPUT
Serial.begin(SERIAL_PORT_SPEED);
Serial.println(F("Starting Conductors Baton w/ BNO055"));
Serial.println(F("COMMANDS: restart -- print output -- restore -- set MAC"));
Serial.println();
#endif
#ifdef EXPORT_TO_ETHERNET
SDNetwork = new SD_Network();
netSettings = &SDNetwork->settings;
//set network settings
ip = IPAddress(netSettings->ipArray[0], netSettings->ipArray[1], netSettings->ipArray[2], netSettings->ipArray[3]);
remoteIp = IPAddress(netSettings->remoteIpArray[0], netSettings->remoteIpArray[1], netSettings->remoteIpArray[2], netSettings->remoteIpArray[3]);
// start the Ethernet and UDP:
Ethernet.begin(SDNetwork->MAC, ip, dnsdefault, netSettings->gateway, netSettings->subnet);
Udp.begin(netSettings->localPortID);
#endif
/* Initialise the sensor */
if(bno.begin())
{
Serial.print(F("BNO055 detected"));
sensorSucceed = true;
delay(100);
bno.setExtCrystalUse(true);
/* Display some basic information on this sensor */
displaySensorStatus();
}
else {
/* There was a problem detecting the BNO055 ... check your connections */
Serial.print(F("BNO055 not detected!!"));
sensorSucceed = false;
}
/* remap axes */
// bno.setAxisRemap(Adafruit_BNO055::REMAP_DEFAULT, Adafruit_BNO055::REMAP_NO_SIGN);
//bno.setAxisRemap(Adafruit_BNO055::REMAP_X_Y, Adafruit_BNO055::REMAP_XAXIS_SIGN);
bno.setAxisRemap(Adafruit_BNO055::REMAP_X_Y, Adafruit_BNO055::REMAP_ZAXIS_SIGN);
//// Setup some variables
outStr.reserve(UDP_OUT_PACKET_SIZE);
// apply a delay
delay(1000);
}
/// ------- UTILITY FUNCTIONS
void displaySensorStatus(void)
{
#ifdef SERIAL_OUTPUT
uint8_t system_status, self_test_result, system_error;
bno.getSystemStatus(&system_status, &self_test_result, &system_error);
Serial.print(F("Self test (0F : good): "));
Serial.print(self_test_result, HEX);
Serial.print(F("System error (0 : good): "));
Serial.print(system_error);
Serial.println();
#endif
}
/*
bool checkMagnetometerCalibrated()
{
uint8_t sysStat, gyroStat, accelStat, magStat;
bno.getCalibration(&sysStat, &gyroStat, &accelStat, &magStat);
return (magStat == 3);
}
*/
/*
void printCalibrationStatus()
{
//Collect Calibration Status
uint8_t sysStat, gyroStat, accelStat, magStat;
bno.getCalibration(&sysStat, &gyroStat, &accelStat, &magStat);
Serial.print("G-A-M: ");
Serial.print(gyroStat);
Serial.print(accelStat);
Serial.print(magStat);
Serial.println();
}
*/
/////// MAIN LOOP FUNCTIONS
void doPingReply()
{
#ifdef SERIAL_OUTPUT
Serial.println("Ping received");
#endif
#ifdef EXPORT_TO_ETHERNET
Udp.beginPacket(remoteIp, netSettings->remotePortID);
if (sensorSucceed) Udp.write(pingMessageGood);
else Udp.write(pingMessageBad);
Udp.endPacket();
#endif
}
void doRestart()
{
#ifdef SERIAL_OUTPUT
Serial.println(" ");
Serial.println(F("--- Restarting -----"));
Serial.println(" ");
Serial.println(" ");
#endif
delay(30);
asm volatile (" jmp 0");
}
/// ------ MAIN LOOP
void loop() {
// put your main code here, to run repeatedly:
// Listen for UDP data over network
#ifdef EXPORT_TO_ETHERNET
int packetSize = Udp.parsePacket();
if (packetSize)
{
#ifdef SERIAL_OUTPUT
Serial.println(F("received message: "));
#endif
memset(&packetBuffer[0], 0, sizeof(packetBuffer));
Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
#ifdef SERIAL_OUTPUT
Serial.println(packetBuffer);
#endif
if (strcmp(packetBuffer, "restart") ==0) doRestart();
if (strcmp(packetBuffer, "hello") ==0) doPingReply();
}
#endif
// Listen for serial data
if (Serial.available()) {
inStr = Serial.readStringUntil('\n');
if (inStr == "restart") doRestart();
/*if (str == "set IP")
{
if (SDNetwork) SDNetwork->doIPSetup();
doRestart();
}
*/
if (inStr == "set MAC")
{
if (SDNetwork) SDNetwork->doMACSetup();
doRestart();
}
if (inStr == "restore")
{
if (SDNetwork) SDNetwork->doRestoreDefaults();
doRestart();
}
if (inStr == "print output")
{
printUDP = !printUDP;
}
//if (inStr == "print cal")
//{
// printcal = !printcal;
//}
}
// print calibration if called for
//if (printcal) printCalibrationStatus();
// Get and post data only if the sensor started properly
if (sensorSucceed)
{
dataT = millis();
// Get Orientation as Euler angle: (head - roll - pitch)
//euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);
quat = bno.getQuat();
// Chck for zeros and restart
if (quat.w()==0 && quat.x() == 0 && quat.y() == 0 && quat.z() == 0) doRestart();
// Get Acceleration vector
acc = bno.getVector(Adafruit_BNO055::VECTOR_LINEARACCEL);
accMag = acc.magnitude();
// printCalibrationStatus();
//// print data
// Send heading, pitch, and mag of accel
outStr = String(dataT) + " ";
outStr = outStr + String((int)(EXPORT_ANGLE_MULTIPLE * quat.w())) + " " + String((int)(EXPORT_ANGLE_MULTIPLE * quat.x())) + " " + String((int)(EXPORT_ANGLE_MULTIPLE * quat.y())) + " " + String((int)(EXPORT_ANGLE_MULTIPLE * quat.z())) +" " + String((int)(EXPORT_ACC_MULTIPLE * accMag)) + " ";
//str = str + String((int)(EXPORT_ANGLE_MULTIPLE * euler.x())) + " " + String((int)(EXPORT_ANGLE_MULTIPLE * euler.y())) + " " + String((int)(EXPORT_ANGLE_MULTIPLE * euler.z())) + " " + String((int)(EXPORT_ACC_MULTIPLE * accMag)) + " ";
//str = str + String((int)(EXPORT_MULTIPLE * y)) + " " + String((int)(EXPORT_MULTIPLE * z)) + " " + String((int)(EXPORT_MULTIPLE * accMag)) + " ";
/// --- export data to ethernet
#ifdef EXPORT_TO_ETHERNET
SendBuffer[0] = 0;
outStr.toCharArray(SendBuffer, UDP_OUT_PACKET_SIZE);
Udp.beginPacket(remoteIp, netSettings->remotePortID);
Udp.write(SendBuffer);
Udp.endPacket();
#endif
#ifdef SERIAL_OUTPUT
if (printUDP)
{
Serial.println(outStr);
}
#endif
}
else
{
delay(1000);
doRestart();
}
}
| 26.55287
| 295
| 0.642053
|
71ef815c56a8d7c7a94ea32a7912f05d59472106
| 1,216
|
ino
|
Arduino
|
examples/basicExample/basicExample.ino
|
intentfulmotion/AddressableLED
|
6e37c1147543224638bde7929db7180d6a6c2722
|
[
"MIT"
] | null | null | null |
examples/basicExample/basicExample.ino
|
intentfulmotion/AddressableLED
|
6e37c1147543224638bde7929db7180d6a6c2722
|
[
"MIT"
] | null | null | null |
examples/basicExample/basicExample.ino
|
intentfulmotion/AddressableLED
|
6e37c1147543224638bde7929db7180d6a6c2722
|
[
"MIT"
] | null | null | null |
#include <Arduino.h>
#include <AddressableLED.h>
#include <OneWireLED.h>
#include <TwoWireLED.h>
const int LED_COUNT = 15;
const int DATA_PIN = 22;
const int CHANNEL = 0;
AddressableLED *leds;
// SmartLed -> RMT driver (WS2812/WS2812B/SK6812/WS2813)
leds = new OneWireLED(WS2812B, CHANNEL, DATA_PIN, LED_COUNT);
// APA102 -> SPI driver
// const int CLK_PIN = 23;
// leds = new TwoWireLED(HSPI_HOST, LED_COUNT, CLK_PIN, DATA_PIN)
void setup() {
Serial.begin(9600);
}
uint8_t hue;
void showGradient() {
hue++;
// Use HSV to create nice gradient
for ( int i = 0; i != LED_COUNT; i++ )
(*leds)[i] = Hsv{ static_cast<uint8_t>(hue + 30 * i), 255, 255 };
leds->show();
// Show is asynchronous; if we need to wait for the end of transmission,
// we can use leds.wait(); however we use double buffered mode, so we
// can start drawing right after showing.
}
void showRgb() {
(*leds)[0] = Rgb{ 255, 0, 0 };
(*leds)[1] = Rgb{ 0, 255, 0 };
(*leds)[2] = Rgb{ 0, 0, 255 };
(*leds)[3] = Rgb{ 0, 0, 0 };
(*leds)[4] = Rgb{ 255, 255, 255 };
leds->show();
}
void loop() {
Serial.println("New loop");
if (millis() % 10000 < 5000)
showGradient();
else
showRgb();
delay(50);
}
| 22.943396
| 74
| 0.623355
|
fc0f5f9a4e0c8b16d566f286ec457afdd99dbaa4
| 980
|
ino
|
Arduino
|
workspace/esp32_test_SPIFFS/esp32_test_SPIFFS.ino
|
LeoSf/arduino_projects
|
a53f0e19e94b342e697ab5b47cb507f4c0dd9f6f
|
[
"Unlicense"
] | null | null | null |
workspace/esp32_test_SPIFFS/esp32_test_SPIFFS.ino
|
LeoSf/arduino_projects
|
a53f0e19e94b342e697ab5b47cb507f4c0dd9f6f
|
[
"Unlicense"
] | null | null | null |
workspace/esp32_test_SPIFFS/esp32_test_SPIFFS.ino
|
LeoSf/arduino_projects
|
a53f0e19e94b342e697ab5b47cb507f4c0dd9f6f
|
[
"Unlicense"
] | null | null | null |
/**
* @file esp32_template.ino
*
* @brief Brief description of the file
*
* @ingroup noPackageYet
* (Note: this needs exactly one @defgroup somewhere)
*
* @author Leo Medus
*
* Details:
* [setup] - ESP-32 Dev Kit C V2
* - The circuit: No external hardware needed
*
* Date: 21/01/2020 (dd/mm/yyyy)
*
* This program receives a byte from the serial port and displays it again (echo).
*
* https://randomnerdtutorials.com/install-esp32-filesystem-uploader-arduino-ide/
*/
#include "SPIFFS.h"
void setup() {
Serial.begin(115200);
if(!SPIFFS.begin(true)){
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}
File file = SPIFFS.open("/test_example.txt");
if(!file){
Serial.println("Failed to open file for reading");
return;
}
Serial.println("File Content:");
while(file.available()){
Serial.write(file.read());
}
file.close();
}
void loop() {
}
| 20.416667
| 87
| 0.621429
|
59b992f8751ad4d0f16c67244b1c51a05ca8866c
| 4,222
|
ino
|
Arduino
|
kvak.ino
|
Pravidnik/Quantologoi
|
a9ac18a526f80569334618bdffb1698af9847c43
|
[
"MIT"
] | null | null | null |
kvak.ino
|
Pravidnik/Quantologoi
|
a9ac18a526f80569334618bdffb1698af9847c43
|
[
"MIT"
] | null | null | null |
kvak.ino
|
Pravidnik/Quantologoi
|
a9ac18a526f80569334618bdffb1698af9847c43
|
[
"MIT"
] | null | null | null |
//-------Настройки сервопривода-------------------
#define SERVO_PIN_1 11
#define MIN_POS_1 15 // Минимальная позиция сервопривода
#define MAX_POS_1 110
#define DELAY_1 1047
#define SERVO_PIN_2 9
#define MIN_POS_2 30 // Минимальная позиция сервопривода
#define MAX_POS_2 115 // Максимальная позиция сервопривода
#define DELAY_2 1047
#define TIME_ON 15000
#include <Servo.h>
int Red;
int Delay_Led;
Servo servo1;
Servo servo2;
int Pos;
unsigned long LastOn;
unsigned long LastOn_1;
unsigned long LastOn_2;
boolean flag = 0;
boolean flag_1;
boolean flag_2;
#include "FastLED.h"
//------------------
#define NUM_LEDS 35
#define PIN 5
#define BRIGHTNESS 255
#define MIN_HUE 110
#define MAX_HUE 170
#define MAX_BRIGH 255
#define MIN_BRIGH 200
#define MAX_DIST 80
#define AVER_DIST 40
#define MIN_DIST 20 // Меньше 15 не ставить!!!!!!!!!!!!!!!!!!
#define TRIG1_PIN 3
#define TRIG2_PIN 4
#define TRIG3_PIN 6
#define TRIG4_PIN 7
CRGB leds[NUM_LEDS];
int Dist;
int RanNum;
int Bright;
boolean Trig1;
boolean Trig2;
boolean Trig3;
boolean Trig4;
void setup() {
servo1.attach(SERVO_PIN_1);
servo2.attach(SERVO_PIN_2);
servo1.write(MAX_POS_1);
servo2.write(MAX_POS_2);
//Pos = MIN_POS;
FastLED.addLeds<WS2811, PIN, GRB>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
FastLED.setBrightness(BRIGHTNESS);
pinMode(PIN, OUTPUT);
pinMode(TRIG1_PIN, INPUT_PULLUP);
pinMode(TRIG2_PIN, INPUT_PULLUP);
pinMode(TRIG3_PIN, INPUT_PULLUP);
pinMode(TRIG4_PIN, INPUT_PULLUP);
Serial.begin(9600);
}
void loop()
{
Trig2 = !digitalRead(TRIG2_PIN);
//Trig1 = !digitalRead(TRIG1_PIN);
//Serial.println(Trig2);
if (Trig2 == 0 && flag == 1) flag = 0;
if (Trig2 == 1 && flag == 0)
{
LastOn = millis();
flag = 1;
while (millis() - LastOn < TIME_ON)
{
servoOn1(1);
servoOn2(1);
}
}
//plamyOn(1);
servoOn1(0);
servoOn2(0);
Serial.println(Trig2);
//servo2.write(35);
//delay(1000);
// servo1.write(110);
//delay(1000);
//servo2.write(115);
//delay(1000);
//servo1.write(25);
//delay(1000);
}
void loop228() {
Trig1 = !digitalRead(TRIG1_PIN);
//Serial.println(Trig1);
Trig2 = !digitalRead(TRIG2_PIN);
Serial.println(Trig2);
// plamyOn(Trig2);
if (Trig1 == 1)
{
servo2.write(30);
// servo1.write(25);
delay(1000);
// servo2.write(100);
// servo1.write(110);
delay(1000);
}
else
{
servo2.write(100);
//servo1.write(110);
}
/*servo1.write(65);
servo2.write(20);
delay(1000);
servo1.write(160);
servo2.write(110);
delay(1000);
*/
}
void plamyOn(int mode)
{
if (mode == 1)
{
for (int i = 0; i < NUM_LEDS; i++)
{
Red = random(MIN_HUE, MAX_HUE);
// Serial.println(Red);
Bright = random(200, 255);
leds[i] = CHSV(Red, 255, Bright);
FastLED.show();
Delay_Led = random(18, 29);
delay(Delay_Led);
}
}
else if (mode == 0)
{
for (int i = 0; i < NUM_LEDS; i++)
{
leds[i] = CHSV(0, 0, 0);
FastLED.show();
}
}
}
void servoOn1(int mode_1) {
if (mode_1 == 1)
{
if (millis() - LastOn_1 > DELAY_1 && flag_1 == 0)
{
servo1.write(MIN_POS_1);
flag_1 = 1;
LastOn_1 = millis();
// Serial.println("0011");
}
if (millis() - LastOn_1 > DELAY_1 && flag_1 == 1)
{
servo1.write(MAX_POS_1);
flag_1 = 0;
LastOn_1 = millis();
// Serial.println("1111");
}
}
else
{
servo1.write(MAX_POS_1);
flag_1 = 0;
}
}
void servoOn2(int mode_2) {
if (mode_2 == 1)
{
if (millis() - LastOn_2 > DELAY_2 && flag_2 == 0)
{
servo2.write(MIN_POS_2);
flag_2 = 1;
LastOn_2 = millis();
// Serial.println("0022");
}
if (millis() - LastOn_2 > DELAY_2 && flag_2 == 1)
{
servo2.write(MAX_POS_2);
flag_2 = 0;
LastOn_2 = millis();
// Serial.println("1122");
}
}
else
{
servo2.write(MAX_POS_2);
flag_2 = 0;
}
}
| 18.517544
| 86
| 0.568688
|
cb6e31332d4b6ae94aa3abd082401e28d35dda68
| 2,409
|
ino
|
Arduino
|
Chapter 13/Sketch/Nokia5110/Nokia5110.ino
|
PacktPublishing/Mastering-Arduino
|
449b0f0b92d5524d72c85985412174969f9332ce
|
[
"MIT"
] | 5
|
2018-10-31T00:28:33.000Z
|
2021-11-08T13:10:35.000Z
|
Chapter 13/Sketch/Nokia5110/Nokia5110.ino
|
PacktPublishing/Mastering-Arduino
|
449b0f0b92d5524d72c85985412174969f9332ce
|
[
"MIT"
] | null | null | null |
Chapter 13/Sketch/Nokia5110/Nokia5110.ino
|
PacktPublishing/Mastering-Arduino
|
449b0f0b92d5524d72c85985412174969f9332ce
|
[
"MIT"
] | 4
|
2020-05-22T23:13:03.000Z
|
2021-06-02T00:10:42.000Z
|
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_PCD8544.h>
// pin 13 - Serial clock out (SCLK)
// pin 11 - 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(13, 11, 5, 4, 3);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
display.begin();
// init done
display.setContrast(40);
display.display();
delay(2000);
display.clearDisplay();
display.drawPixel(10, 10, BLACK);
display.drawPixel(11, 11, BLACK);
display.drawPixel(12, 12, BLACK);
display.display();
delay(2000);
display.clearDisplay();
// draw a line
display.drawLine(3,3,30,30, BLACK);
display.display();
delay(2000);
display.clearDisplay();
// Display text
display.setTextSize(1);
display.setTextColor(BLACK);
display.setCursor(0,0);
display.println("Hello, world!");
// Reverse Text
display.setTextColor(WHITE, BLACK);
display.println(3.141592);
display.setTextSize(2);
display.setTextColor(BLACK);
display.print("This is larger text");
display.display();
delay(2000);
display.clearDisplay();
// display rotated text
display.setRotation(1); // rotate 90 degrees counter clockwise, can also use values of 2 and 3 to go further.
display.setTextSize(1);
display.setTextColor(BLACK);
display.setCursor(0,0);
display.println("Hello, world!");
display.display();
delay(2000);
display.clearDisplay();
// draw circle
display.drawCircle(display.width()/2, display.height()/2, 6, BLACK);
display.display();
delay(2000);
display.clearDisplay();
// draw fill circle
display.fillCircle(display.width()/2, display.height()/2, 6, BLACK);
display.display();
delay(2000);
display.clearDisplay();
// draw rectangle
display.drawRect(15,15,30,15,BLACK);
display.display();
delay(2000);
display.clearDisplay();
// draw fill rectangle
display.fillRect(15,15,30,15,BLACK);
display.display();
delay(2000);
display.clearDisplay();
// draw round rectangle
display.drawRoundRect(15,15,30,15,4,BLACK);
display.display();
delay(2000);
display.clearDisplay();
// draw fill round rectangle
display.fillRoundRect(15,15,30,15,8,BLACK);
display.display();
delay(2000);
display.clearDisplay();
}
void loop() {
// put your main code here, to run repeatedly:
}
| 23.163462
| 112
| 0.681611
|
de2680170f76a279e2c3c7daa0f02ceee8287062
| 19,331
|
ino
|
Arduino
|
LineRiderRobot.ino
|
AnLiMan/Line_Rider_Robot
|
76f89433661a1e6b626e16f4383500a70ca49df7
|
[
"Unlicense"
] | null | null | null |
LineRiderRobot.ino
|
AnLiMan/Line_Rider_Robot
|
76f89433661a1e6b626e16f4383500a70ca49df7
|
[
"Unlicense"
] | null | null | null |
LineRiderRobot.ino
|
AnLiMan/Line_Rider_Robot
|
76f89433661a1e6b626e16f4383500a70ca49df7
|
[
"Unlicense"
] | null | null | null |
//-----Библиотеки---------
#include <avr/eeprom.h> // Для работы с EEPROM памятью
//-------------------Все постоянные-----------------
//---Постоянные автомобиля---
#define L 0.02 //Расстояние между передним и задним колесом (м)
#define dr 0.01 // Расстояние между задними колесами (м)
#define lr 0.01 // Расстояние между задним колесом и центром тяжести (м)
#define r 0.003 // Радиус колеса (м)
#define K 0.01 // Расстояние между правым и левым kingpin (м)
#define MinAngleSensetivity -5 // Минимальный угол нечувствительности руля в градусах
#define MaxAngleSensetivity 5 // Максимальный угол нечувствительности руля в градусах
#define BlinkPeriodForTurnSignal 200 //Период моргания поворотников
#define MaxModes 5 //Количество режимов
#define idleSpeedLineAndMemory 105 // Скорость для режима работы следования по линии и движения по памяти
//-----Выводы------
#define Button1 0 // Кнопка 1 (перключение режимов)
#define Button2 7 // Кнопка 2 (разрешение работы)
#define EncoderRight 2 // Энкодер правого двигателя
#define EncoderLeft 3 // Энкодер левого двигателя
#define LeftTurnSignal 4 // Левый поворотник
#define RightTurnSignal 5 // Правый поворотник
#define RearDimensionsAndHeadlights 6 // Задние габариты и передние фары
#define LeftMotor 9 // Левый двигатель
#define RightMotor 10 // Правый двигатель
#define RightMotorAdj 1
//#define RightMotorAdj 0.956 // Подстройка правого двигателя 0.956
#define BlueChannelRGB 11 // Синий канал RGB-светодиода
#define GrennChannelRGB 12 // Зелёный канал RGB-светодиода
#define RedChannelRGB 13 // Красный канал RGB-светодиода
#define StearingValue A0 // Сигнал с потенциометра руля
#define Accelerator A1 // Установка скорости (педаль газа)
#define InfraredSensorLeft A2 // Инфракрасный датчик слева
#define InfraredSensorRight A3 // Инфракрасный датчик справа
#define InfraredSensorStraight A4 // Инфракрасный датчик по середине
//---------------Все переменные------------
bool Buttflag1 = false; //Флаг нажатия кнопки 1
bool Buttflag2 = false; //Флаг нажатия кнопки 2
volatile int counter = 0; // Переменная-счётчик для переключения режимов
volatile bool OnWork = false; // Переменная разрешения на работу
//Для электронного дифференциала
float Omega1; //Скорость вращения 1
float Omega2; //Скорость вращения 2
float LinearIdleSpeed = 0.25; //Скорость машинки, линейная (м/c) по дефолту указана максимальная
int idleSpeed; //Скорость движения машинки
uint32_t myTimer1; // Переменная хранения времени 1
uint32_t myTimer2; // Переменная хранения времени 2
//Для энкодеров
volatile uint32_t LeftMotorTurnCounts; //Количество тиков с левого энкодера
volatile uint32_t RightMotorTurnCounts; //Количество тиков с правого энкодера
int DeltaT = 1500; // Переменная частоты снятия показаний с энкодеров (миллисекунды)
byte ArrayOfTheWay[] = {0, 0, 70, 70, 70, 70, 70, 50, 70, 50, 70, 70, 50, 70, 70, 0, 70, 50, 70, 50, 70, 70, 0, 70, 70, 0, 70, 70};
int NumberOfEntriesInEEPROM = 0; // Количество записей в EPPROM-память
bool StartRecord = false; //Перемнная разрешения записи
byte RightMotorTurnCountsEEPROM; // Значение для записи в EEPROM для правого колеса
byte LeftMotorTurnCountsEEPROM; // Значение для записи в EEPROM для левого колеса
/* Переменная частоты снятия показаний с энкодеров "DeltaT", напрямую влияет на то, как долго мы сможем писать
значения в EEPROM-память, формулы для расчёта приведены ниже
tmax = 1021 / 1сек - Максимальное время записи
1сек = 1 / DeltaT * 2 - "Стоимость записи одной секнды"
Пара готовых значений:
DeltaT = 100, tmax = 51 сек
DeltaT = 250, tmax = 128 сек
DeltaT = 500, tmax = 256 сек
*/
//----------------------//
//--------Setup-------
//---------------------//
void setup() {
Serial.begin(9600); //Для отладки
//Законфигурируем порты
pinMode(Button1, INPUT_PULLUP);
pinMode(Button2, INPUT_PULLUP);
pinMode(LeftTurnSignal, OUTPUT);
pinMode(RightTurnSignal, OUTPUT);
pinMode(RearDimensionsAndHeadlights, OUTPUT);
pinMode(LeftMotor, OUTPUT);
pinMode(RightMotor, OUTPUT);
pinMode(BlueChannelRGB, OUTPUT);
pinMode(GrennChannelRGB, OUTPUT);
pinMode(RedChannelRGB, OUTPUT);
// Расгоняем ШИМ на пинах D9 и D10 до 31.4 кГц, разрядность 8 бит
TCCR1A = 0b00000001; // 8bit
TCCR1B = 0b00000001; // x1 phase correct
//Выключаем двигатели
digitalWrite(LeftMotor, LOW);
digitalWrite(RightMotor, LOW);
//Подключаем прерывания
attachInterrupt(digitalPinToInterrupt(Button1), Button1Tick, FALLING); //Подключаем прерывание для кнопки 1
attachInterrupt(digitalPinToInterrupt(Button2), Button2Tick, FALLING); //Подключаем прерывание для кнопки 2
attachInterrupt(digitalPinToInterrupt(EncoderLeft), EncoderLeftTick, RISING); //Подключаем прерывание для левого энкодера
attachInterrupt(digitalPinToInterrupt(EncoderRight), EncoderRightTick, RISING); //Подключаем прерывание для правого энкодера
}
//---------------------------//
//-------Основной цикл--------
//---------------------------//
void loop() {
Buttflag1 = false; //Сброс флага кнопки 1
Buttflag2 = false; //Сброс флага кнопки 2
CurrentMode(counter); //Отображение текущего режима
//Работа разрешена
if (OnWork) {
//Включение разных режимов работы, в зависимости от значения текущей переменной
switch (counter) {
//1.1. Ручное управление. Индикатор - красный цвет светодиода
case 0:
digitalWrite(RearDimensionsAndHeadlights, HIGH);
ManualControl();
break;
// 1.2. Движение по линии. Индикатор - зелёный цвет светодиода
case 1:
digitalWrite(RearDimensionsAndHeadlights, HIGH);
idleSpeed = map(analogRead(Accelerator), 0, 1022, 0, 255); // Преобразуем входное значение сопротивления к новому диапазону
LineRider();
break;
//1.3. Движение по памяти. Индикатор - синий цвет светодиода
case 2:
idleSpeed = map(analogRead(Accelerator), 0, 1022, 0, 255); // Преобразуем входное значение сопротивления к новому диапазону
digitalWrite(RearDimensionsAndHeadlights, HIGH); // Включим индикацию
RideByMemory();
break;
//1.4. Запись в память. Индикатор - мигающий синий
case 3:
digitalWrite(RearDimensionsAndHeadlights, HIGH);
idleSpeed = map(analogRead(Accelerator), 0, 1022, 0, 255); // Преобразуем входное значение сопротивления к новому диапазону
WriteWayInMemory();
break;
//1.5. Очистка памяти. Индикатор - мигающий зелёный
case 4:
MemoryClean();
break;
}
}
//Если работа не разрешена, переходим в режим ожидания
else {
StandBy();
}
}
//--------------------------------------------------------------//
//-----------------1. Основные режимы работы-------------
//--------------------------------------------------------------//
//------------1.1. Ручное управление-----------------
void ManualControl() {
idleSpeed = map(analogRead(Accelerator), 0, 1022, 0, 255); // Преобразуем входное значение сопротивления к новому диапазону
int SteeringAngle = map(analogRead(StearingValue), 1023, 0, -60, 60); // Преобразуем входное значение сопротивления к новому диапазону
//Если едем прямо
if (MinAngleSensetivity < SteeringAngle && SteeringAngle < MaxAngleSensetivity) {
analogWrite(RightMotor, int (RightMotorAdj * idleSpeed));
analogWrite(LeftMotor, idleSpeed);
//Выключаем поворотники
digitalWrite(LeftTurnSignal, LOW);
digitalWrite(RightTurnSignal, LOW);
}
//Поворот вправо
else if (SteeringAngle > MaxAngleSensetivity) {
analogWrite(LeftMotor, idleSpeed);
ElectronicDiff(SteeringAngle); //Расчитаем скорости
int RightMotorSpeed = idleSpeed * (Omega1 / Omega2) * RightMotorAdj; //Корректируем скорость правого двигателя на Omega1/Omega2
analogWrite(RightMotor, RightMotorSpeed);
BlinkTurnLight(LeftTurnSignal, RightTurnSignal); //Добавим индикации
}
//Поворот налево
else if (SteeringAngle < MinAngleSensetivity) {
analogWrite(RightMotor, int (idleSpeed * RightMotorAdj));
ElectronicDiff(SteeringAngle); //Расчитаем скорости
int LeftMotorSpeed = idleSpeed * (Omega1 / Omega2); //Корректируем скорость левого двигателя на Omega1/Omega2
analogWrite(LeftMotor, LeftMotorSpeed);
BlinkTurnLight(RightTurnSignal, LeftTurnSignal); //Добавим индикации
}
}
//------------1.2. Движение по линии-----------------
void LineRider() {
//Считаем значения с датчиков
byte InfraredSensorRightState = digitalRead(InfraredSensorRight); // 1 - белый, чёрный - 0
byte InfraredSensorLeftState = digitalRead(InfraredSensorLeft); // 1 - белый, чёрный - 0
byte InfraredSensorStraightState = digitalRead(InfraredSensorStraight); // 1 - белый, чёрный - 0
// Если датчик посередине на черной линии
if (InfraredSensorStraightState == 0) {
analogWrite(LeftMotor, idleSpeed);
analogWrite(RightMotor, int (idleSpeed * RightMotorAdj));
}
// Иначе
else {
//Поворот налево
if (InfraredSensorRightState == 1 && InfraredSensorLeftState == 0) {
digitalWrite(LeftMotor, 0);
}
//Поворот направо
else if (InfraredSensorRightState == 0 && InfraredSensorLeftState == 1) {
digitalWrite(RightMotor, 0);
}
//Оба датчика на белом
else if (InfraredSensorRightState == 1 && InfraredSensorLeftState == 1) {
analogWrite(LeftMotor, idleSpeed);
analogWrite(RightMotor, int (idleSpeed * RightMotorAdj));
}
}
}
//------------1.3. Движение по памяти-----------------
void RideByMemory () {
//idleSpeed = map(analogRead(Accelerator), 0, 1022, 0, 255); // Преобразуем входное значение сопротивления к новому диапазону
// ---В случае если память пустая, едем по заранее записанному массиву ArrayOfTheWay-----
if (NumberOfEntriesInEEPROM == 0) {
for (int i = 0; i <= sizeof(ArrayOfTheWay);) {
// Если едем прямо
if (ArrayOfTheWay[i] == ArrayOfTheWay[i + 1]) {
analogWrite(LeftMotor, idleSpeed);
analogWrite(RightMotor, int (idleSpeed * RightMotorAdj));
analogWrite(LeftMotor, idleSpeed);
if (millis() - myTimer2 >= DeltaT) {
myTimer2 += DeltaT;
i += 2;
}
}
//Иначе считаем корректировку
else {
//Если записан поворот направо
if (ArrayOfTheWay[i] > ArrayOfTheWay[i + 1]) {
analogWrite(LeftMotor, idleSpeed);
int RightMotorSpeed = idleSpeed * ArrayOfTheWay[i + 1] / ArrayOfTheWay[i] * RightMotorAdj; //Корректируем скорость правого двигателя
analogWrite(RightMotor, RightMotorSpeed);
if (millis() - myTimer2 >= DeltaT) {
myTimer2 += DeltaT;
i += 2;
}
}
//Если записан поворот налево
else if (ArrayOfTheWay[i] < ArrayOfTheWay[i + 1]) {
analogWrite(RightMotor, int (idleSpeed * RightMotorAdj));
int LeftMotorSpeed = idleSpeed * ArrayOfTheWay[i] / ArrayOfTheWay[i + 1]; //Корректируем скорость левого двигателя
analogWrite(LeftMotor, LeftMotorSpeed);
if (millis() - myTimer2 >= DeltaT) {
myTimer2 += DeltaT;
i += 2;
}
}
}
}
}
//--В противном случае идем по EEPROM-памяти--
for (int i = 0; i <= eeprom_read_word(1022);) {
// Если едем прямо
if (eeprom_read_byte(i) == eeprom_read_byte(i + 1)) {
analogWrite(LeftMotor, idleSpeed);
analogWrite(RightMotor, int (idleSpeed * RightMotorAdj));
analogWrite(LeftMotor, idleSpeed);
if (millis() - myTimer2 >= DeltaT) {
myTimer2 += DeltaT;
i += 2;
}
}
//Иначе считаем корректировку
else {
//Если записан поворот направо
if (eeprom_read_byte(i) > eeprom_read_byte(i + 1)) {
analogWrite(LeftMotor, idleSpeed);
int RightMotorSpeed = idleSpeed * eeprom_read_byte(i + 1) / eeprom_read_byte(i) * RightMotorAdj; //Корректируем скорость правого двигателя
analogWrite(RightMotor, RightMotorSpeed);
if (millis() - myTimer2 >= DeltaT) {
myTimer2 += DeltaT;
i += 2;
}
}
//Если записан поворот налево
else if (eeprom_read_byte(i + 1) > eeprom_read_byte(i)) {
analogWrite(RightMotor, int (idleSpeed * RightMotorAdj));
int LeftMotorSpeed = idleSpeed * eeprom_read_byte(i) / eeprom_read_byte(i + 1); //Корректируем скорость левого двигателя
analogWrite(LeftMotor, LeftMotorSpeed);
if (millis() - myTimer2 >= DeltaT) {
myTimer2 += DeltaT;
i += 2;
}
}
}
}
}
//------------1.4. Запись в память-----------------
void WriteWayInMemory () {
//Считаем значения с датчиков
byte InfraredSensorRightState = digitalRead(InfraredSensorRight); // 1 - белый, чёрный - 0
byte InfraredSensorLeftState = digitalRead(InfraredSensorLeft); // 1 - белый, чёрный - 0
byte InfraredSensorStraightState = digitalRead(InfraredSensorStraight); // 1 - белый, чёрный - 0
// Если датчик посередине на черной линии
if (InfraredSensorStraightState == 0) {
analogWrite(LeftMotor, idleSpeed);
analogWrite(RightMotor, int (idleSpeed * RightMotorAdj));
}
// Иначе
else {
//Поворот налево
if (InfraredSensorRightState == 1 && InfraredSensorLeftState == 0) {
digitalWrite(LeftMotor, 0);
}
//Поворот направо
else if (InfraredSensorRightState == 0 && InfraredSensorLeftState == 1) {
digitalWrite(RightMotor, 0);
}
//Оба датчика на белом
else if (InfraredSensorRightState == 1 && InfraredSensorLeftState == 1) {
analogWrite(LeftMotor, idleSpeed);
analogWrite(RightMotor, int (idleSpeed * RightMotorAdj));
}
}
//Пришло время для записи
if (millis() - myTimer2 >= DeltaT) {
int Max = max(LeftMotorTurnCounts, RightMotorTurnCounts); // Найдём наибольшее значение
// --------Смаштабируем полученые значения----
//Если тиков с левого датчика больше
if (Max == LeftMotorTurnCounts) {
LeftMotorTurnCountsEEPROM = 255;
RightMotorTurnCountsEEPROM = 255 * RightMotorTurnCounts / LeftMotorTurnCounts;
NumberOfEntriesInEEPROM += 2;
}
//Если тиков с правого датчика больше
if (Max == RightMotorTurnCounts) {
RightMotorTurnCountsEEPROM = 255;
LeftMotorTurnCountsEEPROM = 255 * LeftMotorTurnCounts / RightMotorTurnCounts;
NumberOfEntriesInEEPROM += 2;
}
//Если одинаково
else {
RightMotorTurnCountsEEPROM = 255;
LeftMotorTurnCountsEEPROM = 255;
NumberOfEntriesInEEPROM += 2;
}
//Записываем данные в память
if (NumberOfEntriesInEEPROM <= 1021 && StartRecord) {
eeprom_update_byte(NumberOfEntriesInEEPROM, LeftMotorTurnCountsEEPROM); // Значение с левого энкодера (смасштабированные)
eeprom_update_byte(NumberOfEntriesInEEPROM - 1, RightMotorTurnCountsEEPROM); // Значение с правого энкодера (смасштабированные)
LeftMotorTurnCounts = 0;
RightMotorTurnCounts = 0;
myTimer2 += DeltaT;
}
//Если превышен лимит записи
if (NumberOfEntriesInEEPROM > 1021) {
NumberOfEntriesInEEPROM = 0;
StartRecord = false; //Заканчиваем запись
}
//Зписываем количество значений
if (StartRecord == false) {
eeprom_update_word(1022, NumberOfEntriesInEEPROM); // Значение с правого энкодера (смасштабированные)
}
}
}
//------------1.4. Очистка памяти-----------------
void MemoryClean () {
for (int i = 0; i <= 1023; i++ ) {
eeprom_update_byte(i, 0);
}
counter = 0; //Выходим в нулевой режим
}
//--------------------------------------------------------------//
//----------------2 Функции отработки прерываний--------------
//--------------------------------------------------------------//
// 2.1. Обработка прерываний с левого энкодера
void EncoderLeftTick() {
LeftMotorTurnCounts++;
}
// ---2.2. Обработка прерываний с правого энкодера---
void EncoderRightTick() {
RightMotorTurnCounts++;
}
// --2.3. Отработка нажатия первой кнопки (для переключения режимов)---
void Button1Tick () {
if (!Buttflag1) {
Buttflag1 = true;
counter++;
if (counter >= MaxModes) {
counter = 0;
}
}
}
//--2.4. Отработка нажатия второй кнопки (включение/отключение текущего режима)---
void Button2Tick () {
if (!Buttflag2) {
Buttflag2 = true;
OnWork = !OnWork; //Инвертируем переменную разрешения работы
StartRecord = true;
}
}
//--------------------------------------------------------------//
//-----------------3. Иные вспомогательные функциии--------------
//--------------------------------------------------------------//
//-----3.1. Функция отображения текущего режима----
void CurrentMode(int currentMode) {
switch (counter) {
case 0:
digitalWrite(RedChannelRGB, HIGH);
digitalWrite(GrennChannelRGB, LOW);
digitalWrite(BlueChannelRGB, LOW);
break;
case 1:
digitalWrite(RedChannelRGB, LOW);
digitalWrite(GrennChannelRGB, HIGH);
digitalWrite(BlueChannelRGB, LOW);
break;
case 2:
digitalWrite(RedChannelRGB, LOW);
digitalWrite(GrennChannelRGB, LOW);
digitalWrite(BlueChannelRGB, HIGH);
break;
case 3:
digitalWrite(RedChannelRGB, LOW);
digitalWrite(GrennChannelRGB, LOW);
if (millis() - myTimer1 >= BlinkPeriodForTurnSignal) {
myTimer1 += BlinkPeriodForTurnSignal;
digitalWrite(BlueChannelRGB, !digitalRead(BlueChannelRGB));
}
break;
case 4:
digitalWrite(RedChannelRGB, LOW);
digitalWrite(BlueChannelRGB, LOW);
if (millis() - myTimer1 >= BlinkPeriodForTurnSignal) {
myTimer1 += BlinkPeriodForTurnSignal;
digitalWrite(GrennChannelRGB, !digitalRead(GrennChannelRGB));
}
break;
}
}
//------3.2. Функция электронного дифференциала----
void ElectronicDiff(int Angle) {
float AngleRad = Angle / 57.32; //Переведём градусы в радианы
float tanAngle = tan(fabs(AngleRad));
float delta1 = atan((L / (L / tanAngle - K / 2)));
float delta2 = atan((L / (L / tanAngle + K / 2)));
float R1 = L / sin(delta1);
float R2 = L / sin(delta2);
float R3 = L / tanAngle - dr / 2;
float Rcg = sqrtf(R3 + dr * dr / 4 + lr * lr);
Omega1 = (LinearIdleSpeed * R1) / (Rcg * r);
Omega2 = (LinearIdleSpeed * R2) / (Rcg * r);
}
//------3.3. Функция моргания поворотниками-----
void BlinkTurnLight (int LightOff, int LightOn) {
digitalWrite(LightOff, LOW);
if (millis() - myTimer1 >= BlinkPeriodForTurnSignal) {
myTimer1 += BlinkPeriodForTurnSignal;
digitalWrite(LightOn, !digitalRead(LightOn));
}
}
//------3.4. Функция отключения текущего режима и выход в ожидание-----
void StandBy() {
//Выключаем свет
digitalWrite(RearDimensionsAndHeadlights, LOW);
digitalWrite(LeftTurnSignal, LOW);
digitalWrite(RightTurnSignal, LOW);
//Выключаем двигатели
digitalWrite(LeftMotor, LOW);
digitalWrite(RightMotor, LOW);
}
| 36.681214
| 147
| 0.643992
|
7e8cdde224a64858ba5c32d37d3f9f658c4573fc
| 59,392
|
ino
|
Arduino
|
KISS_OSD/KISS_OSD.ino
|
awolf78/KISS_OSD
|
ba05dec8b16f891d0e071a45404497baea8454c1
|
[
"Unlicense"
] | 53
|
2016-10-13T19:46:48.000Z
|
2020-12-17T01:41:34.000Z
|
KISS_OSD/KISS_OSD.ino
|
awolf78/KISS_OSD
|
ba05dec8b16f891d0e071a45404497baea8454c1
|
[
"Unlicense"
] | 64
|
2016-10-13T05:13:54.000Z
|
2021-02-07T21:39:28.000Z
|
KISS_OSD/KISS_OSD.ino
|
awolf78/KISS_OSD
|
ba05dec8b16f891d0e071a45404497baea8454c1
|
[
"Unlicense"
] | 23
|
2016-12-13T19:34:10.000Z
|
2020-05-17T09:43:27.000Z
|
/*
KISS FC OSD v1.0
By Felix Niessen (felix.niessen@googlemail.com)
for Flyduino.net
KISS FC OSD v2.x
by Alexander Wolf (awolf78@gmx.de)
for everyone who loves KISS
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org>
*/
// CONFIGURATION
// motors magnepole count (to display the right RPMs)
//=============================
#define MAGNETPOLECOUNT 14 // 2 for ERPMs
// Filter for ESC datas (higher value makes them less erratic) 0 = no filter, 20 = very strong filter
//=============================
#define ESC_FILTER 10
/* Low battery warning config
-----------------------------
This feature will show a flashing "BATTERY LOW" warning just below the center of your
display when bat_mAh_warning is exceeded - letting you know when it is time to land.
I have found the mAh calculation of my KISS setup (KISS FC with 24RE ESCs using ESC telemetry) to
be very accurate, so be careful when using other ESCs - mAh calculation might not be as accurate.
While disarmed, yaw to the right. This will display the selected battery. Roll left or right to
select a different battery. Pitch up or down to change the battery capacity. The warning will be
displayed according to the percentage configured in the menu. Enter the menu with a yaw to the left
for more than 3 seconds. Default is 23%, so if you have a 1300 mAh battery, it would start warning
you at 1001 mAh used capacity.
=============================*/
static const uint8_t BAT_MAH_INCREMENT = 50;
// END OF CONFIGURATION
//=========================================================================================================================
// internals
//=============================
//#define DEBUG
//#define SIMULATE_VALUES
static bool doItOnce = true;
#include <SPI.h>
#include "MAX7456.h"
#include "MyMAX7456.h"
#include <EEPROM.h>
#include "SerialPort.h"
#include "CSettings.h"
#include "CStickInput.h"
#include "fixFont.h"
#include "CMeanFilter.h"
#include "Config.h"
#if defined(ADVANCED_STATS) || defined(ADVANCED_ESC_STATS)
#include "CStatGenerator.h"
#endif
#ifdef RC_SPLIT_CONTROL
#include "MiniSoftSerial.h"
#ifdef IMPULSERC_VTX
MiniSoftSerial softSerial(A3);
#else
MiniSoftSerial softSerial(A1);
#endif
bool oldRCsplitState = false;
bool newRCsplitState = false;
unsigned long RCsplitChangeTime = 0;
#endif
#ifdef STEELE_PDB
static const char KISS_OSD_VER[] PROGMEM = "steele pdb v2.5.1";
#elif defined(BF32_MODE)
static const char KISS_OSD_VER[] PROGMEM = "bf32 osd v2.5";
#else
static const char KISS_OSD_VER[] PROGMEM = "kiss osd v2.5.1";
#endif
#if (defined(IMPULSERC_VTX) || defined(STEELE_PDB)) && !defined(STEELE_PDB_OVERRIDE)
const uint8_t osdChipSelect = 10;
#else
const uint8_t osdChipSelect = 6;
#endif
const byte masterOutSlaveIn = MOSI;
const byte masterInSlaveOut = MISO;
const byte slaveClock = SCK;
const byte osdReset = 2;
static uint8_t serialBuf[256];
CMyMax7456 OSD( osdChipSelect );
SerialPort<0, 63, 0> NewSerial;
CStickInput inputChecker;
CSettings settings(serialBuf);
static int16_t DV_PPMs[CSettings::DISPLAY_DV_SIZE];
static uint8_t vTxType = 0;
static uint8_t vTxChannel = 0;
static uint8_t oldvTxChannel = 0;
static uint8_t oldvTxBand = 0;
static uint8_t vTxBand = 0;
static uint16_t vTxLowPower, vTxHighPower, oldvTxLowPower, oldvTxHighPower;
const uint8_t VTX_BAND_COUNT = 5;
const uint8_t VTX_CHANNEL_COUNT = 8;
static const uint16_t vtx_frequencies[VTX_BAND_COUNT][VTX_CHANNEL_COUNT] PROGMEM = {
{ 5865, 5845, 5825, 5805, 5785, 5765, 5745, 5725 }, //A
{ 5733, 5752, 5771, 5790, 5809, 5828, 5847, 5866 }, //B
{ 5705, 5685, 5665, 5645, 5885, 5905, 5925, 5945 }, //E
{ 5740, 5760, 5780, 5800, 5820, 5840, 5860, 5880 }, //F
{ 5658, 5695, 5732, 5769, 5806, 5843, 5880, 5917 } //R
};
static const char bandSymbols[VTX_BAND_COUNT][2] PROGMEM = { {'a',0x00} , {'b', 0x00}, {'e', 0x00}, {'f', 0x00}, {'r', 0x00}};
#ifdef IMPULSERC_VTX
static uint8_t vTxPower, vTxMinPower;
//static unsigned long changevTxTime = 0;
void setvTxSettings()
{
oldvTxChannel = vTxChannel = settings.s.m_vTxChannel;
oldvTxBand = vTxBand = settings.s.m_vTxBand;
vTxPower = settings.s.m_vTxPower;
vTxMinPower = settings.s.m_vTxMinPower;
}
#endif
void cleanScreen()
{
OSD.clear();
while(!OSD.clearIsBusy());
}
static uint8_t lastTempUnit;
static boolean triggerCleanScreen = true;
void checkVideoMode()
{
uint8_t videoSys = OSD.videoSystem();
if(videoSys != settings.m_videoMode)
{
settings.m_videoMode = videoSys;
if(settings.m_videoMode == MAX7456_PAL) settings.ROWS = 15;
else settings.ROWS = 13;
OSD.setDefaultSystem(videoSys);
OSD.setTextArea(settings.COLS, settings.ROWS);
triggerCleanScreen = true;
}
}
void setupMAX7456()
{
#if (defined(IMPULSERC_VTX) || defined(STEELE_PDB)) && !defined(STEELE_PDB_OVERRIDE)
MAX7456Setup();
delay(100);
#endif
OSD.begin(settings.COLS,13);
#ifdef FORCE_NTSC
OSD.setDefaultSystem(MAX7456_NTSC);
#elif defined(FORCE_PAL)
OSD.setDefaultSystem(MAX7456_PAL);
#else
delay(1000);
checkVideoMode();
#endif
OSD.setTextArea(settings.COLS, settings.ROWS);
OSD.setSwitchingTime( 5 );
OSD.display();
delay(100);
OSD.setTextOffset(settings.s.m_xOffset, settings.s.m_yOffset);
}
static uint8_t throttle = 0;
static uint16_t roll = 0;
static uint16_t pitch = 0;
static uint16_t yaw = 0;
static uint16_t current = 0;
static uint8_t armed = 0;
static uint16_t LipoVoltage = 0;
static uint16_t LipoMAH = 0;
static uint16_t previousMAH = 0;
static uint16_t totalMAH = 0;
static uint16_t statMAH = 0;
static uint16_t remainMAH = 0;
static uint16_t MaxAmps = 0;
static uint8_t MaxC = 0;
static uint16_t MaxRPMs = 0;
static uint16_t MaxWatt = 0;
static uint8_t MaxTemp = 0;
static uint16_t MinBat = 0;
static uint8_t MinRSSI = 100;
static int16_t rssiVal;
static int16_t angleY = 0;
static uint16_t motorKERPM[4] = {0,0,0,0};
static uint16_t maxKERPM[4] = {0,0,0,0};
static uint16_t motorCurrent[4] = {0,0,0,0};
static uint16_t maxCurrent[4] = {0,0,0,0};
static uint16_t ESCTemps[4] = {0,0,0,0};
static uint16_t maxTemps[4] = {0,0,0,0};
static uint16_t ESCVoltage[4] = {0,0,0,0};
static uint16_t minVoltage[4] = {10000,10000,10000,10000};
static uint16_t ESCmAh[4] = {0,0,0,0};
static int16_t AuxChanVals[5] = {0,0,0,0,0};
static unsigned long start_time = 0;
static unsigned long time = 0;
static unsigned long old_time = 0;
static unsigned long total_time = 0;
static unsigned long DV_change_time = 0;
static int16_t last_Aux_Val = -10000;
static boolean armedOnce = false;
static boolean showBat = false;
static boolean settingChanged = false;
static uint8_t statPage = 0;
static bool flipOnce = true;
static uint8_t FCProfile = 0;
#ifdef NEW_FILTER
CMeanFilter rssiFilter(10);
#else
CMeanFilter rssiFilter(7);
#endif
uint16_t findMax4(uint16_t maxV, uint16_t *values, uint8_t length)
{
for(uint8_t i = 0; i < length; i++)
{
if(values[i] > maxV)
{
maxV = values[i];
}
}
return maxV;
}
uint16_t findMax(uint16_t maxV, uint16_t newVal)
{
if(newVal > maxV) {
return newVal;
}
return maxV;
}
uint16_t findMin(uint16_t minV, uint16_t newVal)
{
if(newVal < minV) {
return newVal;
}
return minV;
}
void ReviveOSD()
{
while(OSD.resetIsBusy()) delay(100);
OSD.reset();
while(OSD.resetIsBusy()) delay(100);
setupMAX7456();
delay(2000);
}
enum _ROLL_PITCH_YAW
{
_ROLL,
_PITCH,
_YAW
};
#ifdef BF32_MODE
struct BF32_FILTERS
{
uint8_t gyro_soft_lpf_hz;
uint16_t dterm_lpf_hz;
uint16_t yaw_lpf_hz;
uint16_t gyro_soft_notch_hz_1;
uint16_t gyro_soft_notch_cutoff_1;
uint16_t dterm_notch_hz;
uint16_t dterm_notch_cutoff;
uint16_t gyro_soft_notch_hz_2;
uint16_t gyro_soft_notch_cutoff_2;
uint8_t dterm_filter_type;
} bf32_filters;
struct BF32_RATES
{
uint8_t rcRate;
uint8_t rcExpo;
uint8_t rates[3];
uint8_t dynThrPID;
uint8_t thr_Mid;
uint8_t thr_Expo;
uint16_t tpa_breakpoint;
uint8_t rc_yawExpo;
uint8_t rc_yawRate;
} bf32_rates;
static uint8_t vTx_powerIDX, oldvTx_powerIDX, vTx_pitmode;
static uint8_t pid_p[10], pid_i[10], pid_d[10];
static boolean pidProfileChanged = false, rateProfileChanged = false;
static uint8_t rateProfile = 0, pidProfile = 0, oldPidProfile = 0, oldRateProfile = 0, rateProfileSelected = 0;
static uint8_t setpointRelaxRatio, dtermSetpointWeight;
#else
static uint16_t pid_p[3], pid_i[3], pid_d[3];
struct _FC_FILTERS
{
uint8_t lpf_frq;
uint8_t yawFilterCut;
uint8_t notchFilterEnabledR;
uint16_t notchFilterCenterR;
uint16_t notchFilterCutR;
uint8_t notchFilterEnabledP;
uint16_t notchFilterCenterP;
uint16_t notchFilterCutP;
uint8_t yawLpF;
uint8_t DLpF;
} fc_filters;
struct _FC_TPA
{
uint16_t tpa[3];
uint8_t customTPAEnabled;
uint8_t ctpa_bp1;
uint8_t ctpa_bp2;
uint8_t ctpa_infl[4];
} fc_tpa;
static bool DsetpointAvailable = false;
static uint8_t Dsetpoint = 0;
#endif
static uint16_t rcrate[3], rate[3], rccurve[3];
static uint16_t rcrate_roll, rate_roll, rccurve_roll, rcrate_pitch, rate_pitch, rccurve_pitch, rcrate_yaw, rate_yaw, rccurve_yaw;
static boolean moreLPFfilters = false;
static boolean fcSettingsReceived = false;
static boolean armOnYaw = true;
static uint32_t LastLoopTime = 0;
static boolean dShotEnabled = false;
static boolean logoDone = false;
static uint8_t protoVersion = 0;
static uint8_t failSafeState = 10;
typedef void* (*fptr)();
static char tempSymbol[] = {0xB0, 0x00};
static char ESCSymbol[] = {0x7E, 0x00};
static const char crossHairSymbol[] = {0x11, 0x00};
static uint8_t code = 0;
static boolean menuActive = false;
static boolean menuDisabled = false;
static boolean menuWasActive = false;
static boolean fcSettingChanged = false;
static void* activePage = NULL;
static boolean batterySelect = false;
static uint8_t activeMenuItem = 0;
static uint8_t stopWatch = 0x94;
static char batteryIcon[] = { 0x83, 0x84, 0x84, 0x89, 0x00 };
static char wattMeterSymbol[] = { 0xD7, 0xD8, 0x00 };
/*static bool angleXpositive = true;
static bool angleYpositive = true;*/
static uint8_t krSymbol[4] = { 0x9C, 0x9C, 0x9C, 0x9C };
static char crossHairSymbols[] = { 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E };
// 70-75, 76-80, 81-85, 86-95, 96-100, 101-105, 106-110
static unsigned long krTime[4] = { 0, 0, 0, 0 };
bool timer1sec = false;
bool timer40Hz = false;
static unsigned long timer1secTime = 0;
static bool symbolOnOffChanged = false;
static uint16_t fcNotConnectedCount = 0;
static bool telemetryReceived = false;
static bool batWarnSymbol = true;
static uint8_t zeroBlanks = 0;
static bool failsafeTriggered = false;
static bool vTxPowerActive = false;
static int8_t vTxPowerKnobChannel = -1;
static int16_t vTxPowerKnobLastPPM = -1;
static unsigned long vTxPowerTime = 0;
static uint8_t oldPrintCount = 0;
static uint8_t printCount = 0;
static bool statsActive = false;
unsigned long armingStatusChangeTime = 0;
#ifdef ADVANCED_STATS
static const uint8_t STAT_GENERATOR_SIZE = 6;
CStatGenerator statGenerators[STAT_GENERATOR_SIZE] = { CStatGenerator(5,20), CStatGenerator(20,40), CStatGenerator(40,60), CStatGenerator(60,80), CStatGenerator(80,100), CStatGenerator(95,100) };
#endif
#ifdef ADVANCED_ESC_STATS
CStatGenerator ESCstatGenerators[4] = { CStatGenerator(90,100), CStatGenerator(90,100), CStatGenerator(90,100), CStatGenerator(90,100) };
#endif
#ifdef BF32_MODE
enum _SETTING_MODES
{
FC_SETTINGS = 1,
FC_RATES = 1,
FC_PIDS = 1,
FC_VTX = 1,
FC_FILTERS = 1,
FC_TPA = 1
};
static uint8_t telemetryMSP = 0;
static const uint8_t MAX_TELEMETRY_MSPS = 7;
static const uint8_t telemetryMSPs[MAX_TELEMETRY_MSPS] = { 105, 110, 119, 150, 128, 129, 134 }; //FIXME: Move define for MSPs
extern void mspRequest(uint8_t mspCommand);
static const unsigned long minLoop = 5000;
static const uint8_t MAX_SETTING_MODES = 7;
static const uint8_t getSettingModes[MAX_SETTING_MODES] = { 1, 112, 111, 92, 88, 34, 94 }; //FIXME: Move define for MSPs
static const uint8_t setSettingModes[MAX_SETTING_MODES] = { 0, 202, 204, 93, 89, 35, 95 }; //FIXME: Move define for MSPs
static bool fcSettingModeChanged[MAX_SETTING_MODES] = { false, false, false, false, false, false, false };
#else
enum _SETTING_MODES
{
FC_SETTINGS,
FC_RATES,
FC_PIDS,
FC_VTX,
FC_FILTERS,
FC_TPA,
FC_DSETPOINT
};
static const unsigned long minLoop = 10000;
static const uint8_t MAX_SETTING_MODES = 7;
static const uint8_t getSettingModes[MAX_SETTING_MODES] = { 0x30, 0x4D, 0x43, 0x45, 0x47, 0x4B, 0x52 };
static const uint8_t setSettingModes[MAX_SETTING_MODES] = { 0x10, 0x4E, 0x44, 0x46, 0x48, 0x4C, 0x53 };
static bool fcSettingModeChanged[MAX_SETTING_MODES] = { false, false, false, false, false, false, false };
#endif
static uint8_t settingMode = 0;
static unsigned long _StartupTime = 0;
extern void* MainMenu();
static char iconPrintBuf1[] = { 0x00, 0x00, 0x00 };
static char iconPrintBuf2[] = { 0x00, 0x00, 0x00 };
static char ESC_STAT_STR1[] = "esc";
void getIconPos(uint16_t value, uint16_t maxValue, uint8_t steps, char &iconPos1, char &iconPos2, char inc = 1)
{
if(value > maxValue) value = maxValue;
uint16_t halfMax = maxValue / 2;
uint16_t stepValue = (uint16_t)(maxValue / (uint16_t)(steps));
uint16_t tempValue1 = 0;
if(value > halfMax) tempValue1 = value - halfMax;
value -= tempValue1;
iconPos1 += ((char)(value / stepValue)) * inc;
if(tempValue1 > 0)
{
iconPos2 += ((char)(tempValue1 / stepValue)) * inc;
}
}
void setup()
{
uint8_t i = 0;
SPI.begin();
SPI.setClockDivider( SPI_CLOCK_DIV2 );
setupMAX7456();
settings.cleanEEPROM();
settings.ReadSettings();
OSD.setTextOffset(settings.s.m_xOffset, settings.s.m_yOffset);
//clean used area
while (!OSD.notInVSync());
cleanScreen();
#ifdef IMPULSERC_VTX
//Ignore setting because this is critical to making sure we can detect the
//VTX power jumper being installed. If we aren't using 5V ref there is
//the chance we will power up on wrong frequency.
analogReference(DEFAULT);
setvTxSettings();
vtx_init();
vtx_set_frequency(vTxBand, vTxChannel);
vtx_flash_led(5);
#endif
lastTempUnit = settings.s.m_tempUnit;
settings.SetupPPMs(DV_PPMs);
NewSerial.begin(115200);
#ifdef RC_SPLIT_CONTROL
softSerial.begin(115200);
#endif
}
#ifdef BF32_MODE
extern void ReadFCSettings(boolean skipValues, uint8_t sMode, boolean notReceived = true);
#endif
void loop(){
uint8_t i = 0;
unsigned long _millis = millis();
#ifdef IMPULSERC_VTX
vtx_process_state(_millis, vTxBand, vTxChannel);
#endif
/*if(!OSD.status()) //trying to revive MAX7456 if it got a voltage hickup
{
ReviveOSD();
}*/
if(_StartupTime == 0)
{
_StartupTime = _millis;
}
if((_millis-timer1secTime) > 500)
{
timer1secTime = _millis;
timer1sec = !timer1sec;
}
#ifdef RC_SPLIT_CONTROL
if(!newRCsplitState && oldRCsplitState && settings.s.m_timerMode == 2 && (time / 1000) < 115) RCsplitChangeTime = _millis;
if(newRCsplitState != oldRCsplitState && (_millis-RCsplitChangeTime) > 5000)
{
static const uint8_t rc_split_record[] = {0x55, 0x01, 0x02, 0xf5, 0xaa};
softSerial.write(rc_split_record, (uint8_t)5);
if(newRCsplitState && !oldRCsplitState) RCsplitChangeTime = _millis;
else RCsplitChangeTime = 0;
oldRCsplitState = newRCsplitState;
}
#endif
#ifdef IMPULSERC_VTX
if(timer1sec) vtx_flash_led(1);
#endif
#if defined(STEELE_PDB) && !defined(STEELE_PDB_OVERRIDE)
if(timer1sec) steele_flash_led(_millis, 1);
#endif
if(micros()-LastLoopTime > minLoop)
{
LastLoopTime = micros();
#if !defined(FORCE_PAL) && !defined(FORCE_NTSC)
checkVideoMode();
#endif
#ifdef IMPULSERC_VTX
if (timer1sec)
{
vtx_set_power(armed ? vTxPower : vTxMinPower);
}
#endif
for(i=0; i<MAX_SETTING_MODES; i++)
{
if(fcSettingModeChanged[i]) fcSettingChanged = true;
}
if(!fcSettingsReceived && !menuDisabled)
{
#ifdef BF32_MODE
mspRequest(getSettingModes[settingMode]);
#else
if(fcNotConnectedCount % 10 == 0)
{
NewSerial.write(getSettingModes[settingMode]); // request settings
if(getSettingModes[settingMode] > 0x30)
{
NewSerial.write((uint8_t)0x00);
NewSerial.write((uint8_t)0x00);
}
}
#endif
ReadFCSettings(fcSettingChanged, settingMode);
if(!fcSettingsReceived && settingMode == 6) fcSettingsReceived = true; // override if D setpoint is not available
else if(!fcSettingsReceived) fcNotConnectedCount++;
else fcNotConnectedCount = 0;
if(fcSettingsReceived && settingMode < MAX_SETTING_MODES)
{
settingMode++;
if(settingMode < MAX_SETTING_MODES) fcSettingsReceived = false;
else settingMode = 0;
}
}
else
{
if(!fcSettingChanged || menuActive)
{
#ifdef BF32_MODE
mspRequest(telemetryMSPs[telemetryMSP]);
#else
uint8_t requestTelemetry = 0x20;
if(protoVersion > 108) requestTelemetry = 0x13;
NewSerial.write(requestTelemetry);
#endif
}
telemetryReceived = ReadTelemetry();
if(!telemetryReceived)
{
if(fcSettingChanged && !menuActive)
{
bool savedBefore = false;
for(i=1; i<MAX_SETTING_MODES; i++)
{
#ifdef BF32_MODE
SendFCSettings(setSettingModes[i]);
fcSettingModeChanged[i] = false;
#else
if(savedBefore && fcSettingModeChanged[i])
{
while (!OSD.notInVSync());
cleanScreen();
static const char WAIT_SAVE_STR[] PROGMEM = "saving please wait!!!";
OSD.printP(settings.COLS/2 - strlen_P(WAIT_SAVE_STR)/2, settings.ROWS/2, WAIT_SAVE_STR);
delay(1000);
}
if(fcSettingModeChanged[i])
{
SendFCSettings(i);
fcSettingModeChanged[i] = false;
savedBefore = true;
}
#endif
}
fcSettingChanged = false;
#ifdef BF32_MODE
mspRequest(250); //MSP_EEPROM_WRITE
#endif
}
else
{
fcNotConnectedCount++;
#ifdef BF32_MODE
if(telemetryMSP == (MAX_TELEMETRY_MSPS-1)) //skipping MSP_EXTRA_ESC_DATA if it does not exist
{
telemetryReceived = true;
telemetryMSP = 0;
fcNotConnectedCount = 0;
}
#endif
}
}
else
{
fcNotConnectedCount = 0;
#ifdef BF32_MODE
telemetryMSP++;
if(telemetryMSP < MAX_TELEMETRY_MSPS)
{
telemetryReceived = false;
}
else telemetryMSP = 0;
#endif
}
}
while (!OSD.notInVSync());
/*OSD.printInt16(settings.COLS, settings.ROWS/2, roll, 0, " ", 1);
OSD.printInt16(settings.COLS, settings.ROWS/2+1, pitch, 0, " ", 1);
OSD.printInt16(settings.COLS, settings.ROWS/2+2, yaw, 0, " ", 1);*/
if(fcNotConnectedCount > 500)
{
cleanScreen();
#ifdef BF32_MODE
static const char FC_NOT_CONNECTED_STR[] PROGMEM = "no connection to fc";
#else
static const char FC_NOT_CONNECTED_STR[] PROGMEM = "no connection to kiss fc";
#endif
OSD.printP(settings.COLS/2 - strlen_P(FC_NOT_CONNECTED_STR)/2, settings.ROWS-2, FC_NOT_CONNECTED_STR);
triggerCleanScreen = true;
logoDone = true;
fcNotConnectedCount = 0;
/*OSD.printInt16(0, settings.ROWS/2, checksumDebug, 0);
OSD.printInt16(0, settings.ROWS/2+1, bufMinusOne, 0);
OSD.printInt16(0, settings.ROWS/2+2, settingMode, 0);*/
return;
}
if(telemetryReceived) code = inputChecker.ProcessStickInputs(roll, pitch, yaw, armed);
#ifdef CAMERA_CONTROL
if(armed == 0 && throttle > 50)
{
SendFCSettings(98); //MSP_CAMERA_CONTROL
code = 0;
cleanScreen();
static const char CAMERA_CONTROL_STR[] PROGMEM = "camera control";
OSD.printP(settings.COLS/2 - strlen_P(CAMERA_CONTROL_STR)/2, settings.ROWS - 1, CAMERA_CONTROL_STR);
}
#endif
/*OSD.printInt16(0, settings.ROWS/2, armed, 0);
OSD.printInt16(0, settings.ROWS/2+1, vTxPowerActive, 0);*/
if(settings.m_lastMAH > 0)
{
static const char LAST_BATTERY_STR[] PROGMEM = "continue last battery?";
OSD.printP(settings.COLS/2 - strlen_P(LAST_BATTERY_STR)/2, settings.ROWS/2 - 1, LAST_BATTERY_STR);
static const char ROLL_RIGHT_STR[] PROGMEM = "roll right to confirm";
OSD.printP(settings.COLS/2 - strlen_P(ROLL_RIGHT_STR)/2, settings.ROWS/2, ROLL_RIGHT_STR);
static const char ARM_CANCEL_STR[] PROGMEM = "roll left to cancel";
OSD.printP(settings.COLS/2 - strlen_P(ARM_CANCEL_STR)/2, settings.ROWS/2 + 1, ARM_CANCEL_STR);
if(code & inputChecker.ROLL_RIGHT)
{
previousMAH = settings.m_lastMAH;
settings.m_lastMAH = 0;
cleanScreen();
}
if(code & inputChecker.ROLL_LEFT || armed > 0)
{
settings.m_lastMAH = 0;
settings.WriteLastMAH();
cleanScreen();
}
return;
}
#ifdef SHOW_KISS_LOGO
if(!logoDone && armed == 0 && !menuActive && !armedOnce && settings.m_IconSettings[KISS_ICON] == 1)
{
#if defined(IMPULSERC_VTX) || defined(STEELE_PDB)
uint8_t logoCol = settings.COLS/2-3;
uint8_t logoRow = settings.ROWS/2-2;
static const char impulseRC_logo[][7] PROGMEM = { { 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0x00 },
{ 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF, 0x00 },
{ 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0x00 },
{ 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0x00 } };
for(i=0; i<4; i++)
{
OSD.setCursor(logoCol, logoRow);
OSD.print(fixPStr(impulseRC_logo[i]));
logoRow++;
}
// This was for the big logo
/*static const char impulseRC_logo2[][17] = { { 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xCC, 0xCD, 0xCE, 0xCF, 0x00 },
{ 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0x00 } };
logoCol = settings.COLS/2-8;
for(i=0; i<2; i++)
{
OSD.setCursor(logoCol, logoRow);
OSD.print(impulseRC_logo2[i]);
logoRow++;
}*/
static const char impulseRC_logo2[][13] PROGMEM = { { 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0x00 },
{ 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xED, 0x00 } };
logoCol = settings.COLS/2-6;
for(i=0; i<2; i++)
{
OSD.setCursor(logoCol, logoRow);
OSD.print(fixPStr(impulseRC_logo2[i]));
logoRow++;
}
/*#ifdef STEELE_PDB
logoCol = settings.COLS/2-2;
OSD.setCursor(logoCol, logoRow);
static const char mustache[] PROGMEM = { 0x7F, 0x80, 0x81, 0x82, 0x00 };
OSD.print(fixPStr(mustache));
#endif*/
#else
uint8_t logoCol = 11;
uint8_t logoRow = 5;
OSD.setCursor(logoCol, logoRow);
static const char kiss_logo1[] PROGMEM = { 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0x00 };
static const char kiss_logo2[] PROGMEM = { 0xBB, 0xBC, 0xBD, 0xBE, 0xBF, 0xC0, 0xC1, 0xC2, 0x00 };
static const char kiss_logo3[] PROGMEM = { 0xC3, 0xC4, 0xC5, 0xC6, 0x00 };
OSD.print(fixPStr(kiss_logo1));
logoRow++;
logoCol--;
OSD.setCursor(logoCol, logoRow);
OSD.print(fixPStr(kiss_logo2));
logoRow++;
logoCol -= 2;
OSD.setCursor(logoCol, logoRow);
OSD.print(fixPStr(kiss_logo3));
if(dShotEnabled)
{
static const char DShot_logo1[] PROGMEM = { 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0x00 };
static const char DShot_logo2[] PROGMEM = { 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0x00 };
OSD.print(fixPStr(DShot_logo1));
logoRow++;
logoCol += 4;
OSD.setCursor(logoCol, logoRow);
OSD.print(fixPStr(DShot_logo2));
}
#endif
if(_StartupTime > 0 && _millis - _StartupTime > 60000)
{
logoDone = true;
cleanScreen();
}
}
#else
logoDone = true;
#endif
if(fcNotConnectedCount <= 500 && ((!fcSettingsReceived && !menuDisabled) || !telemetryReceived) ) return;
#ifdef IMPULSERC_VTX
vtx_flash_led(1);
#endif
#if defined(STEELE_PDB) && !defined(STEELE_PDB_OVERRIDE)
steele_flash_led(_millis, 1);
#endif
#ifdef FAILSAFE
if(armedOnce && failSafeState > 9)
{
if(!failsafeTriggered) cleanScreen();
static const char FAILSAFE_STR[] PROGMEM = "failsafe";
OSD.printP(settings.COLS/2 - strlen_P(FAILSAFE_STR)/2, settings.ROWS/2, FAILSAFE_STR);
failsafeTriggered = true;
return;
}
else if(failsafeTriggered)
{
failsafeTriggered = false;
cleanScreen();
}
#endif
#ifdef ARMING_STATUS
static const char ARMED_STR[] PROGMEM = " armed ";
static const char DISARMED_STR[] PROGMEM = " disarmed ";
static const char _3D_MODE_STR[] PROGMEM = " 3d mode ";
static const char TURTLE_MODE_STR[] PROGMEM = "turtle mode";
uint8_t colArm = settings.COLS/2 - strlen_P(TURTLE_MODE_STR)/2;
uint8_t rowArm = settings.ROWS/2+2;
if(_millis - armingStatusChangeTime < 1000 || armed == 3)
{
switch(armed)
{
case 0:
if(settings.s.m_stats != 1) OSD.printP(colArm, rowArm, DISARMED_STR);
break;
case 1:
OSD.printP(colArm, rowArm, ARMED_STR);
break;
case 2:
OSD.printP(colArm, rowArm, _3D_MODE_STR);
break;
case 3:
OSD.blink1sec();
OSD.printP(colArm, rowArm, TURTLE_MODE_STR);
break;
}
}
else if(logoDone && !statsActive && !menuActive) OSD.printSpaces(colArm, rowArm, strlen_P(TURTLE_MODE_STR));
#endif
#ifdef DEBUG
vTxType = 2;
OSD.printInt16(0,8,protoVersion,0);
#endif
if(triggerCleanScreen)
{
triggerCleanScreen = false;
cleanScreen();
}
if(oldPrintCount != printCount)
{
cleanScreen();
oldPrintCount = printCount;
}
if(settings.s.m_tempUnit == 1)
{
tempSymbol[0] = fixChar(0xB1);
}
else
{
tempSymbol[0] = fixChar(0xB0);
}
if(code & inputChecker.ROLL_RIGHT)
{
logoDone = true;
cleanScreen();
}
if(armed == 0 && code & inputChecker.YAW_LONG_LEFT && code & inputChecker.ROLL_LEFT && code & inputChecker.PITCH_DOWN)
{
ReviveOSD();
}
#ifdef CAMERA_CONTROL
if(batterySelect || (!menuActive && !armOnYaw && yaw > 1900 && armed == 0 && throttle < 50))
#else
if(batterySelect || (!menuActive && !armOnYaw && yaw > 1900 && armed == 0))
#endif
{
if(!showBat)
{
cleanScreen();
showBat = true;
logoDone = true;
}
if((code & inputChecker.ROLL_LEFT) && settings.s.m_activeBattery > 0)
{
settings.s.m_activeBattery--;
settings.FixBatWarning();
settingChanged = true;
}
if((code & inputChecker.ROLL_RIGHT) && settings.s.m_activeBattery < 3)
{
settings.s.m_activeBattery++;
settings.FixBatWarning();
settingChanged = true;
}
if((code & inputChecker.PITCH_UP) && settings.s.m_batMAH[settings.s.m_activeBattery] < 32000)
{
settings.s.m_batMAH[settings.s.m_activeBattery] += (int16_t)BAT_MAH_INCREMENT;
settings.FixBatWarning();
settingChanged = true;
}
if((code & inputChecker.PITCH_DOWN) && settings.s.m_batMAH[settings.s.m_activeBattery] > 300)
{
settings.s.m_batMAH[settings.s.m_activeBattery] -= (int16_t)BAT_MAH_INCREMENT;
settings.FixBatWarning();
settingChanged = true;
}
static const char BATTERY_STR[] PROGMEM = "battery ";
uint8_t batCol = settings.COLS/2 - (strlen_P(BATTERY_STR)+1)/2;
OSD.printInt16P(batCol, settings.ROWS/2 - 1, BATTERY_STR, settings.s.m_activeBattery+1, 0);
batCol = settings.COLS/2 - 3;
OSD.printInt16(batCol, settings.ROWS/2, settings.s.m_batMAH[settings.s.m_activeBattery], 0, "mah", 2);
static const char WARN_STR[] PROGMEM = "warn at ";
OSD.printInt16P(settings.COLS/2 - (strlen_P(WARN_STR) + 6)/2, settings.ROWS/2 + 1, WARN_STR, settings.s.m_batWarningMAH, 0, "mah", 2);
if(batterySelect)
{
static const char YAW_LEFT_STR[] PROGMEM = "yaw left to go back";
OSD.printP(settings.COLS/2 - strlen_P(YAW_LEFT_STR)/2,settings.ROWS/2 + 2, YAW_LEFT_STR);
}
if(batterySelect && yaw < 250)
{
batterySelect = false;
}
return;
}
else
{
if(showBat)
{
cleanScreen();
showBat = false;
}
}
if(armed == 0 && ((code & inputChecker.YAW_LONG_LEFT) || menuActive) && !menuDisabled)
{
if(!menuActive)
{
menuActive = true;
cleanScreen();
activePage = (void*)MainMenu;
fcSettingsReceived = false;
#ifdef BF32_MODE
oldPidProfile = pidProfile;
oldRateProfile = rateProfile;
#endif
}
fptr temp = (fptr) activePage;
activePage = (void*)temp();
return;
}
else
{
if(menuWasActive)
{
menuWasActive = false;
activeMenuItem = 0;
cleanScreen();
}
}
if(settingChanged)
{
settings.WriteSettings();
settingChanged = false;
}
if(armed == 0 && armedOnce && last_Aux_Val != AuxChanVals[settings.s.m_DVchannel])
{
DV_change_time = _millis;
last_Aux_Val = AuxChanVals[settings.s.m_DVchannel];
}
#ifndef IMPULSERC_VTX
#ifdef VTX_POWER_KNOB
//OSD.printInt16(0, settings.ROWS/2, vTxPowerKnobChannel, 0);
if(vTxPowerKnobChannel > -1 && vTxPowerKnobLastPPM == -1 && failSafeState < 10) vTxPowerKnobLastPPM = AuxChanVals[vTxPowerKnobChannel]+1000;
if(vTxPowerKnobChannel > -1 && failSafeState < 10 && ((AuxChanVals[vTxPowerKnobChannel]+1000 != vTxPowerKnobLastPPM) || vTxPowerActive))
{
if((!vTxPowerActive || AuxChanVals[vTxPowerKnobChannel]+1000 != vTxPowerKnobLastPPM) && armed == 0)
{
if(!vTxPowerActive)
{
logoDone = true;
cleanScreen();
}
vTxPowerTime = _millis;
vTxPowerActive = true;
vTxPowerKnobLastPPM = AuxChanVals[vTxPowerKnobChannel]+1000;
}
else
{
if(_millis - vTxPowerTime > 1000 || armed > 0)
{
vTxPowerActive = false;
cleanScreen();
}
}
if(vTxPowerActive)
{
static const char VTX_POWER_STATE[] PROGMEM = "vtx power:";
OSD.printP(settings.COLS/2 - strlen_P(VTX_POWER_STATE)/2, settings.ROWS/2, VTX_POWER_STATE);
static const char suffix[] = "mw";
uint8_t maxMWmult = 60;
if(vTxType > 2)
{
maxMWmult = 80;
}
if(settings.s.m_vTxMaxPower > 0) maxMWmult = (uint8_t)(settings.s.m_vTxMaxPower/(int16_t)10);
int16_t currentVTXPower = ((vTxPowerKnobLastPPM/(int16_t)20)*(int16_t)maxMWmult)/(int16_t)10;
OSD.printInt16(settings.COLS/2 - 2, settings.ROWS/2+1, currentVTXPower, 0, suffix, 1);
}
}
#endif
#endif
//OSD.printInt16(0, settings.ROWS/2, settings.s.m_stats, 0);
if(!vTxPowerActive && DV_change_time == 0 && armed == 0 && armedOnce && time > 0)
{
switch(settings.s.m_stats)
{
case 1:
statsActive = true;
break;
case 2:
if(code & inputChecker.ROLL_RIGHT)
{
cleanScreen();
statsActive = false;
}
if(code & inputChecker.ROLL_LEFT)
{
cleanScreen();
statsActive = true;
}
break;
}
}
else statsActive = false;
statMAH = LipoMAH+previousMAH;
if(statsActive)
{
if(code & inputChecker.PITCH_UP && statPage > 0)
{
statPage--;
cleanScreen();
}
#ifdef ADVANCED_STATS
uint8_t maxPages = 5;
#else
uint8_t maxPages = 4;
#endif
if(code & inputChecker.PITCH_DOWN && statPage < maxPages)
{
statPage++;
cleanScreen();
}
uint8_t middle_infos_y = 1;
static const char STATS_STR[] PROGMEM = "stats ";
OSD.printInt16P( settings.COLS/2 - (strlen_P(STATS_STR)+4)/2, middle_infos_y, STATS_STR, statPage+1, 0);
#ifdef ADVANCED_STATS
OSD.print( fixStr("/6") );
#else
OSD.print( fixStr("/5") );
#endif
middle_infos_y++;
uint8_t statCol, j;
int16_t avgTotal = 0;
switch(statPage)
{
case 0:
static const char TIME_STR[] PROGMEM = "time : ";
static const char MAX_AMP_STR[] PROGMEM = "max amps : ";
#ifdef ADVANCED_ESC_STATS
static const char MAX_AVG_STR[] PROGMEM = "max avg : ";
#endif
static const char MIN_V_STR[] PROGMEM = "min v : ";
static const char MAX_WATT_STR[] PROGMEM = "max watt : ";
static const char MAX_C_STR[] PROGMEM = "c rating : ";
static const char MAH_STR[] PROGMEM = "mah : ";
static const char MAX_RPM_STR[] PROGMEM = "max rpm : ";
static const char MAX_TEMP_STR[] PROGMEM = "max temp : ";
static const char MIN_RSSI_STR[] PROGMEM = "min rssi : ";
statCol = settings.COLS/2 - (strlen_P(TIME_STR)+7)/2;
OSD.printP(statCol, ++middle_infos_y, TIME_STR);
OSD.printTime( statCol+strlen_P(TIME_STR), middle_infos_y, total_time);
OSD.printInt16P( statCol, ++middle_infos_y, MAX_AMP_STR, MaxAmps, 2, "a" );
#ifdef ADVANCED_ESC_STATS
for(i=0; i<4; i++) avgTotal += ESCstatGenerators[i].GetAverage();
OSD.printInt16P( statCol, ++middle_infos_y, MAX_AVG_STR, avgTotal, 2, "a" );
#endif
OSD.printInt16P( statCol, ++middle_infos_y, MIN_V_STR, MinBat, 2, "v" );
OSD.printInt16P( statCol, ++middle_infos_y, MAX_WATT_STR, MaxWatt, 1, "w" ); //OSD.printInt16( OSD.cursorRow()+1, middle_infos_y, settings.s.m_maxWatts, 1, "w)", 0, 0, "(" );
OSD.printInt16P( statCol, ++middle_infos_y, MAX_C_STR, MaxC, 0, "c");
OSD.printInt16P( statCol, ++middle_infos_y, MAH_STR, statMAH, 0, "mah" );
OSD.printInt16P( statCol, ++middle_infos_y, MAX_RPM_STR, MaxRPMs, 1, "kr" );
OSD.printInt16P( statCol, ++middle_infos_y, MAX_TEMP_STR, MaxTemp, 0, tempSymbol);
if(settings.s.m_RSSIchannel > -1)
{
char *suffix;
char DB_suffix[] = "db";
suffix = DB_suffix;
char PERC_suffix[] = "%";
if(settings.s.m_RSSImax > settings.s.m_RSSImin)
{
suffix = PERC_suffix;
}
OSD.printInt16P( statCol, ++middle_infos_y, MIN_RSSI_STR, MinRSSI, 0, suffix);
}
OSD.printInt16( 0, 1, LipoVoltage, 2, "v");
break;
case 1:
#ifdef ADVANCED_STATS
static const char STAT_GEN_STRS[][17] PROGMEM = { {"5-20 thr avg: "},
{"20-40 thr avg: "},
{"40-60 thr avg: "},
{"60-80 thr avg: "},
{"80-100 thr avg: "},
{"95-100 thr avg: "},
{"5-20 thr max: "},
{"20-40 thr max: "},
{"40-60 thr max: "},
{"60-80 thr max: "} };
statCol = settings.COLS/2 - (strlen_P(STAT_GEN_STRS[0])+7)/2;
j = 0;
for(i=0; i<MAX_SETTING_MODES; i++)
{
OSD.printInt16P( statCol, ++middle_infos_y, STAT_GEN_STRS[j], statGenerators[i].GetAverage(), 2, "a" );
j++;
}
for(i=0; i<4; i++)
{
OSD.printInt16P( statCol, ++middle_infos_y, STAT_GEN_STRS[j], statGenerators[i].m_Max, 2, "a" );
j++;
}
break;
#endif
case 2:
case 3:
case 4:
case 5:
char* ESC_STAT_STR = ESC_STAT_STR1;
if(settings.s.m_displaySymbols == 1 && settings.m_IconSettings[ESC_ICON] == 1)
{
ESC_STAT_STR = ESCSymbol;
}
static const char ESC_A_STR[] PROGMEM = " max a : ";
#ifdef ADVANCED_ESC_STATS
static const char ESC_AVG_MAX_A_STR[] PROGMEM = " avg max : ";
#endif
static const char ESC_MINV_STR[] PROGMEM = " min v : ";
static const char ESC_RPM_STR[] PROGMEM = " max rpm : ";
static const char ESC_TEMP_STR[] PROGMEM = " max temp: ";
static const char ESC_MAH_STR[] PROGMEM = " mah : ";
uint8_t startCol = settings.COLS/2 - (strlen_P(ESC_RPM_STR)+strlen(ESC_STAT_STR)+7)/2;
#ifdef ADVANCED_STATS
uint8_t ESCnumber = statPage - 1;
#else
uint8_t ESCnumber = statPage;
#endif
#ifdef BF32_MODE
uint8_t ESCLookup = (ESCnumber+1)%4;
#else
uint8_t ESCLookup = ESCnumber-1;
#endif
OSD.printInt16( startCol, ++middle_infos_y, ESC_STAT_STR, ESCnumber, 0);
OSD.printInt16P( startCol + strlen(ESC_STAT_STR) + 1, middle_infos_y, ESC_A_STR, maxCurrent[ESCLookup], 2, "a");
#ifdef ADVANCED_ESC_STATS
OSD.printInt16( startCol, ++middle_infos_y, ESC_STAT_STR, ESCnumber, 0);
OSD.printInt16P( startCol + strlen(ESC_STAT_STR) + 1, middle_infos_y, ESC_AVG_MAX_A_STR, ESCstatGenerators[ESCLookup].GetAverage(), 2, "a");
#endif
OSD.printInt16( startCol, ++middle_infos_y, ESC_STAT_STR, ESCnumber, 0);
OSD.printInt16P( startCol + strlen(ESC_STAT_STR) + 1, middle_infos_y, ESC_MINV_STR, minVoltage[ESCLookup], 2, "v");
OSD.printInt16( startCol, ++middle_infos_y, ESC_STAT_STR, ESCnumber, 0);
OSD.printInt16P( startCol + strlen(ESC_STAT_STR) + 1, middle_infos_y, ESC_RPM_STR, maxKERPM[ESCLookup], 1, "kr");
OSD.printInt16( startCol, ++middle_infos_y, ESC_STAT_STR, ESCnumber, 0);
OSD.printInt16P( startCol + strlen(ESC_STAT_STR) + 1, middle_infos_y, ESC_TEMP_STR, maxTemps[ESCLookup], 0, tempSymbol);
OSD.printInt16( startCol, ++middle_infos_y, ESC_STAT_STR, ESCnumber, 0);
OSD.printInt16P( startCol + strlen(ESC_STAT_STR) + 1, middle_infos_y, ESC_MAH_STR, ESCmAh[ESCLookup], 0, "mah");
break;
}
}
else
{
#ifdef SIMULATE_VALUES
static int16_t currentRT2 = 0;
static int16_t LipoMAH2 = 0;
static int16_t rssi2 = 0;
if(doItOnce && timer1sec)
{
currentRT2 += 50;
if(currentRT2 > 1000) currentRT2 = 0;
LipoMAH2 += 100;
if(LipoMAH2 > settings.s.m_batMAH[settings.s.m_activeBattery]) LipoMAH2 = 0;
rssi2 += 10;
if(rssi2 > 100) rssi2 = 0;
doItOnce = false;
}
if(!timer1sec) doItOnce = true;
currentRT = currentRT2;
LipoMAH = LipoMAH2;
if(settings.s.m_RSSIchannel < 4) AuxChanVals[settings.s.m_RSSIchannel] = rssi2;
#endif
printCount = 0;
if(armed == 0 && armedOnce && last_Aux_Val != AuxChanVals[settings.s.m_DVchannel])
{
DV_change_time = _millis;
last_Aux_Val = AuxChanVals[settings.s.m_DVchannel];
}
if(AuxChanVals[settings.s.m_DVchannel] > DV_PPMs[DISPLAY_RC_THROTTLE])
{
printCount++;
char *suffix;
char PERC_suffix[] = "%";
suffix = PERC_suffix;
char T_suffix[] = "%t";
if(settings.s.m_RSSImax > settings.s.m_RSSImin)
{
suffix = T_suffix;
}
OSD.printInt16( settings.m_OSDItems[THROTTLE][0], settings.m_OSDItems[THROTTLE][1], throttle, 0, suffix, 2, THROTTLEp);
}
if(AuxChanVals[settings.s.m_DVchannel] > DV_PPMs[DISPLAY_NICKNAME])
{
printCount++;
OSD.checkPrintLength(settings.m_OSDItems[NICKNAME][0], settings.m_OSDItems[NICKNAME][1], strlen(settings.s.m_nickname), zeroBlanks, NICKNAMEp);
OSD.print( fixStr(settings.s.m_nickname) );
}
if(AuxChanVals[settings.s.m_DVchannel] > DV_PPMs[DISPLAY_COMB_CURRENT])
{
printCount++;
#ifdef WATTMETER
if(settings.s.m_wattMeter > 0)
{
const int16_t wattPercentage = 20; //95% of max
uint32_t Watts = (uint32_t)LipoVoltage * (uint32_t)current;
int16_t tempWatt = (int16_t)(Watts/1000);
if(settings.s.m_displaySymbols == 1 && settings.m_IconSettings[WATT_ICON] == 1)
{
int8_t wattRow2 = settings.m_OSDItems[AMPS][1]-1;
if(wattRow2 < 0) wattRow2 = 0;
int8_t wattRow1 = wattRow2 + 1;
uint8_t steps;
switch(settings.s.m_wattMeter)
{
case 1:
#ifndef BEERMUG
case 2:
#endif
iconPrintBuf1[0] = 0xD7;
iconPrintBuf2[0] = 0xE3;
steps = 8;
break;
#ifdef BEERMUG
case 2:
iconPrintBuf1[0] = 0x01;
iconPrintBuf2[0] = 0x09;
steps = 6;
wattRow1--;
wattRow2++;
break;
#endif
}
getIconPos(tempWatt, settings.s.m_maxWatts - settings.s.m_maxWatts/wattPercentage, steps, iconPrintBuf1[0], iconPrintBuf2[0], 2);
if((uint8_t)iconPrintBuf2[0] > 0xE3) iconPrintBuf1[0] = 0xE1;
if((uint8_t)iconPrintBuf1[0] == 0x07 && (uint8_t)iconPrintBuf2[0] == 0x09) iconPrintBuf2[0] = 0x0B;
iconPrintBuf1[1] = iconPrintBuf1[0] + 1;
iconPrintBuf2[1] = iconPrintBuf2[0] + 1;
OSD.checkPrintLength(settings.m_OSDItems[AMPS][0], wattRow1, 2, zeroBlanks, AMPSp);
OSD.print(iconPrintBuf1);
OSD.checkPrintLength(settings.m_OSDItems[AMPS][0], wattRow2, 2, zeroBlanks, AMPSp);
OSD.print(iconPrintBuf2);
}
else
{
tempWatt /= 10;
if(tempWatt > 1000) OSD.printInt16(settings.m_OSDItems[AMPS][0], settings.m_OSDItems[AMPS][1], tempWatt/100, 1, "kw", 1, AMPSp);
else OSD.printInt16(settings.m_OSDItems[AMPS][0], settings.m_OSDItems[AMPS][1], tempWatt, 0, "w", 1, AMPSp);
}
}
else
#endif
{
OSD.printInt16(settings.m_OSDItems[AMPS][0], settings.m_OSDItems[AMPS][1], current/10, 1, "a", 2, AMPSp);
}
}
if(AuxChanVals[settings.s.m_DVchannel] > DV_PPMs[DISPLAY_LIPO_VOLTAGE])
{
printCount++;
OSD.printInt16( settings.m_OSDItems[VOLTAGE][0], settings.m_OSDItems[VOLTAGE][1], LipoVoltage / 10, 1, "v", 1, VOLTAGEp);
}
if(AuxChanVals[settings.s.m_DVchannel] > DV_PPMs[DISPLAY_MA_CONSUMPTION])
{
printCount++;
#ifdef _MAH_ICON
if(settings.s.m_displaySymbols == 1 && settings.m_IconSettings[MAH_ICON] == 1)
{
batteryIcon[1] = 0x84;
batteryIcon[2] = 0x84;
remainMAH = settings.s.m_batMAH[settings.s.m_activeBattery]-statMAH;
if(statMAH > settings.s.m_batMAH[settings.s.m_activeBattery]) remainMAH = 0;
getIconPos(remainMAH, settings.s.m_batMAH[settings.s.m_activeBattery], 8, batteryIcon[2], batteryIcon[1]);
OSD.checkPrintLength(settings.m_OSDItems[MAH][0], settings.m_OSDItems[MAH][1], 4, zeroBlanks, MAHp);
OSD.print(batteryIcon);
}
else
#endif
{
OSD.printInt16(settings.m_OSDItems[MAH][0], settings.m_OSDItems[MAH][1], statMAH, 0, "mah", 0, MAHp);
}
}
if(settings.s.m_displaySymbols == 1 && settings.m_IconSettings[ESC_ICON] == 1)
{
ESCSymbol[0] = fixChar((char)0x7E);
}
else
{
ESCSymbol[0] = 0x00;
}
uint8_t TMPmargin = 0;
uint8_t CurrentMargin = 0;
if(AuxChanVals[settings.s.m_DVchannel] > DV_PPMs[DISPLAY_ESC_KRPM])
{
printCount++;
#ifdef PROP_ICON
static char KR[4][2];
if(settings.s.m_displaySymbols == 1 && settings.m_IconSettings[PROPS_ICON] == 1)
{
for(i=0; i<4; i++)
{
if(_millis - krTime[i] > (10000/motorKERPM[i]))
{
krTime[i] = _millis;
if((i+1)%2 == 0)
{
krSymbol[i]--;
}
else
{
krSymbol[i]++;
}
if(krSymbol[i] > 0xA3)
{
krSymbol[i] = 0x9C;
}
if(krSymbol[i] < 0x9C)
{
krSymbol[i] = 0xA3;
}
}
KR[i][0] = (char)krSymbol[i];
KR[i][1] = 0x00;
}
OSD.checkPrintLength(settings.m_OSDItems[ESC1kr][0], settings.m_OSDItems[ESC1kr][1], 1, zeroBlanks, ESC1kr);
OSD.print(KR[0]);
OSD.checkPrintLength(settings.m_OSDItems[ESC2kr][0], settings.m_OSDItems[ESC2kr][1], 1, zeroBlanks, ESC2kr);
OSD.print(KR[1]);
OSD.checkPrintLength(settings.m_OSDItems[ESC3kr][0], settings.m_OSDItems[ESC3kr][1], 1, zeroBlanks, ESC3kr);
OSD.print(KR[2]);
OSD.checkPrintLength(settings.m_OSDItems[ESC4kr][0], settings.m_OSDItems[ESC4kr][1], 1, zeroBlanks, ESC4kr);
OSD.print(KR[3]);
}
else
#endif
{
static char KR2[4];
KR2[0] = 'k';
KR2[1] = 'r';
KR2[2] = 0x00;
KR2[3] = 0x00;
OSD.printInt16(settings.m_OSDItems[ESC1kr][0], settings.m_OSDItems[ESC1kr][1], motorKERPM[0], 1, KR2, 1, ESC1kr, ESCSymbol);
KR2[2] = ESCSymbol[0];
OSD.printInt16(settings.m_OSDItems[ESC2kr][0], settings.m_OSDItems[ESC2kr][1], motorKERPM[1], 1, KR2, 1, ESC2kr);
OSD.printInt16(settings.m_OSDItems[ESC3kr][0], settings.m_OSDItems[ESC3kr][1], motorKERPM[2], 1, KR2, 1, ESC3kr);
KR2[2] = 0x00;
OSD.printInt16(settings.m_OSDItems[ESC4kr][0], settings.m_OSDItems[ESC4kr][1], motorKERPM[3], 1, KR2, 1, ESC4kr, ESCSymbol);
}
TMPmargin++;
CurrentMargin++;
}
if(AuxChanVals[settings.s.m_DVchannel] > DV_PPMs[DISPLAY_ESC_CURRENT])
{
printCount++;
static char ampESC[3];
ampESC[0] = 'a';
ampESC[1] = ESCSymbol[0];
ampESC[2] = 0x00;
OSD.printInt16(settings.m_OSDItems[ESC1voltage][0], settings.m_OSDItems[ESC1voltage][1]+CurrentMargin, motorCurrent[0]/10, 1, "a", 1, ESC1voltage, ESCSymbol);
OSD.printInt16(settings.m_OSDItems[ESC2voltage][0], settings.m_OSDItems[ESC2voltage][1]+CurrentMargin, motorCurrent[1]/10, 1, ampESC, 1, ESC2voltage);
OSD.printInt16(settings.m_OSDItems[ESC3voltage][0], settings.m_OSDItems[ESC3voltage][1]-CurrentMargin, motorCurrent[2]/10, 1, ampESC, 1, ESC3voltage);
OSD.printInt16(settings.m_OSDItems[ESC4voltage][0], settings.m_OSDItems[ESC4voltage][1]-CurrentMargin, motorCurrent[3]/10, 1, "a", 1, ESC4voltage, ESCSymbol);
TMPmargin++;
}
if(AuxChanVals[settings.s.m_DVchannel] > DV_PPMs[DISPLAY_ESC_TEMPERATURE])
{
printCount++;
static char tempESC[3];
tempESC[0] = tempSymbol[0];
tempESC[1] = ESCSymbol[0];
tempESC[2] = 0x00;
OSD.printInt16(settings.m_OSDItems[ESC1temp][0], settings.m_OSDItems[ESC1temp][1]+TMPmargin, ESCTemps[0], 0, tempSymbol, 1, ESC1temp, ESCSymbol);
OSD.printInt16(settings.m_OSDItems[ESC2temp][0], settings.m_OSDItems[ESC2temp][1]+TMPmargin, ESCTemps[1], 0, tempESC, 1, ESC2temp);
OSD.printInt16(settings.m_OSDItems[ESC3temp][0], settings.m_OSDItems[ESC3temp][1]-TMPmargin, ESCTemps[2], 0, tempESC, 1, ESC3temp);
OSD.printInt16(settings.m_OSDItems[ESC4temp][0], settings.m_OSDItems[ESC4temp][1]-TMPmargin, ESCTemps[3], 0, tempSymbol, 1, ESC4temp, ESCSymbol);
}
if(AuxChanVals[settings.s.m_DVchannel] > DV_PPMs[DISPLAY_TIMER])
{
printCount++;
static char stopWatchStr[] = { 0x00, 0x00 };
#ifdef STOPWATCH_ICON
if(settings.s.m_displaySymbols == 1 && settings.m_IconSettings[TIMER_ICON] == 1)
{
if(time - old_time > 1000)
{
stopWatch++;
old_time = time;
}
if(stopWatch > 0x9B)
{
stopWatch = 0x94;
}
stopWatchStr[0] = stopWatch;
}
else
{
stopWatchStr[0] = 0x00;
}
#endif
if(settings.s.m_timerMode == 2 && (time / 1000) > 109)
{
OSD.blink1sec();
}
OSD.printTime(settings.m_OSDItems[STOPW][0], settings.m_OSDItems[STOPW][1], time, stopWatchStr, STOPWp);
}
#ifdef CROSSHAIR
if(settings.s.m_crossHair && (logoDone || armed > 0) && !vTxPowerActive)
{
int8_t crossOffset = 0;
if(settings.s.m_crossHair > 1) crossOffset = (int8_t)settings.s.m_crossHair - (int8_t)5;
OSD.setCursor(settings.COLS/2 - 1, (int8_t)(settings.ROWS/2) + crossOffset);
#ifdef CROSSHAIR_ANGLE
uint8_t crossHairPos = 0;
int8_t angleOffset = settings.s.m_angleOffset;
if(angleY > (75+angleOffset) && angleY < (106+angleOffset))
{
if(angleY > (85+angleOffset) && angleY < (96+angleOffset)) crossHairPos = 3;
if(angleY < (86+angleOffset)) crossHairPos = 2 - (((85+angleOffset) - angleY) / 5);
if(angleY > (95+angleOffset)) crossHairPos = 5 - (((105+angleOffset) - angleY) / 5);
}
if(angleY > (105+angleOffset)) crossHairPos = 6;
OSD.print(crossHairSymbols[crossHairPos]);
//OSD.printInt16(0, settings.ROWS/2, angleY, 0, "", 1);
#else
OSD.print(crossHairSymbol);
#endif
}
#endif
#ifdef RSSI_
if(settings.s.m_RSSIchannel > -1)
{
if(settings.s.m_RSSIchannel < 4) rssiVal = AuxChanVals[settings.s.m_RSSIchannel];
if (rssiVal > 100 || settings.s.m_RSSImax > settings.s.m_RSSImin)
{
if (settings.s.m_RSSImax > settings.s.m_RSSImin)
{
if ((rssiVal + 1000) <= settings.s.m_RSSImin) rssiVal = 0;
else rssiVal = (((uint32_t)((uint32_t)rssiVal + (uint32_t)1000) - (uint32_t)settings.s.m_RSSImin)*(uint32_t)100) / (uint32_t)(settings.s.m_RSSImax - settings.s.m_RSSImin);
}
else while (rssiVal > 120) rssiVal /= 10;
}
if (rssiVal < 0) rssiVal = 0;
rssiVal = rssiFilter.ProcessValue(rssiVal);
if(MinRSSI > rssiVal && armedOnce) MinRSSI = rssiVal;
}
if(settings.s.m_RSSIchannel > -1 && AuxChanVals[settings.s.m_DVchannel] > DV_PPMs[DISPLAY_RSSI])
{
//OSD.printInt16(0, settings.ROWS/2, rssiVal, 0, "db", 1);
printCount++;
if(rssiVal < 45 && timer1sec)
{
uint8_t spaces = 5;
if(settings.s.m_displaySymbols == 1 && settings.m_IconSettings[RSSI_ICON] == 1) spaces = 2;
OSD.checkPrintLength(settings.m_OSDItems[RSSIp][0], settings.m_OSDItems[RSSIp][1], 2, zeroBlanks, RSSIp);
OSD.printSpaces(spaces);
}
else
{
#ifdef _RSSI_ICON
if(settings.s.m_displaySymbols == 1 && settings.m_IconSettings[RSSI_ICON] == 1)
{
static const uint8_t maxRSSIvalue = 50;
iconPrintBuf1[0] = 0x12;
iconPrintBuf1[1] = 0x15;
rssiVal -= 30;
getIconPos(rssiVal, maxRSSIvalue, 5, iconPrintBuf1[0], iconPrintBuf1[1]);
if(iconPrintBuf1[0] < 0x14) iconPrintBuf1[1] = 0x20;
OSD.checkPrintLength(settings.m_OSDItems[RSSIp][0], settings.m_OSDItems[RSSIp][1], 2, zeroBlanks, RSSIp);
OSD.print(iconPrintBuf1);
}
else
#endif
{
char *suffix;
char DB_suffix[] = "db";
suffix = DB_suffix;
char PERC_suffix[] = "%";
if(settings.s.m_RSSImax > settings.s.m_RSSImin)
{
suffix = PERC_suffix;
}
OSD.printInt16(settings.m_OSDItems[RSSIp][0], settings.m_OSDItems[RSSIp][1], rssiVal, 0, suffix, 1, RSSIp);
}
}
}
#endif
if(settings.s.m_batWarning > 0 && statMAH >= settings.s.m_batWarningMAH)
{
totalMAH = 0;
static const char BATTERY_LOW[] PROGMEM = "battery low";
if(timer1sec)
{
if(batWarnSymbol)
{
if(settings.s.m_displaySymbols == 1)// && settings.m_IconSettings[MAH_ICON] == 1)
{
OSD.setCursor(settings.COLS/2 - 2, settings.ROWS/2 + 3);
OSD.print(batteryIcon);
}
else
{
OSD.printP(settings.COLS/2 - strlen_P(BATTERY_LOW)/2, settings.ROWS/2 +3, BATTERY_LOW);
}
}
else
{
OSD.printInt16(settings.COLS/2 - 3, settings.ROWS/2 + 3, statMAH, 0, "mah");
}
flipOnce = true;
}
else
{
if(flipOnce)
{
batWarnSymbol = !batWarnSymbol;
flipOnce = false;
}
OSD.printSpaces(settings.COLS/2 - strlen_P(BATTERY_LOW)/2, settings.ROWS/2 +3, 11);
}
}
else
{
if(settings.s.m_batWarning > 0)
{
totalMAH = statMAH;
}
else
{
totalMAH = 0;
}
}
#ifdef ARMING_STATUS
if(armed > 0 && _millis - armingStatusChangeTime > 1000 && armed != 3)
#else
if(armed > 0)
#endif
{
if(settings.s.m_voltWarning > 0 && settings.s.m_minVolts > (LipoVoltage / 10) && !timer1sec)
{
OSD.printInt16(settings.COLS/2 - 3, settings.ROWS/2 + 2, LipoVoltage / 10, 1, "v", 1);
}
else
{
OSD.printSpaces(settings.COLS/2 - 3, settings.ROWS/2 + 2, 5);
}
}
if(DV_change_time > 0 && (_millis - DV_change_time) > 3000 && last_Aux_Val == AuxChanVals[settings.s.m_DVchannel])
{
DV_change_time = 0;
cleanScreen();
}
if(symbolOnOffChanged)
{
cleanScreen();
settings.fixColBorders();
symbolOnOffChanged = false;
}
}
}
}
#ifdef DEBUG
int freeRam() {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
#endif
| 35.564072
| 196
| 0.582351
|
e483c878c2e3f46901a9be8494eecb1078ff117e
| 865
|
ino
|
Arduino
|
examples/sender.ino
|
NAzT/ESPNowW
|
baba71ed6bdc84c967b9dd2c30a0efe52de020b4
|
[
"Beerware"
] | 12
|
2019-02-04T14:19:11.000Z
|
2022-03-25T07:09:42.000Z
|
examples/sender.ino
|
NAzT/ESPNowW
|
baba71ed6bdc84c967b9dd2c30a0efe52de020b4
|
[
"Beerware"
] | null | null | null |
examples/sender.ino
|
NAzT/ESPNowW
|
baba71ed6bdc84c967b9dd2c30a0efe52de020b4
|
[
"Beerware"
] | 3
|
2019-02-08T07:55:08.000Z
|
2021-10-07T23:31:50.000Z
|
/*
* "THE BEER-WARE LICENSE" (Revision 42):
* regenbogencode@gmail.com wrote this file. As long as you retain this notice
* you can do whatever you want with this stuff. If we meet some day, and you
* think this stuff is worth it, you can buy me a beer in return
*/
#include <Arduino.h>
#ifdef ESP8266
#include <ESP8266WiFi.h>
#elif ESP32
#include <WiFi.h>
#endif
#include "ESPNowW.h"
uint8_t receiver_mac[] = {0x36, 0x33, 0x33, 0x33, 0x33, 0x33};
void setup() {
Serial.begin(115200);
Serial.println("ESPNow sender Demo");
#ifdef ESP8266
WiFi.mode(WIFI_STA); // MUST NOT BE WIFI_MODE_NULL
#elif ESP32
WiFi.mode(WIFI_MODE_STA);
#endif
WiFi.disconnect();
ESPNow.init();
ESPNow.add_peer(receiver_mac);
}
void loop() {
static uint8_t a = 0;
delay(100);
ESPNow.send_message(receiver_mac, &a, 1);
Serial.println(a++);
}
| 24.714286
| 78
| 0.684393
|
b8447e00266483fc63bd6b0e1564987e23798fbf
| 4,375
|
ino
|
Arduino
|
MCU/v43z-test-suite3/DeviceInfo.ino
|
danielkucera/RatatoskrIoT
|
d174414085b317ffe74eddb6b8230e717c849f33
|
[
"Apache-2.0"
] | null | null | null |
MCU/v43z-test-suite3/DeviceInfo.ino
|
danielkucera/RatatoskrIoT
|
d174414085b317ffe74eddb6b8230e717c849f33
|
[
"Apache-2.0"
] | null | null | null |
MCU/v43z-test-suite3/DeviceInfo.ino
|
danielkucera/RatatoskrIoT
|
d174414085b317ffe74eddb6b8230e717c849f33
|
[
"Apache-2.0"
] | null | null | null |
#include "DeviceInfo.h"
#if defined(ESP32)
#include <ESP.h>
extern "C" {
#include <esp_spiram.h>
#include <esp_himem.h>
}
void formatMemorySize( char * ptr, long msize )
{
float out;
char * jednotka;
if( msize > 1048576 ) {
out = ((float)msize) / 1048576.0;
jednotka = (char*)"MB";
} else if( msize > 1024 ) {
out = ((float)msize) / 1024.0;
jednotka = (char*)"kB";
} else if( msize > 0 ) {
out = ((float)msize);
jednotka = (char*)"B";
} else {
out = 0;
}
if( out>0 ) {
sprintf( ptr, "%.1f %s", out, jednotka );
} else {
strcpy( ptr, "--" );
}
}
#define LOW_PSRAM_ONLY
void formatDeviceInfo( char * out )
{
strcpy( out, "RAM " );
formatMemorySize( out+strlen(out), ESP.getHeapSize() );
#ifdef LOW_PSRAM_ONLY
strcat( out, "; PSRAM " );
formatMemorySize( out+strlen(out), ESP.getPsramSize() );
#else
long psramtotal = esp_spiram_get_size();
strcat( out, "; PSRAM [" );
formatMemorySize( out+strlen(out), psramtotal );
if( psramtotal>0 ) {
strcat( out, ": low: " );
formatMemorySize( out+strlen(out), ESP.getPsramSize() );
strcat( out, ", high: " );
formatMemorySize( out+strlen(out), esp_himem_get_phys_size() );
}
strcat( out, "]" );
#endif
sprintf( out+strlen(out), "; CPUr%d %d MHz; flash %d MHz; RA %s",
ESP.getChipRevision(),
ESP.getCpuFreqMHz(),
(ESP.getFlashChipSpeed()/1000000),
RA_CORE_VERSION
);
}
/*
const char * wakeupReasonText( int wakeup_reason )
{
switch(wakeup_reason)
{
case 1 : return "external RTC_IO";
case 2 : return "external RTC_CNTL");
case 3 : return "timer");
case 4 : return "touchpad");
case 5 : return "ULP program");
default : return "deep sleep");
}
}
*/
#endif
/**
* Pokud nejde o probuzeni po deep sleepu, vypise informaci o duvodu restartu, aplikaci a ESP cipu.
*
* Zapise kod typu restartu do globalni promenne 'wakeupReason'
* a do 'deepSleepStart' zapise bool, zda jde o probuzeni z deep sleep.
*/
void read_wakeup_and_print_startup_info( bool print, const char * appInfo )
{
#if defined(ESP8266)
// https://www.espressif.com/sites/default/files/documentation/esp8266_reset_causes_and_common_fatal_exception_causes_en.pdf
wakeupReason = ESP.getResetInfoPtr()->reason;
if( wakeupReason != 5 ) {
deepSleepStart = false;
if( print ) {
// pokud to NENI probuzeni po deep sleep, vypiseme info
logger->log( "rst rsn %d; CPU %d MHz; RA %s", wakeupReason, ESP.getCpuFreqMHz(), RA_CORE_VERSION );
logger->log( "app: %s", appInfo );
}
} else {
deepSleepStart = true;
}
#elif defined(ESP32)
esp_sleep_wakeup_cause_t wakeup_reason = esp_sleep_get_wakeup_cause();
wakeupReason = (int)wakeup_reason;
if( wakeupReason!=4 ) {
// pokud to NENI probuzeni po deep sleep, vypiseme info
deepSleepStart = false;
if( print ) {
char buff[120];
formatDeviceInfo( buff );
logger->log( "rst rsn %d; %s", wakeupReason, buff );
logger->log( "app: %s", appInfo );
}
} else {
deepSleepStart = true;
}
#endif
}
/**
* Vraci preklad wifi statusu na text.
* Pole 'desc' musi mit alespon 32 byte
*/
char * getWifiStatusText( int status, char * desc )
{
switch ( status ) {
case WL_IDLE_STATUS: strcpy( desc, (char*)"IDLE" ); break; // ESP32, = 0
case WL_NO_SSID_AVAIL: strcpy( desc, (char*)"NO_SSID" ); break; // WL_NO_SSID_AVAIL = 1,
case WL_SCAN_COMPLETED: strcpy( desc, (char*)"SCAN_COMPL" ); break; // WL_SCAN_COMPLETED = 2,
case WL_CONNECT_FAILED: strcpy( desc, (char*)"CONN_FAIL" ); break; // WL_CONNECT_FAILED = 4,
case WL_CONNECTION_LOST: strcpy( desc, (char*)"CONN_LOST" ); break; // WL_CONNECTION_LOST = 5,
case WL_DISCONNECTED: strcpy( desc, (char*)"DISC" ); break; // WL_DISCONNECTED = 6
case WL_NO_SHIELD: strcpy( desc, (char*)"NO_SHIELD" ); break; // ESP32, = 255
case WIFI_POWER_OFF: strcpy( desc, (char*)"OFF" ); break;
default: sprintf( desc, "%d", status ); break;
}
return desc;
}
| 28.782895
| 128
| 0.586057
|
5f51b693f855c82dc56f446760581302aa7c4626
| 3,580
|
ino
|
Arduino
|
arduino_codes/_2ultrasonis_servo_DC-v2.ino
|
montaserFath/Wheelchair-controlled-by-Brain-Signal
|
b32f1f5c1964e12aebbf2fa72a17ebf0d4d7a261
|
[
"MIT"
] | 1
|
2020-06-27T10:20:33.000Z
|
2020-06-27T10:20:33.000Z
|
arduino_codes/_2ultrasonis_servo_DC-v2.ino
|
montaserFath/Wheelchair-controlled-by-Brain-Signal
|
b32f1f5c1964e12aebbf2fa72a17ebf0d4d7a261
|
[
"MIT"
] | null | null | null |
arduino_codes/_2ultrasonis_servo_DC-v2.ino
|
montaserFath/Wheelchair-controlled-by-Brain-Signal
|
b32f1f5c1964e12aebbf2fa72a17ebf0d4d7a261
|
[
"MIT"
] | 1
|
2020-06-27T10:20:43.000Z
|
2020-06-27T10:20:43.000Z
|
#include<Servo.h>
#include "Arduino.h"
class Ultrasonic
{
public:
Ultrasonic(int pin);
void DistanceMeasure(void);
long microsecondsToCentimeters(void);
long microsecondsToInches(void);
private:
int _pin;//pin number of Arduino that is connected with SIG pin of Ultrasonic Ranger.
long duration;// the Pulse time received;
};
Ultrasonic::Ultrasonic(int pin)
{
_pin = 7;
}
/*Begin the detection and get the pulse back signal*/
void Ultrasonic::DistanceMeasure(void)
{
pinMode(_pin, OUTPUT);
digitalWrite(_pin, LOW);
delayMicroseconds(2);
digitalWrite(_pin, HIGH);
delayMicroseconds(5);
digitalWrite(_pin,LOW);
pinMode(_pin,INPUT);
duration = pulseIn(_pin,HIGH);
}
/*The measured distance from the range 0 to 400 Centimeters*/
long Ultrasonic::microsecondsToCentimeters(void)
{
return duration/29/2;
}
/*The measured distance from the range 0 to 157 Inches*/
Ultrasonic ultrasonic(7);
#define trigPin 22
#define echoPin 23
#define trigPin2 24
#define echoPin2 25
long duration1,duration2, front,left , right;
int DC1 = 13;
int DC2 = 12;
int SPEED=11;
Servo myservo;
float a =1.6667;
float b=110;
float angle;
void setup() {
//serial communication
Serial.begin (9600);
//for 2 ultrasonic sensors
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(trigPin2, OUTPUT);
pinMode(echoPin2, INPUT);
//for DC drive
pinMode(DC1, OUTPUT);
pinMode(DC2, OUTPUT);
pinMode(SPEED,OUTPUT);
//for servo motor
myservo.attach(9);
}
void loop() {
///////////////////get front///////////////
right = getRight();
///////////////////get leftt///////////////
left = getLeft();
//////////////////////get right/////////////////
ultrasonic.DistanceMeasure();// get the current signal time;
front= ultrasonic.microsecondsToCentimeters();//convert the time to centimeters
/////////////////print/////////////////
/*
Serial.print("front is ");
Serial.println(front);
Serial.print("right is ");
Serial.println(right);
Serial.print("left is ");
Serial.println(left);
*/
//////////////control///////////////
if ( ultrasonic.microsecondsToCentimeters() <= 30)
{
if ( (getRight() < 30 && getLeft() > 30) || ( getRight() <= 30 && getLeft() <= 30))
{
angle = b-(a*(ultrasonic.microsecondsToCentimeters()));
//left//
myservo.write(angle);
//FORWARD
goFront(255);
delay (550);
//stop
Stop();
myservo.write(50);
//FORWARD
goFront(100);
}
else
{
//right//
angle = -(a*(ultrasonic.microsecondsToCentimeters()));
//left//
myservo.write(angle);
//FORWARD
goFront(255);
delay (550);
//stop
Stop();
myservo.write(50);
//FORWARD
goFront(100);
}
}
else
{
//FORWARD
goFront(100);
}
}
int getRight()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration2 = pulseIn(echoPin, HIGH);
int front1 = (duration2/2) / 29.1;
return(front1);
}
int getLeft()
{
digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
duration1 = pulseIn(echoPin2, HIGH);
int left1 = (duration1/2) / 29.1;
return(left1);
}
void goFront(int Speed)
{
//FORWARD
digitalWrite(DC1,HIGH);
digitalWrite(DC2,LOW);
analogWrite(SPEED,Speed);
}
void Stop()
{
digitalWrite(DC1,LOW);
digitalWrite(DC2,LOW);
}
| 21.183432
| 88
| 0.617877
|
8fb04f04648b3256307ac0a82eb552ad6ee1e605
| 762
|
ino
|
Arduino
|
examples/EntropySeed/EntropySeed.ino
|
pmjdebruijn/Arduino-ArcFour-Library
|
b687f248496c1c88565fe6578236e1c158c1a941
|
[
"MIT"
] | 1
|
2021-01-05T22:00:39.000Z
|
2021-01-05T22:00:39.000Z
|
examples/EntropySeed/EntropySeed.ino
|
pmjdebruijn/Arduino-ArcFour-Library
|
b687f248496c1c88565fe6578236e1c158c1a941
|
[
"MIT"
] | null | null | null |
examples/EntropySeed/EntropySeed.ino
|
pmjdebruijn/Arduino-ArcFour-Library
|
b687f248496c1c88565fe6578236e1c158c1a941
|
[
"MIT"
] | null | null | null |
/*
ArcFour Entropy Seeding Demo
created 10 Jun 2014
by Pascal de Bruijn
*/
#include <Entropy.h>
#include <ArcFour.h>
ArcFour ArcFour;
int ledPin = 13;
void setup()
{
Serial.begin(9600);
while (!Serial)
{
; // wait for serial port to connect. Needed for Leonardo and Due
}
Entropy.initialize();
ArcFour.initialize();
for (int i = 0; i < ARCFOUR_MAX; i++)
{
if (i / 4 % 2)
digitalWrite(ledPin, LOW);
else
digitalWrite(ledPin, HIGH);
ArcFour.seed(i, Entropy.random(WDT_RETURN_BYTE));
}
ArcFour.finalize();
for (int i = 0; i < ARCFOUR_MAX; i++)
{
ArcFour.random();
}
digitalWrite(ledPin, HIGH);
}
void loop()
{
Serial.println(ArcFour.random());
delay(1000);
}
| 14.111111
| 69
| 0.599738
|
780b4bcac424c10f4e37f7cd8b613e9f0a639ecb
| 1,708
|
ino
|
Arduino
|
examples/arduino/arduino.ino
|
brendan0powers/hwplatform
|
25667696d6ccfe08260d2fc742ce9ffdea18d206
|
[
"MIT"
] | 16
|
2021-12-31T20:42:49.000Z
|
2022-02-13T20:23:08.000Z
|
examples/arduino/arduino.ino
|
brendan0powers/bakelite
|
25667696d6ccfe08260d2fc742ce9ffdea18d206
|
[
"MIT"
] | null | null | null |
examples/arduino/arduino.ino
|
brendan0powers/bakelite
|
25667696d6ccfe08260d2fc742ce9ffdea18d206
|
[
"MIT"
] | null | null | null |
#include "proto.h"
// Create an instance of our protocol. Use the Serial port for sending and receiving data.
Protocol proto(
[]() { return Serial.read(); },
[](const char *data, size_t length) { return Serial.write(data, length); }
);
// keep track of how many responses we've set.
int numResponses = 0;
void setup() {
Serial.begin(9600);
// For boards that have a native USB port, wait for the serial device to be initialized.
while(!Serial) {}
// Send a hello message, because, why not?
Ack ack;
ack.code = 42;
strcpy(ack.message, "Hello world!");
proto.send(ack);
}
// Send an error message to the PC for debugging.
void send_err(const char *msg, uint8_t code) {
Ack ack;
ack.code = code;
strcpy(ack.message, msg);
proto.send(ack);
}
void loop() {
// Check and see if a new message has arrived
Protocol::Message messageId = proto.poll();
switch(messageId) {
case Protocol::Message::NoMessage: // Nope, better luch next time
break;
case Protocol::Message::TestMessage: // We received a test message!
{
//Decode the test message
TestMessage msg;
int ret = proto.decode(msg);
if(ret != 0) {
send_err("Decode Failed", ret);
return;
}
// Reply
numResponses++;
Ack ack;
ack.code = numResponses;
snprintf(ack.message, sizeof(ack.message), "a=%d b=%d status=%s msg='%s'", (int)msg.a, (int)msg.b, msg.status ? "true" : "false", msg.message);
ret = proto.send(ack);
if(ret != 0) {
send_err("Send failed", ret);
return;
}
break;
}
default: // Just in case we get something unexpected...
send_err("Unkown message received!", (uint8_t)messageId);
break;
}
}
| 24.4
| 147
| 0.63466
|
4e3bc53cdf2763525e27fbcc9a2744bb62728af7
| 8,340
|
ino
|
Arduino
|
src/AircraftFlightController.ino
|
akashnag/arduino-flight-controller
|
33ec54fe60890d87a672606e8a41d15c3a7b71fc
|
[
"MIT"
] | 2
|
2021-10-05T17:26:49.000Z
|
2022-02-13T06:02:58.000Z
|
src/AircraftFlightController.ino
|
akashnag/arduino-flight-controller
|
33ec54fe60890d87a672606e8a41d15c3a7b71fc
|
[
"MIT"
] | null | null | null |
src/AircraftFlightController.ino
|
akashnag/arduino-flight-controller
|
33ec54fe60890d87a672606e8a41d15c3a7b71fc
|
[
"MIT"
] | null | null | null |
// ---------------------------------------------------------------------------------------------
// Copyright (c) Akash Nag. All rights reserved.
// Licensed under the MIT License. See LICENSE.md in the project root for license information.
// ---------------------------------------------------------------------------------------------
/*
* Arduino On-Board Autonomous Flight Controller for Multi-Propeller Fixed-Wing Cargo Aircraft
* --------------------------------------------------------------------------------------------------
* Normal operation requires:
* 1. Arduino Mega
* 2. BLDC motors
* 3. ESCs
* 4. LiPo battery pack
* 5. Servo motors (for flaps, rudder, ailerons, spoilers, landing-gear, package doors)
* 6. 3-Axis Gyroscope + Accelerometer
* 7. GPS Module
* 8. NRF24L01+ / HC-12 Module
* 9. Barometer
* 10. Magnetometer
* 11. Landing-Gears x 3-sets
* 12. Propellers as required
* 13. Connectors for connecting battery with ESCs
* 14. AA-battery pack/holder for powering Arduino
*/
#include "FlightPlan.h"
#include "Aircraft.h"
#include "AirTrafficControl.h"
#include "ATCCommand.h"
#include "Global.h"
#include "AutoPilot.h"
bool airportDesignated = false;
Airport *airport = NULL;
FlightPlan flightPlan;
Aircraft aircraft;
AirTrafficControl atc;
AutoPilot autoPilot(&aircraft);
void setup()
{
atc.establishCommunication();
aircraft.initControls();
autoPilot.testFlightControls();
}
bool startMission()
{
if(!airportDesignated) return false;
atc.inform("Initiating take-off procedure...");
autoPilot.takeOff();
//atc.inform("Commencing training procedure...");
//autoPilot.train();
//atc.inform("Training complete");
atc.inform("Attempting to reach cruise altitude...");
autoPilot.setAltitude(CRUISE_ALTITUDE);
int maxWaypoints = flightPlan.getWaypointCount();
bool altFlag = false, courseFlag = false;
Waypoint *currentWaypoint;
if(maxWaypoints > 0)
{
bool emergency = false;
for(int i=0; i<maxWaypoints; i++)
{
currentWaypoint = flightPlan.getWaypoint(i);
atc.inform("Setting course to Waypoint #" + i);
autoPilot.setCourse(currentWaypoint->getLocation());
while(autoPilot.getETA() > 2)
{
if(RTB_ON_LOW_FUEL && aircraft.isLowOnFuel())
{
atc.inform("Low fuel warning! Executing emergency RTB procedure...");
emergency = true;
break;
} else if(RTB_ON_LOSS_OF_TELEMETRY && !atc.withinRange()) {
atc.inform("Outside ATC coverage area! Executing emergency RTB procedure...");
emergency = true;
break;
}
do {
courseFlag = autoPilot.keepOnCourse(70);
altFlag = autoPilot.maintainAltitude(70);
} while(!courseFlag || !altFlag);
delay(500);
}
if(emergency) break;
if(currentWaypoint->isDeliveryPoint())
{
atc.inform("Nearing drop location, preparing to drop package...");
aircraft.dropPackage(currentWaypoint->getPackageID());
} else {
atc.inform("Waypoint reached.");
}
}
}
atc.inform("Initiating landing procedure...");
autoPilot.land(*airport);
return true;
}
void startDemoMission()
{
if(!aircraft.isLandingGearDeployed()) return;
// TURN --> CRUISE --> DROP --> repeat
const int turns[] = { 0, -45, -90, -45, 0, -90, -45 };
const int delays[] = { 5, 5, 5, 5, 5, 5, 0 }; // delays (in seconds) AFTER the corresponding turn has been completed
const int dropPoints[] = { -1, -1, -1, 0, -1, -1, -1 }; // drop packages (-1:no, >=0:yes) AFTER the cruise has been completed
const int maxWaypoints = 7;
// TAKEOFF
const float alt = aircraft.getAltitude();
atc.inform("Initiating take-off procedure...");
autoPilot.takeOff();
// CLIMB
atc.inform("Attempting to reach cruise altitude...");
autoPilot.setAltitude(CRUISE_ALTITUDE);
String x;
for(int i=0; i<maxWaypoints; i++)
{
// TURN
if(turns[i] != 0)
{
x = String("Turning ");
x = x + abs(turns[i]) + " degrees " + (turns[i] < 0 ? "left" : "right") + "...";
atc.inform(x);
autoPilot.turn(turns[i]);
}
// CRUISE
int timer=delays[i];
while(timer>0)
{
x = String("Cruising for ");
x = x + timer + " more seconds...";
atc.inform(x);
timer--;
aircraft.refresh();
delay(1000);
}
// DROP
if(dropPoints[i] > -1)
{
x = String("Dropping package #");
x = x + dropPoints[i] + "...";
atc.inform(x);
aircraft.dropPackage(dropPoints[i]);
}
}
// LAND
atc.inform("Preparing to land...");
autoPilot.landImmediately(alt);
}
void loop()
{
aircraft.refresh();
String message;
int fuel, n;
float lat, lon;
int param = 0;
int command = atc.receiveCommand(param);
switch(command)
{
case ATCC_NOCOMM:
break;
case ATCC_HELLO:
atc.inform("Command received: ATCC_HELLO | Hello");
break;
case ATCC_TEST_CONTROLS:
atc.inform("Command received: ATCC_TEST_CONTROLS | Initiating test of flight controls...");
autoPilot.testFlightControls();
atc.inform("Flight-controls test complete");
break;
case ATCC_START_MISSION:
atc.inform("Command received: ATCC_START_MISSION | Starting mission...");
bool flag = startMission();
atc.inform((flag ? "Mission complete" : "Mission failure: no airport designated"));
break;
case ATCC_REPORT_LOCATION_AND_FUEL:
fuel = aircraft.getFuel();
Location loc = aircraft.getLocation();
message = String("Command received: ATCC_REPORT_LOCATION_AND_FUEL | Fuel remaining: ");
message = message + fuel + "%, Coordinates=" + loc.toString();
atc.inform(message);
break;
case ATCC_MARK_CURRENT_LOCATION_AS_AIRPORT:
if(airportDesignated) delete airport;
airport = new Airport(&aircraft.getLocation(), aircraft.getBearing(), aircraft.getAltitude());
airportDesignated = true;
message = String("Command received: ATCC_MARK_CURRENT_LOCATION_AS_AIRPORT | Airport marked at: ");
message = message + airport->location->toString();
atc.inform(message);
break;
case ATCC_ADD_CURRENT_LOCATION_AS_WAYPOINT:
Waypoint wp(Location(aircraft.getLocation()), false, -1);
flightPlan.appendWaypoint(wp);
atc.inform("Command received: ATCC_ADD_CURRENT_LOCATION_AS_WAYPOINT | Waypoint marked");
break;
case ATCC_INSERT_CURRENT_LOCATION_AS_WAYPOINT:
Waypoint wp1(Location(aircraft.getLocation()), false, -1);
flightPlan.insertWaypoint(param,wp1);
atc.inform("Command received: ATCC_INSERT_CURRENT_LOCATION_AS_WAYPOINT | Waypoint inserted");
break;
case ATCC_ADD_CURRENT_LOCATION_AS_DELIVERY_POINT:
Waypoint wp2(Location(aircraft.getLocation()), true, param);
flightPlan.appendWaypoint(wp2);
atc.inform("Command received: ATCC_ADD_CURRENT_LOCATION_AS_DELIVERY_POINT | Delivery point marked");
break;
case ATCC_REMOVE_WAYPOINT:
flightPlan.removeWaypoint(param);
atc.inform("Command received: ATCC_REMOVE_WAYPOINT | Waypoint removed");
break;
case ATCC_CLEAR_FLIGHTPLAN:
flightPlan.clearAll();
atc.inform("Command received: ATCC_CLEAR_FLIGHTPLAN | Flightplan cancelled");
break;
case ATCC_REPORT_FLIGHTPLAN:
atc.inform("Command received: ATCC_REPORT_FLIGHTPLAN | Retrieving flight-plan...");
atc.inform(airportDesignated ? "Airport coordinates: " + airport->location->toString() : "No airport designated");
n = flightPlan.getWaypointCount();
if(n==0)
atc.inform("Flight-plan empty.");
else {
atc.inform("Waypoint count: " + n);
atc.inform("#\tDel\tPID\tCoordinates\n--\t---\t---\t----------------------------");
for(int i=0; i<n; i++) atc.inform(String(i) + "\t" + flightPlan.getWaypoint(i)->toString());
atc.inform("--------------------------------------------------------------------");
}
break;
case ATCC_OPEN_DOOR:
atc.inform("Command received: ATCC_OPEN_DOOR | Opening door...");
aircraft.openDoor(param);
break;
case ATCC_CLOSE_DOOR:
atc.inform("Command received: ATCC_CLOSE_DOOR | Closing door...");
aircraft.closeDoor(param);
break;
case ATCC_START_DEMO_MISSION:
atc.inform("Command received: ATCC_START_DEMO_MISSION | Starting demo mission...");
startDemoMission();
atc.inform("Demo Mission complete");
break;
default:
message = String("Command not recognized | Received: ");
message = message + command + " with parameter " + param;
atc.inform(message);
break;
}
atc.clearedToSend();
}
| 29.160839
| 134
| 0.652398
|
9f961da57134b5461005d3b10cfe91a733470708
| 8,180
|
ino
|
Arduino
|
Firmeware/EnsembleFive/EnsembleFive.ino
|
Sonoscopia/Phobos
|
5f420055d18f2776db2e68ef79ae80f345ab77dd
|
[
"MIT"
] | null | null | null |
Firmeware/EnsembleFive/EnsembleFive.ino
|
Sonoscopia/Phobos
|
5f420055d18f2776db2e68ef79ae80f345ab77dd
|
[
"MIT"
] | null | null | null |
Firmeware/EnsembleFive/EnsembleFive.ino
|
Sonoscopia/Phobos
|
5f420055d18f2776db2e68ef79ae80f345ab77dd
|
[
"MIT"
] | null | null | null |
/* PHOBOS - EnsembleFive firmware v.0.3 (20.06.2017)
*
* using:
* Arduino v1.8.0
* MIDI_Library v.4.3.1 by fortyseveneffects
* Servo Library v.1.1.2
* EEPROM Library v.2.0.0
*
* plays:
* A - 1 motor on a vynil with attached strings
* B - 1 motor with loose strings
* C - 3 servos plucking strings
* D - 4 lights controlled by relays
*/
#include <EEPROM.h>
#include <Servo.h>
#include <MIDI.h>
#define MIDICH 1
#define START 43
#define SIZE 9
// VM VYNIL'S PINS
#define A1 10
// VM STRINGS' PINS
#define B1 9
// VM SERVOS' PINS
#define C1 6
#define C2 7
#define C3 8
// LIGHTS' PINS
#define D1 2
#define D2 3
#define D3 4
#define D4 5
/* Addresses on Arduino EEPROM for servo control parameters*/
#define S1MININC 0 // servo1 min increment (cc=116)
#define S1MAXINC 1 // servo1 max increment (cc=117)
#define S2MININC 2 // servo2 min increment (cc=118)
#define S2MAXINC 3 // servo2 max increment (cc=119)
#define S3MININC 4 // servo3 min increment (cc=120)
#define S3MAXINC 5 // servo3 max increment (cc=121)
#define S1MINANG 6 // servo1 min angle (cc=122)
#define S1MAXANG 7 // servo1 max angle (cc=123)
#define S2MINANG 8 // servo2 min angle (cc=124)
#define S2MAXANG 9 // servo2 max angle (cc=125)
#define S3MINANG 10 // servo3 min angle (cc=126)
#define S3MAXANG 11 // servo3 max angle (cc=127)
// servos
Servo servo1, servo2, servo3;
bool servoState[3]; // servo state to control servos out of MIDI loop
bool _servoState[3]; // servo previous state
float servoPos[3]; // servo current position
float servoInc[3]; //servo increment value which relates to movement speed
float servoMinInc[3]; // servo min increment values
float servoMaxInc[3]; // servo min increment values
float servoMinAng[3]; // servo min angle
float servoMaxAng[3]; // servo max angle
// make note to pin array
byte note2pin[SIZE];
byte vel, pitch, val, cc;
MIDI_CREATE_DEFAULT_INSTANCE();
void setup() {
MIDI.begin(MIDICH);
MIDI.turnThruOn();
// set output pins
pinMode(A1, OUTPUT);
pinMode(B1, OUTPUT);
servo1.attach(C1);
servo2.attach(C2);
servo3.attach(C3);
pinMode(D1, OUTPUT);
pinMode(D2, OUTPUT);
pinMode(D3, OUTPUT);
pinMode(D4, OUTPUT);
// turn relays off
digitalWrite(D1, HIGH);
digitalWrite(D2, HIGH);
digitalWrite(D3, HIGH);
digitalWrite(D4, HIGH);
// set servos to initial position
servoPos[0] = midi2angle(EEPROM.read(S1MINANG));
servo1.write(servoPos[0]);
servoPos[1] = midi2angle(EEPROM.read(S2MINANG));
servo2.write(servoPos[1]);
servoPos[2] = midi2angle(EEPROM.read(S3MINANG));
servo3.write(servoPos[2]);
// set servos previous state
_servoState[0] = false;
_servoState[1] = false;
_servoState[2] = false;
// set servos' min&max increment values
// NOTE: min/max inc values are between 0 and 127 (after mapped correspond to 0.1 to 10 degrees per millisecond)
servoMinInc[0] = EEPROM.read(S1MININC);
servoMaxInc[0] = EEPROM.read(S1MAXINC);
servoMinInc[1] = EEPROM.read(S2MININC);
servoMaxInc[1] = EEPROM.read(S2MAXINC);
servoMinInc[2] = EEPROM.read(S3MININC);
servoMaxInc[2] = EEPROM.read(S3MAXINC);
// set servos0 min&max angle
// NOTE: min/max angle values are already converted to angles
servoMinAng[0] = midi2angle( EEPROM.read(S1MINANG) );
servoMaxAng[0] = midi2angle( EEPROM.read(S1MAXANG) );
servoMinAng[1] = midi2angle( EEPROM.read(S2MINANG) );
servoMaxAng[1] = midi2angle( EEPROM.read(S2MAXANG) );
servoMinAng[2] = midi2angle( EEPROM.read(S3MINANG) );
servoMaxAng[2] = midi2angle( EEPROM.read(S3MAXANG) );
// set note2pin array
note2pin[43-START] = A1; //motor
note2pin[44-START] = B1; //motor
note2pin[45-START] = C1; // servos
note2pin[46-START] = C2;
note2pin[47-START] = C3;
note2pin[48-START] = D1; // relays
note2pin[49-START] = D2;
note2pin[50-START] = D3;
note2pin[51-START] = D4;
}
void loop() {
if(MIDI.read()){
switch(MIDI.getType()){
case midi::NoteOn:
pitch = MIDI.getData1();
vel = MIDI.getData2();
if(pitch > 44 && pitch < 48){ // activate servos and relays
// set servos' values only (activation is done in runServos function)
servoInc[pitch-45] = velocity2inc( servoMinInc[pitch-45], servoMaxInc[pitch-45], vel);
servoState[pitch-45] = true;
_servoState[pitch-45] = true;
if(pitch==45) servo1.attach(C1);
if(pitch==46) servo2.attach(C2);
if(pitch==47) servo3.attach(C3);
}
if(pitch > 47 && pitch < 52){ // activate relays
digitalWrite(note2pin[pitch-START], LOW);
}
if(pitch > 42 && pitch < 45){ // activate motors
analogWrite(note2pin[pitch-START], vel << 1);
}
break;
case midi::NoteOff:
pitch = MIDI.getData1();
if(pitch > 44 && pitch < 48){
// deactivate servos
servoState[pitch-45] = false;
}
if(pitch > 47 && pitch < 52){ // deactivate relays
digitalWrite(note2pin[pitch-START], HIGH);
}
if(pitch > 42 && pitch < 45){ // deactivate motors
analogWrite(note2pin[pitch-START], LOW);
}
break;
// CONTROL CHANGE (SET SERVO PARAMETERS)
case midi::ControlChange:
cc = MIDI.getData1();
val = MIDI.getData2();
// from cc=100 to cc=111
if(cc > 99 && cc < 112){
EEPROM.write(cc-100, val); // store...
updateServoParams(cc, val);//...and update
break;
}
}
}
runServos(); // activate servos
//delay(1); // (used only to set servo increments in a millisecond basis)
}
/***************** FUNTCIONS *****************/
byte voltage2byte(float v){
return v*255/5.f;
}
float midi2angle(byte m){
return 180/127.f*m;
}
float velocity2inc(byte _min, byte _max, byte v){ // translate velocity values into position increments usign a min/max inc.
return map(v, 0, 127, _min, _max);
}
void runServos(){
// servo1 attack
if( servoState[0]==true && servoPos[0] < servoMaxAng[0] ){
servo1.write(servoPos[0]);
servoPos[0] += servoInc[0];
}
// servo1 release
else if (servoState[0] == false && _servoState[0] == true){
servoPos[0] = servoMinAng[0];
servo1.write( servoPos[0] );
_servoState[0] = false;
}
// servo2 attack
if( servoState[1]==true && servoPos[1] < servoMaxAng[1] ){
servo2.write(servoPos[1]);
servoPos[1] += servoInc[1];
}
// servo2 release
else if (servoState[1] == false && _servoState[1] == true){
servoPos[1] = servoMinAng[1];
servo2.write( servoPos[1] );
_servoState[1] = false;
}
// servo3 attack
if( servoState[2]==true && servoPos[2] < servoMaxAng[2] ){
servo3.write(servoPos[2]);
servoPos[2] += servoInc[2];
}
// servo3 release
else if (servoState[2] == false && _servoState[2] == true){
servoPos[2] = servoMinAng[2];
servo3.write( servoPos[2] );
_servoState[2] = false;
}
}
void updateServoParams(byte addr, byte v){
switch(addr){
case 100:
servoMinInc[0] = v;
break;
case 101:
servoMaxInc[0] = v;
break;
case 102:
servoMinInc[1] = v;
break;
case 103:
servoMaxInc[1] = v;
break;
case 104:
servoMinInc[2] = v;
break;
case 105:
servoMaxInc[2] = v;
break;
case 106:
servoMinAng[0] = midi2angle(v);
servo1.write(servoMinAng[0]);
break;
case 107:
servoMaxAng[0] = midi2angle(v);
servo1.write(servoMaxAng[0]);
break;
case 108:
servoMinAng[1] = midi2angle(v);
servo2.write(servoMinAng[1]);
break;
case 109:
servoMaxAng[1] = midi2angle(v);
servo2.write(servoMaxAng[1]);
break;
case 110:
servoMinAng[2] = midi2angle(v);
servo3.write(servoMinAng[2]);
break;
case 111:
servoMaxAng[2] = midi2angle(v);
servo3.write(servoMaxAng[2]);
break;
default:
break;
}
}
| 26.644951
| 124
| 0.609535
|
5cf73ca22d6b9adcc2d9789dfc3c253e412b78e9
| 7,614
|
ino
|
Arduino
|
Arduino/RadarDriver/RadarDriver.ino
|
GoWinston/Arduino-Ultrasonic-Radar
|
fad68fdd5e9127ea37d924191d6e615fe49f910a
|
[
"MIT"
] | null | null | null |
Arduino/RadarDriver/RadarDriver.ino
|
GoWinston/Arduino-Ultrasonic-Radar
|
fad68fdd5e9127ea37d924191d6e615fe49f910a
|
[
"MIT"
] | null | null | null |
Arduino/RadarDriver/RadarDriver.ino
|
GoWinston/Arduino-Ultrasonic-Radar
|
fad68fdd5e9127ea37d924191d6e615fe49f910a
|
[
"MIT"
] | null | null | null |
/*
ADDING FAST SCANNING!!
*/
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
#include <SoftwareSerial.h>
SoftwareSerial rangeSerial(2, 3);
uint16_t SERVOMIN = 206;
uint16_t SERVOMAX = 580;
uint16_t ANGLEMIN = 23;
uint16_t ANGLEMAX = 158;
uint16_t ServoPosition = SERVOMIN;
uint8_t SlewSpeed = 1;
static byte RangePin = 13;
static byte ServoPowerPin = 12;
static byte PulsePin = 1;
boolean static debugging = false;
void setup() {
Serial.begin(19200);
rangeSerial.begin (9600);
pinMode(ServoPowerPin, OUTPUT);
digitalWrite(ServoPowerPin, HIGH);
pinMode(RangePin, OUTPUT);
digitalWrite(RangePin, LOW);
pwm.begin();
pwm.setPWMFreq(60); // Analog servos run at ~60 Hz updates
Serial.println("5");
moveRadar (map (90,ANGLEMIN,ANGLEMAX,SERVOMIN,SERVOMAX));
}
void loop() {
if (Serial.available() > 0) {
switch (Serial.read ()) {
/* START Calibration Functions
case 49 : // 1
moveRadar (SERVOMIN);
Serial.print("Servo set to MIN position of ");
Serial.println(SERVOMIN);
break;
case 50 : // 2
SERVOMIN --;
moveRadar (SERVOMIN);
Serial.print("Servo MIN Reduced to: ");
Serial.println(SERVOMIN);
break;
case 51: // 3
SERVOMIN ++;
moveRadar (SERVOMIN);
Serial.print("Servo MIN Increased to: ");
Serial.println(SERVOMIN);
break;
case 52 : // 4
moveRadar (SERVOMAX);
Serial.print("Servo set to MAX position of ");
Serial.println(SERVOMAX);
break;
case 53 : // 5
SERVOMAX --;
moveRadar (SERVOMAX);
Serial.print("Servo MAX Reduced to: ");
Serial.println(SERVOMAX);
break;
case 54: // 6
SERVOMAX ++;
moveRadar (SERVOMAX);
Serial.print("Servo MAX Increased to: ");
Serial.println(SERVOMAX);
break;
case 55: // 7
moveRadar (map (90,ANGLEMIN,ANGLEMAX,SERVOMIN,SERVOMAX));
Serial.println("This is center");
break;
END Calibration Functions */
case 112: // p followed by three numbers for position
{
if (debugging) {
Serial.print("Enter position to move to now ");
}
while ( Serial.available() < 3) {
delay (5);
}
int pos = ((Serial.read()-48)*100);
pos = pos + ((Serial.read()-48)*10);
pos = pos + ((Serial.read()-48));
if (debugging) {
Serial.print(pos);
Serial.println(" will be input into goMeasure");
}
int rangeOut= goMeasure (pos);
if (rangeOut == -1) {
break;
}
Serial.print("R");
if (rangeOut < 1000) {
Serial.print ("0");
}
Serial.println(rangeOut);
}
break;
case 102: // f followed by three numbers for position ** FAST MODE **
{
if (debugging) {
Serial.print("Enter FAST MODE position to move to now ");
}
while ( Serial.available() < 3) {
delay (5);
}
int pos = ((Serial.read()-48)*100);
pos = pos + ((Serial.read()-48)*10);
pos = pos + ((Serial.read()-48));
if (debugging) {
Serial.print(pos);
Serial.println(" will be input into goMeasureFAST");
}
int rangeOut= goMeasureFAST (pos);
if (rangeOut == -1) {
break;
}
Serial.print("R");
if (rangeOut < 1000) {
Serial.print ("0");
}
Serial.println(rangeOut);
}
break;
} // END switch
} // END if Serial Avail
} // END LOOP
int goMeasureFAST (int pos) {
int range = 0;
if (pos >= ANGLEMIN && pos <= ANGLEMAX) {
if (debugging) {
Serial.print("FastScan Moving to position ");
Serial.println(pos);
}
moveRadar (map (pos,ANGLEMIN,ANGLEMAX,SERVOMIN,SERVOMAX));
delay (30); // let the sensor become stable
}
else {
Serial.println("E");
range = -1;
return range;
}
int readings[5] = {0,0,0,0,0};
digitalWrite(RangePin, HIGH);
delay (30);
digitalWrite(RangePin, LOW);
delay (30);
while (rangeSerial.available() < 1) {
delay (10);
}
while (rangeSerial.peek() != 82 ) {
rangeSerial.read();
}
if (rangeSerial.read() == 82) { // this is ascii R and a dirty ascii to dec conversion
range = 0;
range = range + ((rangeSerial.read()-48)*1000);
range = range + ((rangeSerial.read()-48)*100);
range = range + ((rangeSerial.read()-48)*10);
range = range + (rangeSerial.read()-48);
if (rangeSerial.read() == 13) {
if (debugging) {
Serial.print("Range: ");
Serial.println(range);
}
return range; //*********
}
else {
Serial.println("E");
}
}
delay (70);
}
int goMeasure (int pos) {
int range = 0;
if (pos >= ANGLEMIN && pos <= ANGLEMAX) {
if (debugging) {
Serial.print("Moving to position ");
Serial.println(pos);
}
moveRadar (map (pos,ANGLEMIN,ANGLEMAX,SERVOMIN,SERVOMAX));
delay (30); // let the sensor become stable
}
else {
Serial.println("E");
range = -1;
return range;
}
int readings[5] = {0,0,0,0,0};
for (int a = 0 ; a < 5 ; a++) {
digitalWrite(RangePin, HIGH);
delay (30);
digitalWrite(RangePin, LOW);
delay (30);
while (rangeSerial.available() < 1) {
delay (10);
}
while (rangeSerial.peek() != 82 ) {
rangeSerial.read();
}
if (rangeSerial.read() == 82) { // this is ascii R and a dirty ascii to dec conversion
range = 0;
range = range + ((rangeSerial.read()-48)*1000);
range = range + ((rangeSerial.read()-48)*100);
range = range + ((rangeSerial.read()-48)*10);
range = range + (rangeSerial.read()-48);
if (rangeSerial.read() == 13) {
if (debugging) {
Serial.print("Range: ");
Serial.println(range);
}
readings[a] = range;
}
else {
Serial.println("E");
}
}
delay (70);
}
if (debugging) {
Serial.print("Values Array is: ");
for ( int x = 0; x < 5; x++) {
Serial.print (readings [x]);
Serial.print(",");
}
Serial.println ();
}
int minValue = 10001;
int minIndex = 0;
for( int i = 0 ; i < 5 ; i++) {
if(readings[i] < minValue) {
minValue = readings[i];
minIndex = i;
}
}
if (debugging) {
Serial.print ("Min: ");
Serial.print (minValue);
Serial.print (" at index ");
Serial.println (minIndex);
}
readings[minIndex] = 0;
int maxValue = 0;
int maxIndex = 0;
for( int i = 0 ; i < 5 ; i++) {
if(readings[i] > maxValue) {
maxValue = readings[i];
maxIndex = i;
}
}
if (debugging) {
Serial.print ("Max: ");
Serial.print (maxValue);
Serial.print (" at index ");
Serial.println (maxIndex);
}
readings[maxIndex] = 0;
int avgValue = 0;
for( int i = 0 ; i < 5 ; i++) {
avgValue = avgValue + readings[i];
}
avgValue = avgValue / 3 ;
if (debugging) {
Serial.print ("Avg: ");
Serial.println (avgValue);
}
return avgValue;
}
void moveRadar (uint16_t ending) {
if (debugging) {
Serial.println("Moving with moveRadar...");
}
for ((ServoPosition-ending)>0; ServoPosition > ending; ServoPosition--) { //move backwards
pwm.setPWM(0, 0, ServoPosition);
delay(SlewSpeed);
}
for ((ServoPosition-ending)<0; ServoPosition < ending; ServoPosition++) { //move forwards
pwm.setPWM(0, 0, ServoPosition);
delay(SlewSpeed);
}
}
| 22.864865
| 94
| 0.555687
|
245ea41146c9bf3bfe38506d1d40c2a098c0b2d2
| 859
|
ino
|
Arduino
|
Arduino/quadrature_encoder_basic/quadrature_encoder_basic.ino
|
6r1d/Arduino_archive
|
dfc0a5e2e693ae6749c42ac43549ba40c9afdbec
|
[
"MIT"
] | null | null | null |
Arduino/quadrature_encoder_basic/quadrature_encoder_basic.ino
|
6r1d/Arduino_archive
|
dfc0a5e2e693ae6749c42ac43549ba40c9afdbec
|
[
"MIT"
] | null | null | null |
Arduino/quadrature_encoder_basic/quadrature_encoder_basic.ino
|
6r1d/Arduino_archive
|
dfc0a5e2e693ae6749c42ac43549ba40c9afdbec
|
[
"MIT"
] | null | null | null |
/*
* Quadrature encoder example with no debouncing.
*
* Based on a sketch by Max Wolf (www.meso.net)
*/
#define encoder_pin_a 3
#define encoder_pin_b 4
#define encoder_btn_pin 5
int val;
int encoder_position = 0;
bool encoder_pin_a_last = LOW;
bool n = LOW;
void setup() {
pinMode(encoder_pin_a, INPUT_PULLUP);
pinMode(encoder_pin_b, INPUT_PULLUP);
pinMode(encoder_btn_pin, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
// Process encoder
n = digitalRead(encoder_pin_a);
if ((encoder_pin_a_last == LOW) && (n == HIGH)) {
if (digitalRead(encoder_pin_b) == LOW) {
encoder_position--;
} else {
encoder_position++;
}
Serial.println(encoder_position);
}
encoder_pin_a_last = n;
// Process button on an encoder
if (digitalRead(encoder_btn_pin) == LOW) {
Serial.println("pressed");
}
}
| 20.452381
| 51
| 0.67404
|
66871d54721efa7c220a0d1f0048ea1555254793
| 4,949
|
ino
|
Arduino
|
sketchbook/libraries/virtuino/examples/webserver_ehternet_shield_example_03/webserver_ehternet_shield_example_03.ino
|
technoman72/BlocklyArduino_electrified
|
b91c1d37313ba5f5d0065e8cb264e7d7b45eb2e9
|
[
"MIT"
] | null | null | null |
sketchbook/libraries/virtuino/examples/webserver_ehternet_shield_example_03/webserver_ehternet_shield_example_03.ino
|
technoman72/BlocklyArduino_electrified
|
b91c1d37313ba5f5d0065e8cb264e7d7b45eb2e9
|
[
"MIT"
] | null | null | null |
sketchbook/libraries/virtuino/examples/webserver_ehternet_shield_example_03/webserver_ehternet_shield_example_03.ino
|
technoman72/BlocklyArduino_electrified
|
b91c1d37313ba5f5d0065e8cb264e7d7b45eb2e9
|
[
"MIT"
] | null | null | null |
/* Virtuino Ethernet Shield web server example No2
* Example name = "Read Write virtual memory"
* Created by Ilias Lamprou
* Updated Jul 01 2016
* Before running this code config the settings below as the instructions on the right
*
*
* Download last Virtuino android app from the link: https://play.google.com/store/apps/details?id=com.javapapers.android.agrofarmlitetrial
* Getting starting link:
* Video tutorial link:
* Contact address for questions or comments: iliaslampr@gmail.com
*/
/*========= Virtuino General methods
*
* void vDigitalMemoryWrite(int digitalMemoryIndex, int value) write a value to a Virtuino digital memory (digitalMemoryIndex=0..31, value range = 0 or 1)
* int vDigitalMemoryRead(int digitalMemoryIndex) read the value of a Virtuino digital memory (digitalMemoryIndex=0..31, returned value range = 0 or 1)
* void vMemoryWrite(int memoryIndex, float value); write a value to Virtuino memory (memoryIndex=0..31, value range as float value)
* float vMemoryRead(int memoryIndex); read a value of Virtuino memory (memoryIndex=0..31, returned a float value
* run(); neccesary command to communicate with Virtuino android app (on start of void loop)
* int getPinValue(int pin); read the value of a Pin. Usefull to read the value of a PWM pin
*/
#include "VirtuinoEthernet_WebServer.h" // Neccesary virtuino library for ethernet shield
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; // Set the ethernet shield mac address.
IPAddress ip(192, 168, 2, 150); // Set the ethernet shield ip address. Check your gateway ip address first
VirtuinoEthernet_WebServer virtuino(80); // default port=80
int secondsCounter = 0;
long storedTime=0;
//================================================================== setup
//==================================================================
//==================================================================
void setup()
{
virtuino.DEBUG=true; // set this value TRUE to enable the serial monitor status
Serial.begin(9600); // Enable this line only if DEBUG=true
Ethernet.begin(mac, ip);
virtuino.password="1234"; // Set a password to your web server for more protection
// avoid special characters like ! $ = @ # % & * on your password. Use only numbers or text characters
//------ enter your setup code below
// Make the following connections to your arduino board to test this example
pinMode(5,INPUT); // Connect a switch or button to pin 5 as digtial input
pinMode(6,OUTPUT); // Connect a LED to pin 12 as digital output
pinMode(9,OUTPUT); // Connect a LED to pin 10 as analog output.
// Connect a potentiometer to analog pin A0
// Don't use pins 10,11,12,13 in your code. They used by Ethernet Shield
}
//================================================================== loop
//==================================================================
//==================================================================
void loop(){
virtuino.run(); // neccesary command to communicate with Virtuino android app
//------ enter your loop code below here
//------ avoid to use delay() function in your code
// your code .....
//----------------------------- example 1 - write to a virtual memory
long t=millis()/1000; // get time in seconds
if (t>storedTime){ // every second
storedTime=t;
secondsCounter ++; // increase counter every second
if (secondsCounter==180) secondsCounter=0; // reset counter
virtuino.vMemoryWrite(1,secondsCounter); // write to virtual memory. On Virtuino app add a Value display to Virtual pin V1 to read the secondsCounter value
}
//----------------------------- example 2 - read a virtual memory
float v= virtuino.vMemoryRead(2); // read a virtual memory. On Virtuino app add a Regulator to Virtual pin V2
if (v>300) digitalWrite(6,HIGH); // do something
else digitalWrite(6,LOW);
//----- end of your code
}
| 48.048544
| 178
| 0.504546
|
d872146a6cf7e4746fc06ac2388f6fb7ef8e55c2
| 3,679
|
ino
|
Arduino
|
servoTest/servoTest.ino
|
MaartenSnels/arduino
|
77ee49c332e98f0bb4663668a4906fb52b23f132
|
[
"MIT"
] | null | null | null |
servoTest/servoTest.ino
|
MaartenSnels/arduino
|
77ee49c332e98f0bb4663668a4906fb52b23f132
|
[
"MIT"
] | null | null | null |
servoTest/servoTest.ino
|
MaartenSnels/arduino
|
77ee49c332e98f0bb4663668a4906fb52b23f132
|
[
"MIT"
] | null | null | null |
// Sweep
// by BARRAGAN <http://barraganstudio.com>
// This example code is in the public domain.
#include <Servo.h>
#define MAX_GRADEN 170
#define MIN_GRADEN 10
#define FRONT 0
#define REAR 1
#define LEFT_WHEEL_INTERRUPT 2
#define RIGHT_WHEEL_INTERRUPT 3
#define FRONT_SERVO_PIN 9
#define REAR_SERVO_PIN 8
#define FRONT_TRIGGER_PIN 10
#define FRONT_ECHO_PIN 11
#define REAR_TRIGGER_PIN 12
#define REAR_ECHO_PIN 13
// groffe afstands indicatie
#define FAR 100
#define CLOSE 5
#define MEDIUM 20
Servo servoFront; //
Servo servoRear; //
int pos = 0; // variable to store the servo position
long leftTicks = 0;
void leftWheelCounter() {
leftTicks++;
Serial.print("left interrupt nr " );
Serial.println(leftTicks);
}
long rightTicks = 0;
void rightWheelCounter() {
rightTicks++;
Serial.print("right interrupt nr " );
Serial.println(rightTicks);
}
void setup()
{
servoFront.attach(FRONT_SERVO_PIN); //
servoRear.attach(REAR_SERVO_PIN); //
setServo(servoFront, 90, 100);
setServo(servoRear, 90, 100);
// HC-RS04 echo module
pinMode(FRONT_TRIGGER_PIN, OUTPUT);
pinMode(FRONT_ECHO_PIN, INPUT );
pinMode(REAR_TRIGGER_PIN, OUTPUT);
pinMode(REAR_ECHO_PIN, INPUT );
Serial.begin(250000);
attachInterrupt(digitalPinToInterrupt(LEFT_WHEEL_INTERRUPT), leftWheelCounter, RISING);
attachInterrupt(digitalPinToInterrupt(RIGHT_WHEEL_INTERRUPT), rightWheelCounter, RISING);
}
void loop()
{
check(FRONT);
check(REAR);
delay(2000);
}
void check(int position) {
String msg;
Servo servo;
switch(position) {
case FRONT:
msg = "front";
servo = servoFront;
break;
case REAR:
msg = "rear";
servo = servoRear;
break;
default:
Serial.println("positie niet gedefinieerd");
return;
}
// bepaal huidige positie
int dist = getDistance(position);
Serial.print("Afstand " + msg + " 90 graden: ");
Serial.println(dist);
if (dist > CLOSE) {
// we mogen doorrijden
Serial.println("We kunnen door");
return;
}
int _delay = 300;
setServo(servo, 10, _delay);
Serial.print("Afstand " + msg + " 10 graden: ");
Serial.println(dist);
if (dist > CLOSE) {
// we mogen doorrijden
Serial.println("We kunnen 10 graden pakken");
setServo(servo, 90, 0);
return;
}
setServo(servo, 170, _delay);
dist = getDistance(position);
Serial.print("Afstand " + msg + " 170 graden: ");
Serial.println(dist);
if (dist > CLOSE) {
// we mogen doorrijden
Serial.println("We kunnen 170 graden pakken");
setServo(servo, 90, 0);
return;
}
// ok, we moeten dus de andere kant op
Serial.println("Versperd, we moeten terug!");
}
int getDistance(int position) {
char triggerPin, echoPin;
switch (position) {
case FRONT:
triggerPin = FRONT_TRIGGER_PIN;
echoPin = FRONT_ECHO_PIN;
break;
case REAR:
triggerPin = REAR_TRIGGER_PIN;
echoPin = REAR_ECHO_PIN;
break;
default:
Serial.println("positie niet gedefinieerd");
return -1;
}
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
int duration = pulseIn(echoPin, HIGH);
//Calculate the distance (in cm) based on the speed of sound.
return duration / 58.2;
}
void setServo(Servo s, int hoek, int _delay) {
s.write(hoek); // tell servo to go to position in variable 'pos'
delay(_delay); // waits 15ms for the servo to reach the position
}
| 22.432927
| 91
| 0.649905
|
3318d590d6fb42756fbb1ccb7c3459f343613146
| 5,641
|
ino
|
Arduino
|
atmega_controller.ino
|
Cube82/atmega_controller
|
e7d4c191e299ae350649483a61eff8882a310318
|
[
"MIT"
] | null | null | null |
atmega_controller.ino
|
Cube82/atmega_controller
|
e7d4c191e299ae350649483a61eff8882a310318
|
[
"MIT"
] | null | null | null |
atmega_controller.ino
|
Cube82/atmega_controller
|
e7d4c191e299ae350649483a61eff8882a310318
|
[
"MIT"
] | null | null | null |
#include <PS2X_lib.h>
#include <VirtualWire.h>
// pseudo-channel to distinguish transmiters
#define channel "1"
// ping message
#define ping "ping"
// pins definition
#define led_pin A5
#define transmit_pin 8
/******************************************************************
* set pins connected to PS2 controller
******************************************************************/
#define PS2_CLK PD4
#define PS2_ATT PD3
#define PS2_CMD PD2
#define PS2_DAT PD1
/******************************************************************
* select modes of PS2 controller:
* - pressures = analog reading of push-butttons
* - rumble = motor rumbling
******************************************************************/
#define pressures false
#define rumble false
// interval at which to send ping (milliseconds)
const long interval = 900;
// will store last time ping was sent
unsigned long previousMillis = 0;
int ps2Error = 0;
/******************************************************************
* Controller class based on PS2X
******************************************************************/
class Controller : public PS2X
{
private:
// sticks values for comparison
byte _lastRx = 128;
byte _lastRy = 128;
byte _lastLx = 128;
byte _lastLy = 128;
public:
static const byte buttons_count = 16;
unsigned int buttons_keys[buttons_count] =
{
PSB_SELECT,
PSB_L3,
PSB_R3,
PSB_START,
PSB_PAD_UP,
PSB_PAD_RIGHT,
PSB_PAD_DOWN,
PSB_PAD_LEFT,
PSB_L2,
PSB_R2,
PSB_L1,
PSB_R1,
PSB_TRIANGLE,
PSB_CIRCLE,
PSB_CROSS,
PSB_SQUARE
};
const char buttons_values[buttons_count][5] =
{
"|se:", // PSB_SELECT,
"|l3:", // PSB_L3,
"|r3:", // PSB_R3,
"|st:", // PSB_START,
"|up:", // PSB_PAD_UP,
"|rt:", // PSB_PAD_RIGHT,
"|dn:", // PSB_PAD_DOWN,
"|lt:", // PSB_PAD_LEFT,
"|l2:", // PSB_L2,
"|r2:", // PSB_R2,
"|l1:", // PSB_L1,
"|r1:", // PSB_R1,
"|tr:", // PSB_TRIANGLE,
"|ci:", // PSB_CIRCLE,
"|cr:", // PSB_CROSS,
"|sq:" // PSB_SQUARE
};
unsigned int sticks_keys[4] =
{
PSS_RX,
PSS_RY,
PSS_LX,
PSS_LY
};
const char sticks_values[4][5] =
{
"|rx:", // PSS_RX,
"|ry:", // PSS_RY,
"|lx:", // PSS_LX,
"|ly:" // PSS_LY
};
// save sticks values at the end of loop for comparison
void SaveSticksValues()
{
_lastRx = Analog(PSS_RX);
_lastRy = Analog(PSS_RY);
_lastLx = Analog(PSS_LX);
_lastLy = Analog(PSS_LY);
}
// returns true if any value of right or left analog changed since previous loop
boolean StickValueChanged()
{
if (Analog(PSS_RX) != _lastRx || Analog(PSS_RY) != _lastRy || Analog(PSS_LX) != _lastLx || Analog(PSS_LY) != _lastLy)
return true;
else
return false;
}
// returns true if given value of right or left analog changed since previous loop
boolean StickValueChanged(byte stick)
{
switch (stick)
{
case PSS_RX:
return Analog(PSS_RX) != _lastRx;
break;
case PSS_RY:
return Analog(PSS_RY) != _lastRy;
break;
case PSS_LX:
return Analog(PSS_LX) != _lastLx;
break;
case PSS_LY:
return Analog(PSS_LY) != _lastLy;
break;
default:
return false;
}
}
};
// Controller Class instance
Controller ctrl;
void setup()
{
// settings for radio
vw_set_tx_pin(transmit_pin);
vw_setup(2000);
pinMode(led_pin, OUTPUT);
// setup pins and settings: GamePad(clock, command, attention, data, Pressures?, Rumble?) check for error
ps2Error = ctrl.config_gamepad(PS2_CLK, PS2_CMD, PS2_ATT, PS2_DAT, pressures, rumble);
}
void loop()
{
// skip loop if no controller found
if (ps2Error != 0)
{
digitalWrite(led_pin, HIGH);
delay(100);
return;
}
// read controller
ctrl.read_gamepad();
if (ctrl.NewButtonState() || ctrl.StickValueChanged()) // will be TRUE if any button changes state (on to off, or off to on) OR any stick changes value
sendValues(); // read, format and send values from controller
// sending ping every interval
if (millis() - previousMillis >= interval)
{
sendPing(); // send ping
}
ctrl.SaveSticksValues();
delay(1);
}
void sendPing()
{
char msg[10];
msg[0] = '\0';
strcat(msg, "C:");
strcat(msg, channel);
strcat(msg, "|");
strcat(msg, ping);
send(msg);
}
void sendValues()
{
// message to send
char msg[VW_MAX_MESSAGE_LEN];
msg[0] = '\0';
char value[5];
// channel
strcat(msg, "C:");
strcat(msg, channel);
// stick values
for (int i = 0; i < 4; i++)
{
if (ctrl.StickValueChanged(ctrl.sticks_keys[i]))
{
strcat(msg, ctrl.sticks_values[i]);
itoa(ctrl.Analog(ctrl.sticks_keys[i]), value, 10);
strcat(msg, value);
}
}
// buttons values
for (int i = 0; i < ctrl.buttons_count; i++)
{
if (strlen(msg) > (VW_MAX_MESSAGE_LEN - 7)) // break if next part of message won't fix in msg
break;
if (ctrl.NewButtonState(ctrl.buttons_keys[i]))
{
strcat(msg, ctrl.buttons_values[i]);
itoa(ctrl.Button(ctrl.buttons_keys[i]), value, 10);
strcat(msg, value);
}
}
// ending pipe
strcat(msg, "|");
// send message
send(msg);
}
// sending radio message
void send(char message[VW_MAX_MESSAGE_LEN])
{
digitalWrite(led_pin, HIGH);
vw_send((uint8_t *)message, strlen(message));
vw_wait_tx();
// save last send time for ping timer
previousMillis = millis();
digitalWrite(led_pin, LOW);
}
| 21.613027
| 153
| 0.566743
|
7d9b7ce701b97504042d6ae7be5130cdc5903215
| 490
|
ino
|
Arduino
|
Analog_Digital_read/Analog_Digital_read.ino
|
Kshitij993/IoT-Classes
|
96301f8a7cc50774dee6d62efefb5f30aa2b292a
|
[
"MIT"
] | 2
|
2021-11-13T08:30:32.000Z
|
2021-11-19T09:23:37.000Z
|
Analog_Digital_read/Analog_Digital_read.ino
|
Kshitij993/IoT-Classes
|
96301f8a7cc50774dee6d62efefb5f30aa2b292a
|
[
"MIT"
] | null | null | null |
Analog_Digital_read/Analog_Digital_read.ino
|
Kshitij993/IoT-Classes
|
96301f8a7cc50774dee6d62efefb5f30aa2b292a
|
[
"MIT"
] | null | null | null |
int s = 5; //initializing sensor pin with 5
void setup() {
pinMode(s,INPUT); //setting up the mode in which the pin will be used
Serial.begin(115200); // starting the serial monitor to see the results
}
void loop()
{
int v = digitalRead(s); //if want to input in digital format that is 1 and 0
//int v= analogRead(s); //if want to input in analog format
Serial.print("value : ");
Serial.print(v); //printing the value.
Serial.println();
}
| 32.666667
| 80
| 0.632653
|
76f2dacede11cb73c7fd6f3920ea71c2d8576a9e
| 20,197
|
ino
|
Arduino
|
weather_station_color_dicoledisplay.ino
|
radimkeseg/NodeMCU-ESP8266-Wheather-Station-Color
|
39822c4832724f4dcc6cfd0bd55fd137e01d006a
|
[
"MIT"
] | 1
|
2017-03-10T20:09:41.000Z
|
2017-03-10T20:09:41.000Z
|
weather_station_color_dicoledisplay.ino
|
radimkeseg/NodeMCU-ESP8266-Wheather-Station-Color
|
39822c4832724f4dcc6cfd0bd55fd137e01d006a
|
[
"MIT"
] | null | null | null |
weather_station_color_dicoledisplay.ino
|
radimkeseg/NodeMCU-ESP8266-Wheather-Station-Color
|
39822c4832724f4dcc6cfd0bd55fd137e01d006a
|
[
"MIT"
] | null | null | null |
/**The MIT License (MIT)
Copyright (c) 2017 by Radim Keseg
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.
See more at http://blog.squix.ch
*/
#include <Arduino.h>
#include <Adafruit_GFX.h> // Core graphics library
#include <Wire.h> // required even though we do not use I2C
#include "Adafruit_STMPE610.h"
// Fonts created by RKG
#include "fonts.h"
// Download helper
#include "WebResource.h"
#include <ESP8266WiFi.h>
#include <ArduinoOTA.h>
#include <ESP8266mDNS.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
// Helps with connecting to internet
#include <WiFiManager.h>
// check settings.h for adapting to your needs
#include "settings.h"
#include <JsonListener.h>
#include <WundergroundClient.h>
#include "TimeClient.h"
#include "embHTML.h"
// HOSTNAME for OTA update
#define HOSTNAME "WSC-ESP8266-OTA-"
/* Fonts */
#define font_Tahoma22 201
#define font_Comic40 202
#define font_System10 203
/*****************************
* display
* ***************************/
#define LCDWidth 176 //define screen width,height
#define LCDHeight 220
#define _Digole_Serial_I2C_ //To tell compiler compile the special communication only,
#define Ver 34 //if the version of firmware on display is V3.3 and newer, use this
#define WHITE 0xFF
#define BLACK 0
#define RED 0xA6
#define GREEN 0x55
#define BLUE 0x97
#include <DigoleSerial.h> // Hardware-specific library
#include <Wire.h>
DigoleSerialDisp tft(&Wire, '\x27');
/*****************************
* Important: see settings.h to configure your settings!!!
* ***************************/
// Additional UI functions
#include "GfxUi.h"
//Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
GfxUi ui = GfxUi(&tft);
Adafruit_STMPE610 spitouch = Adafruit_STMPE610(STMPE_CS);
WebResource webResource;
TimeClient timeClient(UTC_OFFSET);
// Set to false, if you prefere imperial/inches, Fahrenheit
WundergroundClient wunderground(IS_METRIC);
//declaring prototypes
void configModeCallback (WiFiManager *myWiFiManager);
void downloadCallback(String filename, int16_t bytesDownloaded, int16_t bytesTotal);
ProgressCallback _downloadCallback = downloadCallback;
void downloadResources();
void updateData();
void drawProgress(uint8_t percentage, String text);
void drawTime();
void drawCurrentWeather();
void drawForecast();
void drawForecastDetail(uint16_t x, uint16_t y, uint8_t dayIndex);
String getMeteoconIcon(String iconText);
void drawAstronomy();
void drawSeparator(uint16_t y);
void sleepNow(int wakeup);
void installFonts();
long lastDownloadUpdate = millis();
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
ESP8266WebServer server(80);
/* webserver handlers */
void handle_root()
{
String content = FPSTR(PAGE_INDEX);
content.replace("{country}", WUNDERGROUND_COUNTRY);
content.replace("{city}", WUNDERGROUND_CITY);
content.replace("{timeoffset}",String(UTC_OFFSET).c_str());
server.send(200, "text/html", content);
}
static bool forceUpdateData = false;
void handle_store_settings(){
if(server.arg("_country")==NULL && server.arg("_city")==NULL && server.arg("_timeoffset")==NULL){
Serial.println("setting page refreshed only, no params");
}else{
Serial.println("Location changed");
WUNDERGROUND_COUNTRY = server.arg("_country");
WUNDERGROUND_COUNTRY.replace(" ","_");
Serial.println("Coutry: " + WUNDERGROUND_COUNTRY);
WUNDERGROUND_CITY = server.arg("_city");
WUNDERGROUND_CITY.replace(" ","_") ;
Serial.println("City: " + WUNDERGROUND_CITY);
UTC_OFFSET = atof(server.arg("_timeoffset").c_str());
Serial.print("TimeOffset: "); Serial.println(UTC_OFFSET);
Serial.println("writing custom setting start");
Serial.println("file: " + CUSTOM_SETTINGS);
//write location to SPIFF
File f = SPIFFS.open(CUSTOM_SETTINGS, "w");
if (f){
f.print(WUNDERGROUND_COUNTRY.c_str()); f.print("\r");
Serial.println("Country: " + WUNDERGROUND_COUNTRY);
f.print(WUNDERGROUND_CITY.c_str()); f.print("\r");
Serial.println("City: " + WUNDERGROUND_CITY);
f.print(UTC_OFFSET); f.print("\r");
Serial.print("Offset: "); Serial.println(UTC_OFFSET);
}else{
Serial.println("file open failed: " + CUSTOM_SETTINGS);
}
f.flush();
f.close();
Serial.println("writing custom setting end");
//updateData(false);
forceUpdateData = true;
}
timeClient.setTimeOffset(UTC_OFFSET);
server.send(200, "text/html", "OK");
}
void read_custom_settings(){
//read setting from SPIFF
Serial.println("reading custom setting start");
File f = SPIFFS.open(CUSTOM_SETTINGS, "r");
if(f){
int i=0;
char ch;
//WUNDERGROUND_COUNTRY
char country[64]; i=0;
while((ch=f.read())!='\r'){
country[i++]=ch;
} WUNDERGROUND_COUNTRY = String(country);
Serial.println("Country: " + WUNDERGROUND_COUNTRY);
//WUNDERGROUND_CITY
char city[64]; i=0;
while((ch=f.read())!='\r'){
city[i++]=ch;
} WUNDERGROUND_CITY = String(city);
Serial.println("City: " + WUNDERGROUND_CITY);
//UTC_OFFSET
char offset[5]; i=0;
while((ch=f.read())!='\r'){
offset[i++]=ch;
} UTC_OFFSET = atof(offset);
Serial.print("Offset: "); Serial.println(UTC_OFFSET);
}else{
Serial.println("file open failed: " + CUSTOM_SETTINGS);
}
f.close();
Serial.println("reading custom setting end");
timeClient.setTimeOffset(UTC_OFFSET);
}
/**/
void setup() {
pinMode(TFT_POWER_PIN, OUTPUT);
digitalWrite(TFT_POWER_PIN, LOW);
Wire.begin(TFT_I2C_DATA, TFT_I2C_CLOCK);//mcu esp8266
Serial.begin(9600);
tft.begin();
delay(100);
digitalWrite(TFT_POWER_PIN, HIGH);
tft.setMode('C');
// wipe screen & backlight on
tft.setDrawWindow(0, 0, 176, 220);
tft.setBgColor(BLACK);
tft.cleanDrawWindow(); //clear draw window use the new back ground color
tft.backLightOn();
// tft.backLightBrightness(50);
tft.setFont(10);
tft.setColor(WHITE);
ui.setTextAlignment(CENTER);
ui.drawString(10, 200, "Connecting to WiFi");
// Uncomment for testing wifi manager
//wifiManager.resetSettings();
wifiManager.setAPCallback(configModeCallback);
//or use this for auto generated name ESP + ChipID
wifiManager.autoConnect();
//Manual Wifi
//WiFi.begin(WIFI_SSID, WIFI_PWD);
// OTA Setup
String hostname(HOSTNAME);
hostname += String(ESP.getChipId(), HEX);
WiFi.hostname(hostname);
ArduinoOTA.setHostname((const char *)hostname.c_str());
ArduinoOTA.begin();
SPIFFS.begin();
read_custom_settings();
//user setting handling
server.on("/", handle_root);
server.on("/loc", handle_store_settings);
server.begin();
Serial.println("HTTP server started");
//Uncomment if you want to update all internet resources
//SPIFFS.format();
//Uncomment if you want to reinstall all custom Fonts
//installFonts();
// Incomment if you want to download images from the net. If images already exist don't download
//downloadResources();
// load the weather information
// digitalWrite(TFT_POWER_PIN, LOW);
// delay(100);
// digitalWrite(TFT_POWER_PIN, HIGH);
updateData();
}
long lastDrew = 0;
long stamp = 0;
void loop() {
// "standard setup"
{
// Handle web server
server.handleClient();
// Handle OTA update requests
ArduinoOTA.handle();
stamp = millis();
// Check if we should update the clock
if (stamp - lastDrew > 30000 || stamp < lastDrew || forceUpdateData ) {
drawTime(false);
lastDrew = millis();
}
// Check if we should update weather information
if (stamp - lastDownloadUpdate > 1000 * UPDATE_INTERVAL_SECS || stamp < lastDownloadUpdate || forceUpdateData) {
updateData(false);
lastDownloadUpdate = millis();
}
/*
if(timeClient.getHoursInt() == 0 && timeClient.getMinutesInt() && timeClient.getSecondsInt() < 10){
ESP.restart();
}
*/
if(forceUpdateData) forceUpdateData = false;
}
}
// Called if WiFi has not been configured yet
void configModeCallback (WiFiManager *myWiFiManager) {
ui.setTextAlignment(CENTER);
tft.setFont(6);
tft.setColor(BLUE);
ui.drawString(10, 28, "Wifi Manager");
ui.drawString(10, 42, "Please connect to AP");
tft.setColor(WHITE);
ui.drawString(10, 56, myWiFiManager->getConfigPortalSSID());
tft.setColor(BLUE);
ui.drawString(10, 70, "To setup Wifi Configuration");
}
// callback called during download of files. Updates progress bar
void downloadCallback(String filename, int16_t bytesDownloaded, int16_t bytesTotal) {
Serial.println(String(bytesDownloaded) + " / " + String(bytesTotal));
int percentage = 100 * bytesDownloaded / bytesTotal;
if (percentage == 0) {
ui.drawString(10,160,filename);
}
if (percentage % 5 == 0) {
ui.setTextAlignment(CENTER);
tft.setColor(BLUE);
ui.drawString(10,160,String(percentage) + "%");
ui.drawProgressBar(10, 165, 156 , 15, percentage, WHITE, BLUE);
}
}
// Download the bitmaps
void downloadResources() {
tft.setDrawWindow(0, 0, 176, 220);
tft.setBgColor(BLACK);
tft.cleanDrawWindow(); //clear draw window use the new back ground color
tft.setFont(6);
char id[5];
for (int i = 0; i < 21; i++) {
sprintf(id, "%02d", i);
tft.setColor(BLUE);
tft.drawBox(0, 120, 176/20*(i+1), 40);
tft.setColor(RED|BLUE);
ui.drawString(10,138,String(id)+" "+wundergroundIcons[i]);
webResource.downloadFile("http://www.squix.org/blog/wunderground/" + wundergroundIcons[i] + ".bmp", wundergroundIcons[i] + ".bmp", _downloadCallback);
}
for (int i = 0; i < 21; i++) {
sprintf(id, "%02d", i);
tft.setColor(RED);
tft.drawBox(0, 120, 176/20*(i+1), 40);
tft.setColor(RED|BLUE);
ui.drawString(10,138,String(id)+" mini "+wundergroundIcons[i]);
webResource.downloadFile("http://www.squix.org/blog/wunderground/mini/" + wundergroundIcons[i] + ".bmp", "/mini/" + wundergroundIcons[i] + ".bmp", _downloadCallback);
}
for (int i = 0; i < 23; i++) {
sprintf(id, "%02d", i);
tft.setColor(WHITE);
tft.drawBox(0, 120, 176/22*(i+1), 40);
tft.setColor(RED|BLUE);
ui.drawString(10,138,String(id)+" moon ");
webResource.downloadFile("http://www.squix.org/blog/moonphase_L" + String(i) + ".bmp", "/moon" + String(i) + ".bmp", _downloadCallback);
}
}
/********************************************************************************************************/
void installFonts(){
tft.setDrawWindow(0, 0, 176, 220);
tft.setBgColor(BLACK);
tft.cleanDrawWindow();
tft.setColor(WHITE);
tft.setFont(10);
tft.drawStr(0, 0, "Installing Fonts");
Serial.println("Installing Fonts");
tft.drawStr(0, 1, "Tahoma:");
delay(1000); //This delay is very important, it will let the module clean the receiving buffer,then accept bulk data bellow
tft.downloadUserFont(sizeof(tahoma22), tahoma22, 1); //download a user font: (font length, font address, #userfont), one time download needed
delay(500);
tft.drawStr(0, 2, "Comic:");
delay(1000); //This delay is very important, it will let the module clean the receiving buffer,then accept bulk data bellow
tft.downloadUserFont(sizeof(comic40), comic40, 2); //download a user font: (font length, font address, #userfont), one time download needed
delay(500);
tft.drawStr(0, 3, "System:");
delay(1000); //This delay is very important, it will let the module clean the receiving buffer,then accept bulk data bellow
tft.downloadUserFont(sizeof(sysfont12), sysfont12, 3); //download a user font: (font length, font address, #userfont), one time download needed
delay(500);
tft.drawStr(0, 4, "OK");
delay(500);
tft.cleanDrawWindow();
}
// Update the internet based information and update screen
void updateData() { updateData(true); }
void updateData(bool visual) {
tft.setDrawWindow(0, 0, 176, 220);
tft.setBgColor(BLACK);
if(visual){
tft.cleanDrawWindow(); //clear draw window use the new back ground color
tft.setColor(WHITE);
tft.setFont(font_System10);
drawProgress(20, "Updating time...");
}
timeClient.updateTime();
if(visual) drawProgress(50, "Updating conditions...");
wunderground.updateConditions(WUNDERGRROUND_API_KEY, WUNDERGRROUND_LANGUAGE, WUNDERGROUND_COUNTRY, WUNDERGROUND_CITY);
if(visual) drawProgress(70, "Updating forecasts...");
wunderground.updateForecast(WUNDERGRROUND_API_KEY, WUNDERGRROUND_LANGUAGE, WUNDERGROUND_COUNTRY, WUNDERGROUND_CITY);
if(visual) drawProgress(90, "Updating astronomy...");
wunderground.updateAstronomy(WUNDERGRROUND_API_KEY, WUNDERGRROUND_LANGUAGE, WUNDERGROUND_COUNTRY, WUNDERGROUND_CITY);
//lastUpdate = timeClient.getFormattedTime();
//readyForWeatherUpdate = false;
if(visual) drawProgress(100, "Done................");
delay(1000);
if(visual){
tft.setDrawWindow(0, 0, 176, 220);
tft.setBgColor(BLACK);
tft.cleanDrawWindow(); //clear draw window use the new back ground color
}
drawTime();
drawCurrentWeather();
drawForecast();
drawAstronomy();
}
// Progress bar helper
void drawProgress(uint8_t percentage, String text) {
tft.setColor(BLACK);
tft.drawBox(0, 140, 240, 45);
tft.setColor(WHITE);
tft.setFont(6);
ui.drawString(10,186,text);
ui.drawProgressBar(10, 165, 156, 15, percentage, WHITE, BLUE);
}
// draws the clock
void drawTime() { drawTime(true); }
void drawTime(bool clear) {
tft.setDrawWindow(0, 0, 176, 55);
tft.setBgColor(BLACK);
if(clear)
tft.cleanDrawWindow(); //clear draw window use the new back ground color
ui.setTextAlignment(CENTER);
tft.setFont(font_System10);
String date = wunderground.getDate();
tft.setColor(WHITE);
ui.drawString(38,15,date);
tft.setColor(BLUE);
tft.setFont(font_Comic40);
String time = " "+timeClient.getHours() + ":" + timeClient.getMinutes()+" ";
ui.drawString(25,54,time);
// drawSeparator(55);
}
// draws current weather information
void drawCurrentWeather() {
tft.setDrawWindow(0, 45, 176, 90);
tft.setBgColor(BLACK);
// Weather Icon
tft.setDrawWindow(0, 45, 88, 90);
String weatherIcon = getMeteoconIcon(wunderground.getTodayIcon());
ui.drawBmp(weatherIcon + ".bmp", 0, 0);
tft.setDrawWindow(88, 45, 88, 90);
tft.setBgColor(BLACK);
tft.cleanDrawWindow(); //clear draw window use the new back ground color
// City
tft.setFont(6);
tft.setColor(WHITE);
ui.setTextAlignment(RIGHT);
ui.drawString(95, 13, WUNDERGROUND_CITY);
// Weather Text
tft.setFont(font_System10);
tft.setColor(WHITE);
ui.setTextAlignment(RIGHT);
ui.drawString(95, 25, wunderground.getWeatherText());
tft.setFont(/*font_Comic40*/font_Tahoma22);
tft.setColor(BLUE);
ui.setTextAlignment(RIGHT);
char tmp[6];
String temp = wunderground.getCurrentTemp();
float t = atof(temp.c_str());
Serial.print("atof: "); Serial.println(t);
dtostrf(t, 4, 1, tmp);
if(t>0) tft.setTrueColor(20+map(t,0,40,0,43),43,50); /*tft.setColor(RED);*/
tft.setFont(font_Tahoma22);
if(t>0) ui.drawString(88,44,"+");
else if(t<0) ui.drawString(88,44,"-");
dtostrf(abs(t), 4, 1, tmp);
tft.setFont(font_Comic40);
ui.drawString(98,37,tmp);
tft.setMode('|');
String degreeSign = IS_METRIC?"C":"F";
tft.setFont(font_System10);
ui.setTextAlignment(RIGHT);
ui.drawString(160, 40, degreeSign);
tft.setMode('C');
// drawSeparator(125);
}
// draws the three forecast columns
void drawForecast() {
tft.setDrawWindow(0, 130, 176, 70);
tft.setBgColor(BLACK);
// tft.cleanDrawWindow(); //clear draw window use the new back ground color
tft.setDrawWindow(10, 130, 65, 17);
tft.setBgColor(BLACK);
tft.cleanDrawWindow(); //clear draw window use the new back ground color
tft.setDrawWindow(0, 130, 176, 70);
drawForecastDetail(10, 0, 0);
tft.setDrawWindow(65, 130, 55, 17);
tft.setBgColor(BLACK);
tft.cleanDrawWindow(); //clear draw window use the new back ground color
tft.setDrawWindow(0, 130, 176, 70);
drawForecastDetail(65, 0, 2);
tft.setDrawWindow(120, 130, 60, 17);
tft.setBgColor(BLACK);
tft.cleanDrawWindow(); //clear draw window use the new back ground color
tft.setDrawWindow(0, 130, 176, 70);
drawForecastDetail(120, 0, 4);
// drawSeparator(210);
}
// helper for the forecast columns
void drawForecastDetail(uint16_t x, uint16_t y, uint8_t dayIndex) {
tft.setColor(BLUE);
tft.setFont(6);
ui.setTextAlignment(CENTER);
String day = wunderground.getForecastTitle(dayIndex).substring(0, 3);
day.toUpperCase();
tft.setColor(WHITE);
ui.drawString(x + 2, y + 18, day+" ");
tft.setFont(font_System10);
tft.setColor(BLUE);
tft.print(wunderground.getForecastLowTemp(dayIndex) + "|" + wunderground.getForecastHighTemp(dayIndex));
String weatherIcon = getMeteoconIcon(wunderground.getForecastIcon(dayIndex));
ui.drawBmp("/mini/" + weatherIcon + ".bmp", x, y + 18);
}
// draw moonphase and sunrise/set and moonrise/set
void drawAstronomy() {
tft.setDrawWindow(0, 198, 176, 24);
tft.setBgColor(BLACK);
// tft.cleanDrawWindow(); //clear draw window use the new back ground color
int moonAgeImage = 24 * wunderground.getMoonAge().toInt() / 30.0;
ui.drawBmp("/moon" + String(moonAgeImage) + ".bmp", 78, 0, 4);
tft.setFont(6);
tft.setDrawWindow(0, 198, 76, 24);
tft.setBgColor(BLACK);
tft.cleanDrawWindow(); //clear draw window use the new back ground color
tft.setDrawWindow(0, 198, 176, 24);
ui.setTextAlignment(LEFT);
tft.setColor(BLUE);
ui.drawString(10, 12, wunderground.getSunriseTime());
tft.setColor(WHITE);
tft.print(" Sun ");
tft.setColor(BLUE);
tft.print(wunderground.getSunsetTime());
tft.setDrawWindow(100, 198, 76, 24);
tft.setBgColor(BLACK);
tft.cleanDrawWindow(); //clear draw window use the new back ground color
tft.setDrawWindow(0, 198, 176, 24);
ui.setTextAlignment(RIGHT);
tft.setColor(BLUE);
ui.drawString(100, 12, wunderground.getMoonriseTime());
tft.setColor(WHITE);
tft.print(" Moon ");
tft.setColor(BLUE);
tft.print(wunderground.getMoonsetTime());
}
// Helper function, should be part of the weather station library and should disappear soon
String getMeteoconIcon(String iconText) {
if (iconText == "F") return "chanceflurries";
if (iconText == "Q") return "chancerain";
if (iconText == "W") return "chancesleet";
if (iconText == "V") return "chancesnow";
if (iconText == "S") return "chancetstorms";
if (iconText == "B") return "clear";
if (iconText == "Y") return "cloudy";
if (iconText == "F") return "flurries";
if (iconText == "M") return "fog";
if (iconText == "E") return "hazy";
if (iconText == "Y") return "mostlycloudy";
if (iconText == "H") return "mostlysunny";
if (iconText == "H") return "partlycloudy";
if (iconText == "J") return "partlysunny";
if (iconText == "W") return "sleet";
if (iconText == "R") return "rain";
if (iconText == "W") return "snow";
if (iconText == "B") return "sunny";
if (iconText == "0") return "tstorms";
return "unknown";
}
// if you want separators, uncomment the tft-line
void drawSeparator(uint16_t y) {
tft.drawLine(10, y, 176 - 2 * 10, y);
}
| 32.007924
| 170
| 0.686389
|
e35d5a172dad09fb4b180770408eda857d722916
| 2,289
|
ino
|
Arduino
|
arduino/libraries/bitflame/examples/serial-bitflame-step-by-step/serial-bitflame-step-by-step.ino
|
miaucl/bitflame
|
8da1dfee3396d0e637f7238e57199bfa615e79db
|
[
"MIT"
] | 1
|
2021-08-08T08:10:14.000Z
|
2021-08-08T08:10:14.000Z
|
arduino/libraries/bitflame/examples/serial-bitflame-step-by-step/serial-bitflame-step-by-step.ino
|
miaucl/bitflame
|
8da1dfee3396d0e637f7238e57199bfa615e79db
|
[
"MIT"
] | null | null | null |
arduino/libraries/bitflame/examples/serial-bitflame-step-by-step/serial-bitflame-step-by-step.ino
|
miaucl/bitflame
|
8da1dfee3396d0e637f7238e57199bfa615e79db
|
[
"MIT"
] | null | null | null |
#include "bitflame.h"
#define WIDTH 10
#define HEIGHT 10
#define HEAT 0.2f
#define CO2 0.02f
#define CINDER 1
#define FADE 1
#define MONITOR_LINE_HEIGHT 60 // Change this value if you see the old images scrolling up
Bitflame<HEIGHT, WIDTH> bitflame;
void setup()
{
Serial.begin(9600);
while (!Serial) { ; /* wait for serial port to connect. Needed for native USB port only */ }
Serial.println("Initialize <bitflame> example…");
// Set parameters
bitflame.setBitflameHeat(HEAT);
bitflame.setBitflameCO2(CO2);
bitflame.setBitflameCinder(CINDER);
Serial.println("Parameters:");
Serial.print("\t HEAT: ");
Serial.println(bitflame.getBitflameHeat(), 4);
Serial.print("\t CO2: ");
Serial.println(bitflame.getBitflameCO2(), 4);
Serial.print("\t CINDER: ");
Serial.println(bitflame.getBitflameCinder());
// Init matrix
bitflame.init();
Serial.println("Size:");
Serial.print("\t HEIGHT: ");
Serial.println(HEIGHT);
Serial.print("\t WIDTH: ");
Serial.println(WIDTH);
// Ready
while (Serial.available() > 0) Serial.read(); // Flush
Serial.println();
Serial.println("Ready, waiting for user input to start…");
while (Serial.available() == 0) ; // Wait
while (Serial.available() > 0) Serial.read(); // Flush
Serial.println("Go!");
delay(1000);
printBitflame();
}
void printBitflame()
{
for (int i = 0; i<MONITOR_LINE_HEIGHT; i++) Serial.println();
for (int y = 0; y<HEIGHT; y++)
{
for (int x = 0; x<WIDTH; x++)
{
Serial.print(bitflame.getValue(y, x) ? "x" : ".");
}
Serial.println();
}
Serial.println();
}
void printBitflameFaded()
{
for (int i = 0; i<MONITOR_LINE_HEIGHT; i++) Serial.println();
for (int y = 0; y<HEIGHT; y++)
{
for (int x = 0; x<WIDTH; x++)
{
double v = bitflame.getFadedValue(y, x);
if (v > 0.6) Serial.print("* ");
else if (v > 0.3) Serial.print("- ");
else if (v > 0.0) Serial.print(". ");
else Serial.print(" ");
}
Serial.println();
}
Serial.println();
}
void loop()
{
Serial.println("Ready, waiting for user input for next frame…");
while (Serial.available() == 0) ; // Wait
while (Serial.available() > 0) Serial.read(); // Flush
bitflame.next();
if (FADE) printBitflameFaded();
else printBitflame();
}
| 23.597938
| 94
| 0.630406
|
fa2be1d4fdb1501b7e8203269c7292e4722b5205
| 2,054
|
ino
|
Arduino
|
OnBoardADC/OnBoardADC.ino
|
Sanjit1/ThermistorArduino
|
29d8ba456f7a1b0ffab41fba5b04a723a394960f
|
[
"MIT"
] | 4
|
2019-07-22T04:14:05.000Z
|
2019-10-08T15:48:54.000Z
|
OnBoardADC/OnBoardADC.ino
|
Sanjit1/ThermistorArduino
|
29d8ba456f7a1b0ffab41fba5b04a723a394960f
|
[
"MIT"
] | null | null | null |
OnBoardADC/OnBoardADC.ino
|
Sanjit1/ThermistorArduino
|
29d8ba456f7a1b0ffab41fba5b04a723a394960f
|
[
"MIT"
] | null | null | null |
/*
*
* This code snippet uses arduinos onboard ADC(Analog to digital Convertor).
* Look at externalAdc for code using Ads1115
* go to sanjit1.github.io/Calibrator for more info
Reference Formulas:
Voltage Divider
_____
| |
| R1
Vin |
_____ |___ Vout
--- |
| R2
| |
|_____|
Vout = Vin*R2/(R1+R2)
Simplified to: R1 = R2(Vin-Vout)/Vout
Steinhart-hart Equation:
1/T = A + B(ln(R)) + C(ln^3(R))
*/
// Voltage Divider Variables
double opVolt = 5; // The voltage at which Arduino operates
double basRes = 10000; // resistance R1
// Steinhart-hart Variables To calibrate, go to sanjit1.github.io/Calibrator/webCalibrator.html
double A = 0.0021085081731127137;
double B = 0.00007979204726779823;
double C = 6.535076314649466e-7;
double e = 2.7182818284590452353602874713527;
void setup() {
Serial.begin(9600); // initialize the Serial Object
}
void loop() {
Serial.println(getTemp(A0, A, B, C)); // print the Temperature using the get temp Function
delay(1000); // wait for a second before giving another reading
}
double getTemp(int pin, double Av , double Bv , double Cv) {
double res = getR(pin);
return (1.0 / (Av + Bv * (double)ln(res) + Cv * (double)cb((double)ln(res)))) - 273.15;
//Use the steinhart-Hart equation with the resistance from analog input
}
double getR(int pin) {
double v = getV(pin);
return (basRes * (opVolt - v) / v); // use the simplified voltage divider equation to find resistance
}
double getV(int pin) {
double volt = ((double)(analogRead(pin)/ (double)1024) * opVolt;
/* Theory time:
* Arduinos Onboard ADC reads from 0 to 1023(10 bit)
* Since there are 1024 values possible, giving a range of 5 volts, we need to divide by 1024 and multiply by 5 volts.
*/
return volt;
}
double ln(double val) {
return (log(val) / log (e));
// Natural log function
}
double cb(double val) {
return val * val * val;
// cube function, cuz why not
}
| 26.675325
| 120
| 0.644109
|
9de45513fb6c037f38aac56af56417984aa7fb23
| 9,384
|
ino
|
Arduino
|
Code/ePiano/ePiano.ino
|
ctag-fh-kiel/troll-8
|
18b872b5b0290dbb0e9f514edea392601a896346
|
[
"CC-BY-4.0"
] | 11
|
2017-11-01T14:47:33.000Z
|
2022-01-31T09:04:44.000Z
|
Code/ePiano/ePiano.ino
|
ctag-fh-kiel/troll-8
|
18b872b5b0290dbb0e9f514edea392601a896346
|
[
"CC-BY-4.0"
] | null | null | null |
Code/ePiano/ePiano.ino
|
ctag-fh-kiel/troll-8
|
18b872b5b0290dbb0e9f514edea392601a896346
|
[
"CC-BY-4.0"
] | 3
|
2017-11-20T17:22:12.000Z
|
2021-11-08T23:23:13.000Z
|
/* TROLL8 uSynth Development Platform
(c) 2017 www.creative-technologies.de
Main author robert.manzke@fh-kiel.de
Contributors Henrik Langer FH-Kiel, Alexander Konradi FH-Kiel
Licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License
*/
//#include <ADC.h> // Teensy 3.1 uncomment this line and install http://github.com/pedvide/ADC
#include <MozziGuts.h>
#include <Sample.h>
#include "Samples/piano.h"
#include "Samples/click.h"
#include <Metronome.h>
#include <SPI.h>
#define SPI_SS 10
// Reset Pin is used for I2C or SPI
#define CAP1188_RESET A7
// CS pin is used for software or hardware SPI
#define CAP1188_CS1 6
#define CAP1188_CS2 7
#define CAP1188_SENINPUTSTATUS 0x3
#define CAP1188_MTBLK 0x2A
#define CAP1188_LEDLINK 0x72
#define CAP1188_PRODID 0xFD
#define CAP1188_MANUID 0xFE
#define CAP1188_STANDBYCFG 0x41
#define CAP1188_CONFIG1 0x20
#define CAP1188_CONFIG2 0x44
#define CAP1188_INT 0x27
#define CAP1188_REV 0xFF
#define CAP1188_MAIN 0x00
#define CAP1188_MAIN_INT 0x01
#define CAP1188_LEDPOL 0x73
#define CAP1188_SENSITIVITY_CTRL 0x1F
#define CAP1188_AVERAGING_SAMPLE_REG 0x24
// MCP23S18 definitions
#define MCP23S18_IODIRA 0x00
#define MCP23S18_IODIRB 0x01
#define MCP23S18_IPOLA 0x02
#define MCP23S18_IPOLB 0x03
#define MCP23S18_GPINTENA 0x04
#define MCP23S18_GPINTENB 0x05
#define MCP23S18_DEFVALA 0x06
#define MCP23S18_DEFVALB 0x07
#define MCP23S18_INTCONA 0x08
#define MCP23S18_INTCONB 0x09
#define MCP23S18_IOCONA 0x0a
#define MCP23S18_IOCONB 0x0b
#define MCP23S18_GPPUA 0x0c
#define MCP23S18_GPPUB 0x0d
#define MCP23S18_INTFA 0x0e
#define MCP23S18_INTFB 0x0f
#define MCP23S18_INTCAPA 0x10
#define MCP23S18_INTCAPB 0x11
#define MCP23S18_GPIOA 0x12
#define MCP23S18_GPIOB 0x13
#define MCP23S18_OLATA 0x14
#define MCP23S18_OLATB 0x15
#define CONTROL_RATE 64 // powers of 2 please
#define AUDIO_MODE STANDARD
uint16_t voiceOnOff = 0x0;
uint16_t voiceOnOff_o = 0x0;
byte gain[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Sample<piano_NUM_CELLS, AUDIO_RATE> samplePiano[16];
Sample<click_NUM_CELLS, AUDIO_RATE> sampleClick(click_DATA);
byte cs_o[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
byte v_max[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Metronome clickMetro(500);
byte clickGain = 127;
uint16_t sequencerClock = 0;
byte barCount = 0;
void init_gpio()
{
// port a as output
writeRegGPIO(MCP23S18_IODIRA, 0x00);
// port b as input with pullup
writeRegGPIO(MCP23S18_IODIRB, 0xff);
writeRegGPIO(MCP23S18_GPPUB, 0xff);
}
void reset_gpio()
{
pinMode(A4, OUTPUT);
digitalWrite(A4, HIGH);
delay(100);
digitalWrite(A4, LOW);
delay(100);
digitalWrite(A4, HIGH);
delay(100);
}
void writeRegGPIO(byte adr, byte v)
{
digitalWrite(A0, 0x1); // a2
digitalWrite(A1, 0x0); // a1
digitalWrite(A2, 0x1); // a0
//noInterrupts();
digitalWrite(SPI_SS, LOW);
SPI.transfer(0x40);
SPI.transfer(adr);
SPI.transfer(v);
digitalWrite(SPI_SS, HIGH);
//interrupts();
}
byte readRegGPIO(byte adr)
{
digitalWrite(A0, 0x1); // a2
digitalWrite(A1, 0x0); // a1
digitalWrite(A2, 0x1); // a0
byte res = 0;
digitalWrite(SPI_SS, LOW);
SPI.transfer(0x41);
SPI.transfer(adr);
res = SPI.transfer(0);
digitalWrite(SPI_SS, HIGH);
return res;
}
void writeRegCS(byte chip, byte adr, byte v){
digitalWrite(A0, chip & 0x04);
digitalWrite(A1, chip & 0x02);
digitalWrite(A2, chip & 0x01);
digitalWrite(SPI_SS, LOW);
SPI.transfer(0x7d);
SPI.transfer(adr);
SPI.transfer(0x7e);
SPI.transfer(v);
digitalWrite(SPI_SS, HIGH);
}
byte readRegCS(byte chip, byte adr){
digitalWrite(A0, chip & 0x04);
digitalWrite(A1, chip & 0x02);
digitalWrite(A2, chip & 0x01);
byte res = 0;
digitalWrite(SPI_SS, LOW);
SPI.transfer(0x7d);
SPI.transfer(adr);
SPI.transfer(0x7f);
res = SPI.transfer(0);
digitalWrite(SPI_SS, HIGH);
return res;
}
void reset_cs()
{
pinMode(A3, OUTPUT);
digitalWrite(A3, LOW);
delay(100);
digitalWrite(A3, HIGH);
delay(100);
digitalWrite(A3, LOW);
delay(100);
}
void init_cs_chip(byte chip)
{
byte reg;
writeRegCS(chip, CAP1188_MTBLK, 0);
writeRegCS(chip, CAP1188_LEDLINK, 0xFF);
writeRegCS(chip, CAP1188_STANDBYCFG, 0x30);
writeRegCS(chip, 0x28, 0x00);
reg = readRegCS(chip, CAP1188_SENSITIVITY_CTRL);
reg &= 0x0f;
reg |= 0x20; // sensitivity here, larger = less sensitive
writeRegCS(chip, CAP1188_SENSITIVITY_CTRL, reg);
writeRegCS(chip, CAP1188_AVERAGING_SAMPLE_REG, 0x00);
reg = readRegCS(chip, CAP1188_CONFIG2);
reg &= ~0x40;
writeRegCS(chip, CAP1188_CONFIG2, reg);
writeRegCS(chip, CAP1188_MAIN, readRegCS(chip, CAP1188_MAIN) & ~CAP1188_MAIN_INT);
}
void init_cs()
{
init_cs_chip(0);
init_cs_chip(1);
}
uint16_t readADC(byte chan)
{
digitalWrite(A0, 0x0); // a2
digitalWrite(A1, 0x1); // a1
digitalWrite(A2, 0x0); // a0
uint16_t res;
//noInterrupts();
digitalWrite(SPI_SS, LOW);
SPI.transfer(0x01);
res = SPI.transfer((chan<<4)|0x80);
res = (res&0x03)<<8;
res |= SPI.transfer(0);
digitalWrite(SPI_SS, HIGH);
//interrupts();
return res;
}
void setup(){
Serial.begin(115200);
startMozzi(); // start with default control rate of 64
pinMode(A0, OUTPUT);
digitalWrite(A0, LOW);
pinMode(A1, OUTPUT);
digitalWrite(A1, LOW);
pinMode(A2, OUTPUT);
digitalWrite(A2, HIGH);
pinMode(SPI_SS, OUTPUT);
digitalWrite(SPI_SS, HIGH);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV8);
SPI.setDataMode(SPI_MODE0);
reset_cs();
init_cs();
reset_gpio();
init_gpio();
float f = (float)piano_SAMPLERATE/(float)piano_NUM_CELLS;
for(int i=0;i<16;i++){
samplePiano[i] = Sample<piano_NUM_CELLS, AUDIO_RATE>(piano_DATA);
samplePiano[i].setFreq(f);
f *= 1.05946309; // 12th root of 2
}
sampleClick.setFreq((float)click_SAMPLERATE/(float)click_NUM_CELLS);
clickMetro.start();
writeRegGPIO(MCP23S18_GPIOA, 0xff);
writeRegGPIO(MCP23S18_GPIOB, 0xff);
}
void updateVelocityReads(){
byte cs[16];
int v;
cs[0] = readRegCS(0, 0x10);
cs[1] = readRegCS(0, 0x11);
cs[2] = readRegCS(0, 0x12);
cs[3] = readRegCS(0, 0x13);
cs[4] = readRegCS(0, 0x14);
cs[5] = readRegCS(0, 0x15);
cs[6] = readRegCS(0, 0x16);
cs[7] = readRegCS(0, 0x17);
cs[8] = readRegCS(1, 0x10);
cs[9] = readRegCS(1, 0x11);
cs[10] = readRegCS(1, 0x12);
cs[11] = readRegCS(1, 0x13);
cs[12] = readRegCS(1, 0x14);
cs[13] = readRegCS(1, 0x15);
cs[14] = readRegCS(1, 0x16);
cs[15] = readRegCS(1, 0x17);
for(byte i=0;i<16;i++){
v = cs[i] - cs_o[i];
cs_o[i] = cs[i];
if(v>v_max[i])
v_max[i] = v;
}
//Serial.println(v_max[0]);
}
byte vToGain(int v){
if(v>121)v=121;
if(v<90)v=90;
v-=90;
v<<=3;
if(v<32)v=32;
return (byte) v;
}
void updateControl(){
// real-time piano stuff
updateVelocityReads();
writeRegCS(0, CAP1188_MAIN, readRegCS(0, CAP1188_MAIN) & ~CAP1188_MAIN_INT);
voiceOnOff = (uint16_t)readRegCS(0, CAP1188_SENINPUTSTATUS);
writeRegCS(1, CAP1188_MAIN, readRegCS(1, CAP1188_MAIN) & ~CAP1188_MAIN_INT);
voiceOnOff |= (uint16_t)readRegCS(1, CAP1188_SENINPUTSTATUS)<<8;
for(int i=0;i<16;i++){
if((voiceOnOff & ~voiceOnOff_o) & (0x1<<i)){
gain[i] = vToGain(v_max[i]);
v_max[i] = 0;
samplePiano[i].start();
}
}
voiceOnOff_o = voiceOnOff;
// sequencer stuff
static byte bar = 0;
static byte btns_last = 0xff;
byte btns = ~(readRegGPIO(MCP23S18_GPIOB)&0x0f);
static byte stat = 0x00;
if(btns && (btns != btns_last))
stat ^= btns & ~btns_last;
btns_last = btns;
if(clickMetro.ready()){
if(barCount%4) clickGain = 200;
else{
clickGain = 255;
bar++;
if(bar>3){
bar = 0;
Serial.println(sequencerClock);
sequencerClock = 0;
}
}
if(stat&0x1)
sampleClick.start();
stat^=(1<<(bar+4))&0xf0;
barCount++;
}
clickMetro.set(2050 - ((readADC(7)&0xfffc)<<1));
writeRegGPIO(MCP23S18_GPIOA, ~stat);
}
int updateAudio(){
int s = 0;
sequencerClock++;
if(voiceOnOff&0x01)
s += (samplePiano[0].next()*gain[0])>>8;
if(voiceOnOff&0x02)
s += (samplePiano[1].next()*gain[1])>>8;
if(voiceOnOff&0x04)
s += (samplePiano[2].next()*gain[2])>>8;
if(voiceOnOff&0x08)
s += (samplePiano[3].next()*gain[3])>>8;
if(voiceOnOff&0x10)
s += (samplePiano[4].next()*gain[4])>>8;
if(voiceOnOff&0x20)
s += (samplePiano[5].next()*gain[5])>>8;
if(voiceOnOff&0x40)
s += (samplePiano[6].next()*gain[6])>>8;
if(voiceOnOff&0x80)
s += (samplePiano[7].next()*gain[7])>>8;
if(voiceOnOff&0x0100)
s += (samplePiano[8].next()*gain[8])>>8;
if(voiceOnOff&0x0200)
s += (samplePiano[9].next()*gain[9])>>8;
if(voiceOnOff&0x0400)
s += (samplePiano[10].next()*gain[10])>>8;
if(voiceOnOff&0x0800)
s += (samplePiano[11].next()*gain[11])>>8;
if(voiceOnOff&0x1000)
s += (samplePiano[12].next()*gain[12])>>8;
if(voiceOnOff&0x2000)
s += (samplePiano[13].next()*gain[13])>>8;
if(voiceOnOff&0x4000)
s += (samplePiano[14].next()*gain[14])>>8;
if(voiceOnOff&0x8000)
s += (samplePiano[15].next()*gain[15])>>8;
s += (sampleClick.next()*clickGain)>>7;
return s;
}
void loop(){
audioHook(); // required here
}
| 23.401496
| 95
| 0.66656
|
84d8c71c15ecaf06d2e8a58d91f48597a324f309
| 2,744
|
ino
|
Arduino
|
Code_arduino/arduino-1.0.6/libraries/GSM/examples/Tools/BandManagement/BandManagement.ino
|
NeLy-EPFL/SeptaCam
|
7cdf6031193fc68ae5527578e2fd21ea1ed8ee0a
|
[
"MIT"
] | 6
|
2015-05-16T22:07:32.000Z
|
2020-02-21T02:19:04.000Z
|
Code_arduino/arduino-1.0.6/libraries/GSM/examples/Tools/BandManagement/BandManagement.ino
|
NeLy-EPFL/SeptaCam
|
7cdf6031193fc68ae5527578e2fd21ea1ed8ee0a
|
[
"MIT"
] | 52
|
2015-01-02T05:50:10.000Z
|
2021-07-23T20:34:50.000Z
|
Code_arduino/arduino-1.0.6/libraries/GSM/examples/Tools/BandManagement/BandManagement.ino
|
NeLy-EPFL/SeptaCam
|
7cdf6031193fc68ae5527578e2fd21ea1ed8ee0a
|
[
"MIT"
] | 5
|
2015-08-24T10:05:30.000Z
|
2021-12-18T11:58:03.000Z
|
/*
Band Management
This sketch, for the Arduino GSM shield, checks the band
currently configured in the modem and allows you to change
it.
Please check http://www.worldtimezone.com/gsm.html
Usual configurations:
Europe, Africa, Middle East: E-GSM(900)+DCS(1800)
USA, Canada, South America: GSM(850)+PCS(1900)
Mexico: PCS(1900)
Brazil: GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)
Circuit:
* GSM shield
created 12 June 2012
by Javier Zorzano, Scott Fitzgerald
This example is in the public domain.
*/
// libraries
#include <GSM.h>
// initialize the library instance
GSMBand band;
void setup()
{
// initialize serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// Beginning the band manager restarts the modem
Serial.println("Restarting modem...");
band.begin();
Serial.println("Modem restarted.");
};
void loop()
{
// Get current band
String bandName = band.getBand(); // Get and print band name
Serial.print("Current band:");
Serial.println(bandName);
Serial.println("Want to change the band you’re on?");
String newBandName;
newBandName = askUser();
// Tell the user what we are about to do…
Serial.print("\nConfiguring band ");
Serial.println(newBandName);
// Change the band
boolean operationSuccess;
operationSuccess = band.setBand(newBandName);
// Tell the user if the operation was OK
if(operationSuccess)
{
Serial.println("Success");
}
else
{
Serial.println("Error while changing band");
}
if(operationSuccess)
{
while(true);
}
}
// This function offers the user different options
// through the Serial interface
// The user selects one
String askUser()
{
String newBand;
Serial.println("Select band:");
// Print the different options
Serial.println("1 : E-GSM(900)");
Serial.println("2 : DCS(1800)");
Serial.println("3 : PCS(1900)");
Serial.println("4 : E-GSM(900)+DCS(1800) ex: Europe");
Serial.println("5 : GSM(850)+PCS(1900) Ex: USA, South Am.");
Serial.println("6 : GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)");
// Empty the incoming buffer
while(Serial.available())
Serial.read();
// Wait for an answer, just look at the first character
while(!Serial.available());
char c= Serial.read();
if(c=='1')
newBand=GSM_MODE_EGSM;
else if(c=='2')
newBand=GSM_MODE_DCS;
else if(c=='3')
newBand=GSM_MODE_PCS;
else if(c=='4')
newBand=GSM_MODE_EGSM_DCS;
else if(c=='5')
newBand=GSM_MODE_GSM850_PCS;
else if(c=='6')
newBand=GSM_MODE_GSM850_EGSM_DCS_PCS;
else
newBand="GSM_MODE_UNDEFINED";
return newBand;
}
| 22.677686
| 66
| 0.669461
|
248aad3fa367c85a52f2a1f225fb8242d661072b
| 1,368
|
ino
|
Arduino
|
components/arduino/libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopback.ino
|
Jason2866/LILYGO-_T5-4.7-E-Paper_Weather-_Station
|
c41679f84d99c3423a6e7413365804c9acb17458
|
[
"Unlicense"
] | 17
|
2021-07-28T21:57:26.000Z
|
2022-02-28T20:32:04.000Z
|
components/arduino/libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopback.ino
|
Whitolf/esp-idf-arduino
|
0048da468cc844ae5b43b6f568d44d299d60b48a
|
[
"MIT"
] | 7
|
2021-08-07T23:20:14.000Z
|
2022-03-20T15:05:21.000Z
|
components/arduino/libraries/ESP32/examples/RMT/RMTLoopback/RMTLoopback.ino
|
Whitolf/esp-idf-arduino
|
0048da468cc844ae5b43b6f568d44d299d60b48a
|
[
"MIT"
] | 10
|
2021-08-11T13:47:36.000Z
|
2022-03-26T02:41:45.000Z
|
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "Arduino.h"
#include "esp32-hal.h"
rmt_data_t my_data[256];
rmt_data_t data[256];
rmt_obj_t* rmt_send = NULL;
rmt_obj_t* rmt_recv = NULL;
static EventGroupHandle_t events;
void setup()
{
Serial.begin(115200);
events = xEventGroupCreate();
if ((rmt_send = rmtInit(18, true, RMT_MEM_64)) == NULL)
{
Serial.println("init sender failed\n");
}
if ((rmt_recv = rmtInit(21, false, RMT_MEM_192)) == NULL)
{
Serial.println("init receiver failed\n");
}
float realTick = rmtSetTick(rmt_send, 100);
printf("real tick set to: %fns\n", realTick);
}
void loop()
{
// Init data
int i;
for (i=0; i<255; i++) {
data[i].val = 0x80010001 + ((i%13)<<16) + 13-(i%13);
}
data[255].val = 0;
// Start receiving
rmtReadAsync(rmt_recv, my_data, 100, events, false, 0);
// Send in continous mode
rmtWrite(rmt_send, data, 100);
// Wait for data
xEventGroupWaitBits(events, RMT_FLAG_RX_DONE, 1, 1, portMAX_DELAY);
// Printout the received data plus the original values
for (i=0; i<60; i++)
{
Serial.printf("%08x=%08x ", my_data[i].val, data[i].val );
if (!((i+1)%4)) Serial.println("\n");
}
Serial.println("\n");
delay(2000);
}
| 21.714286
| 71
| 0.606725
|
9caeae2e8979717d096e7a394d67bec9c4d15b47
| 2,747
|
ino
|
Arduino
|
Distance/Distance/Distance.ino
|
orangecoding/smarthome
|
92bbd10a988b16143aeaf69af202ddbda27fd609
|
[
"MIT"
] | null | null | null |
Distance/Distance/Distance.ino
|
orangecoding/smarthome
|
92bbd10a988b16143aeaf69af202ddbda27fd609
|
[
"MIT"
] | null | null | null |
Distance/Distance/Distance.ino
|
orangecoding/smarthome
|
92bbd10a988b16143aeaf69af202ddbda27fd609
|
[
"MIT"
] | null | null | null |
#define echoPin D6 // Echo Pin
#define trigPin D7 // Trigger Pin
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
#include "config.h"
#define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3"
ADC_MODE(ADC_VCC);
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
Point sensor(DATAPOINT_NAME);
int wasserMin = 20;
int wasserLow = 17;
int wasserMax = 6;
//this is the distance between the top and the max water level
int correctionValue = 8;
long distance = 0;
void setup(){
//safe power
WiFi.mode( WIFI_OFF );
WiFi.persistent( false );
WiFi.forceSleepBegin();
delay( 1 );
Serial.begin(115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
delay( 50 );
distance = getDistance();
delay( 10 );
WiFi.forceSleepWake();
delay( 1 );
WiFi.begin(wifiSsid, wifiKey);
while (WiFi.status() != WL_CONNECTED) {
delay(200);
Serial.print(".");
}
Serial.println("Connected!");
Serial.println(distance);
Serial.println(getPercentage());
pushDataToInflux();
pushDataToHomebridge();
//deep sleep for 60 minutes
ESP.deepSleep(3600000000);
}
void pushDataToInflux() {
float vccVolt = ((float)ESP.getVcc())/1024;
sensor.addField("wasserstand", getPercentage());
sensor.addField("power", vccVolt);
if (!client.writePoint(sensor)) {
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
}else{
Serial.print("Pushed data to InfluxDB.");
}
}
void pushDataToHomebridge() {
HTTPClient http;
String state = getWarning();
//wasserstand min alarm
http.begin(homebridgeWasserstandStateUrl + state);
int httpCode = http.GET();
Serial.println(httpCode);
Serial.println("Send Wasserstand state Value" + String(state));
http.end();
//wasserstand state
float percentage = getPercentage();
http.begin(homebridgeWasserstandUrl + String(percentage));
int httpCode2 = http.GET();
Serial.println(httpCode2);
Serial.println("Send Wasserstand Value" + String(percentage));
http.end();
}
long getDistance(){
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
//Calculate the distance (in cm) based on the speed of sound.
return pulseIn(echoPin, HIGH)/58.2;
}
float getPercentage(){
float percentage = (float)distance / (float)wasserMin * (float)100;
float waterLeftInPercentage = (float)100 - percentage;
if(waterLeftInPercentage < 0){
return 0;
}
return waterLeftInPercentage;
}
String getWarning(){
if(distance >= wasserMin){
return "true";
}else{
return "false";
}
}
void loop() {}
| 23.279661
| 105
| 0.698944
|
377cf68ad514a3fd7635facc400900dd8095b566
| 833
|
ino
|
Arduino
|
libraries/Timezone/examples/WriteRules/WriteRules.ino
|
mbutki/arduino_projects
|
ace4a3106de5c2a58705794b410b5f0a359a9991
|
[
"MIT"
] | 6
|
2020-10-20T17:12:21.000Z
|
2021-07-21T21:43:52.000Z
|
libraries/Timezone/examples/WriteRules/WriteRules.ino
|
dpwe/arduinoclocks
|
f73de893a7ca25ab45378af2245dc21eb27da5c7
|
[
"BSD-2-Clause"
] | null | null | null |
libraries/Timezone/examples/WriteRules/WriteRules.ino
|
dpwe/arduinoclocks
|
f73de893a7ca25ab45378af2245dc21eb27da5c7
|
[
"BSD-2-Clause"
] | null | null | null |
// Arduino Timezone Library Copyright (C) 2018 by Jack Christensen and
// licensed under GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html
//
// Arduino Timezone Library example sketch.
// Write TimeChangeRules to EEPROM.
// Jack Christensen Mar 2012
#include <Timezone.h> // https://github.com/JChristensen/Timezone
// US Eastern Time Zone (New York, Detroit)
TimeChangeRule usEdt = {"EDT", Second, Sun, Mar, 2, -240}; // UTC - 4 hours
TimeChangeRule usEst = {"EST", First, Sun, Nov, 2, -300}; // UTC - 5 hours
Timezone usEastern(usEdt, usEst);
void setup()
{
pinMode(13, OUTPUT);
usEastern.writeRules(100); // write rules to EEPROM address 100
}
void loop()
{
// fast blink to indicate EEPROM write is complete
digitalWrite(13, HIGH);
delay(100);
digitalWrite(13, LOW);
delay(100);
}
| 27.766667
| 78
| 0.679472
|
2657b526d2a31a49eac2abeb6f52d52292423f5f
| 13,362
|
ino
|
Arduino
|
code.ino
|
agv-salesians/arduino-v1
|
3eacc3958670098d3a9dea1bfd8c66ed4aef59ed
|
[
"MIT"
] | null | null | null |
code.ino
|
agv-salesians/arduino-v1
|
3eacc3958670098d3a9dea1bfd8c66ed4aef59ed
|
[
"MIT"
] | null | null | null |
code.ino
|
agv-salesians/arduino-v1
|
3eacc3958670098d3a9dea1bfd8c66ed4aef59ed
|
[
"MIT"
] | null | null | null |
#include <AFMotor.h>
#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"
// bluetooth
#define KEY 53 // key
#define POWER 52 // vout
#define RX_PIN 19
#define TX_PIN 18
#define BLUETOOTH_LIVE_BAUD_RATE 9600
#define BLUETOOTH_AP_BAUD_RATE 38400
// button
#define buttonFront 30
#define buttonBack 31
#define readDelay 100
// change history
#define arraySize 100
// encoder channels
#define channel1A 22
#define channel1B 23
#define channel2A 24
#define channel2B 25
#define channel3A 26
#define channel3B 27
#define channel4A 28
#define channel4B 29
const int mpuAddress = 0x68; // Puede ser 0x68 o 0x69
MPU6050 mpu(mpuAddress);
int gx, gy, gz;
// bluetooth
enum mode {
AT1,
AT2,
LIVE
};
// motor definitions
AF_DCMotor motor1(1, MOTOR12_64KHZ);
AF_DCMotor motor2(2, MOTOR12_64KHZ);
AF_DCMotor motor3(3, MOTOR12_64KHZ);
AF_DCMotor motor4(4, MOTOR12_64KHZ);
// buttons
float maxSpeed = 3.75;
bool buttonFrontLast = false;
bool buttonBackLast = false;
long lastButtonFrontChange = 0;
long lastButtonBackChange = 0;
// encoder control
bool lastValue1A = false;
long lastChange1A = 0;
bool lastValue1B = false;
long lastChange1B = 0;
bool lastValue2A = false;
long lastChange2A = 0;
bool lastValue2B = false;
long lastChange2B = 0;
bool lastValue3A = false;
long lastChange3A = 0;
bool lastValue3B = false;
long lastChange3B = 0;
bool lastValue4A = false;
long lastChange4A = 0;
bool lastValue4B = false;
long lastChange4B = 0;
// change history
int channelIndex1A = 0;
long channelHistory1A[arraySize] = {0};
int channelIndex2A = 0;
long channelHistory2A[arraySize] = {0};
int channelIndex3A = 0;
long channelHistory3A[arraySize] = {0};
int channelIndex4A = 0;
long channelHistory4A[arraySize] = {0};
// actual program
bool active = true;
long lastSpeedRead = 0;
// speed control
float speedHistory[4] = {0, 0, 0, 0};
float speeds[4] = {0, 0, 0, 0};
float targetSpeeds[4] = {0, 0, 0, 0};
float swervePower = 0;
int giroCalibrationMax = -32767;
int giroCalibrationMin = 32767;
int giroCalibrationSamples = 0;
int giroOffset = 0;
int giroTrigger = 0;
int giroRepeat = 0;
int lastGiroTrigger = 0;
bool straightMovement = false;
int swervePowerPI = 0;
bool giroCalibrationDone = false;
void setup() {
Serial.begin(9600);
while (!Serial) {
// wait for serial
}
Wire.begin();
mpu.initialize();
mpu.testConnection();
// encoder button
pinMode(buttonFront, INPUT_PULLUP);
pinMode(buttonBack, INPUT_PULLUP);
// encoder setup
pinMode(channel1A, INPUT);
pinMode(channel1B, INPUT);
pinMode(channel1A, INPUT);
pinMode(channel1B, INPUT);
pinMode(channel1A, INPUT);
pinMode(channel1B, INPUT);
pinMode(channel1A, INPUT);
pinMode(channel1B, INPUT);
pinMode(KEY, OUTPUT);
pinMode(POWER, OUTPUT);
Serial.println("Calibrating giro");
while (!giroCalibrationDone) {
calibrateGiro();
}
Serial.println("Giro calibrated. ");
Serial.println(giroCalibrationMax);
Serial.println(giroCalibrationMin);
Serial.println("Giro calibrated. ");
// Serial.println(setupBluetooth("1230"));
changeMode(LIVE);
}
void calibrateGiro() {
mpu.getRotation(&gx, &gy, &gz);
if (giroCalibrationSamples >= 1000) {
giroOffset = -((giroCalibrationMin + giroCalibrationMax) / 2);
giroTrigger = abs(giroCalibrationMax - giroCalibrationMin) * 1.1; // +-10% range
giroCalibrationDone = true;
} else {
if (gx > giroCalibrationMax) {
giroCalibrationMax = gx;
}
if (gx < giroCalibrationMin) {
giroCalibrationMin = gx;
}
giroCalibrationSamples++;
}
}
void changeMode(mode mode) {
Serial1.end();
digitalWrite(KEY, LOW);
digitalWrite(POWER, LOW);
delay(20);
if (mode == AT2) {
Serial1.begin(BLUETOOTH_AP_BAUD_RATE);
digitalWrite(KEY, HIGH);
delay(800);
digitalWrite(POWER, HIGH);
delay(800);
digitalWrite(KEY, LOW);
Serial1.println("AT");
while (!Serial1.available()) {
}
} else if (mode == AT1) {
Serial1.begin(BLUETOOTH_LIVE_BAUD_RATE);
digitalWrite(KEY, HIGH);
digitalWrite(POWER, HIGH);
delay(800);
digitalWrite(KEY, LOW);
} else {
Serial1.begin(BLUETOOTH_LIVE_BAUD_RATE);
digitalWrite(POWER, HIGH);
}
}
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]) : "";
}
String setupBluetooth(String password) {
changeMode(AT2);
Serial1.println("AT+NAME=AGV");
int completed = 0;
while (completed < 1) {
if (Serial1.available()) {
Serial1.readString();
completed++;
}
}
Serial1.print("AT+UART=");
Serial1.print(BLUETOOTH_LIVE_BAUD_RATE);
Serial1.println(",0,0");
while (completed < 2) {
if (Serial1.available()) {
Serial1.readString();
completed++;
}
}
Serial1.println("AT+ROLE=0");
while (completed < 3) {
if (Serial1.available()) {
Serial1.readString();
completed++;
}
}
Serial1.print("AT+PSWD=");
Serial1.println(password);
while (completed < 4) {
if (Serial1.available()) {
Serial1.readString();
completed++;
}
}
Serial1.println("AT+ADDR");
String address = "";
while (completed < 6) {
if (Serial1.available()) {
if (completed == 5) {
address = Serial1.readString();
address = address.substring(6, address.length() - 6);
}
completed++;
}
}
while (Serial1.available()) {
Serial1.readString(); // read missing
}
changeMode(LIVE);
return address;
}
bool shouldReadSpeed() {
if (millis() - lastSpeedRead > 100) {
lastSpeedRead = millis();
return true;
} else {
return false;
}
}
bool shouldButtonTrigger(int pin, bool &last, long &lastChange) {
if (last != digitalRead(pin)) {
last = !last;
if (millis() - lastChange > 100 ) {
lastChange = millis();
return !last;
} else {
return false;
}
} else {
return false;
}
}
bool isFrontButtonTriggered() {
return shouldButtonTrigger(buttonFront, buttonFrontLast, lastButtonFrontChange);
}
bool isBackButtonTriggered() {
return shouldButtonTrigger(buttonBack, buttonBackLast, lastButtonBackChange);
}
bool readEncoder(int channelPin, bool &lastValue, long &lastChange) {
if (digitalRead(channelPin) != lastValue) {
lastValue = !lastValue;
if (lastValue) {
lastChange = micros();
}
return true;
} else {
return false;
}
}
void addToCyclicArray(long *targetArray, int &index, long value) {
targetArray[index] = value;
index++;
if (index >= arraySize) {
index = 0;
}
}
// | | | | | | |
// 0 1 2 3 4
// ^ . .
int countFromCyclicArray(long *targetArray, int index, long until) {
index += -1;
if (index < 0) {
index = arraySize - 1;
}
int untilIndex = index - arraySize;
long val = 0;
int count = 0;
for (index + arraySize; index > untilIndex; index += -1) {
if (index < 0) {
val = targetArray[arraySize + index];
} else {
val = targetArray[index];
}
if (val <= 0 || val < until) {
return count;
} else {
count++;
}
}
return count;
}
float pulsesToRadians(int pulses, int totalPulses, long micros) {
if (pulses > 0) {
float radiansPerDefinedTime = ((float) pulses * (float) 2 * (float) 3.14) / (float) totalPulses;
return radiansPerDefinedTime * (float) 1000000 / (float) micros;
} else {
return 0;
}
}
float radiansToRPM(float radians) {
return (radians / (float) 2 * (float) 3.14) * 60;
}
float getUpdatedSpeed(int count, float *previousSpeed, float *targetSpeed, float *history, int index) {
if (targetSpeed[index] != 0) {
float currentSpeed = pulsesToRadians(count, 1497, (long) readDelay * (long) 1000);
history[index] = currentSpeed;
float error = (targetSpeed[index] - currentSpeed) / maxSpeed * (float) 255;
float deriv = 2 * error;
//integr = integr + (error * 10* 0.05);
if(straightMovement){
}
if (previousSpeed[index] > (float) 255) {
return 255;
} else if (previousSpeed[index] < -255) {
return -255;
} else {
return deriv;
}
} else {
return (float) 0;
}
}
int directionFromSpeed(float speed) {
if (speed > 0) {
return BACKWARD;
} else {
return FORWARD;
}
}
void applyNewSpeed(String val) {
float m1 = (float) getValue(val, ':', 0).toFloat();
float m2 = (float) getValue(val, ':', 1).toFloat();
float m3 = (float) getValue(val, ':', 2).toFloat();
float m4 = (float) getValue(val, ':', 3).toFloat();
targetSpeeds[0] = m1;
targetSpeeds[1] = m2;
targetSpeeds[2] = m3;
targetSpeeds[3] = m4;
}
void updateSwervePower() {
if ((gz > giroCalibrationMax || gz < giroCalibrationMin) && abs(lastGiroTrigger - (gz + giroOffset)) > giroTrigger && (gz > giroCalibrationMax || gz < giroCalibrationMin)) {
lastGiroTrigger = (gz + giroOffset);
} else {
lastGiroTrigger = 0;
}
swervePower = (lastGiroTrigger / (float) 32767) * (float) 2.5;
if (swervePower > 1) {
swervePower = 1;
} else if (swervePower < -1) {
swervePower = -1;
}
}
void loop() {
mpu.getRotation(&gx, &gy, &gz);
// put your main code here, to run repeatedly:
if (Serial1.available()) {
String val = Serial1.readStringUntil('\n');
applyNewSpeed(val);
}
if (Serial.available()) {
String val = Serial.readStringUntil('\n');
applyNewSpeed(val);
}
/*
if (Serial1.available()) {
targetSpeeds[0] = Serial1.readStringUntil('\n').toFloat();
targetSpeeds[1] = targetSpeeds[0];
targetSpeeds[2] = targetSpeeds[0];
targetSpeeds[3] = targetSpeeds[0];
}*/
motor1.run(directionFromSpeed(speeds[0]));
motor2.run(directionFromSpeed(speeds[1]));
motor3.run(directionFromSpeed(speeds[2]));
motor4.run(directionFromSpeed(speeds[3]));
if ((targetSpeeds[0] == targetSpeeds[1] && targetSpeeds[2] == targetSpeeds[3] && -targetSpeeds[0] == targetSpeeds[2]) || targetSpeeds[0] == targetSpeeds[1] && targetSpeeds[1] == targetSpeeds[2] && targetSpeeds[2] == targetSpeeds[3]) {
straightMovement = true;
} else {
straightMovement = false;
motor1.setSpeed((int) speeds[0]);
motor2.setSpeed((int) speeds[1]);
motor3.setSpeed((int) speeds[2]);
motor4.setSpeed((int) speeds[3]);
}
if (readEncoder(channel1A, lastValue1A, lastChange1A)) {
addToCyclicArray(channelHistory1A, channelIndex1A, micros());
}
if (readEncoder(channel2A, lastValue2A, lastChange2A)) {
addToCyclicArray(channelHistory2A, channelIndex2A, micros());
}
if (readEncoder(channel3A, lastValue3A, lastChange3A)) {
addToCyclicArray(channelHistory3A, channelIndex3A, micros());
}
if (readEncoder(channel4A, lastValue4A, lastChange4A)) {
addToCyclicArray(channelHistory4A, channelIndex4A, micros());
}
if (shouldReadSpeed()) {
/*
Serial1.print(speedHistory[0]);
Serial1.print(":");
Serial1.print(speedHistory[1]);
Serial1.print(":");
Serial1.print(speedHistory[2]);
Serial1.print(":");
Serial1.print(speedHistory[3]);
Serial1.print("-");
Serial1.print(speeds[0]);
Serial1.print(":");
Serial1.print(speeds[1]);
Serial1.print(":");
Serial1.print(speeds[2]);
Serial1.print(":");
Serial1.print(speeds[3]);
Serial1.print("-");
Serial1.print(targetSpeeds[0]);
Serial1.print(":");
Serial1.print(targetSpeeds[1]);
Serial1.print(":");
Serial1.print(targetSpeeds[2]);
Serial1.print(":");
Serial1.println(targetSpeeds[3]);*/
//
Serial.print("s1:");
Serial.print(speedHistory[0]);
Serial.print(",s2:");
Serial.print(speedHistory[1]);
Serial.print(",s3:");
Serial.print(speedHistory[2]);
Serial.print(",s4:");
Serial.print(speedHistory[3]);
Serial.print(",i1:");
Serial.print(speeds[0]);
Serial.print(",i2:");
Serial.print(speeds[1]);
Serial.print(",i3:");
Serial.print(speeds[2]);
Serial.print(",i4:");
Serial.print(speeds[3]);
Serial.print(",t1:");
Serial.print(targetSpeeds[0]);
Serial.print(",t2:");
Serial.print(targetSpeeds[1]);
Serial.print(",t3:");
Serial.print(targetSpeeds[2]);
Serial.print(",t4:");
Serial.print(targetSpeeds[3]);
Serial.print(",sp:");
Serial.println(swervePower);
updateSwervePower();
speeds[0] = getUpdatedSpeed(countFromCyclicArray(channelHistory1A, channelIndex1A, micros() - ((long) readDelay * (long) 1000)), speeds, targetSpeeds, speedHistory, 0);
speeds[1] = getUpdatedSpeed(countFromCyclicArray(channelHistory2A, channelIndex2A, micros() - ((long) readDelay * (long) 1000)), speeds, targetSpeeds, speedHistory, 1);
speeds[2] = getUpdatedSpeed(countFromCyclicArray(channelHistory3A, channelIndex3A, micros() - ((long) readDelay * (long) 1000)), speeds, targetSpeeds, speedHistory, 2);
speeds[3] = getUpdatedSpeed(countFromCyclicArray(channelHistory4A, channelIndex4A, micros() - ((long) readDelay * (long) 1000)), speeds, targetSpeeds, speedHistory, 3);
}
}
| 23.818182
| 236
| 0.645936
|
77a723c04067a805ff54d43ff1e458e6052188fd
| 360
|
ino
|
Arduino
|
examples/Echo/Echo.ino
|
koendv/Arduino-RttStream
|
f2d4ab8f24518dfd224a9576ad5440ab2825c28d
|
[
"MIT"
] | null | null | null |
examples/Echo/Echo.ino
|
koendv/Arduino-RttStream
|
f2d4ab8f24518dfd224a9576ad5440ab2825c28d
|
[
"MIT"
] | null | null | null |
examples/Echo/Echo.ino
|
koendv/Arduino-RttStream
|
f2d4ab8f24518dfd224a9576ad5440ab2825c28d
|
[
"MIT"
] | null | null | null |
/*
* Echo - RTT echo test
*
* This program requires a "Segger" brand debugger probe to run.
*/
#include <RTTStream.h>
RTTStream rtt;
void setup()
{
rtt.println("rtt echo test");
rtt.println("type a character; the program will echo the next ascii character");
}
void loop()
{
while (rtt.available())
rtt.write(rtt.read() + 1);
}
/* not truncated */
| 16.363636
| 81
| 0.663889
|
2cc4b2f95b3970a0cf07ee0a9c83bd5c2360d379
| 13,054
|
ino
|
Arduino
|
smart_switch_thingsboard/smart_switch_thingsboard.ino
|
kaebmoo/ogoswitch
|
547011b12d004f82df5605d2005c0015ee217dea
|
[
"MIT"
] | 1
|
2019-02-13T12:10:46.000Z
|
2019-02-13T12:10:46.000Z
|
smart_switch_thingsboard/smart_switch_thingsboard.ino
|
kaebmoo/ogoswitch
|
547011b12d004f82df5605d2005c0015ee217dea
|
[
"MIT"
] | null | null | null |
smart_switch_thingsboard/smart_switch_thingsboard.ino
|
kaebmoo/ogoswitch
|
547011b12d004f82df5605d2005c0015ee217dea
|
[
"MIT"
] | null | null | null |
/*
MIT License
Version 1.0 2020-1-9
Copyright (c) 2020 kaebmoo gmail com
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.
*/
#define THINGSBOARD
#include <EEPROM.h>
#include <DNSServer.h> //Local DNS Server used for redirecting all requests to the configuration portal
#include <ESP8266WebServer.h> //Local WebServer used to serve the configuration portal
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager WiFi Configuration Magic
#include <Wire.h>
#include "Adafruit_MCP23008.h"
#include <Arduino.h>
#include "Timer.h"
#include <TimeAlarms.h>
#include <ThingSpeak.h>
#include <ArduinoJson.h>
#include <PubSubClient.h>
#include <assert.h>
WiFiClient switchClient;
Timer timer;
// ThingSpeak information
char thingSpeakAddress[] = "api.thingspeak.com";
unsigned long channelID = 432257;
char *writeAPIKey = "";
char *readAPIKey = "";
// MicroGear microgear(switchClient); // declare microgear object
PubSubClient mqttClient(switchClient);
char clientID[64] = "switch/trakool/";
unsigned long nodeID = 801;
int mqttCountReconnect = 0;
char token[32] = "99999999999999999999"; // device token from thingsboard server vAGJcv4MwAenW8ohYXrI
int mqttport = 1883;
char thingsboardServer[40] = "thingsboard.ogonan.com"; // "box.greenwing.email" "192.168.2.64"
int sendinterval = 60000; // send data interval time ms
// mqtt
char *mqttUserName = "seal";
char *mqttPassword = "sealwiththekiss";
const char* mqttServer = "db.ogonan.com";
String subscribeTopic = "node/" + String( nodeID ) + "/control/messages";
String publishTopic = "node/" + String( nodeID ) + "/status/messages";
unsigned long lastMqttConnectionAttempt = 0;
unsigned long lastSend;
const int MAXRETRY=30;
// for portal config
char c_thingsboardServer[41] = "192.168.1.10";
char c_mqttport[8] = "1883";
char c_token[33] = "12345678901234567890";
char c_sendinterval[8] = "10000"; // ms
char c_nodeid[8] = ""; // node id mqtt
int wifi_reconnect = 0;
bool shouldSaveConfig = false;
Adafruit_MCP23008 mcp;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
EEPROM.begin(512);
// mcp.begin(1); // address = 0 (valid: 0-7)
setup_relayboard(0);
while (!Serial); // wait for serial port to connect. Needed for Leonardo only
Serial.println("I2C Relayboard test - press keys 12345678 (toggle relay) C (clear all)");
relay_reset();
delay(2000);
readConfig();
setupWifi();
setupMqtt();
}
void loop() {
// put your main code here, to run repeatedly:
// Reconnect if MQTT client is not connected.
if (!mqttClient.connected())
{
reconnect();
}
mqttClient.loop(); // Call the loop continuously to establish connection to the server.
}
void readConfig()
{
int saved;
EEPROM.get(103, nodeID);
EEPROM.get(112, token);
EEPROM.get(500, saved);
Serial.println();
Serial.println("Configuration Read");
Serial.print("Saved = ");
Serial.println(saved);
if (saved == 6550) {
strcpy(c_token, token);
ltoa(nodeID, c_nodeid, 10);
const int n = snprintf(NULL, 0, "%lu", nodeID);
assert(n > 0);
char buf[n+1];
int c = snprintf(buf, n+1, "%lu", nodeID);
assert(buf[n] == '\0');
assert(c == n);
strcat(clientID, buf);
Serial.print("Node ID : ");
Serial.println(nodeID);
Serial.print("Device token : ");
Serial.println(token);
Serial.print("Client ID : ");
Serial.println(clientID);
}
}
void setupWifi()
{
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
int saved = 6550;
wifiManager.setBreakAfterConfig(true);
wifiManager.setConfigPortalTimeout(120);
WiFiManagerParameter custom_c_nodeid("c_nodeid", "MQTT Node ID", c_nodeid, 8);
WiFiManagerParameter custom_c_token("c_token", "ThingsBoard Token", c_token, 21);
//set config save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback);
wifiManager.addParameter(&custom_c_nodeid);
wifiManager.addParameter(&custom_c_token);
String alias = "ogoSwitchT-"+String(ESP.getChipId());
if (!wifiManager.autoConnect(alias.c_str(), "")) {
Serial.println("failed to connect and hit timeout");
Alarm.delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
Alarm.delay(5000);
}
//if you get here you have connected to the WiFi
Serial.println("connected...yeey :)");
Serial.print("Device token : ");
Serial.println(token);
if (shouldSaveConfig) { //shouldSaveConfig
Serial.println("Saving config...");
strcpy(c_token, custom_c_token.getValue());
strcpy(c_nodeid, custom_c_nodeid.getValue());
strcpy(token, c_token);
nodeID = (unsigned long) atol(c_nodeid);
const int n = snprintf(NULL, 0, "%lu", nodeID);
assert(n > 0);
char buf[n+1];
int c = snprintf(buf, n+1, "%lu", nodeID);
assert(buf[n] == '\0');
assert(c == n);
strcat(clientID, buf);
Serial.print("Node ID : ");
Serial.println(nodeID);
Serial.print("Device token : ");
Serial.println(token);
Serial.print("Client ID : ");
Serial.println(clientID);
EEPROM.put(103, nodeID);
EEPROM.put(112, token);
EEPROM.put(500, saved);
if (EEPROM.commit()) {
Serial.println("EEPROM successfully committed");
} else {
Serial.println("ERROR! EEPROM commit failed");
}
shouldSaveConfig = false;
}
}
//callback notifying us of the need to save config
void saveConfigCallback () {
Serial.println("Should save config");
shouldSaveConfig = true;
}
void setupMqtt()
{
#ifdef THINGSBOARD
mqttClient.setServer(thingsboardServer, mqttport); // default port 1883, mqtt_server, thingsboardServer
mqttClient.setCallback(callback);
if (mqttClient.connect(clientID, token, NULL)) {
mqttClient.subscribe("v1/devices/me/rpc/request/+");
Serial.print("mqtt connected : ");
Serial.println(thingsboardServer); // mqtt_server
}
#endif
#ifdef MQTT
Serial.print(mqttServer); Serial.print(" "); Serial.println(mqttport);
mqttClient.setCallback(callback);
mqttClient.setServer(mqttServer, mqttport);
if (mqttClient.connect(clientID, mqttUserName, mqttPassword)) {
mqttClient.subscribe( subscribeTopic.c_str() );
Serial.print("mqtt connected : ");
Serial.println(mqtt_server); // mqtt_server
}
#endif
}
void reconnect()
{
// Loop until reconnected.
// while (!mqttClient.connected()) {
// }
Serial.print("Attempting MQTT connection...");
/*
// Generate ClientID
char clientID[9];
for (int i = 0; i < 8; i++) {
clientID[i] = alphanum[random(51)];
}
clientID[8]='\0';
*/
// Connect to the MQTT broker
#ifdef THINGSBOARD
mqttClient.setServer(thingsboardServer, mqttport);
if (mqttClient.connect(clientID, token, NULL)) {
Serial.println();
Serial.print("Connected with Client ID: ");
Serial.print(String(clientID));
Serial.print(", Token: ");
Serial.println(token);
// Subscribing to receive RPC requests
mqttClient.subscribe("v1/devices/me/rpc/request/+");
}
else {
Serial.print("failed, rc=");
// Print to know why the connection failed.
// See https://pubsubclient.knolleary.net/api.html#state for the failure code explanation.
Serial.print(mqttClient.state());
Serial.println(" try again in 2 seconds");
Alarm.delay(2000);
mqttCountReconnect++;
if (mqttCountReconnect >= 10) {
mqttCountReconnect = 0;
Serial.println("Reset..");
ESP.reset();
}
}
#endif
#ifdef MQTT
mqttClient.setServer(mqtt_server, mqttport);
if (mqttClient.connect(clientID,mqttUserName,mqttPassword)) {
Serial.print("Connected with Client ID: ");
Serial.print(String(clientID));
Serial.print(", Username: ");
Serial.print(mqttUserName);
Serial.print(" , Passwword: ");
Serial.println(mqttPassword);
mqttClient.subscribe( subscribeTopic.c_str() );
}
else {
Serial.print("failed, rc=");
// Print to know why the connection failed.
// See https://pubsubclient.knolleary.net/api.html#state for the failure code explanation.
Serial.print(mqttClient.state());
Serial.println(" try again in 2 seconds");
Alarm.delay(2000);
mqttCountReconnect++;
if (mqttCountReconnect >= 10) {
mqttCountReconnect = 0;
Serial.println("Reset..");
ESP.reset();
}
}
#endif
}
void callback(char* topic, byte* payload, unsigned int length)
{
int i = 0;
String responseTopic;
String relayStatus;
#ifdef THINGSBOARD
Serial.println("On message");
char json[length + 1];
strncpy (json, (char*)payload, length);
json[length] = '\0';
Serial.print("Topic: ");
Serial.println(topic);
Serial.print("Message: ");
Serial.println(json);
// Decode JSON request
StaticJsonBuffer<200> jsonBuffer;
JsonObject& data = jsonBuffer.parseObject((char*)json);
if (!data.success())
{
Serial.println("parseObject() failed");
return;
}
// Check request method
String methodName = String((const char*)data["method"]);
String valueName = String((const char *) data["params"]);
if (methodName.equals("turnOff")) {
relay_onoff(valueName.toInt(), LOW);
Serial.println("Turn Relay " + valueName + " OFF");
i = valueName.toInt() - 1;
if (i < 0 || i > 7) {
return;
}
Serial.print("Relay " + valueName + " status: ");
Serial.println(mcp.digitalRead(i) ? 1 : 0);
relayStatus = String(mcp.digitalRead(i) ? 1 : 0, DEC);
responseTopic = String(topic);
responseTopic.replace("request", "response");
mqttClient.publish(responseTopic.c_str(), relayStatus.c_str());
}
else if (methodName.equals("turnOn")) {
relay_onoff(valueName.toInt(), HIGH);
Serial.println("Turn Relay " + valueName + " ON");
i = valueName.toInt() - 1;
if (i < 0 || i > 7) {
return;
}
Serial.print("Relay " + valueName + " status: ");
Serial.println(mcp.digitalRead(i) ? 1 : 0);
relayStatus = String(mcp.digitalRead(i) ? 1 : 0, DEC);
responseTopic = String(topic);
responseTopic.replace("request", "response");
mqttClient.publish(responseTopic.c_str(), relayStatus.c_str());
}
else if (methodName.equals("getValue")) {
i = valueName.toInt() - 1;
if (i < 0 || i > 7) {
return;
}
Serial.print("Relay " + valueName + " status: ");
Serial.println(mcp.digitalRead(i) ? 1 : 0);
relayStatus = String(mcp.digitalRead(i) ? 1 : 0, DEC);
responseTopic = String(topic);
responseTopic.replace("request", "response");
mqttClient.publish(responseTopic.c_str(), relayStatus.c_str());
String message = "{\"Relay Status\":" + relayStatus + "}";
mqttClient.publish("v1/devices/me/telemetry", message.c_str());
Serial.print("topic : ");
Serial.print("v1/devices/me/telemetry");
Serial.print(" : message ");
Serial.println(message);
}
#endif
}
void setup_relayboard(int board)
{
mcp.begin(board);
mcp.writeGPIO(0); // set OLAT to 0
mcp.pinMode(0, OUTPUT); // set IODIR to 0
mcp.pinMode(1, OUTPUT);
mcp.pinMode(2, OUTPUT);
mcp.pinMode(3, OUTPUT);
mcp.pinMode(4, OUTPUT);
mcp.pinMode(5, OUTPUT);
mcp.pinMode(6, OUTPUT);
mcp.pinMode(7, OUTPUT);
}
void relay_reset()
{
int i;
for (i = 0; i < 8; i++) {
mcp.digitalWrite(i, LOW);
}
delay(500);
for (i = 0; i < 8; i++) {
Serial.print(i+1);
Serial.print(mcp.digitalRead(i) ? ": ON " : ": OFF ");
}
Serial.println();
}
void relay_onoff(char port, uint8_t of)
{
int i;
if ((port > 0) && (port < 9)) {
mcp.digitalWrite(port-1, of);
}
for (i = 0; i < 8; i++) {
Serial.print(i+1);
Serial.print(mcp.digitalRead(i) ? ": ON " : ": OFF ");
}
Serial.println();
}
| 28.073118
| 120
| 0.653976
|
81e4baf6501baa547a514d25da1ecd9d54abd282
| 13,028
|
ino
|
Arduino
|
weather_matrix.ino
|
jkeefe/weather-matrix
|
f854ce499b813c5cecd8454bfdcf3630ea6c8928
|
[
"MIT"
] | 1
|
2016-09-26T13:49:51.000Z
|
2016-09-26T13:49:51.000Z
|
weather_matrix.ino
|
jkeefe/weather-matrix
|
f854ce499b813c5cecd8454bfdcf3630ea6c8928
|
[
"MIT"
] | null | null | null |
weather_matrix.ino
|
jkeefe/weather-matrix
|
f854ce499b813c5cecd8454bfdcf3630ea6c8928
|
[
"MIT"
] | null | null | null |
/*
* This code goes a spark.io core, and is part of a #MakeEveryWeek
* project by John Keefe. More info at http://johnkeefe.net
*
* Details on this project at
* http://johnkeefe.net/make-every-week-entryway-weatherbot
*
*/
// The next three include lines call in the libraries. To learn how
// to add them to this project on the spark_io core, see:
// http://johnkeefe.net/make-every-week-entryway-weatherbot
// This #include statement was automatically added by the Spark IDE.
#include "neopixel/neopixel.h"
// This #include statement was automatically added by the Spark IDE.
#include "neomatrix/neomatrix.h"
// This #include statement was automatically added by the Spark IDE.
#include "Adafruit_GFX/Adafruit_GFX.h"
#include "application.h"
// IMPORTANT: Set pixel PIN and TYPE
#define PIXEL_PIN D2
#define PIXEL_TYPE WS2812B
// Carrying over the comments from the NEOMATRIX example application ...
// MATRIX DECLARATION:
// Parameter 1 = width of EACH NEOPIXEL MATRIX (not total display)
// Parameter 2 = height of each matrix
// Parameter 3 = number of matrices arranged horizontally
// Parameter 4 = number of matrices arranged vertically
// Parameter 5 = pin number (most are valid)
// Parameter 6 = matrix layout flags, add together as needed:
// NEO_MATRIX_TOP, NEO_MATRIX_BOTTOM, NEO_MATRIX_LEFT, NEO_MATRIX_RIGHT:
// Position of the FIRST LED in the FIRST MATRIX; pick two, e.g.
// NEO_MATRIX_TOP + NEO_MATRIX_LEFT for the top-left corner.
// NEO_MATRIX_ROWS, NEO_MATRIX_COLUMNS: LEDs WITHIN EACH MATRIX are
// arranged in horizontal rows or in vertical columns, respectively;
// pick one or the other.
// NEO_MATRIX_PROGRESSIVE, NEO_MATRIX_ZIGZAG: all rows/columns WITHIN
// EACH MATRIX proceed in the same order, or alternate lines reverse
// direction; pick one.
// NEO_TILE_TOP, NEO_TILE_BOTTOM, NEO_TILE_LEFT, NEO_TILE_RIGHT:
// Position of the FIRST MATRIX (tile) in the OVERALL DISPLAY; pick
// two, e.g. NEO_TILE_TOP + NEO_TILE_LEFT for the top-left corner.
// NEO_TILE_ROWS, NEO_TILE_COLUMNS: the matrices in the OVERALL DISPLAY
// are arranged in horizontal rows or in vertical columns, respectively;
// pick one or the other.
// NEO_TILE_PROGRESSIVE, NEO_TILE_ZIGZAG: the ROWS/COLUMS OF MATRICES
// (tiles) in the OVERALL DISPLAY proceed in the same order for every
// line, or alternate lines reverse direction; pick one. When using
// zig-zag order, the orientation of the matrices in alternate rows
// will be rotated 180 degrees (this is normal -- simplifies wiring).
// See example below for these values in action.
// Parameter 7 = pixel type flags, add together as needed:
// NEO_RGB Pixels are wired for RGB bitstream (v1 pixels)
// NEO_GRB Pixels are wired for GRB bitstream (v2 pixels)
// NEO_KHZ400 400 KHz bitstream (e.g. FLORA v1 pixels)
// NEO_KHZ800 800 KHz bitstream (e.g. High Density LED strip)
// For Spark Core developement it should probably also be WS2812B if you're
// using adafruit neopixels.
Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(5, 8, 1, 1, PIXEL_PIN,
NEO_MATRIX_TOP + NEO_MATRIX_LEFT + NEO_MATRIX_COLUMNS + NEO_MATRIX_PROGRESSIVE +
NEO_TILE_TOP + NEO_TILE_LEFT + NEO_TILE_ROWS + NEO_TILE_PROGRESSIVE,
PIXEL_TYPE);
// declare color variables
// Thanks to Corey Jones's cool example at
// http://www.hackster.io/jones_corey/christmas-lights-neopixel-led-matrix-glass-block-wall
uint32_t PEACH = matrix.Color(221,171,127);
uint32_t ROSY = matrix.Color(255,176,193);
uint32_t LIGHTBLUE = matrix.Color(94,185,247);
uint32_t RED = matrix.Color(255,0,0);
uint32_t GREEN = matrix.Color(0,255,0);
uint32_t GRAY = matrix.Color(150,150,150);
uint32_t BROWN = matrix.Color(117,76,41);
uint32_t PURPLE = matrix.Color(152,5,229);
uint32_t DARKGREEN = matrix.Color(12,158,17);
uint32_t PINK = matrix.Color(250,101,148);
uint32_t ORANGE = matrix.Color(200,90,41);
uint32_t YELLOW = matrix.Color(255,242,0);
uint32_t BLACK = matrix.Color(0,0,0);
uint32_t WHITE = matrix.Color(255,255,255);
uint32_t BLUE = matrix.Color(0,0,255);
uint32_t AQUA = matrix.Color(2,132,130);
uint32_t DARKBLUE = matrix.Color(0,0,125);
// Variable declaration ...
String icon; // 3 characters indicating forecast icon
int temp = 0; // the forecast temperature
int tens_digit; // the tens digit to display
int ones_digit; // the ones digit to display
uint32_t text_color; // color for the text
// the setup section runs once
void setup() {
matrix.begin();
matrix.setBrightness(60);
// expose the "forecast" component to the api so it responds to
// https://api.spark.io/v1/devices/DEVICE_ID/forecast
// and call the parseForecast function when you see it
Spark.function("forecast", parseForecast);
matrix.fillScreen(0); // clears the screen
}
// the loop section repeats forever
void loop() {
// SHOW THE WEATHER ICON
// clear the screen
matrix.fillScreen(0);
// match the draw functions to the value for icon
// picked up from the server program
if (icon == "sno") { drawSnow(); }
if (icon == "rai") { drawRain(); }
if (icon == "cle") { drawSun(); }
if (icon == "clo") { drawCloudy(); }
if (icon == "sle") { drawSleet(); }
if (icon == "fog") { drawFog(); }
if (icon == "win") { drawWind(); }
if (icon == "par") { drawPartlyCloudy(); }
// draws nothing if icon is empty or doesn't match
matrix.show(); // light it up
delay(2000); // wait 2 seconds
// SHOW THE TEMPERATURE
// clear the screen
matrix.fillScreen(0);
// set the text color of the temperature based on its value
if (temp >= 90 ) { text_color = RED; }
else if (temp >= 80 ) { text_color = ORANGE; }
else if (temp >= 70 ) { text_color = YELLOW; }
else if (temp >= 50 ) { text_color = GREEN; }
else if (temp >= 32 ) { text_color = AQUA; }
else if (temp >= 10 ) { text_color = GRAY; }
else if (temp >= 0 ) { text_color = PINK; }
else if (temp < 0) { text_color = BLUE; }
// calculate and draw the ones digit
ones_digit = temp % 10; // temp modulo 10 ... so 24 becomes 4
drawDigit(ones_digit, 5, text_color); // send the digit, the LED column and the color
// calculate and draw the tens digit,
// provided temp is at greater than 10 or less than -10
if (temp >= 10 || temp <= -10) {
tens_digit = temp / 10; // all are integers, so 24 becomes 2
drawDigit(tens_digit, 1, text_color); // send the digit, the LED column and the color
}
matrix.show(); // light it up
delay(2000); // wait 2 seconds
}
int parseForecast(String command){
// the "command" will come in as a string like these:
// -3 snow
// 89 partly-cloudy-day
// 103clear-day
// grab the temperature from the first three characters
temp = command.substring(0,3).toInt();
// grab the icon from the next three characters
// note: we're always showing a day forecast ... today's if
// it is before noon, tomorrow's if after that. so we can
// ignore the night icons.
String sentIcon = command.substring(3,6);
// update the icon variable with the first three letters of the value sent
icon = sentIcon;
// int fuctions need a return
return 1;
}
// This function draws digits based on the passed value of "digit",
// the y (column) position, and the color.
void drawDigit(int digit, int y, uint32_t textcolor) {
bool negative = false;
// if the temp is negative, note that and turn into a positive digit
if (digit < 0) {
digit = abs(digit);
negative = true;
}
// this picks a draw function based on the value of digit.
// if there is a more efficient way to do this, I'd love to hear it.
switch (digit) {
case 1:
drawOne(y, textcolor);
break;
case 2:
drawTwo(y, textcolor);
break;
case 3:
drawThree(y, textcolor);
break;
case 4:
drawFour(y, textcolor);
break;
case 5:
drawFive(y, textcolor);
break;
case 6:
drawSix(y, textcolor);
break;
case 7:
drawSeven(y, textcolor);
break;
case 8:
drawEight(y, textcolor);
break;
case 9:
drawNine(y, textcolor);
break;
case 0:
drawZero(y, textcolor);
break;
// handle the passing of a 10 or 11 in the
// tens postion for 100+ temperatures
case 10:
drawZero(y, textcolor);
break;
case 11:
drawOne(y, textcolor);
break;
}
// draw a white minus sign for negative numbers
if (negative == true){
matrix.drawLine( 2,0, 2,1, WHITE);
}
}
// FUNCIONS FOR DRAWING ICONS
// The defitions for drawLine, drawPixel, drawRect, etc are here:
// https://learn.adafruit.com/adafruit-gfx-graphics-library/graphics-primitives
void drawSnow() {
matrix.drawLine( 0,1, 0,6, BLUE); // x1,y1, x2,y2, color
matrix.drawLine( 1,0, 1,7, BLUE);
matrix.drawLine( 2,1, 2,6, BLUE);
matrix.drawPixel( 3,2, WHITE); // x1,y1, color
matrix.drawPixel( 3,4, WHITE);
matrix.drawPixel( 3,6, WHITE);
matrix.drawPixel( 4,1, WHITE);
matrix.drawPixel( 4,3, WHITE);
matrix.drawPixel( 4,5, WHITE);
}
void drawSun() {
matrix.drawLine( 0,1, 4,5, YELLOW);
matrix.drawLine( 0,5, 4,1, YELLOW);
matrix.drawLine( 0,3, 4,3, YELLOW);
matrix.drawLine( 2,0, 2,6, YELLOW);
}
void drawRain() {
matrix.drawLine( 0,1, 0,6, DARKBLUE); // x1,y1, x2,y2, color
matrix.drawLine( 1,0, 1,7, DARKBLUE);
matrix.drawLine( 2,1, 2,6, DARKBLUE);
matrix.drawPixel( 3,2, BLUE);
matrix.drawPixel( 3,4, BLUE);
matrix.drawPixel( 3,6, BLUE);
matrix.drawPixel( 4,1, BLUE);
matrix.drawPixel( 4,3, BLUE);
matrix.drawPixel( 4,5, BLUE);
}
void drawCloudy() {
matrix.drawLine( 0,1, 0,6, DARKBLUE); // x1,y1, x2,y2, color
matrix.drawLine( 1,0, 1,7, DARKBLUE);
matrix.drawLine( 2,1, 2,6, DARKBLUE);
}
void drawPartlyCloudy() {
matrix.drawLine( 0,4, 0,6, YELLOW);
matrix.drawLine( 1,5, 1,6, YELLOW);
matrix.drawPixel( 2,6, YELLOW);
matrix.fillRect( 1,1, 4, 4, BLUE); // x0,y0, h, w, color
matrix.drawLine( 2,0, 3,0, BLUE);
matrix.drawLine( 2,5, 3,5, BLUE);
}
void drawFog() {
matrix.fillScreen(GRAY);
matrix.drawPixel( 0,0, BLACK);
matrix.drawPixel( 0,7, BLACK);
matrix.drawPixel( 4,0, BLACK);
matrix.drawPixel( 4,7, BLACK);
matrix.drawLine( 2,0, 2,2, DARKBLUE);
matrix.drawLine( 1,4, 1,6, DARKBLUE);
matrix.drawLine( 3,6, 3,7, DARKBLUE);
}
void drawSleet() {
matrix.drawLine( 1,0, 3,0, AQUA);
matrix.drawLine( 0,2, 2,2, WHITE);
matrix.drawLine( 1,4, 3,4, AQUA);
matrix.drawLine( 0,6, 2,6, WHITE);
}
void drawWind() {
matrix.drawLine( 1,0, 0,1, BLUE);
matrix.drawLine( 4,0, 1,2, BLUE);
matrix.drawPixel( 1,3, BLUE);
matrix.drawLine( 3,3, 2,4, BLUE);
matrix.drawLine( 2,6, 1,7, BLUE);
matrix.drawLine( 4,4, 4,5, BLUE);
}
// FUNCTIONS FOR DRAWING THE ACTUAL NUMBERS
// each of the digit functions get passed
// the LED matrix column to start in
// (which could be 0-7, but we only use 1 and 5)
// and the color to use.
void drawOne(int y, uint32_t textcolor) {
matrix.drawLine( 0,y+2, 4,y+2, textcolor ); // y is the upper-left corner's column
}
void drawTwo(int y, uint32_t textcolor) {
matrix.fillRect( 0,y, 5, 3, textcolor); // make a box ... x,y, h, w
matrix.drawLine( 1,y, 1,y+1, BLACK); // knock out a piece
matrix.drawLine( 3,y+1, 3,y+2, BLACK);
}
void drawThree(int y, uint32_t textcolor) {
matrix.fillRect (0,y, 5,3, textcolor);
matrix.drawLine( 1,y, 1,y+1, BLACK);
matrix.drawLine( 3,y, 3,y+1, BLACK);
}
void drawFour(int y, uint32_t textcolor) {
matrix.fillRect( 0,y, 5, 3, textcolor);
matrix.drawRect( 3,y, 2, 2, BLACK);
matrix.drawLine( 0,y+1, 1,y+1, BLACK);
}
void drawFive(int y, uint32_t textcolor) {
matrix.fillRect( 0,y, 5, 3, textcolor);
matrix.drawLine( 1,y+2, 1,y+1, BLACK);
matrix.drawLine( 3,y, 3,y+1, BLACK);
}
void drawSix(int y, uint32_t textcolor){
matrix.fillRect( 0,y, 5, 3, textcolor);
matrix.drawLine( 1,y+2, 1,y+1, BLACK);
matrix.drawPixel( 3,y+1, BLACK);
}
void drawSeven(int y, uint32_t textcolor) {
matrix.drawLine( 0,y, 0,y+2, textcolor);
matrix.drawLine( 1,y+2, 4,y+2, textcolor);
}
void drawEight(int y, uint32_t textcolor) {
matrix.fillRect( 0,y, 5, 3, textcolor);
matrix.drawPixel( 1,y+1, BLACK);
matrix.drawPixel( 3,y+1, BLACK);
}
void drawNine(int y, uint32_t textcolor) {
matrix.fillRect( 0,y, 5, 3, textcolor);
matrix.drawPixel( 1,y+1, BLACK);
matrix.drawLine( 3,y, 3,y+1, BLACK);
}
void drawZero(int y, uint32_t textcolor) {
matrix.drawRect( 0,y, 5, 3, textcolor);
}
| 32.733668
| 91
| 0.646607
|
8816fe1d10c7064aa6d4c7cb3f518a83592c0472
| 667
|
ino
|
Arduino
|
PracticeProjects/LowLightLamp/LowLightLamp.ino
|
joe-sharp/old-arduino-projects
|
ae732df41abd2178f4911b27bd181ca960db83de
|
[
"MIT"
] | null | null | null |
PracticeProjects/LowLightLamp/LowLightLamp.ino
|
joe-sharp/old-arduino-projects
|
ae732df41abd2178f4911b27bd181ca960db83de
|
[
"MIT"
] | 3
|
2020-12-22T04:24:49.000Z
|
2021-01-25T02:11:36.000Z
|
PracticeProjects/LowLightLamp/LowLightLamp.ino
|
joe-sharp/old-arduino-projects
|
ae732df41abd2178f4911b27bd181ca960db83de
|
[
"MIT"
] | null | null | null |
// Example 02: Turn on LED while the button is pressed
const int LED = 13; // the pin for the LED
const int BUTTON = 7; // the input pin where the
// pushbutton is connected
int val = 0; // val will be used to store the state
// of the input pin
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
val = digitalRead(BUTTON); // read input value and store it
// check whether the input is HIGH (button pressed)
if (val == LOW) {
digitalWrite(LED, HIGH); // turn LED ON
} else {
digitalWrite(LED, LOW);
}
}
| 33.35
| 61
| 0.608696
|
060516915ab69c5344e713465ae87a307a8b4c2e
| 4,382
|
ino
|
Arduino
|
IR_ETHERNET_AR.ino
|
guilhermelirio/arduino_ir_ar_ethernet
|
d2ef71e17c89b544557f5be31d1880a4b1d4acd4
|
[
"MIT"
] | 1
|
2020-06-06T21:20:31.000Z
|
2020-06-06T21:20:31.000Z
|
IR_ETHERNET_AR.ino
|
guilhermelirio/arduino_ir_ar_ethernet
|
d2ef71e17c89b544557f5be31d1880a4b1d4acd4
|
[
"MIT"
] | null | null | null |
IR_ETHERNET_AR.ino
|
guilhermelirio/arduino_ir_ar_ethernet
|
d2ef71e17c89b544557f5be31d1880a4b1d4acd4
|
[
"MIT"
] | null | null | null |
/* Arduino + Ethernet Shield + AR
Versão: 1.0
Feito por Guilherme Lirio Tomasi de Oliveira
Retirado de: http://arduinodemcu.blogspot.com
*/
#include <SPI.h>
#include <Ethernet.h>
#include <IRremote.h>
IRsend irsend;
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x9B, 0x36 }; //MAC ADRESS UNIVERSAL PARA PLACAS GENÉRICAS
byte ip[] = { 192, 168, 1, 99 }; // ENDEREÇO DE IP - DEFINIDO PELO USUÁRIO
byte gateway[] = { 192, 168, 1, 1 }; // ENDEREÇO GATEWAY DO ROTEADOR
byte subnet[] = { 255, 255, 255, 0 }; //SUBMASCARA DO ROTEADOR
EthernetServer server(80); //PORTA QUE SERÁ ABERTA
String readString;
//////////////////////
void setup() {
Ethernet.begin(mac, ip, gateway, subnet); //COMEÇAR O ETHERNET SHIELD, COM OS DADOS ACIMA
server.begin(); //COMECAR O WEBSERVER
Serial.begin(9600); //HABILITAR O SERIAL
Serial.println("Arduino + Ethernet Shield + AR"); //IMPRIMIR NO SERIAL
}
void loop() {
// CRIAR A CONEXÃO COM O CLIENTE
EthernetClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
char c = client.read();
//read char by char HTTP request
if (readString.length() < 100) {
//store characters to string
readString += c;
Serial.print(c);
}
//if HTTP request has ended
if (c == '\n') {
Serial.println(readString); //Imprime no Serial para acompanhamento
if (readString.indexOf("?ligaar") > 0) //checks for on
{
ligaar();
Serial.print("Ligou Ar");
}
//clearing string for next read
readString = "";
/////////////// PAGINA HTML //////////////////////////
client.println("HTTP/1.1 200 OK"); //send new page
client.println("Content-Type: text/html");
client.println();
client.println("<html>");
client.println("<title>Arduino + Ethernet Shield + AR</title>");
client.println("<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>");
client.println("<meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'>");
client.println("<body>");
client.println("<h2>Arduino + Ethernet Shield + AR</h2>");
client.println("<hr>");
client.println("<a href='?ligaar'>LIGA AR</a>");
client.println("</body>");
client.println("</html>");
delay(1);
//stopping client
client.stop();
}
}
}
}
}
void ligaar() {
int khz = 38; // 38kHz carrier frequency for the NEC protocol
unsigned int irSignal[] = {4776, 2380, 628, 572, 548, 656, 548, 652, 548, 1856, 548, 652, 548, 656, 620, 556, 572, 652, 548, 656, 548, 652, 548, 656, 624, 576, 548, 1800, 680, 576, 624, 516, 688, 576, 548, 1856, 624, 1776, 624, 1684, 720, 580, 548, 652, 548, 632, 644, 580, 620, 512, 692, 576, 624, 1780, 548, 656, 544, 636, 568, 652, 548, 656, 548, 652, 548, 652, 548, 580, 624, 652, 548, 656, 544, 656, 548, 652, 548, 656, 548, 1852, 548, 656, 548, 656, 544, 656, 548, 652, 548, 1856, 548, 652, 548, 652, 552, 652, 548, 576, 624, 1856, 548, 652, 548, 656, 548, 628, 572, 656, 548, 616, 584, 652, 548, 656, 548, 1852, 552, 1852, 548, 656, 548, 652, 548, 1856, 548, 652, 548, 628, 572, 588, 616, 652, 548, 1856, 548, 652, 548, 624, 580, 652, 548, 652, 548, 656, 548, 628, 572, 656, 548, 600, 600, 652, 548, 1856, 548, 652, 548, 656, 548, 1856, 548, 652, 548, 628, 572, 656, 548, 652, 548, 580, 624, 652, 548, 652, 548, 656, 548, 652, 548, 652, 620, 584, 548, 652, 548, 652, 548, 656, 548, 652, 548, 652, 552, 652, 548, 652, 624, 576, 552, 652, 548, 632, 568, 656, 548, 652, 548, 632, 644, 580, 620, 580, 624, 580, 548, 652, 548, 652, 628, 552, 572, 656, 620, 580, 620, 572, 628, 584, 544, 656, 624, 1780, 620, 1780, 548, 656, 548, 1852, 548, 1856, 548, 1856, 548, 652, 548, 1856, 548, 1832, 572, 1776, 628, 652, 620, 1784, 548, 652, 624, 1780, 620, 556, 648, 1760, 568, 1856, 620, 1784, 548, 1852, 624, 556, 644, 1780, 628, 1780, 620}; //AnalysIR Batch Export (IRremote) - RAW
irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz); //Note the approach used to automatically calculate the size of the array.
}
| 46.617021
| 1,479
| 0.578959
|
e9122d0ff6c5497a538103ef8ce57c8242f45969
| 5,869
|
ino
|
Arduino
|
line-follower-arduino-pro-mini.ino
|
dmitryrybakov/line-follower-arduino-pro-mini
|
e558378cd5823ad0fbe7e1d11f16fcc160f62af7
|
[
"Artistic-2.0"
] | null | null | null |
line-follower-arduino-pro-mini.ino
|
dmitryrybakov/line-follower-arduino-pro-mini
|
e558378cd5823ad0fbe7e1d11f16fcc160f62af7
|
[
"Artistic-2.0"
] | null | null | null |
line-follower-arduino-pro-mini.ino
|
dmitryrybakov/line-follower-arduino-pro-mini
|
e558378cd5823ad0fbe7e1d11f16fcc160f62af7
|
[
"Artistic-2.0"
] | null | null | null |
// Line follower based on arduino pro mini
#include <Servo.h>
#include <SimpleTimer.h>
const int lineSensorServoPositionMinVal = 20;
const int lineSensorServoPositionMaxVal = 110;
const int lineSensorThresholdVal = 5;
const int lineServoSensorPinNo = 9;
const int lineSensorServoStep = 5;
const int leftMotorForwardPinNo = 10;
const int leftMotorBackwardPinNo = 11;
const int rightMotorForwardPinNo = 12;
const int rightMotorBackwardPinNo = 13;
const int leftMotorSpeedPinNo = 5;
const int rightMotorSpeedPinNo = 6;
const int rightLineSensorPinNo = 0; // Right part of the line sensor
const int middleLineSensorPinNo = 1; // Middle part of the line sensor
const int leftLineSensorPinNo = 2; // Left part of the line sensor
const int motorMinimumSpeedValue = 0;
const int motorMaximumSpeedValue = 255;
Servo lineSensorServo; // Servo object to control servo of line sensor
int lineSensorServoPos = (lineSensorServoPositionMinVal + lineSensorServoPositionMaxVal) >> 1;
int trackFindingLineServoStep = lineSensorServoStep;
int fakeServoPosForSpiraleMove = lineSensorServoPositionMinVal;
unsigned long time;
//SimpleTimer timer;
// a function to be executed periodically
void repeatMe() {
}
void setup() {
Serial.begin(115200);
lineSensorServo.attach(lineServoSensorPinNo); // attaches the servo on pin 9 to the servo object
lineSensorServo.write(lineSensorServoPos); // Turn servo to the initial position
pinMode(leftMotorForwardPinNo, OUTPUT) ;
pinMode(leftMotorBackwardPinNo, OUTPUT) ;
pinMode(rightMotorForwardPinNo, OUTPUT) ;
pinMode(rightMotorBackwardPinNo, OUTPUT) ;
pinMode(leftMotorSpeedPinNo, OUTPUT) ;
pinMode(rightMotorSpeedPinNo, OUTPUT) ;
digitalWrite(leftMotorForwardPinNo, HIGH) ;
digitalWrite(leftMotorBackwardPinNo, LOW) ;
digitalWrite(rightMotorForwardPinNo, HIGH) ;
digitalWrite(rightMotorBackwardPinNo, LOW) ;
//timer.setInterval(1000, repeatMe);
}
void setMotorSpeedByServoPosition(int servoPos) {
int middlePos = (lineSensorServoPositionMinVal + lineSensorServoPositionMaxVal) >> 1;
int leftOrRightPart = servoPos - middlePos; // Set less speed for the right part if it has plus, for the left part otherwise
int servoHalfRangeLength = (lineSensorServoPositionMaxVal - lineSensorServoPositionMinVal) >> 1;
int leftOrRightPartPercent = leftOrRightPart * 100 / servoHalfRangeLength;
int motorSpeedRangeLength = motorMaximumSpeedValue - motorMinimumSpeedValue;
int motorSpeedRelativeValue = motorSpeedRangeLength * leftOrRightPartPercent / 100;
int actualMotorSpeed = motorMaximumSpeedValue - abs(motorSpeedRelativeValue);
Serial.println(actualMotorSpeed);
if (motorSpeedRelativeValue > 0) {
analogWrite(leftMotorSpeedPinNo, motorMaximumSpeedValue);
analogWrite(rightMotorSpeedPinNo, actualMotorSpeed);
Serial.println(actualMotorSpeed);
}
else {
analogWrite(rightMotorSpeedPinNo, motorMaximumSpeedValue);
analogWrite(leftMotorSpeedPinNo, actualMotorSpeed);
Serial.println(actualMotorSpeed);
}
}
void loop() {
boolean lineSensorServoPosChanged = false;
boolean utmostLineSensorsCrossTrack = false;
boolean isOnTheField = true;
boolean isTrackFind = false;
//timer.run();
int val=analogRead(rightLineSensorPinNo);
if (val < lineSensorThresholdVal && lineSensorServoPos < lineSensorServoPositionMaxVal) {
lineSensorServoPos += lineSensorServoStep;
lineSensorServoPosChanged = true;
utmostLineSensorsCrossTrack = true;
lineSensorServoPos = min(lineSensorServoPositionMaxVal, lineSensorServoPos);
}
val=analogRead(leftLineSensorPinNo);
if (val < lineSensorThresholdVal && lineSensorServoPos > lineSensorServoPositionMinVal) {
if (!lineSensorServoPosChanged) {
lineSensorServoPos -= lineSensorServoStep;
lineSensorServoPosChanged = true;
utmostLineSensorsCrossTrack = true;
lineSensorServoPos = max(lineSensorServoPositionMinVal, lineSensorServoPos);
}
else {
// In this case do nothing. It seems that line sensor does not see white (robot is turned out or is out of the playing field)
lineSensorServoPosChanged = false;
lineSensorServoPos -= lineSensorServoStep;
isOnTheField = false;
}
}
val=analogRead(middleLineSensorPinNo);
if (val > lineSensorThresholdVal && !utmostLineSensorsCrossTrack) {
// We are in the track finding mode
lineSensorServoPos += trackFindingLineServoStep;
if (lineSensorServoPos >= lineSensorServoPositionMaxVal ||
lineSensorServoPos <= lineSensorServoPositionMinVal) {
trackFindingLineServoStep = -trackFindingLineServoStep;
lineSensorServoPos = max(lineSensorServoPositionMinVal, lineSensorServoPos);
lineSensorServoPos = min(lineSensorServoPositionMaxVal, lineSensorServoPos);
}
lineSensorServoPosChanged = true;
isTrackFind = true;
}
// Change line sensor servo position
if (lineSensorServoPosChanged) {
lineSensorServo.write(lineSensorServoPos);
}
// Change motors speed
if (isTrackFind) {
setMotorSpeedByServoPosition(fakeServoPosForSpiraleMove);
// Try to increase servo pos with respective to time
unsigned long dt = millis() - time;
if (dt > 500) {
time = millis();
fakeServoPosForSpiraleMove += abs(trackFindingLineServoStep);
if (fakeServoPosForSpiraleMove >= lineSensorServoPositionMaxVal) {
fakeServoPosForSpiraleMove = lineSensorServoPositionMinVal;
}
}
} else if (isOnTheField) {
// Try to connect line servo position with motors speed
// Vehicle should rotate according to the line sensor servo position. Moving like this helps us to follow the line.
setMotorSpeedByServoPosition(lineSensorServoPos);
}
else {
analogWrite(leftMotorSpeedPinNo, 0);
analogWrite(rightMotorSpeedPinNo, 0);
}
delay(15); // waits for the servo to get target position
}
| 38.359477
| 131
| 0.767252
|
318fb02a716a8b449247739126a15643a7d502f9
| 8,729
|
ino
|
Arduino
|
tasmota/Sonoff-Tasmota-6.4.0/sonoff/xnrg_02_cse7766.ino
|
zorcec/SARAH
|
c7936ce9467fb11594b6ae4a937d6766060bec05
|
[
"MIT"
] | null | null | null |
tasmota/Sonoff-Tasmota-6.4.0/sonoff/xnrg_02_cse7766.ino
|
zorcec/SARAH
|
c7936ce9467fb11594b6ae4a937d6766060bec05
|
[
"MIT"
] | null | null | null |
tasmota/Sonoff-Tasmota-6.4.0/sonoff/xnrg_02_cse7766.ino
|
zorcec/SARAH
|
c7936ce9467fb11594b6ae4a937d6766060bec05
|
[
"MIT"
] | null | null | null |
/*
xnrg_02_cse7766.ino - CSE7766 energy sensor support for Sonoff-Tasmota
Copyright (C) 2018 Theo Arends
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef USE_ENERGY_SENSOR
#ifdef USE_CSE7766
/*********************************************************************************************\
* CSE7766 - Energy (Sonoff S31 and Sonoff Pow R2)
*
* Based on datasheet from http://www.chipsea.com/UploadFiles/2017/08/11144342F01B5662.pdf
\*********************************************************************************************/
#define XNRG_02 2
#define CSE_MAX_INVALID_POWER 128 // Number of invalid power receipts before deciding active power is zero
#define CSE_NOT_CALIBRATED 0xAA
#define CSE_PULSES_NOT_INITIALIZED -1
#define CSE_PREF 1000
#define CSE_UREF 100
uint8_t cse_receive_flag = 0;
long voltage_cycle = 0;
long current_cycle = 0;
long power_cycle = 0;
unsigned long power_cycle_first = 0;
long cf_pulses = 0;
long cf_pulses_last_time = CSE_PULSES_NOT_INITIALIZED;
uint8_t cse_power_invalid = CSE_MAX_INVALID_POWER;
void CseReceived(void)
{
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// 55 5A 02 F7 60 00 03 5A 00 40 10 04 8B 9F 51 A6 58 18 72 75 61 AC A1 30 - Power not valid (load below 5W)
// 55 5A 02 F7 60 00 03 AB 00 40 10 02 60 5D 51 A6 58 03 E9 EF 71 0B 7A 36
// Hd Id VCal---- Voltage- ICal---- Current- PCal---- Power--- Ad CF--- Ck
uint8_t header = serial_in_buffer[0];
if ((header & 0xFC) == 0xFC) {
AddLog_P(LOG_LEVEL_DEBUG, PSTR("CSE: Abnormal hardware"));
return;
}
// Get chip calibration data (coefficients) and use as initial defaults
if (HLW_UREF_PULSE == Settings.energy_voltage_calibration) {
long voltage_coefficient = 191200; // uSec
if (CSE_NOT_CALIBRATED != header) {
voltage_coefficient = serial_in_buffer[2] << 16 | serial_in_buffer[3] << 8 | serial_in_buffer[4];
}
Settings.energy_voltage_calibration = voltage_coefficient / CSE_UREF;
}
if (HLW_IREF_PULSE == Settings.energy_current_calibration) {
long current_coefficient = 16140; // uSec
if (CSE_NOT_CALIBRATED != header) {
current_coefficient = serial_in_buffer[8] << 16 | serial_in_buffer[9] << 8 | serial_in_buffer[10];
}
Settings.energy_current_calibration = current_coefficient;
}
if (HLW_PREF_PULSE == Settings.energy_power_calibration) {
long power_coefficient = 5364000; // uSec
if (CSE_NOT_CALIBRATED != header) {
power_coefficient = serial_in_buffer[14] << 16 | serial_in_buffer[15] << 8 | serial_in_buffer[16];
}
Settings.energy_power_calibration = power_coefficient / CSE_PREF;
}
uint8_t adjustement = serial_in_buffer[20];
voltage_cycle = serial_in_buffer[5] << 16 | serial_in_buffer[6] << 8 | serial_in_buffer[7];
current_cycle = serial_in_buffer[11] << 16 | serial_in_buffer[12] << 8 | serial_in_buffer[13];
power_cycle = serial_in_buffer[17] << 16 | serial_in_buffer[18] << 8 | serial_in_buffer[19];
cf_pulses = serial_in_buffer[21] << 8 | serial_in_buffer[22];
if (energy_power_on) { // Powered on
if (adjustement & 0x40) { // Voltage valid
energy_voltage = (float)(Settings.energy_voltage_calibration * CSE_UREF) / (float)voltage_cycle;
}
if (adjustement & 0x10) { // Power valid
cse_power_invalid = 0;
if ((header & 0xF2) == 0xF2) { // Power cycle exceeds range
energy_active_power = 0;
} else {
if (0 == power_cycle_first) { power_cycle_first = power_cycle; } // Skip first incomplete power_cycle
if (power_cycle_first != power_cycle) {
power_cycle_first = -1;
energy_active_power = (float)(Settings.energy_power_calibration * CSE_PREF) / (float)power_cycle;
} else {
energy_active_power = 0;
}
}
} else {
if (cse_power_invalid < CSE_MAX_INVALID_POWER) { // Allow measurements down to about 1W
cse_power_invalid++;
} else {
power_cycle_first = 0;
energy_active_power = 0; // Powered on but no load
}
}
if (adjustement & 0x20) { // Current valid
if (0 == energy_active_power) {
energy_current = 0;
} else {
energy_current = (float)Settings.energy_current_calibration / (float)current_cycle;
}
}
} else { // Powered off
power_cycle_first = 0;
energy_voltage = 0;
energy_active_power = 0;
energy_current = 0;
}
}
bool CseSerialInput(void)
{
if (cse_receive_flag) {
serial_in_buffer[serial_in_byte_counter++] = serial_in_byte;
if (24 == serial_in_byte_counter) {
AddLogSerial(LOG_LEVEL_DEBUG_MORE);
uint8_t checksum = 0;
for (byte i = 2; i < 23; i++) { checksum += serial_in_buffer[i]; }
if (checksum == serial_in_buffer[23]) {
CseReceived();
cse_receive_flag = 0;
return 1;
} else {
AddLog_P(LOG_LEVEL_DEBUG, PSTR("CSE: " D_CHECKSUM_FAILURE));
do { // Sync buffer with data (issue #1907 and #3425)
memmove(serial_in_buffer, serial_in_buffer +1, 24);
serial_in_byte_counter--;
} while ((serial_in_byte_counter > 2) && (0x5A != serial_in_buffer[1]));
if (0x5A != serial_in_buffer[1]) {
cse_receive_flag = 0;
serial_in_byte_counter = 0;
}
}
}
} else {
if ((0x5A == serial_in_byte) && (1 == serial_in_byte_counter)) { // 0x5A - Packet header 2
cse_receive_flag = 1;
} else {
serial_in_byte_counter = 0;
}
serial_in_buffer[serial_in_byte_counter++] = serial_in_byte;
}
serial_in_byte = 0; // Discard
return 0;
}
/********************************************************************************************/
void CseEverySecond(void)
{
long cf_frequency = 0;
if (CSE_PULSES_NOT_INITIALIZED == cf_pulses_last_time) {
cf_pulses_last_time = cf_pulses; // Init after restart
} else {
if (cf_pulses < cf_pulses_last_time) { // Rolled over after 65535 pulses
cf_frequency = (65536 - cf_pulses_last_time) + cf_pulses;
} else {
cf_frequency = cf_pulses - cf_pulses_last_time;
}
if (cf_frequency && energy_active_power) {
cf_pulses_last_time = cf_pulses;
energy_kWhtoday_delta += (cf_frequency * Settings.energy_power_calibration) / 36;
EnergyUpdateToday();
}
}
}
void CseDrvInit(void)
{
if (!energy_flg) {
if ((SONOFF_S31 == Settings.module) || (SONOFF_POW_R2 == Settings.module)) { // Sonoff S31 or Sonoff Pow R2
baudrate = 4800;
serial_config = SERIAL_8E1;
energy_flg = XNRG_02;
}
}
}
boolean CseCommand(void)
{
boolean serviced = true;
if (CMND_POWERSET == energy_command_code) {
if (XdrvMailbox.data_len && power_cycle) {
Settings.energy_power_calibration = ((unsigned long)CharToDouble(XdrvMailbox.data) * power_cycle) / CSE_PREF;
}
}
else if (CMND_VOLTAGESET == energy_command_code) {
if (XdrvMailbox.data_len && voltage_cycle) {
Settings.energy_voltage_calibration = ((unsigned long)CharToDouble(XdrvMailbox.data) * voltage_cycle) / CSE_UREF;
}
}
else if (CMND_CURRENTSET == energy_command_code) {
if (XdrvMailbox.data_len && current_cycle) {
Settings.energy_current_calibration = ((unsigned long)CharToDouble(XdrvMailbox.data) * current_cycle) / 1000;
}
}
else serviced = false; // Unknown command
return serviced;
}
/*********************************************************************************************\
* Interface
\*********************************************************************************************/
int Xnrg02(byte function)
{
int result = 0;
if (FUNC_PRE_INIT == function) {
CseDrvInit();
}
else if (XNRG_02 == energy_flg) {
switch (function) {
case FUNC_EVERY_SECOND:
CseEverySecond();
break;
case FUNC_COMMAND:
result = CseCommand();
break;
case FUNC_SERIAL:
result = CseSerialInput();
break;
}
}
return result;
}
#endif // USE_CSE7766
#endif // USE_ENERGY_SENSOR
| 34.231373
| 119
| 0.630198
|
024e53247ca10d214d90d9498059e7e688936ffe
| 2,927
|
ino
|
Arduino
|
scoutlab-2018/stimmungsboard/code/Arduino_Code.ino
|
joek/vcp-scoutlab.github.io
|
343c9116b49c5dbeb399a1c421b97ab7852c8ec3
|
[
"MIT"
] | 1
|
2018-08-20T10:13:11.000Z
|
2018-08-20T10:13:11.000Z
|
scoutlab-2018/stimmungsboard/code/Arduino_Code.ino
|
joek/vcp-scoutlab.github.io
|
343c9116b49c5dbeb399a1c421b97ab7852c8ec3
|
[
"MIT"
] | 3
|
2017-08-17T17:47:55.000Z
|
2018-02-22T09:09:55.000Z
|
scoutlab-2018/stimmungsboard/code/Arduino_Code.ino
|
joek/vcp-scoutlab.github.io
|
343c9116b49c5dbeb399a1c421b97ab7852c8ec3
|
[
"MIT"
] | 2
|
2020-10-03T09:03:25.000Z
|
2020-10-03T09:11:07.000Z
|
#include<Wire.h>
#include<LiquidCrystal_I2C.h>
// HDI
const int LED = 13; // LED
const int BT_I = 3; // positiv
const int BT_II = 4; // mittel
const int BT_III = 5; // negativ
const int BT_IV = 6; // Auslesen
const int LED_ON = 500; // Delay nach auslösen der LED
// Statistik
long int pos = 0; // positiv
long int meg = 0; // mittel
long int neg = 0; // negativ
double ins = 0; // insgesammt
double val = 0; // durschchintt
// Boolsche Variablen für Doppelt Click
bool BT_IV_Pressed = false;
bool BT_IV_double = false;
LiquidCrystal_I2C lcd(0x27,16,2);
// Funcktions
void Fled_output(double outp) { // Gibt den Durchschnitt [outp] auf dem LCD Screen aus
lcd.setCursor(4,0);
lcd.print("Feedback");
lcd.setCursor(0,1);
lcd.print("AVR: " + String(outp));
}
void Fclean() { // Cleaner: Löscht Statistikvariablen und leert den LCD Screen
// Reset Statistik
pos = 0;
meg = 0;
neg = 0;
ins = 0;
val = 0;
// Reset LCD Screen
lcd.clear();
// Reset Double Click Variables
BT_IV_double = false;
BT_IV_Pressed = false;
}
void Fapi() { //output für anderer Anwendungen
Serial.println(String(pos)+"|"+String(meg)+"|"+String(neg)+"|"+String(val));
}
void Fled() { // LED nutzen
digitalWrite(LED, HIGH);
delay(LED_ON);
digitalWrite(LED, LOW);
}
// Eigentlcihes Programm
void setup() {
// Pins declarieren
pinMode(LED, OUTPUT);
pinMode(BT_I, INPUT_PULLUP);
pinMode(BT_II, INPUT_PULLUP);
pinMode(BT_III, INPUT_PULLUP);
pinMode(BT_IV, INPUT_PULLUP);
// Init LCD Display
lcd.init();
lcd.backlight();
Fclean();
// API output
Serial.begin(9600);
}
void loop() {
// Decklare
// Bouttons Readed
bool P_BT_I = false;
bool P_BT_II = false;
bool P_BT_III = false;
bool P_BT_IV = false;
// Einlesen der Buttons
if (digitalRead(BT_I) == LOW) {
P_BT_I = true;
BT_IV_Pressed = false;
}
if (digitalRead(BT_II) == LOW) {
P_BT_II = true;
BT_IV_Pressed = false;
}
if (digitalRead(BT_III) == LOW) {
P_BT_III = true;
BT_IV_Pressed = false;
}
if (digitalRead(BT_IV) == LOW) {
P_BT_IV = true;
if (BT_IV_Pressed) {
BT_IV_double = true;
}
BT_IV_Pressed = true;
}
// Einbeziehen der gedrückten Buttons
if (P_BT_I) {
pos += 1;
}
if (P_BT_II) {
meg += 1;
}
if (P_BT_III) {
neg += 1;
}
if (P_BT_IV) { // Statistische Ausgabe
if (BT_IV_double) { // Doppelcklick löscht
Fclean();
}
else {
ins = pos + meg +neg;
val = (pos * 3 + meg * 2 + neg) / ins;
Fapi();
Fled_output(val);
}
delay (100);
}
// Fedback for Users
if (P_BT_I || P_BT_II || P_BT_III || P_BT_IV) {
Fled();
}
// Reset bool var
P_BT_I = false;
P_BT_II = false;
P_BT_III = false;
P_BT_IV = false;
}
| 20.468531
| 98
| 0.586949
|
0d7de99d17ec2ccd19cdfde1b866db68d2589e1d
| 8,129
|
ino
|
Arduino
|
mqtt-example-arduino.ino
|
m4rc77/mqtt-example-arduino
|
84c7af29a604b0bacf2c77103a9938ded1184331
|
[
"MIT"
] | null | null | null |
mqtt-example-arduino.ino
|
m4rc77/mqtt-example-arduino
|
84c7af29a604b0bacf2c77103a9938ded1184331
|
[
"MIT"
] | null | null | null |
mqtt-example-arduino.ino
|
m4rc77/mqtt-example-arduino
|
84c7af29a604b0bacf2c77103a9938ded1184331
|
[
"MIT"
] | null | null | null |
// Board Libraries
#include <ESP8266WiFi.h>
// Required libraries:
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#include <PubSubClient.h>
// The Wemos D1 mini's pins do not map to arduino pin numbers accurately ... see
// https://github.com/esp8266/Arduino/issues/1243
#define DHT_PIN 2 // => D3
#define LED_PIN 0 // => D4
// Define DHT Temperature/Humidity Sensor type ...
#define DHTTYPE DHT22
#include "config.h"
// File config.h sould contain the configuration in the following form ...
/*
const char *ssid = "your WLAN SSID";
const char *password = "your WLAN password";
const char *mqttServer = "the broker url";
// see https://github.com/mqtt-smarthome/mqtt-smarthome/blob/master/Architecture.
const char *mqttTopicTemperature = "REPLACE_ME/status/temperature";
const char *mqttTopicHumidity = "REPLACE_ME/status/humidity";
const char *mqttTopicLedStatus = "REPLACE_ME/status/led";
const char *mqttTopicLedSet = "REPLACE_ME/set/led";
*/
const char *lastWillMessage = "-1"; // the last will message show clients that we are offline
const int PUBLISH_SENSOR_DATA_DELAY = 10000; //milliseconds
// Variables ...
long sensorDelay;
long lastDhtRead;
float temperature = -1234;
float humidity = -1;
boolean ledSwitchedOn = false;
DHT_Unified dht(DHT_PIN, DHTTYPE);
WiFiClient espClient;
PubSubClient mqttClient(espClient);
void setup() {
Serial.begin(9600);
// setup io-pins
pinMode(LED_PIN, OUTPUT);
pinMode(DHT_PIN, INPUT);
ledOff();
setupDhtSensor();
setupWifi();
setupMqtt();
}
void setupDhtSensor() {
// Initialize device.
dht.begin();
// Print temperature sensor details.
sensor_t sensor;
dht.temperature().getSensor(&sensor);
Serial.println(" ");
Serial.println("=================================================");
Serial.println("Temperature: ------------------------");
Serial.print ("Sensor: "); Serial.println(sensor.name);
Serial.print ("Driver Ver: "); Serial.println(sensor.version);
Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
Serial.print ("Min Delay: "); Serial.print(sensor.min_delay/1000); Serial.println(" ms");
Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" *C");
Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" *C");
Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" *C");
Serial.println("-------------------------------------");
dht.humidity().getSensor(&sensor);
Serial.println("Humidity: ---------------------------");
Serial.print ("Sensor: "); Serial.println(sensor.name);
Serial.print ("Driver Ver: "); Serial.println(sensor.version);
Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id);
Serial.print ("Min Delay: "); Serial.print(sensor.min_delay/1000); Serial.println(" ms");
Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println("%");
Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println("%");
Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println("%");
Serial.println("-------------------------------------");
// Set delay between sensor readings based on sensor details.
sensorDelay = max(sensor.min_delay / 1000, PUBLISH_SENSOR_DATA_DELAY);
lastDhtRead = millis();
Serial.print("Checking DHT Sensor every ");Serial.print(sensorDelay); Serial.println("ms");
Serial.println("=================================================");
}
void setupWifi() {
delay(10);
Serial.println();Serial.print("Connecting to ");Serial.println(ssid);
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 setupMqtt() {
mqttClient.setServer(mqttServer, 1883);
mqttClient.setCallback(mqttCallback);
}
void mqttCallback(char* topic, byte* payload, unsigned int length) {
String topicStr = String(topic);
Serial.print("Message arrived [");Serial.print(topicStr);Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
if (topicStr == mqttTopicLedSet) {
Serial.println("Got LED switching command ...");
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
ledOn();
} else {
ledOff();
}
mqttPublishLedState();
}
}
void loop() {
checkWifi();
checkMqtt();
mqttClient.loop();
if(lastDhtRead + sensorDelay <= millis()) {
getTemperatureAndHumidity();
Serial.print("Temperature: "); Serial.print(temperature); Serial.println(" *C");
Serial.print("Humidity: "); Serial.print(humidity); Serial.println("%");
mqttPublishTemperatureAndHumidity();
}
}
void checkWifi() {
if (WiFi.status() != WL_CONNECTED) {
setupWifi();
}
}
void checkMqtt() {
if (!mqttClient.connected()) {
while (!mqttClient.connected()) {
Serial.print("Attempting to open MQTT connection...");
// connect with last will (QoS=1, retain=true, ) ...
if (mqttClient.connect("ESP8266_Client", mqttTopicLedStatus, 1, true, lastWillMessage)) {
Serial.println("connected");
mqttClient.subscribe(mqttTopicLedSet);
mqttPublishLedState();
flashLed();
} else {
Serial.print("MQTT connection failed, retry count: ");
Serial.print(mqttClient.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
}
void mqttPublishTemperatureAndHumidity() {
Serial.print("Publishing to server: ");Serial.println(mqttServer);
Serial.print("Publishing ");Serial.print(temperature);Serial.print(" to topic ");Serial.println(mqttTopicTemperature);
String temperatureStr = String(temperature); //converting temperature (the float variable above) to a string
char charBufTemperature[temperatureStr.length() + 1];
temperatureStr.toCharArray(charBufTemperature, temperatureStr.length() + 1); //packaging up the data to publish to mqtt ...
mqttClient.publish(mqttTopicTemperature, charBufTemperature);
Serial.print("Publishing ");Serial.print(humidity);Serial.print(" to topic ");Serial.println(mqttTopicHumidity);
String humidityStr = String(humidity); //converting humidity (the float variable above) to a string
char charBufHumidity[humidityStr.length() + 1];
humidityStr.toCharArray(charBufHumidity, humidityStr.length() + 1); //packaging up the data to publish to mqtt ...
mqttClient.publish(mqttTopicHumidity, charBufHumidity);
}
void mqttPublishLedState() {
Serial.print("Publishing to server: ");Serial.println(mqttServer);
String ledStateStr = ledSwitchedOn ? "1" : "0";
Serial.print("Publishing ");Serial.print(ledStateStr);Serial.print(" to topic ");Serial.println(mqttTopicLedStatus);
char charBufLed[ledStateStr.length() + 1];
ledStateStr.toCharArray(charBufLed, ledStateStr.length() + 1);
// retain message ...
mqttClient.publish(mqttTopicLedStatus, charBufLed, true);
}
// =================================================================================================================================
// Helper methods
// =================================================================================================================================
void ledOn() {
ledSwitchedOn = true;
digitalWrite(LED_PIN, HIGH);
}
void ledOff() {
ledSwitchedOn = false;
digitalWrite(LED_PIN, LOW);
}
void flashLed() {
for (int i=0; i < 5; i++){
ledOn();
delay(100);
ledOff();
delay(100);
}
ledOff();
}
void getTemperatureAndHumidity() {
sensors_event_t event;
dht.temperature().getEvent(&event);
if (isnan(event.temperature)) {
temperature = -9999;
} else {
temperature = event.temperature;
}
dht.humidity().getEvent(&event);
if (isnan(event.relative_humidity)) {
humidity = -1;
} else {
humidity = event.relative_humidity;
}
lastDhtRead = millis();
}
| 33.315574
| 132
| 0.642145
|
f127a44f86b7790af6d6e2c36d6a0f74f41c1fe5
| 1,478
|
ino
|
Arduino
|
Files/EEPROM_Programmer/ControlUnit/io.ino
|
cepdnaclk/e15-co221-SAP-I-Computer
|
ccef2d452ca80bb8034829272c982778cb88951d
|
[
"Apache-2.0"
] | null | null | null |
Files/EEPROM_Programmer/ControlUnit/io.ino
|
cepdnaclk/e15-co221-SAP-I-Computer
|
ccef2d452ca80bb8034829272c982778cb88951d
|
[
"Apache-2.0"
] | null | null | null |
Files/EEPROM_Programmer/ControlUnit/io.ino
|
cepdnaclk/e15-co221-SAP-I-Computer
|
ccef2d452ca80bb8034829272c982778cb88951d
|
[
"Apache-2.0"
] | null | null | null |
void writeAddress(int data) {
// Write given address to ports
if (data == 0) {
for (int i = 0; i < 7; i++) {
digitalWrite(addPins[i], LOW);
}
} else {
for (int i = 0; i < 7; i++) {
digitalWrite(addPins[i], bitRead(data, 6 - i));
//Serial.print(bitRead(data, i));
}
}
delay(10);
}
uint16_t readOutput() {
// Read current input
uint16_t buff = 0;
//Serial.print(" [");
for (int i = 0; i < 16; i++) {
bitWrite(buff, 15 - i, digitalRead(outPins[i]));
//Serial.print(digitalRead(outPins[i]));
}
//Serial.print("] ");
delay(10);
return buff;
}
void writeOutput(uint16_t data) {
//Write given output to DataOut pins
for (int i = 0; i < 16; i++) {
digitalWrite(outPins[i], bitRead(data, 15 - i));
}
digitalWrite(pinW, LOW);
digitalWrite(pinW2, LOW);
delayMicroseconds(500);
digitalWrite(pinW, HIGH);
digitalWrite(pinW2, HIGH);
delay(50);
}
void setWriteMode() {
for (int i = 0; i < 16; i++) {
pinMode(outPins[i], OUTPUT);
digitalWrite(outPins[i], LOW);
}
digitalWrite(pinE, LOW);
digitalWrite(pinG, HIGH);
digitalWrite(pinW, HIGH);
digitalWrite(pinG2, HIGH);
digitalWrite(pinW2, HIGH);
}
void setReadMode() {
for (int i = 0; i < 16; i++) {
digitalWrite(outPins[i], LOW);
pinMode(outPins[i], INPUT);
}
digitalWrite(pinE, LOW);
digitalWrite(pinG, LOW);
digitalWrite(pinW, HIGH);
digitalWrite(pinG2, LOW);
digitalWrite(pinW2, HIGH);
}
| 18.246914
| 53
| 0.594723
|
559541c154c133cdf80ce8ec188e6e32989eb2ac
| 5,379
|
ino
|
Arduino
|
FirePrevent_firmware.ino
|
adomenech73/FirePrevent_firmware
|
8c398e3e14d99a24b866ba235e081f0b68fc8998
|
[
"MIT"
] | null | null | null |
FirePrevent_firmware.ino
|
adomenech73/FirePrevent_firmware
|
8c398e3e14d99a24b866ba235e081f0b68fc8998
|
[
"MIT"
] | null | null | null |
FirePrevent_firmware.ino
|
adomenech73/FirePrevent_firmware
|
8c398e3e14d99a24b866ba235e081f0b68fc8998
|
[
"MIT"
] | null | null | null |
#include <ESP8266WiFi.h> //ESP8266 Core WiFi Library (you most likely already have this in your sketch)
#include <DNSServer.h> //Local DNS Server used for redirecting all requests to the configuration portal
#include <ESP8266WebServer.h> //Local WebServer used to serve the configuration portal
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager WiFi Configuration Magic
#include <DHT.h> // DHT11 & DHT22 Temperature and humidity sensor
#include <Wire.h> //
#include <WiFiUdp.h> // Wifi UDP packets generation
#include <max6675.h>
#include <LiquidCrystal_I2C.h> // I2c LCD display
/*-----( Declare Constants & objects)-----*/
int thermoDO = 14; // D5
int thermoCS1 = 12; // D6
int thermoCLK = 13; // D7
int thermoCS2 = 16; // D0
MAX6675 thermocouple1(thermoCLK, thermoCS1, thermoDO);
MAX6675 thermocouple2(thermoCLK, thermoCS2, thermoDO);
// make a cute degree symbol
//uint8_t degree[8] = {140,146,146,140,128,128,128,128};
// objects to store
uint8_t MAC_array[6];
char MAC_char[18];
// InfluxDB server ip
byte host[] = {192, 168, 1, 101};
// the port that the InfluxDB UDP plugin is listening on
int port = 8888;
#define DHTPIN D4 // what pin we connect DHT to
// note GPIO5 is D1 at NodeMCU - http://www.14core.com/wp-content/uploads/2015/06/Node-MCU-Pin-Out-Diagram1.png
// note GPIO5 is D15 http://www.wemos.cc/wiki/doku.php?id=en:d1
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22
DHT dht(DHTPIN, DHTTYPE);
WiFiUDP udp;
// set the LCD address to 0x27 for a 20 chars 4 line display
// Set the LCD I2C address
LiquidCrystal_I2C lcd(0x27, 20, 4);
// Callback definition for WiFiManager
void configModeCallback (WiFiManager *myWiFiManager) {
Serial.println("Entered config mode");
Serial.println(WiFi.softAPIP());
//if you used auto generated SSID, print it
Serial.println(myWiFiManager->getConfigPortalSSID());
}
void setup() {
Serial.begin(115200);
Serial.println("Wemos sensors sketch");
WiFiManager wifiManager;
//set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
wifiManager.setAPCallback(configModeCallback);
//fetches ssid and pass and tries to connect
//if it does not connect it starts an access point with the specified name
//here "AutoConnectAP"
//and goes into a blocking loop awaiting configuration
if(!wifiManager.autoConnect()) {
Serial.println("failed to connect and hit timeout");
//reset and try again, or maybe put it to deep sleep
ESP.reset();
delay(1000);
}
// Devices initialitation
lcd.begin();
lcd.clear();
lcd.leftToRight();
lcd.home();
dht.begin();
// create MAC string
WiFi.macAddress(MAC_array);
for (int i = 0; i < sizeof(MAC_array); ++i){
sprintf(MAC_char,"%s%02x:",MAC_char,MAC_array[i]);
}
Serial.print("MAC @:");
Serial.println(MAC_char);
Serial.println("");
Serial.println("");
//lcd.createChar(0, degree);
delay(3000);
}
void loop() {
// Get sensors data
float f_dhtemp = dht.readTemperature();
float f_humidity = dht.readHumidity();
float f_therm_c1 = thermocouple1.readCelsius();
float f_therm_f1 = thermocouple1.readFahrenheit();
float f_therm_c2 = thermocouple2.readCelsius();
float f_therm_f2 = thermocouple2.readFahrenheit();
// Generating line protocol
String temperature = String("dhtemp,host=") \
+ MAC_char + String(" value=") + String(f_dhtemp, 2) + "\n";
String humidity = String("humidity,host=") \
+ MAC_char + String(" value=") + String(f_humidity,2) + "\n";
String thermc1 = String("therm_C,host=") \
+ MAC_char + String(" value=") + String(f_therm_c1,2) + "\n";
String thermf1 = String("therm_F,host=") \
+ MAC_char + String(" value=") + String(f_therm_f1,2) + "\n";
String thermc2 = String("therm_C,host=") \
+ MAC_char + String(" value=") + String(f_therm_c2,2) + "\n";
String thermf2 = String("therm_F,host=") \
+ MAC_char + String(" value=") + String(f_therm_f2,2) + "\n";
// Print serial output (format validation purpose)
Serial.println();
Serial.println("SENSORS VALUE:");
Serial.print(temperature);
Serial.print(humidity);
Serial.print(thermc1);
Serial.print(thermf1);
Serial.print(thermc2);
Serial.print(thermf2);
// Send UDP packet
Serial.println();
Serial.println("Preparing UDP packet...");
udp.beginPacket(host, port);
udp.print(temperature);
udp.print(humidity);
udp.print(thermc1);
udp.print(thermf1);
udp.print(thermc2);
udp.print(thermf2);
udp.endPacket();
Serial.println("UDP packet sent...");
Serial.println();
Serial.println("Waiting...");
// Print LCD output
lcd.setCursor(0x00,0);
lcd.print("tmp1:");
lcd.print(f_dhtemp);
lcd.print(" hum:");
lcd.print(f_humidity);
lcd.setCursor(0x14,0);
lcd.print("1C:");
lcd.print(f_therm_c1);
lcd.print(" 1F:");
lcd.print(f_therm_f1);
lcd.setCursor(0x54,0);
lcd.print("2C:");
lcd.print(f_therm_c2);
lcd.print(" 2F:");
lcd.print(f_therm_f2);
/* lcd.print(thermocouple.readCelsius());
#if ARDUINO >= 100
lcd.write((byte)0);
#else
lcd.print(0, BYTE);
#endif
lcd.print("C ");
lcd.print(thermocouple.readFahrenheit());
#if ARDUINO >= 100
lcd.write((byte)0);
#else
lcd.print(0, BYTE);
#endif
lcd.print('F');*/
delay(3000);
}
| 28.919355
| 114
| 0.675962
|
3f584ce1ba98e97cd77c8a02548c39b8c25bcc9e
| 1,426
|
ino
|
Arduino
|
Advanced_voice_controlled_robot/Advanced_voice_controlled_robot.ino
|
ndrohith09/arduino
|
a2c04e15789dd58a37559cb7ed0cee4b39d12bc4
|
[
"MIT"
] | 8
|
2020-10-25T14:18:16.000Z
|
2022-03-07T10:25:15.000Z
|
Advanced_voice_controlled_robot/Advanced_voice_controlled_robot.ino
|
ndrohith09/arduino
|
a2c04e15789dd58a37559cb7ed0cee4b39d12bc4
|
[
"MIT"
] | null | null | null |
Advanced_voice_controlled_robot/Advanced_voice_controlled_robot.ino
|
ndrohith09/arduino
|
a2c04e15789dd58a37559cb7ed0cee4b39d12bc4
|
[
"MIT"
] | 3
|
2020-10-26T12:42:50.000Z
|
2022-02-06T15:11:36.000Z
|
#include<SoftwareSerial.h>
int motorPin1 = 3;
int motorPin2 = 4;
int motorPin3 = 5;
int motorPin4 = 6;
SoftwareSerial BT(11, 12);
String readvoice;
void setup() {
BT.begin(9600);
Serial.begin(9600);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
}
void loop() {
while (BT.available()) {
delay(10);
char c = BT.read();
readvoice += c ;
}
if (readvoice.length() > 0) {
Serial.println(readvoice);
if (readvoice == "forward") {
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
digitalWrite(5, HIGH);
digitalWrite(6, LOW );
delay(100);
}
else if (readvoice == "backward") {
digitalWrite(3, LOW);
digitalWrite(4, HIGH);
digitalWrite(5, LOW);
digitalWrite(6, HIGH );
delay(100);
}
else if (readvoice == "right") {
digitalWrite(3, LOW);
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, LOW );
delay(100);
}
else if (readvoice == "left") {
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
digitalWrite(6, HIGH );
delay(100);
}
else if (readvoice == "stop") {
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
digitalWrite(6, LOW );
delay(100);
}
readvoice = "";
}
}
| 22.634921
| 40
| 0.538569
|
4243811b4356b64a3b6ab3ea5c54bb964c0a5afd
| 3,508
|
ino
|
Arduino
|
lcdtext.ino
|
arpruss/nokiatext
|
3bc8fa30b1c571bcd8d06b02005a408389b60cc2
|
[
"MIT"
] | null | null | null |
lcdtext.ino
|
arpruss/nokiatext
|
3bc8fa30b1c571bcd8d06b02005a408389b60cc2
|
[
"MIT"
] | null | null | null |
lcdtext.ino
|
arpruss/nokiatext
|
3bc8fa30b1c571bcd8d06b02005a408389b60cc2
|
[
"MIT"
] | null | null | null |
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_PCD8544.h> // use fork at github.com/arpruss
#define REMAP_SPI1 // MOSI PB5, MISO PB4, SCK PB3, NSS PA8 (!!)
// unmapped: MOSI PA7, SCK PA5, MISO PA6, NSS PA4
#define SCREEN_WIDTH 84
#define SCREEN_HEIGHT 48
#define TEXT_HEIGHT 6
#define NUM_LINES (SCREEN_HEIGHT/TEXT_HEIGHT)
#include "6pt.h"
#include "SPI.h"
//Adafruit_PCD8544 display = Adafruit_PCD8544(PB3, PB5, PB0, /*PB1*/0, PB11);
SPIClass mySPI(1);
// CS isn't really needed, is it?
Adafruit_PCD8544 display = Adafruit_PCD8544(PB0, 0/*PB1*/, PB11, &mySPI); // warning: MISO is input, NSS is output
static uint8_t* pcd8544_buffer;
template<bool shiftLeft, bool invert>void writePartialLine(char* text, unsigned xStart, unsigned xEnd, unsigned line, unsigned shift) {
uint8_t* out = pcd8544_buffer+line*SCREEN_WIDTH + xStart;
uint8_t* end = out + xEnd-xStart;
uint8_t mask = shiftLeft ? ((1<<TEXT_HEIGHT)-1)<<shift : ((1<<TEXT_HEIGHT)-1)>>shift;
if (!invert)
mask = ~mask;
while (out < end && *text) {
uint8_t c = *text++;
if (c < 32 || c > 126)
c = 0;
else
c -= 32;
uint8_t width = font_widths[c];
const uint8_t* f = font_data[c];
do {
if (invert) {
if (shiftLeft)
*out = (*out | mask) ^ (*f << shift);
else
*out = (*out | mask) ^ (*f >> shift);
}
else {
if (shiftLeft)
*out = (*out & mask) | (*f << shift);
else
*out = (*out & mask) | (*f >> shift);
}
width--;
f++;
out++;
}
while (width && out < end);
}
while (out < end) {
if (invert) {
*out |= mask;
}
else {
*out &= mask;
}
out++;
}
}
void writeText(char* text, unsigned xStart, unsigned xEnd, unsigned y, bool invert) {
if (xStart >= SCREEN_WIDTH || y >= SCREEN_HEIGHT || xStart >= xEnd)
return;
if (xEnd >= SCREEN_WIDTH)
xEnd = SCREEN_WIDTH;
unsigned line1 = y>>3;
unsigned modulus = y%0x7;
if (invert)
writePartialLine<true,true>(text, xStart, xEnd, line1, modulus);
else
writePartialLine<true,false>(text, xStart, xEnd, line1, modulus);
line1++;
if (modulus>8-TEXT_HEIGHT && line1 < (SCREEN_HEIGHT>>3)) {
if(invert)
writePartialLine<false,true>(text, xStart, xEnd, line1, 8-modulus);
else
writePartialLine<false,false>(text, xStart, xEnd, line1, 8-modulus);
}
display.updateBoundingBox(xStart, y, xEnd, y+TEXT_HEIGHT-1);
}
void writeLine(char*s , int number, bool invert) {
writeText(s, 0, SCREEN_WIDTH, number*TEXT_HEIGHT, invert);
}
void setup() {
Serial.begin(9600);
#ifdef REMAP_SPI1
afio_cfg_debug_ports(AFIO_DEBUG_SW_ONLY); // release PB3 and PB5
afio_remap(AFIO_REMAP_SPI1);
gpio_set_mode(GPIOB, 3, GPIO_AF_OUTPUT_PP);
gpio_set_mode(GPIOB, 4, GPIO_INPUT_FLOATING);
gpio_set_mode(GPIOB, 5, GPIO_AF_OUTPUT_PP);
#endif
mySPI.begin();
mySPI.setModule(1);
pcd8544_buffer = display.getPixelBuffer();
display.begin(); //40,5
}
uint32_t t0,t1,t2,t3,t4;
boolean rev = false;
void loop() {
t0 = micros();
display.clearDisplay();
display.display();
t1 = micros();
writeLine("joystick (2 sli.), 0.64x rot", 0, rev);
t2 = micros();
writeLine("Jetset Radio joystick", 1,!rev);
t3 = micros();
display.display();
t4 = micros();
Serial.println(String(t1-t0)+" "+String(t2-t1)+" "+String(t3-t2)+" "+String(t4-t3));
delay(1000);
rev = ! rev;
}
// 2484 410 380 840
// 2460 50 83 834
// 530 50 83 180 // fast
| 28.064
| 135
| 0.624572
|
37047563bbc34a49ae7b5cff1759ddd38f22fde6
| 792
|
ino
|
Arduino
|
AlphaBot2-Demo/Arduino/arduino/demo/Run_Test/Run_Test.ino
|
VusumuziDube/Agent
|
abff15260dc0e6c5f6007e704d6a21e1123b12d0
|
[
"BSD-3-Clause"
] | null | null | null |
AlphaBot2-Demo/Arduino/arduino/demo/Run_Test/Run_Test.ino
|
VusumuziDube/Agent
|
abff15260dc0e6c5f6007e704d6a21e1123b12d0
|
[
"BSD-3-Clause"
] | null | null | null |
AlphaBot2-Demo/Arduino/arduino/demo/Run_Test/Run_Test.ino
|
VusumuziDube/Agent
|
abff15260dc0e6c5f6007e704d6a21e1123b12d0
|
[
"BSD-3-Clause"
] | null | null | null |
#define PWMA 6 //Left Motor Speed pin (ENA)
#define AIN2 A0 //Motor-L forward (IN2).
#define AIN1 A1 //Motor-L backward (IN1)
#define PWMB 5 //Right Motor Speed pin (ENB)
#define BIN1 A2 //Motor-R forward (IN3)
#define BIN2 A3 //Motor-R backward (IN4)
void setup() {
// put your setup code here, to run once:
pinMode(PWMA,OUTPUT);
pinMode(AIN2,OUTPUT);
pinMode(AIN1,OUTPUT);
pinMode(PWMB,OUTPUT);
pinMode(AIN1,OUTPUT);
pinMode(AIN2,OUTPUT);
analogWrite(PWMA,50);
digitalWrite(AIN1,LOW);
digitalWrite(AIN2,HIGH);
analogWrite(PWMB,50);
digitalWrite(BIN1,LOW);
digitalWrite(BIN2,HIGH);
}
void loop() {
// put your main code here, to run repeatedly:
}
| 27.310345
| 56
| 0.594697
|
b968db568833ae3ba65aec4c7d74fb57a527d5a6
| 2,699
|
ino
|
Arduino
|
Examples/Movement/Motors/FixedSpeed/FixedSpeed.ino
|
RocketLauncherCDMX/RocketLauncher_RobbusKidsy
|
ea8946e03a85899426e1764c063afe1675e54d05
|
[
"MIT"
] | 1
|
2021-12-15T04:25:35.000Z
|
2021-12-15T04:25:35.000Z
|
Examples/Movement/Motors/FixedSpeed/FixedSpeed.ino
|
RocketLauncherCDMX/RocketLauncher_RobbusKidsy
|
ea8946e03a85899426e1764c063afe1675e54d05
|
[
"MIT"
] | null | null | null |
Examples/Movement/Motors/FixedSpeed/FixedSpeed.ino
|
RocketLauncherCDMX/RocketLauncher_RobbusKidsy
|
ea8946e03a85899426e1764c063afe1675e54d05
|
[
"MIT"
] | null | null | null |
// ------------------------------------------------ ROBBUS KIDSY ----------------------------------------------
//
// EJEMPLO DE USO DE LOS MOTORES IZQUIERDO Y DERECHO A UNA VELOCIDAD FIJA
// Este ejemplo es de uso libre y esta pensado para dar una introduccion al hardware de Robbus Kidsy.
// Autor: Rocket Launcher
// Fecha: 20 de febrero de 2020
// ------------------------------------------------------------------------------------------------------------
//
// Robbus Kidsy cuenta con 2 motorreductores:
// - MotorLeft
// - MotorRight
//
// Con este ejemplo entenderas el funcionamiento de los motores que impulsan a tu Robot
// Si quieres mover los motores por separado, basta con utilizar las funciones:
//
// Kidsy.Move.MotorLeft(speed);
// Kidsy.Move.MotorRight(speed);
//
// speed sera la velocidad que quieres darle a un motor en especifico y puede ser desde -255 a 255.
//
// -255 -> Velocidad maxima hacia atras en ese motor
// 255 -> Velocidad maxima hacia adelante en ese motor
// 0 -> Motor detenido
//
// Considera que valores cercanos a 0 ya sean positivos o negativos, pueden no generar la fuerza
// suficiente para comenzar a girar las ruedas.
// ------------------------------------------------------------------------------------------------------------
#include<RobbusKidsy.h>
RobbusKidsy Kidsy; // Llama a Robbus Kidsy
// Variables para la velocidad de los motores
int speedLeft = 100; // 100 hacia el FRENTE, puedes poner un valor entre -255 y 255
int speedRight = -100; // 100 hacia ATRAS, puedes poner un valor entre -255 y 255
void setup() {
Kidsy.begin(); // Inicializa el hardware del Robbus Kidsy
}
void loop() {
Kidsy.ButtonA.read(); // captura estado nuevo del boton A
Kidsy.ButtonB.read(); // captura estado nuevo del boton B
Kidsy.ButtonC.read(); // captura estado nuevo del boton C
// REVISION DEL BOTON A
// ----------------------
if(Kidsy.ButtonA.status == PRESSED) {
Kidsy.Move.MotorLeft(speedLeft); // Si el boton se presiono, acciona motor izquierdo
}
if(Kidsy.ButtonA.status == RELEASED) {
}
// REVISION DEL BOTON B
// ----------------------
if(Kidsy.ButtonB.status == PRESSED) {
Kidsy.Move.MotorLeft(0); // Si el boton se presiono, acciona ambos motores
Kidsy.Move.MotorRight(0); // Si el boton se presiono, acciona ambos motores
}
if(Kidsy.ButtonB.status == RELEASED) {
}
// REVISION DEL BOTON C
// ----------------------
if(Kidsy.ButtonC.status == PRESSED) {
Kidsy.Move.MotorRight(speedRight); // Si el boton se presiono, acciona motor derecho
}
if(Kidsy.ButtonC.status == RELEASED) {
}
}
| 36.972603
| 111
| 0.582438
|
f5d75aa4f061bf5f8852c40995ee1854a84beb9d
| 2,442
|
ino
|
Arduino
|
dc_motor_controller/dc_motor_controller.ino
|
andreucm/btr-ino
|
763dece51eee31f308ee4f3a8cb60bc99f8bbe34
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
dc_motor_controller/dc_motor_controller.ino
|
andreucm/btr-ino
|
763dece51eee31f308ee4f3a8cb60bc99f8bbe34
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
dc_motor_controller/dc_motor_controller.ino
|
andreucm/btr-ino
|
763dece51eee31f308ee4f3a8cb60bc99f8bbe34
|
[
"BSD-2-Clause-FreeBSD"
] | null | null | null |
//testing maxon DC motor
//pin assignement
int pin_led = 13; // Pin 13 has a LED connected on most Arduino boards.
int pin_motor_controller_e2 = 3; //pwm
int pin_motor_controller_m2 = 2; //turn direction
unsigned long motor_iteration_delta_t = 200; //duration of each iteration [milliseconds]
int pwm_min = 100;
int pwm_max = 200;
int pwm_step = 2;
//setup
void setup()
{
//sets pin_led as a digital output
pinMode(pin_led, OUTPUT);
//sets pin_motor_enable as a digital output
pinMode(pin_motor_controller_m2, OUTPUT);
}
//stops a motor at a given pin
void stop(int _pin)
{
//just send a PWM 0% at the pin
analogWrite(_pin, 0);
}
//ramp-up/down pwm to a given pin
void pwmRamp(int _pin, int _pwm_init, int _pwm_end, int _pwm_delta, unsigned long _delay)
{
int pwm_level;//running level of pwm. 0-> off; 255->100%
//ramp-up case
if (_pwm_delta > 0)
{
for(pwm_level = _pwm_init; pwm_level <= _pwm_end; pwm_level += _pwm_delta)
{
//set analog level for speed Control
analogWrite(_pin, pwm_level);
//delay
delay(_delay);
}
}
//ramp-down case
if (_pwm_delta < 0)
{
for(pwm_level = _pwm_init; pwm_level >= _pwm_end; pwm_level += _pwm_delta)
{
//set analog level for speed Control
analogWrite(_pin, pwm_level);
//delay
delay(_delay);
}
}
}
//main loop
void loop()
{
//1st cycle
// turn the LED on
digitalWrite(pin_led, HIGH);
//set motor direction
digitalWrite(pin_motor_controller_m2, HIGH);
//ramp-up
pwmRamp(pin_motor_controller_e2,pwm_min,pwm_max,pwm_step,motor_iteration_delta_t);
//ramp-down
pwmRamp(pin_motor_controller_e2,pwm_max,pwm_min,-pwm_step,motor_iteration_delta_t);
//stop
stop(pin_motor_controller_e2);
//breath
delay(200);
//2n cycle
// turn the LED of
digitalWrite(pin_led, LOW);
//change motor direction
digitalWrite(pin_motor_controller_m2, LOW);
//ramp-up
pwmRamp(pin_motor_controller_e2,pwm_min,pwm_max,pwm_step,motor_iteration_delta_t);
//ramp-down
pwmRamp(pin_motor_controller_e2,pwm_max,pwm_min,-pwm_step,motor_iteration_delta_t);
//stop
stop(pin_motor_controller_e2);
//breath
delay(200);
}
| 23.708738
| 89
| 0.630631
|
ddc87d40ca00c96bd9158dbd83bc67abac6a0909
| 17,016
|
ino
|
Arduino
|
arduino/beestation/beestation.ino
|
tomwillis608/beestation
|
b4a8bb44e09e0d6752e053222f48299e2bfe499c
|
[
"MIT"
] | 2
|
2020-02-09T20:15:05.000Z
|
2022-02-22T17:43:06.000Z
|
arduino/beestation/beestation.ino
|
tomwillis608/beestation
|
b4a8bb44e09e0d6752e053222f48299e2bfe499c
|
[
"MIT"
] | 3
|
2016-12-29T17:16:35.000Z
|
2022-03-31T13:52:20.000Z
|
arduino/beestation/beestation.ino
|
tomwillis608/beestation
|
b4a8bb44e09e0d6752e053222f48299e2bfe499c
|
[
"MIT"
] | null | null | null |
/*
* WiFi beekeeping monitor station with Arduino,
* BME 280 temperature-pressure-humidity sensor,
* Maxim DS2401 silicon serial number,
* Maxim DS18B20 temperature sensors,
* & the CC3000 chip WiFi.
*
* Part of the code is based on the work done by Adafruit on the CC3000 chip & the DHT11 sensor.
* Based in part on dht11/cc3300 weatherstation written by Marco Schwartz for Open Home Automation.
* Based in part on OneWire/DS18B20 sample code from the OneWire library.
* Lots of ideas taken from the many helpful posts in the community online.
*
* Purpose:
* Sends data to LAMP backend with HTTP GETs
* Be stable over all conditions (Hardware reset cicruit currently required)
*
* To Do:
* More sensors, besides temperature. <<In Progress>>
* Better network recovery code - I saw some ideas online
* Powersaving by sleeping instead of waiting
* Reduce code size
*
*/
#define USE_DHT 0
#define USE_CC3300 01
#define USE_DS2401 1
#define USE_DS18B20 1
#define USE_BME 1
#define MY_DEBUG 0
// Include required libraries
#include <Adafruit_CC3000.h> // wifi library
#include <SPI.h> // how to talk to adafruit cc3300 board
#include <OneWire.h> // PJRC OneWire library to read DS 1-Wire sensors, like DS2401 and DS18B20
// http://www.pjrc.com/teensy/td_libs_OneWire.html
#if USE_BME
// Using I2C protocol
#include <Adafruit_BME280.h>
#endif // USE_BME
#include <avr/wdt.h> // Watchdog timer
#include <mynetwork.h> // defines network secrets and addresses
// WLAN_SSID
// WLAN_PASS
// WEB_SERVER_IP_COMMAS
// WEB_SERVER_IP_DOTS
// WiFi network
#define WLAN_SECURITY WLAN_SEC_WPA2
// Define CC3000 chip pins (WiFi board)
#define ADAFRUIT_CC3000_IRQ 3
#define ADAFRUIT_CC3000_VBAT 5
#define ADAFRUIT_CC3000_CS 10
// DS2401 bus pin
#define DS2401PIN 9
#define DS18B20PIN 6
// Create global CC3000 instance
Adafruit_CC3000 gCc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,
ADAFRUIT_CC3000_IRQ,
ADAFRUIT_CC3000_VBAT,
SPI_CLOCK_DIVIDER);
#if USE_BME
Adafruit_BME280 gBme280; // I2C
// Variables to be exposed
int gHumidity = 0;
int gPressure = 0;
int gTemperature = 0;
#endif // USE_BME
#if USE_DS18B20
OneWire gDs(DS18B20PIN);
int gDevices;
#define DS_COUNT 10
byte gDsAddrs[DS_COUNT][8];
// Use array for DS18B20 temperatures and simplify HTTP printout code
int gDsTemps[DS_COUNT];
#endif // USE_DS18B20
// PHP server on backend
const char gWebServer[] = WEB_SERVER_IP_DOTS; // IP Address (or name) of server to dump data to
#define WEB_PORT 80
uint32_t gIp;
//unsigned long gTimeNow;
unsigned long gCycles = 0;
// Serial Number of this beestation
char gSerialNumber[3]; // read from Maxim DS2401 on pin 9, use rightmost word
const int gRedLED = 8; // LED on pin
const int gYellowLED = 7; // LED on pin 7
void setup(void)
{
wdt_disable();
// Blink LED
pinMode(gRedLED, OUTPUT);
pinMode(gYellowLED, OUTPUT);
digitalWrite(gYellowLED, HIGH);
digitalWrite(gRedLED, HIGH);
delay(500);
digitalWrite(gRedLED, LOW);
// Start Serial
Serial.begin(115200); // 9600
Serial.print(F("\n\nInitializing BeeStation #"));
// DS2401
readSerialNumber(); // Populate gSerialNumber
printFreeRam();
#if USE_DS18B20
setupDs18B20();
#endif // USE_DS18B20
#if USE_BME
// Initialize BMP180 sensor
if (!gBme280.begin())
{
Serial.print(F("Cannot read BME280 sensor!"));
while (1);
}
#endif // USE_BME
printFreeRam();
#if USE_CC3300
setupCc3000();
displayConnectionDetails();
#endif // USE_CC3300
delay(2000);
#if USE_CC3300
gIp = gCc3000.IP2U32(WEB_SERVER_IP_COMMAS);
Serial.print(F("Connecting to web server "));
gCc3000.printIPdotsRev(gIp);
Serial.println();
postStatusToWeb(gIp, "Start");
#endif
Serial.println(F("Looping"));
digitalWrite(gYellowLED, LOW);
wdt_enable(WDTO_8S); // options: WDTO_1S, WDTO_2S, WDTO_4S, WDTO_8S
}
void loop(void)
{
wdt_reset();
resetHardwareWatchdog();
gCycles++;
Serial.print(F("Cycles:"));
Serial.println(gCycles);
printFreeRam();
#if USE_BME
// Measure from BMP180
measureBme280();
// As I suspected, the temperature reading on the particular BME280 sensor is high about 1 degree C
// compared to other temperature measurements - 29 Aug 2016 TCW
wdt_reset();
#endif
#if USE_DS18B20
measureDs18B20();
wdt_reset();
#endif // USE_DS18B20
#if USE_CC3300
Serial.println(F("Connecting to web server"));
wdt_reset();
postReadingsToWeb(gIp);
wdt_reset();
if (0 == (gCycles % 100)) {
char message[64];
char iBuf[12];
strlcpy(message, itoa(gCycles, iBuf, 10), 64);
strlcat(message, ("%20cycles"), 64);
postStatusToWeb(gIp, message);
}
wdt_reset();
// Check WiFi connection, reset if connection is lost
checkAndResetWifi();
#endif // USE_CC3300
wdt_reset();
delayBetweenMeasurements(70); // Wait about a minute between measurements.
}
bool
displayConnectionDetails(void)
{
uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;
if (!gCc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
{
Serial.println(F("Can't get IP"));
return false;
}
else
{
Serial.print(F("IP: ")); gCc3000.printIPdotsRev(ipAddress);
Serial.println(F("\nGateway: ")); gCc3000.printIPdotsRev(gateway);
return true;
}
}
#define MILLISEC_IN_A_SECOND 1000
// take a little nap between measurements
void
delayBetweenMeasurements(int delaySeconds)
{
for (int i = 0; i < delaySeconds; i++) {
wdt_reset();
delay(MILLISEC_IN_A_SECOND);
}
}
#define OUTSTRSIZE 256
// send sensor measurements to the webserver
void
postReadingsToWeb(uint32_t ip)
{
// Build the URL string
char outStr[OUTSTRSIZE];
char itoaBuf[12];
strlcpy(outStr, ("GET /add_data.php?"), OUTSTRSIZE);
strlcat(outStr, ("sn="), OUTSTRSIZE);
strlcat(outStr, (gSerialNumber), OUTSTRSIZE);
strlcat(outStr, ("&"), OUTSTRSIZE);
#if USE_BME
strlcat(outStr, ("t1="), OUTSTRSIZE);
itoa(gTemperature, itoaBuf, 10);
strlcat(outStr, (itoaBuf), OUTSTRSIZE);
strlcat(outStr, ("&"), OUTSTRSIZE);
strlcat(outStr, ("hu="), OUTSTRSIZE);
itoa(gHumidity, itoaBuf, 10);
strlcat(outStr, (itoaBuf), OUTSTRSIZE);
strlcat(outStr, ("&"), OUTSTRSIZE);
strlcat(outStr, ("pr="), OUTSTRSIZE);
itoa(gPressure, itoaBuf, 10);
strlcat(outStr, (itoaBuf), OUTSTRSIZE);
#endif // USE_BME
/* Write DS18B20 results */
#if USE_DS18B20
for (int j = 0; j < DS_COUNT; j++) {
strlcat(outStr, ("&t"), OUTSTRSIZE);
itoa((j+2), itoaBuf, 10);
strlcat(outStr, (itoaBuf), OUTSTRSIZE);
strlcat(outStr, ("="), OUTSTRSIZE);
itoa(gDsTemps[j], itoaBuf, 10);
strlcat(outStr, (itoaBuf), OUTSTRSIZE);
}
#endif
Serial.println(outStr);
postToWeb(ip, outStr);
}
// Send startup or other message about the station to the webserver
void
postStatusToWeb(uint32_t ip, const char * message)
{
// Build the URL string
char outStr[OUTSTRSIZE];
strlcpy(outStr, ("GET /add_info.php?"), OUTSTRSIZE);
strlcat(outStr, ("serial="), OUTSTRSIZE);
strlcat(outStr, (gSerialNumber), OUTSTRSIZE);
strlcat(outStr, ("&"), OUTSTRSIZE);
strlcat(outStr, ("message="), OUTSTRSIZE);
strlcat(outStr, (message), OUTSTRSIZE);
postToWeb(ip, outStr);
}
/// Connect to webserver and send it the urlString
void
postToWeb(uint32_t ip, const char * urlString)
{
Adafruit_CC3000_Client client;
unsigned int gConnectTimeout = 2000;
unsigned long gTimeNow;
digitalWrite(gRedLED, HIGH);
gTimeNow = millis();
do {
Serial.println(F("->connectTCP"));
client = gCc3000.connectTCP(ip, WEB_PORT);
Serial.println(F("<-connectTCP"));
delay(20);
} while ((!client.connected()) && ((millis() - gTimeNow) < gConnectTimeout));
if (client.connected())
{
//Serial.println(F("Created client interface"));
Serial.println(urlString);
Serial.println(F("->")); // Connected
client.fastrprint(urlString);
client.fastrprint(" HTTP/1.1\r\n");
client.fastrprint("Host: ");
client.fastrprint(gWebServer);
client.fastrprint("\r\n");
//client.fastrprint("Connection: close\r\n");
client.fastrprint("User-Agent: Arduino Beestation/0.0\r\n");
client.fastrprintln("\r\n");
//client.fastrprintln("");
delay(100);
while (client.available()) {
char c = client.read();
Serial.print(c);
}
client.close();
Serial.println(F("<-")); // Disconnected
}
else
{ // you didn't get a connection to the server:
Serial.println(F("--> connection failed/n"));
}
digitalWrite(gRedLED, LOW);
}
bool
readSerialNumber(void)
{
const char hex[] = "0123456789ABCDEF";
byte i = 0, j = 0;
boolean present;
byte data;
OneWire ds2401(DS2401PIN); // create local 1-Wire instance on DS2401PIN for silicon serial number ds2401
present = ds2401.reset();
if (present == TRUE) {
//Serial.println(F("1-Wire Device present bus"));
ds2401.write(0x33); //Send READ data command to 1-Wire bus
for (i = 0; i <= 7; i++) {
data = ds2401.read();
if (i == 7) {
gSerialNumber[j++] = hex[data / 16];
gSerialNumber[j++] = hex[data % 16];
}
}
gSerialNumber[j] = 0;
Serial.println(gSerialNumber);
}
else { //Nothing is connected in the bus
//Serial.println(F("No 1-Wire Device detected on bus"));
strlcpy(gSerialNumber, "00", 3);
}
//Serial.print(F("Serial Number for this kit: "));
return present;
}
#if USE_BME
void
measureBme280(void)
{
float temperature;
float pressure;
float humidity;
temperature = gBme280.readTemperature();
wdt_reset();
pressure = gBme280.readPressure() / 100.0F;
wdt_reset();
humidity = gBme280.readHumidity();
gPressure = (int)(pressure + 0.5);
#if MY_DEBUG
Serial.print(F("Pressure: "));
Serial.print(pressure);
Serial.print(F(" hPa => "));
Serial.println(gPressure);
#endif // MY_DEBUG
gTemperature = (int)(temperature + 0.5);
#if MY_DEBUG
Serial.print(F("Temperature: "));
Serial.print(temperature);
Serial.print(F(" C =>"));
Serial.println(gTemperature);
#endif
gHumidity = (int)(humidity + 0.5);
#if MY_DEBUG
Serial.print(F("Humidity: "));
Serial.print(humidity);
Serial.print(F(" RH =>"));
Serial.println(gHumidity);
#endif
wdt_reset();
}
#endif // USE_BME
void
setupCc3000(void)
{
Serial.println(F("CC3000 setup..."));
/* 5/4/17 hack - seems stable 6/30/17 TCW */
gCc3000.reboot();
Serial.println(F("CC3000 reboot initialize"));
delay(500);
#if 01
if (!gCc3000.begin())
{
Serial.println(F("CC3000 failed initialize"));
do { /* do nothing without reset, let the watchdog bite */ } while (1);
}
#endif
// cleanup profiles the CC3000 module
if (!gCc3000.deleteProfiles())
{
Serial.println(F("CC3000 failed to delete old profiles"));
do { /* do nothing without reset, let the watchdog bite */ } while (1);
}
// Connect to WiFi network
Serial.println(F("Connecting to WiFi"));
gCc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY);
// Check DHCP
int dhcpCount = 0;
while (!gCc3000.checkDHCP())
{
delay(100);
Serial.println(F("Trying WiFi again..."));
if (++dhcpCount > 100) {
do { /* do nothing without reset, let the watchdog bite */ } while (1);
}
}
}
void
checkAndResetWifi(void)
{
wdt_reset();
if (!gCc3000.checkConnected() )
{
Serial.print(F("Time: "));
#if 0
gTimeNow = millis();
//prints time since program started
Serial.println(gTimeNow);
#endif
Serial.println(F("Lost WiFi. Rebooting CC3000"));
gCc3000.disconnect();
gCc3000.stop();
wdt_reset();
gCc3000.reboot(0);
// setupCc3000() was rarely finishing before the watchdog bites, so let it
do { /* do nothing without reset, let the watchdog bite */ } while (1);
}
}
int
calculateFreeRam(void) {
extern int __heap_start, *__brkval;
int v;
return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
}
// Feed the dog so it doesn't bite
void
resetHardwareWatchdog(void)
{
pinMode(DD4, OUTPUT);
delay(200);
pinMode(DD4, INPUT);
}
// DS 18B20 Temperature sensor array
void
setupDs18B20(void)
{
gDevices = countDsDevices(gDs);
Serial.print(F("Found "));
Serial.print(gDevices);
Serial.println(F(" devices on bus"));
for (int i = 0; i < gDevices; i++) {
getDsAddrByIndex(gDs, gDsAddrs[i], i);
}
}
int
countDsDevices(OneWire myDs)
{
byte addr[8];
int deviceCount = 0;
myDs.reset();
myDs.reset_search();
while (myDs.search(addr)) {
if (checkDsCrc(myDs, addr)) {
deviceCount++;
}
}
return deviceCount;
}
bool
checkDsCrc(OneWire myDs, byte addr[8])
{
return (OneWire::crc8(addr, 7) == addr[7]);
}
bool
getDsAddrByIndex(OneWire myDs, byte firstadd[], int index)
{
byte i;
// byte present = 0;
byte addr[8];
int count = 0;
myDs.reset();
myDs.reset_search();
//Serial.print(F("OneWire @ "));
//Serial.println(index);
while (myDs.search(addr) && (count <= index)) {
if ((count == index) && checkDsCrc(myDs, addr))
{
//Serial.print(F("Found addr: "));
//Serial.print(F("0x"));
for (i = 0; i < 8; i++) {
firstadd[i] = addr[i];
//if (addr[i] < 16) {
// //Serial.print(F("0"));
//}
//Serial.print(addr[i], HEX);
//if (i < 7) {
// Serial.print(F(", "));
//}
}
//Serial.println();
return true;
}
count++;
}
return false;
}
// There are 10 DS12B80 sensors connected
// Three are in a linear probe that will go in the hive, above the first brood box, at 2, 6 and 10 inches spacing in a 12 inch tube
// Three more are in another linear probe that will go in the hive, above the second brood box, at 2, 6 and 10 inches spacing in a 12 inch tube
// Three more are in yet another linear probe that will go in the hive, aboce the first honey super, at 2, 6 and 10 inches spacing in a 12 inch tube
// There is one more mounted in the station near the BME280 sensor
void
measureDs18B20(void) {
for (int i = 0; i < gDevices; i++) {
int intTemp = getDsTempeature(gDs, gDsAddrs[i]);
#if MY_DEBUG
Serial.println(intTemp);
#endif // MY_DEBUG
// save some bytes over switch with cascading if's - ha ha
if (0x67 == gDsAddrs[i][7]) {
gDsTemps[1] = intTemp;
#if MY_DEBUG
Serial.print(F("2in temp: "));
#endif
}
else if (0x36 == gDsAddrs[i][7]) {
gDsTemps[2] = intTemp;
#if MY_DEBUG
Serial.print(F("6in temp: "));
#endif
}
else if (0xC0 == gDsAddrs[i][7]) {
gDsTemps[0] = intTemp;
#if MY_DEBUG
Serial.print(F("box temp: "));
#endif
}
else if (0xB1 == gDsAddrs[i][7]) {
gDsTemps[3] = intTemp;
#if MY_DEBUG
Serial.print(F("10in temp: "));
#endif
}
else if (0xEC == gDsAddrs[i][7]) {
gDsTemps[4] = intTemp;
#if MY_DEBUG
Serial.print(F("2in temp2: "));
#endif
}
else if (0xDD == gDsAddrs[i][7]) {
gDsTemps[5] = intTemp;
#if MY_DEBUG
Serial.print(F("6in temp2: "));
#endif
}
else if (0x4D == gDsAddrs[i][7]) {
gDsTemps[6] = intTemp;
#if MY_DEBUG
Serial.print(F("10in temp2: "));
#endif
}
else if (0x6F == gDsAddrs[i][7]) {
gDsTemps[7] = intTemp;
#if MY_DEBUG
Serial.print(F("2in temp2: "));
#endif
}
else if (0x52 == gDsAddrs[i][7]) {
gDsTemps[8] = intTemp;
#if MY_DEBUG
Serial.print(F("6in temp2: "));
#endif
}
else if (0xAB == gDsAddrs[i][7]) {
gDsTemps[9] = intTemp;
#if MY_DEBUG
Serial.print(F("10in temp2: "));
#endif
}
#if MY_DEBUG
Serial.println(intTemp);
#endif
}
}
// Testing shows 10-bit resolution give more than adequate precision and accuracy
int
getDsTempeature(OneWire myDs, byte addr[8])
{
byte data[12];
wdt_reset();
// Get byte for desired resolution
byte resbyte = 0x3F; // for 10-bit resolution
// Set configuration
myDs.reset();
myDs.select(addr);
myDs.write(0x4E); // Write scratchpad
myDs.write(0); // TL
myDs.write(0); // TH
myDs.write(resbyte); // Configuration Register
myDs.write(0x48); // Copy Scratchpad
myDs.reset();
myDs.select(addr);
//long starttime = millis();
myDs.write(0x44, 1); // start conversion
while (!myDs.read()) {
// do nothing
}
#if MY_DEBUG1
Serial.print(F("Conversion took: "));
Serial.print(millis() - starttime);
Serial.println(F(" ms"));
#endif // MY_DEBUG
//delay(1000); // maybe 750ms is enough, maybe not
// we might do a ds.depower() here, but the reset will take care of it.
wdt_reset();
myDs.reset();
myDs.select(addr);
myDs.write(0xBE); // Read Scratchpad
#if MY_DEBUG
Serial.print(F("Raw Data: "));
#endif // MY_DEBUG
for (int i = 0; i < 9; i++) { // we need 9 bytes
data[i] = myDs.read();
#if MY_DEBUG
Serial.print(data[i], HEX);
Serial.print(F(" "));
#endif // MY_DEBUG
}
#if MY_DEBUG
Serial.println();
#endif // MY_DEBUG
// convert the data to actual temperature
int raw = (data[1] << 8) + data[0];
// What about negative temps?
// look for sign bit per http://stackoverflow.com/questions/30646783/arduino-temperature-sensor-negative-temperatures
int signBit = raw & 0x8000; // test most sig bit
if (signBit) { // negative
raw = ((raw ^ 0xffff) + 1) * (-1); // 2's comp
}
int celsius_100 = (6 * raw) + raw / 4; // multiply by (100 * 0.0625) or 6.25
int whole = celsius_100 / 100; // separate off the whole and fractional portions
//int fraction = celsius_100 % 100;
#if MY_DEBUG
Serial.print("Temp (C): ");
#endif // MY_DEBUG
return whole;
}
void
printFreeRam(void)
{
Serial.print(F("Free:"));
Serial.println(calculateFreeRam());
}
| 24.239316
| 148
| 0.678244
|
3b90a6ef1133550655b8ebaf07108ffa85010663
| 29,210
|
ino
|
Arduino
|
esp8266/arduino/src/platform/ESP8266/Arduino/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino
|
xsession/cmake_based_embedded_project_templates
|
e4a5be10bd01d204c1fe94e70e38c72d13c858fa
|
[
"MIT"
] | null | null | null |
esp8266/arduino/src/platform/ESP8266/Arduino/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino
|
xsession/cmake_based_embedded_project_templates
|
e4a5be10bd01d204c1fe94e70e38c72d13c858fa
|
[
"MIT"
] | null | null | null |
esp8266/arduino/src/platform/ESP8266/Arduino/libraries/ESP8266WiFiMesh/examples/HelloEspnow/HelloEspnow.ino
|
xsession/cmake_based_embedded_project_templates
|
e4a5be10bd01d204c1fe94e70e38c72d13c858fa
|
[
"MIT"
] | null | null | null |
#define ESP8266WIFIMESH_DISABLE_COMPATIBILITY // Excludes redundant compatibility code. TODO: Should be used for new code until the compatibility code is removed with release 3.0.0 of the Arduino core.
#include <ESP8266WiFi.h>
#include <EspnowMeshBackend.h>
#include <TcpIpMeshBackend.h>
#include <TypeConversionFunctions.h>
#include <assert.h>
namespace TypeCast = MeshTypeConversionFunctions;
/**
NOTE: Although we could define the strings below as normal String variables,
here we are using PROGMEM combined with the FPSTR() macro (and also just the F() macro further down in the file).
The reason is that this approach will place the strings in flash memory which will help save RAM during program execution.
Reading strings from flash will be slower than reading them from RAM,
but this will be a negligible difference when printing them to Serial.
More on F(), FPSTR() and PROGMEM:
https://github.com/esp8266/Arduino/issues/1143
https://arduino-esp8266.readthedocs.io/en/latest/PROGMEM.html
*/
constexpr char exampleMeshName[] PROGMEM = "MeshNode_"; // The name of the mesh network. Used as prefix for the node SSID and to find other network nodes in the example networkFilter and broadcastFilter functions below.
constexpr char exampleWiFiPassword[] PROGMEM = "ChangeThisWiFiPassword_TODO"; // Note: " is an illegal character. The password has to be min 8 and max 64 characters long, otherwise an AP which uses it will not be found during scans.
// A custom encryption key is required when using encrypted ESP-NOW transmissions. There is always a default Kok set, but it can be replaced if desired.
// All ESP-NOW keys below must match in an encrypted connection pair for encrypted communication to be possible.
// Note that it is also possible to use Strings as key seeds instead of arrays.
uint8_t espnowEncryptedConnectionKey[16] = {0x33, 0x44, 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, // This is the key for encrypting transmissions of encrypted connections.
0x33, 0x44, 0x33, 0x44, 0x33, 0x44, 0x32, 0x11
};
uint8_t espnowEncryptionKok[16] = {0x22, 0x44, 0x33, 0x44, 0x33, 0x44, 0x33, 0x44, // This is the key for encrypting the encrypted connection key.
0x33, 0x44, 0x33, 0x44, 0x33, 0x44, 0x32, 0x33
};
uint8_t espnowHashKey[16] = {0xEF, 0x44, 0x33, 0x0C, 0x33, 0x44, 0xFE, 0x44, // This is the secret key used for HMAC during encrypted connection requests.
0x33, 0x44, 0x33, 0xB0, 0x33, 0x44, 0x32, 0xAD
};
unsigned int requestNumber = 0;
unsigned int responseNumber = 0;
const char broadcastMetadataDelimiter = 23; // 23 = End-of-Transmission-Block (ETB) control character in ASCII
String manageRequest(const String &request, MeshBackendBase &meshInstance);
TransmissionStatusType manageResponse(const String &response, MeshBackendBase &meshInstance);
void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance);
bool broadcastFilter(String &firstTransmission, EspnowMeshBackend &meshInstance);
/* Create the mesh node object */
EspnowMeshBackend espnowNode = EspnowMeshBackend(manageRequest, manageResponse, networkFilter, broadcastFilter, FPSTR(exampleWiFiPassword), espnowEncryptedConnectionKey, espnowHashKey, FPSTR(exampleMeshName), TypeCast::uint64ToString(ESP.getChipId()), true);
/**
Callback for when other nodes send you a request
@param request The request string received from another node in the mesh
@param meshInstance The MeshBackendBase instance that called the function.
@return The string to send back to the other node. For ESP-NOW, return an empy string ("") if no response should be sent.
*/
String manageRequest(const String &request, MeshBackendBase &meshInstance) {
// To get the actual class of the polymorphic meshInstance, do as follows (meshBackendCast replaces dynamic_cast since RTTI is disabled)
if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast<EspnowMeshBackend *>(&meshInstance)) {
String transmissionEncrypted = espnowInstance->receivedEncryptedTransmission() ? F(", Encrypted transmission") : F(", Unencrypted transmission");
Serial.print(String(F("ESP-NOW (")) + espnowInstance->getSenderMac() + transmissionEncrypted + F("): "));
} else if (TcpIpMeshBackend *tcpIpInstance = TypeCast::meshBackendCast<TcpIpMeshBackend *>(&meshInstance)) {
(void)tcpIpInstance; // This is useful to remove a "unused parameter" compiler warning. Does nothing else.
Serial.print(F("TCP/IP: "));
} else {
Serial.print(F("UNKNOWN!: "));
}
/* Print out received message */
// Only show first 100 characters because printing a large String takes a lot of time, which is a bad thing for a callback function.
// If you need to print the whole String it is better to store it and print it in the loop() later.
// Note that request.substring will not work as expected if the String contains null values as data.
Serial.print(F("Request received: "));
if (request.charAt(0) == 0) {
Serial.println(request); // substring will not work for multiStrings.
} else {
Serial.println(request.substring(0, 100));
}
/* return a string to send back */
return (String(F("Hello world response #")) + String(responseNumber++) + F(" from ") + meshInstance.getMeshName() + meshInstance.getNodeID() + F(" with AP MAC ") + WiFi.softAPmacAddress() + String('.'));
}
/**
Callback for when you get a response from other nodes
@param response The response string received from another node in the mesh
@param meshInstance The MeshBackendBase instance that called the function.
@return The status code resulting from the response, as an int
*/
TransmissionStatusType manageResponse(const String &response, MeshBackendBase &meshInstance) {
TransmissionStatusType statusCode = TransmissionStatusType::TRANSMISSION_COMPLETE;
// To get the actual class of the polymorphic meshInstance, do as follows (meshBackendCast replaces dynamic_cast since RTTI is disabled)
if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast<EspnowMeshBackend *>(&meshInstance)) {
String transmissionEncrypted = espnowInstance->receivedEncryptedTransmission() ? F(", Encrypted transmission") : F(", Unencrypted transmission");
Serial.print(String(F("ESP-NOW (")) + espnowInstance->getSenderMac() + transmissionEncrypted + F("): "));
} else if (TcpIpMeshBackend *tcpIpInstance = TypeCast::meshBackendCast<TcpIpMeshBackend *>(&meshInstance)) {
Serial.print(F("TCP/IP: "));
// Getting the sent message like this will work as long as ONLY(!) TCP/IP is used.
// With TCP/IP the response will follow immediately after the request, so the stored message will not have changed.
// With ESP-NOW there is no guarantee when or if a response will show up, it can happen before or after the stored message is changed.
// So for ESP-NOW, adding unique identifiers in the response and request is required to associate a response with a request.
Serial.print(F("Request sent: "));
Serial.println(tcpIpInstance->getCurrentMessage().substring(0, 100));
} else {
Serial.print(F("UNKNOWN!: "));
}
/* Print out received message */
// Only show first 100 characters because printing a large String takes a lot of time, which is a bad thing for a callback function.
// If you need to print the whole String it is better to store it and print it in the loop() later.
// Note that response.substring will not work as expected if the String contains null values as data.
Serial.print(F("Response received: "));
Serial.println(response.substring(0, 100));
return statusCode;
}
/**
Callback used to decide which networks to connect to once a WiFi scan has been completed.
@param numberOfNetworks The number of networks found in the WiFi scan.
@param meshInstance The MeshBackendBase instance that called the function.
*/
void networkFilter(int numberOfNetworks, MeshBackendBase &meshInstance) {
// Note that the network index of a given node may change whenever a new scan is done.
for (int networkIndex = 0; networkIndex < numberOfNetworks; ++networkIndex) {
String currentSSID = WiFi.SSID(networkIndex);
int meshNameIndex = currentSSID.indexOf(meshInstance.getMeshName());
/* Connect to any _suitable_ APs which contain meshInstance.getMeshName() */
if (meshNameIndex >= 0) {
uint64_t targetNodeID = TypeCast::stringToUint64(currentSSID.substring(meshNameIndex + meshInstance.getMeshName().length()));
if (targetNodeID < TypeCast::stringToUint64(meshInstance.getNodeID())) {
if (EspnowMeshBackend *espnowInstance = TypeCast::meshBackendCast<EspnowMeshBackend *>(&meshInstance)) {
espnowInstance->connectionQueue().emplace_back(networkIndex);
} else if (TcpIpMeshBackend *tcpIpInstance = TypeCast::meshBackendCast<TcpIpMeshBackend *>(&meshInstance)) {
tcpIpInstance->connectionQueue().emplace_back(networkIndex);
} else {
Serial.println(F("Invalid mesh backend!"));
}
}
}
}
}
/**
Callback used to decide which broadcast messages to accept. Only called for the first transmission in each broadcast.
If true is returned from this callback, the first broadcast transmission is saved until the entire broadcast message has been received.
The complete broadcast message will then be sent to the requestHandler (manageRequest in this example).
If false is returned from this callback, the broadcast message is discarded.
Note that the BroadcastFilter may be called multiple times for messages that are discarded in this way, but is only called once for accepted messages.
@param firstTransmission The first transmission of the broadcast. Modifications to this String are passed on to the broadcast message.
@param meshInstance The EspnowMeshBackend instance that called the function.
@return True if the broadcast should be accepted. False otherwise.
*/
bool broadcastFilter(String &firstTransmission, EspnowMeshBackend &meshInstance) {
// This example broadcastFilter will accept a transmission if it contains the broadcastMetadataDelimiter
// and as metaData either no targetMeshName or a targetMeshName that matches the MeshName of meshInstance.
int32_t metadataEndIndex = firstTransmission.indexOf(broadcastMetadataDelimiter);
if (metadataEndIndex == -1) {
return false; // broadcastMetadataDelimiter not found
}
String targetMeshName = firstTransmission.substring(0, metadataEndIndex);
if (!targetMeshName.isEmpty() && meshInstance.getMeshName() != targetMeshName) {
return false; // Broadcast is for another mesh network
} else {
// Remove metadata from message and mark as accepted broadcast.
// Note that when you modify firstTransmission it is best to avoid using substring or other String methods that rely on null values for String length determination.
// Otherwise your broadcasts cannot include null values in the message bytes.
firstTransmission.remove(0, metadataEndIndex + 1);
return true;
}
}
/**
Once passed to the setTransmissionOutcomesUpdateHook method of the ESP-NOW backend,
this function will be called after each update of the latestTransmissionOutcomes vector during attemptTransmission.
(which happens after each individual transmission has finished)
Example use cases is modifying getMessage() between transmissions, or aborting attemptTransmission before all nodes in the connectionQueue have been contacted.
@param meshInstance The MeshBackendBase instance that called the function.
@return True if attemptTransmission should continue with the next entry in the connectionQueue. False if attemptTransmission should stop.
*/
bool exampleTransmissionOutcomesUpdateHook(MeshBackendBase &meshInstance) {
// Currently this is exactly the same as the default hook, but you can modify it to alter the behaviour of attemptTransmission.
(void)meshInstance; // This is useful to remove a "unused parameter" compiler warning. Does nothing else.
return true;
}
/**
Once passed to the setResponseTransmittedHook method of the ESP-NOW backend,
this function will be called after each attempted ESP-NOW response transmission.
In case of a successful response transmission, this happens just before the response is removed from the waiting list.
Only the hook of the EspnowMeshBackend instance that is getEspnowRequestManager() will be called.
@param transmissionSuccessful True if the response was transmitted successfully. False otherwise.
@param response The sent response.
@param recipientMac The MAC address the response was sent to.
@param responseIndex The index of the response in the waiting list.
@param meshInstance The EspnowMeshBackend instance that called the function.
@return True if the response transmission process should continue with the next response in the waiting list.
False if the response transmission process should stop once processing of the just sent response is complete.
*/
bool exampleResponseTransmittedHook(bool transmissionSuccessful, const String &response, const uint8_t *recipientMac, uint32_t responseIndex, EspnowMeshBackend &meshInstance) {
// Currently this is exactly the same as the default hook, but you can modify it to alter the behaviour of sendEspnowResponses.
(void)transmissionSuccessful; // This is useful to remove a "unused parameter" compiler warning. Does nothing else.
(void)response;
(void)recipientMac;
(void)responseIndex;
(void)meshInstance;
return true;
}
void setup() {
// Prevents the flash memory from being worn out, see: https://github.com/esp8266/Arduino/issues/1054 .
// This will however delay node WiFi start-up by about 700 ms. The delay is 900 ms if we otherwise would have stored the WiFi network we want to connect to.
WiFi.persistent(false);
Serial.begin(115200);
Serial.println();
Serial.println();
Serial.println(F("Note that this library can use static IP:s for the nodes with the TCP/IP backend to speed up connection times.\n"
"Use the setStaticIP method to enable this.\n"
"Ensure that nodes connecting to the same AP have distinct static IP:s.\n"
"Also, remember to change the default mesh network password and ESP-NOW keys!\n\n"));
Serial.println(F("Setting up mesh node..."));
/* Initialise the mesh node */
espnowNode.begin();
// Note: This changes the Kok for all EspnowMeshBackend instances on this ESP8266.
// Encrypted connections added before the Kok change will retain their old Kok.
// Both Kok and encrypted connection key must match in an encrypted connection pair for encrypted communication to be possible.
// Otherwise the transmissions will never reach the recipient, even though acks are received by the sender.
EspnowMeshBackend::setEspnowEncryptionKok(espnowEncryptionKok);
espnowNode.setEspnowEncryptedConnectionKey(espnowEncryptedConnectionKey);
// Makes it possible to find the node through scans, makes it possible to recover from an encrypted connection where only the other node is encrypted, and also makes it possible to receive broadcast transmissions.
// Note that only one AP can be active at a time in total, and this will always be the one which was last activated.
// Thus the AP is shared by all backends.
espnowNode.activateAP();
// Storing our message in the EspnowMeshBackend instance is not required, but can be useful for organizing code, especially when using many EspnowMeshBackend instances.
// Note that calling the multi-recipient versions of espnowNode.attemptTransmission and espnowNode.attemptAutoEncryptingTransmission will replace the stored message with whatever message is transmitted.
// Also note that the maximum allowed number of ASCII characters in a ESP-NOW message is given by EspnowMeshBackend::getMaxMessageLength().
espnowNode.setMessage(String(F("Hello world request #")) + String(requestNumber) + F(" from ") + espnowNode.getMeshName() + espnowNode.getNodeID() + String('.'));
espnowNode.setTransmissionOutcomesUpdateHook(exampleTransmissionOutcomesUpdateHook);
espnowNode.setResponseTransmittedHook(exampleResponseTransmittedHook);
// In addition to using encrypted ESP-NOW connections the framework can also send automatically encrypted messages (AEAD) over both encrypted and unencrypted connections.
// Using AEAD will only encrypt the message content, not the transmission metadata.
// The AEAD encryption does not require any pairing, and is thus faster for single messages than establishing a new encrypted connection before transfer.
// AEAD encryption also works with ESP-NOW broadcasts and supports an unlimited number of nodes, which is not true for encrypted connections.
// Encrypted ESP-NOW connections do however come with built in replay attack protection, which is not provided by the framework when using AEAD encryption,
// and allow EspnowProtocolInterpreter::aeadMetadataSize extra message bytes per transmission.
// Transmissions via encrypted connections are also slightly faster than via AEAD once a connection has been established.
//
// Uncomment the lines below to use automatic AEAD encryption/decryption of messages sent/received.
// All nodes this node wishes to communicate with must then also use encrypted messages with the same getEspnowMessageEncryptionKey(), or messages will not be accepted.
// Note that using AEAD encrypted messages will reduce the number of message bytes that can be transmitted.
//espnowNode.setEspnowMessageEncryptionKey(F("ChangeThisKeySeed_TODO")); // The message encryption key should always be set manually. Otherwise a default key (all zeroes) is used.
//espnowNode.setUseEncryptedMessages(true);
}
int32_t timeOfLastScan = -10000;
void loop() {
// The performEspnowMaintenance() method performs all the background operations for the EspnowMeshBackend.
// It is recommended to place it in the beginning of the loop(), unless there is a need to put it elsewhere.
// Among other things, the method cleans up old Espnow log entries (freeing up RAM) and sends the responses you provide to Espnow requests.
// Note that depending on the amount of responses to send and their length, this method can take tens or even hundreds of milliseconds to complete.
// More intense transmission activity and less frequent calls to performEspnowMaintenance will likely cause the method to take longer to complete, so plan accordingly.
//Should not be used inside responseHandler, requestHandler, networkFilter or broadcastFilter callbacks since performEspnowMaintenance() can alter the ESP-NOW state.
EspnowMeshBackend::performEspnowMaintenance();
if (millis() - timeOfLastScan > 10000) { // Give other nodes some time to connect between data transfers.
Serial.println(F("\nPerforming unencrypted ESP-NOW transmissions."));
uint32_t startTime = millis();
espnowNode.attemptTransmission(espnowNode.getMessage());
Serial.println(String(F("Scan and ")) + String(espnowNode.latestTransmissionOutcomes().size()) + F(" transmissions done in ") + String(millis() - startTime) + F(" ms."));
timeOfLastScan = millis();
// Wait for response. espnowDelay continuously calls performEspnowMaintenance() so we will respond to ESP-NOW request while waiting.
// Should not be used inside responseHandler, requestHandler, networkFilter or broadcastFilter callbacks since performEspnowMaintenance() can alter the ESP-NOW state.
espnowDelay(100);
// One way to check how attemptTransmission worked out
if (espnowNode.latestTransmissionSuccessful()) {
Serial.println(F("Transmission successful."));
}
// Another way to check how attemptTransmission worked out
if (espnowNode.latestTransmissionOutcomes().empty()) {
Serial.println(F("No mesh AP found."));
} else {
for (TransmissionOutcome &transmissionOutcome : espnowNode.latestTransmissionOutcomes()) {
if (transmissionOutcome.transmissionStatus() == TransmissionStatusType::TRANSMISSION_FAILED) {
Serial.println(String(F("Transmission failed to mesh AP ")) + transmissionOutcome.SSID());
} else if (transmissionOutcome.transmissionStatus() == TransmissionStatusType::CONNECTION_FAILED) {
Serial.println(String(F("Connection failed to mesh AP ")) + transmissionOutcome.SSID());
} else if (transmissionOutcome.transmissionStatus() == TransmissionStatusType::TRANSMISSION_COMPLETE) {
// No need to do anything, transmission was successful.
} else {
Serial.println(String(F("Invalid transmission status for ")) + transmissionOutcome.SSID() + String('!'));
assert(F("Invalid transmission status returned from responseHandler!") && false);
}
}
Serial.println(F("\nPerforming ESP-NOW broadcast."));
startTime = millis();
// Remove espnowNode.getMeshName() from the broadcastMetadata below to broadcast to all ESP-NOW nodes regardless of MeshName.
// Note that data that comes before broadcastMetadataDelimiter should not contain any broadcastMetadataDelimiter characters,
// otherwise the broadcastFilter function used in this example file will not work.
String broadcastMetadata = espnowNode.getMeshName() + String(broadcastMetadataDelimiter);
String broadcastMessage = String(F("Broadcast #")) + String(requestNumber) + F(" from ") + espnowNode.getMeshName() + espnowNode.getNodeID() + String('.');
espnowNode.broadcast(broadcastMetadata + broadcastMessage);
Serial.println(String(F("Broadcast to all mesh nodes done in ")) + String(millis() - startTime) + F(" ms."));
espnowDelay(100); // Wait for responses (broadcasts can receive an unlimited number of responses, other transmissions can only receive one response).
// If you have a data array containing null values it is possible to transmit the raw data by making the array into a multiString as shown below.
// You can use String::c_str() or String::begin() to retreive the data array later.
// Note that certain String methods such as String::substring use null values to determine String length, which means they will not work as normal with multiStrings.
uint8_t dataArray[] = {0, '\'', 0, '\'', ' ', '(', 'n', 'u', 'l', 'l', ')', ' ', 'v', 'a', 'l', 'u', 'e'};
String espnowMessage = TypeCast::uint8ArrayToMultiString(dataArray, sizeof dataArray) + F(" from ") + espnowNode.getMeshName() + espnowNode.getNodeID() + String('.');
Serial.println(String(F("\nTransmitting: ")) + espnowMessage);
espnowNode.attemptTransmission(espnowMessage, false);
espnowDelay(100); // Wait for response.
Serial.println(F("\nPerforming encrypted ESP-NOW transmissions."));
uint8_t targetBSSID[6] {0};
// We can create encrypted connections to individual nodes so that all ESP-NOW communication with the node will be encrypted.
if (espnowNode.constConnectionQueue()[0].getBSSID(targetBSSID) && espnowNode.requestEncryptedConnection(targetBSSID) == EncryptedConnectionStatus::CONNECTION_ESTABLISHED) {
// The WiFi scan will detect the AP MAC, but this will automatically be converted to the encrypted STA MAC by the framework.
String peerMac = TypeCast::macToString(targetBSSID);
Serial.println(String(F("Encrypted ESP-NOW connection with ")) + peerMac + F(" established!"));
// Making a transmission now will cause messages to targetBSSID to be encrypted.
String espnowMessage = String(F("This message is encrypted only when received by node ")) + peerMac;
Serial.println(String(F("\nTransmitting: ")) + espnowMessage);
espnowNode.attemptTransmission(espnowMessage, false);
espnowDelay(100); // Wait for response.
// A connection can be serialized and stored for later use.
// Note that this saves the current state only, so if encrypted communication between the nodes happen after this, the stored state is invalid.
String serializedEncryptedConnection = EspnowMeshBackend::serializeEncryptedConnection(targetBSSID);
Serial.println();
// We can remove an encrypted connection like so.
espnowNode.removeEncryptedConnection(targetBSSID);
// Note that the peer will still be encrypted, so although we can send unencrypted messages to the peer, we cannot read the encrypted responses it sends back.
espnowMessage = String(F("This message is no longer encrypted when received by node ")) + peerMac;
Serial.println(String(F("\nTransmitting: ")) + espnowMessage);
espnowNode.attemptTransmission(espnowMessage, false);
espnowDelay(100); // Wait for response.
Serial.println(F("Cannot read the encrypted response..."));
// Let's re-add our stored connection so we can communicate properly with targetBSSID again!
espnowNode.addEncryptedConnection(serializedEncryptedConnection);
espnowMessage = String(F("This message is once again encrypted when received by node ")) + peerMac;
Serial.println(String(F("\nTransmitting: ")) + espnowMessage);
espnowNode.attemptTransmission(espnowMessage, false);
espnowDelay(100); // Wait for response.
Serial.println();
// If we want to remove the encrypted connection on both nodes, we can do it like this.
EncryptedConnectionRemovalOutcome removalOutcome = espnowNode.requestEncryptedConnectionRemoval(targetBSSID);
if (removalOutcome == EncryptedConnectionRemovalOutcome::REMOVAL_SUCCEEDED) {
Serial.println(peerMac + F(" is no longer encrypted!"));
espnowMessage = String(F("This message is only received by node ")) + peerMac + F(". Transmitting in this way will not change the transmission state of the sender.");
Serial.println(String(F("Transmitting: ")) + espnowMessage);
espnowNode.attemptTransmission(espnowMessage, EspnowNetworkInfo(targetBSSID));
espnowDelay(100); // Wait for response.
Serial.println();
// Of course, we can also just create a temporary encrypted connection that will remove itself once its duration has passed.
if (espnowNode.requestTemporaryEncryptedConnection(targetBSSID, 1000) == EncryptedConnectionStatus::CONNECTION_ESTABLISHED) {
espnowDelay(42);
uint32_t remainingDuration = 0;
EspnowMeshBackend::getConnectionInfo(targetBSSID, &remainingDuration);
espnowMessage = String(F("Messages this node sends to ")) + peerMac + F(" will be encrypted for ") + String(remainingDuration) + F(" ms more.");
Serial.println(String(F("\nTransmitting: ")) + espnowMessage);
espnowNode.attemptTransmission(espnowMessage, false);
EspnowMeshBackend::getConnectionInfo(targetBSSID, &remainingDuration);
espnowDelay(remainingDuration + 100);
espnowMessage = String(F("Due to encrypted connection expiration, this message is no longer encrypted when received by node ")) + peerMac;
Serial.println(String(F("\nTransmitting: ")) + espnowMessage);
espnowNode.attemptTransmission(espnowMessage, false);
espnowDelay(100); // Wait for response.
}
// Or if we prefer we can just let the library automatically create brief encrypted connections which are long enough to transmit an encrypted message.
// Note that encrypted responses will not be received, unless there already was an encrypted connection established with the peer before attemptAutoEncryptingTransmission was called.
// This can be remedied via the requestPermanentConnections argument, though it must be noted that the maximum number of encrypted connections supported at a time is 6.
espnowMessage = F("This message is always encrypted, regardless of receiver.");
Serial.println(String(F("\nTransmitting: ")) + espnowMessage);
espnowNode.attemptAutoEncryptingTransmission(espnowMessage);
espnowDelay(100); // Wait for response.
} else {
Serial.println(String(F("Ooops! Encrypted connection removal failed. Status: ")) + String(static_cast<int>(removalOutcome)));
}
// Finally, should you ever want to stop other parties from sending unencrypted messages to the node
// setAcceptsUnencryptedRequests(false);
// can be used for this. It applies to both encrypted connection requests and regular transmissions.
Serial.println(F("\n##############################################################################################"));
}
// Our last request was sent to all nodes found, so time to create a new request.
espnowNode.setMessage(String(F("Hello world request #")) + String(++requestNumber) + F(" from ")
+ espnowNode.getMeshName() + espnowNode.getNodeID() + String('.'));
}
Serial.println();
}
}
| 64.197802
| 258
| 0.737932
|
932aad0da16876bb2a1aa4c8556337059bdf8858
| 6,956
|
ino
|
Arduino
|
arduino/keyboard_extensions.ino
|
th0m4s/keyboard_extensions
|
41f4d3e0eb7e0198861aa66dd0cf819af9c67281
|
[
"MIT"
] | null | null | null |
arduino/keyboard_extensions.ino
|
th0m4s/keyboard_extensions
|
41f4d3e0eb7e0198861aa66dd0cf819af9c67281
|
[
"MIT"
] | null | null | null |
arduino/keyboard_extensions.ino
|
th0m4s/keyboard_extensions
|
41f4d3e0eb7e0198861aa66dd0cf819af9c67281
|
[
"MIT"
] | null | null | null |
#include <EEPROM.h>
#define TYPE_PING 1
#define TYPE_NORMAL 2
#define PING_TIME 500
#define CMD_REQ_SETTINGS 1
#define CMD_RESP_SETTINGS 2
#define CMD_SET_KEY_SETTING 3
#define CMD_REQ_VOICE 4
// resp_voice is also used when updates are received from discord
#define CMD_RESP_VOICE 5
#define CMD_KEY 6
#define CMD_SPECIAL 7
#define CMD_SET_OTHER_SETTING 8
#define VOICE_MUTE 0
#define VOICE_DEAF 1
#define VOICE_ALL 2
#define SETTING_DEBOUNCE 0
#define SETTING_TRIGGER 1
#define TRIGGER_UP 0
#define TRIGGER_DOWN 1
const byte numKeys = 7;
const byte pins[numKeys] = {2, 3, 4, 5, 6, 7, 8};
bool pressed[numKeys];
byte debounces[numKeys];
const byte numSpecial = 2;
const byte specialKeys[numSpecial] = {5, 6};
bool isSpecial[numKeys];
const byte specialLedPins[numSpecial] = {9, 10};
byte debounceCount = 12;
byte specialTrigger = TRIGGER_DOWN;
byte keyModes[numKeys];
byte keyValues[numKeys];
void setup() {
Serial.begin(19200);
for(byte i = 0; i < numKeys; i++) {
byte pin = pins[i];
pinMode(pin, INPUT_PULLUP);
pressed[i] = false;
debounces[i] = 0;
isSpecial[i] = false;
}
for(byte i = 0; i < numSpecial; i++) {
pinMode(specialLedPins[i], OUTPUT);
isSpecial[specialKeys[i]] = true;
}
pinMode(LED_BUILTIN, OUTPUT);
loadSave();
}
byte messageType = 0;
byte messageLength = 0;
byte message[255];
byte msgPosition = 0;
long LastTickReceived = -2*PING_TIME;
bool connected = false;
bool discordMute = false;
bool discordDeaf = false;
void loop() {
long now = millis();
if(connected && now - LastTickReceived > 2*PING_TIME) {
connected = false;
digitalWrite(LED_BUILTIN, LOW);
discordMute = false;
discordDeaf = false;
updateSpecialKeys();
} else if(!connected && now - LastTickReceived < 2* PING_TIME) {
connected = true;
digitalWrite(LED_BUILTIN, HIGH);
sendCommand(TYPE_NORMAL, 2, new byte[2] {CMD_REQ_VOICE, VOICE_ALL});
}
for(byte i = 0; i < numKeys; i++) {
byte pin = pins[i];
bool current = pressed[i];
bool newState = !digitalRead(pin);
if(current != newState) {
if(debounces[i]++ >= debounceCount) {
pressed[i] = newState;
if(isSpecial[i]) {
if(specialTrigger == newState)
sendCommand(TYPE_NORMAL, 2, new byte[3] {CMD_SPECIAL, i});
} else {
sendCommand(TYPE_NORMAL, 3, new byte[3] {CMD_KEY, i, newState});
}
}
} else {
debounces[i] = 0;
}
}
if(Serial.available() > 0) {
if(messageType == 0) {
messageType = Serial.read();
}
if(Serial.available() > 0) {
if(messageLength == 0) {
messageLength = Serial.read() + 1;
msgPosition = 0;
}
while(Serial.available() > 0 && msgPosition < messageLength-1) {
message[msgPosition++] = Serial.read();
}
}
}
if(messageLength > 0 && messageLength-1 == msgPosition) {
processCommand(messageType, messageLength, message);
messageType = 0;
messageLength = 0;
msgPosition = 0;
}
}
void updateSpecialKeys() {
for(byte i = 0; i < numSpecial; i++) {
byte key = specialKeys[i];
byte specialPin = specialLedPins[i];
if(keyModes[key] == 1) {
if(keyValues[key] == 0) {
digitalWrite(specialPin, discordMute);
} else if(keyValues[key] == 1) {
digitalWrite(specialPin, discordDeaf);
} else digitalWrite(specialPin, LOW);
} else {
digitalWrite(specialPin, LOW);
}
}
}
void processCommand(byte type, byte length, byte message[]) {
if(type == TYPE_PING) {
LastTickReceived = millis();
sendCommand(TYPE_PING, 0, new byte[0]);
} else if(type == TYPE_NORMAL && length >= 1) {
byte command = message[0];
if(command == CMD_REQ_SETTINGS) {
byte respLength = 1 + 2 + numKeys*2 + numSpecial + 2;
byte settings[respLength];
settings[0] = CMD_RESP_SETTINGS;
settings[1] = numKeys;
settings[2] = numSpecial;
for(byte i = 0; i < numSpecial; i++) {
settings[3 + i] = specialKeys[i];
}
for(byte i = 0; i < numKeys; i++) {
settings[3 + numSpecial + i*2] = keyModes[i];
settings[4 + numSpecial + i*2] = keyValues[i];
}
byte settingBasePos = 3 + numSpecial + numKeys * 2;
settings[settingBasePos + SETTING_DEBOUNCE] = debounceCount;
settings[settingBasePos + SETTING_TRIGGER] = specialTrigger;
sendCommand(TYPE_NORMAL, respLength, settings);
} else if(command == CMD_SET_KEY_SETTING) {
byte key = message[1];
byte setting = message[2];
byte data = message[3];
if(setting == 0) { // key mode
keyModes[key] = data;
} else if(setting == 1) { // key val
keyValues[key] = data;
}
EEPROM.write(2 + setting + key*2, data);
} else if(command == CMD_RESP_VOICE) {
byte voiceType = message[1];
if(voiceType == VOICE_MUTE) {
discordMute = message[2] != 0;
} else if(voiceType == VOICE_DEAF) {
discordDeaf = message[2] != 0;
} else if(voiceType == VOICE_ALL) {
discordMute = message[2] != 0;
discordDeaf = message[3] != 0;
}
updateSpecialKeys();
} else if(command == CMD_SET_OTHER_SETTING) {
byte setting = message[1];
byte value = message[2];
if(setting == SETTING_DEBOUNCE) {
debounceCount = value;
} else if(setting == SETTING_TRIGGER) {
specialTrigger = value;
}
writeSave();
}
}
}
void sendCommand(byte type, byte length, byte message[]) {
Serial.write(type);
Serial.write(length);
Serial.write(message, length);
}
void loadDefaults(bool save = true) {
for(byte i = 0; i < numKeys; i++) {
keyModes[i] = 0;
keyValues[i] = 18+i;
}
debounceCount = 12;
specialTrigger = TRIGGER_DOWN;
if(save) writeSave();
}
void _loadSaveV1() {
byte _numKeys = EEPROM.read(1);
bool newSave = _numKeys != numKeys;
if(newSave) {
loadDefaults(false);
}
for(byte i = 0; i < numKeys; i++) {
keyModes[i] = EEPROM.read(2 + i*2);
keyValues[i] = EEPROM.read(3 + i*2);
}
}
void loadSave() {
byte saveVersion = EEPROM.read(0);
if(saveVersion == 1) {
_loadSaveV1();
writeSave(); // rewrite save because it is not last version
} else if(saveVersion == 2) {
_loadSaveV1(); // v2 = v1 + new settings (debounce + special trigger)
byte basePos = 2 + numKeys * 2;
debounceCount = EEPROM.read(basePos + SETTING_DEBOUNCE);
specialTrigger = EEPROM.read(basePos + SETTING_TRIGGER);
} else {
loadDefaults();
}
}
void writeSave() {
EEPROM.write(0, 2); // index 0: save version (here its 2)
EEPROM.write(1, numKeys);
for(byte i = 0; i < numKeys; i++) {
EEPROM.write(2 + i*2, keyModes[i]);
EEPROM.write(3 + i*2, keyValues[i]);
}
byte basePos = 2 + numKeys*2;
EEPROM.write(basePos + SETTING_DEBOUNCE, debounceCount);
EEPROM.write(basePos + SETTING_TRIGGER, specialTrigger);
}
| 25.294545
| 74
| 0.620759
|
b9b99092742a6f42b5f51b062af07348d06742e1
| 4,700
|
ino
|
Arduino
|
scatdat_v2/scatdat_v2.ino
|
MattFerraro/scatdat
|
6c5aa05ed3a2e83de4effff173e5d64924cc5b51
|
[
"Apache-2.0"
] | 2
|
2016-03-08T03:00:44.000Z
|
2018-02-09T22:19:15.000Z
|
scatdat_v2/scatdat_v2.ino
|
MattFerraro/scatdat
|
6c5aa05ed3a2e83de4effff173e5d64924cc5b51
|
[
"Apache-2.0"
] | null | null | null |
scatdat_v2/scatdat_v2.ino
|
MattFerraro/scatdat
|
6c5aa05ed3a2e83de4effff173e5d64924cc5b51
|
[
"Apache-2.0"
] | 2
|
2016-02-26T03:42:28.000Z
|
2021-03-21T18:46:30.000Z
|
// Code for Scatdat door sensors with power saving shield installed.
// Arduino ESP8266 Wifi library
#include <ESP8266WiFi.h>
//////////////////////////
// Constant Definitions //
//////////////////////////
#define CLOSED 0
#define OPEN 1
#define VOLTAGE_DIVIDER_CONST 5.7
//////////////////////
// WiFi Definitions //
//////////////////////
const char WIFI_SSID[] = "exoplanet"; //planetoids
const char WIFI_PSK[] = "kEf8Qr28vNSv"; //62D4A6ED
const char STALL_ID[] = "Floor2Mens1";
/////////////////////////////
// Remote Site Definitions //
/////////////////////////////
const char http_site[] = "scatdat.earth.planet.com";
const int http_port = 5000;
/////////////////////
// Pin Definitions //
/////////////////////
const int LED_PIN = 5;
const int ANALOG_PIN = A0; // The only analog pin on the Thing
const int DOOR_SENSOR_PIN = 4; // Digital pin to be read
const int SLEEP_TIME_US = 3600000000; //sleep time between non door wakeups (in seconds), max is about 1 hr
//////////////////////
// Global Variables //
//////////////////////
WiFiClient client;
int doorState = OPEN;
int analogValue = 0;
int vbatt = 0;
//////////////////////////
// connectWiFi Function //
//////////////////////////
void connectWiFi() {
byte led_status = 0;
// Set WiFi mode to station (client)
WiFi.mode(WIFI_STA);
// Initiate connection with SSID and PSK
WiFi.begin(WIFI_SSID, WIFI_PSK);
// Blink LED while we wait for WiFi connection
while ( WiFi.status() != WL_CONNECTED ) {
digitalWrite(LED_PIN, led_status);
led_status ^= 0x01;
delay(100);
}
// Turn LED on when we are connected
digitalWrite(LED_PIN, LOW);
}
////////////////////////
// postEvent Function //
////////////////////////
// Perform an HTTP POST to a remote page
bool postEvent(int doorOpen,int battmV) {
char paramString[256];
Serial.println("Attempting to connect to");
sprintf(paramString, "%s:%i", http_site, http_port);
Serial.println(paramString);
// Attempt to make a connection to the remote server
if ( !client.connect(http_site, http_port) ) {
return false;
}
// Construct parameter string
sprintf(paramString, "POST /events?stall_id=%s&door_open=%i&batt_v=%i HTTP/1.1", STALL_ID, doorOpen, battmV);
// Make an HTTP GET request
client.println(paramString);
client.print("Host: ");
client.println(http_site);
client.println("Connection: close");
client.println();
return true;
}
///////////////////////////
// initHardware Function //
///////////////////////////
void initHardware(){
Serial.begin(230400);
// Set door sensor pin as input, no pull up needed because there is an external pull up
pinMode(DOOR_SENSOR_PIN, INPUT);
// Set led pin as output and turn it off
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
// Don't need to set ANALOG_PIN as input, that's all it can be.
}
//////////////////////////////
// calcBattVoltage Function //
//////////////////////////////
int calcBattmV(int analogValue){
// Input is the ADC, its 10 bit so 0-1023 for 1V FSR
// The power saver has a built in voltage divider
// R1 = 470000 R2 = 100000
// VOUT = R2/ (R1+R2) * VIN
float v_adc = 0;
float battmV = 0;
v_adc = (float) analogValue / 1023;
battmV = VOLTAGE_DIVIDER_CONST * v_adc * 1000;
return (int) battmV;
}
////////////////////
// setup Function //
////////////////////
byte led_status = 0;
void setup() {
Serial.begin(230400);
Serial.println("hello world!");
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
// for (int i = 0; i < 25; ++i)
// {
// Serial.println("in loop");
// Serial.println(i);
// digitalWrite(LED_PIN, led_status);
// led_status ^= 0x01;
// delay(500);
// }
// setup pins/serial comms
initHardware();
Serial.println("Done with init hardware!");
// connect to the newtwork
connectWiFi();
Serial.println("Done with connect wifi!");
// turn on LED
digitalWrite(LED_PIN, HIGH);
Serial.println("LED on!");
// Read door sensor state
doorState = digitalRead(DOOR_SENSOR_PIN);
Serial.println("Read door state!");
// get analog reading & calculate battery voltage
analogValue = analogRead(ANALOG_PIN);
Serial.println("got analog value!");
vbatt = calcBattmV(analogValue);
Serial.println("got vbatt!");
// Post the data
while (!postEvent(doorState,vbatt)) {
Serial.println("POST request failed");
}
// turn off LED
digitalWrite(LED_PIN,LOW);
Serial.println("LED off. Going to sleep");
// go into deep sleep mode
ESP.deepSleep(SLEEP_TIME_US, WAKE_RF_DEFAULT);
Serial.println("in deep sleep");
}
///////////////////
// loop Function //
///////////////////
void loop() {
// intentially left empty
}
| 26.111111
| 111
| 0.607872
|
866fc92c2786910d73dae2f7c302a838c915342b
| 8,684
|
ino
|
Arduino
|
ArduinoIDE/ESP8266/users-demo/bmp180/bmp180.ino
|
4refr0nt/iot-manager-demo
|
5ceed46ccf538e5bac9b92a03452eed21d27f74f
|
[
"MIT"
] | 69
|
2016-02-10T05:58:27.000Z
|
2022-02-23T09:46:02.000Z
|
ArduinoIDE/ESP8266/users-demo/bmp180/bmp180.ino
|
4refr0nt/iot-manager-demo
|
5ceed46ccf538e5bac9b92a03452eed21d27f74f
|
[
"MIT"
] | 36
|
2016-05-29T18:30:29.000Z
|
2021-11-02T18:02:01.000Z
|
ArduinoIDE/ESP8266/users-demo/bmp180/bmp180.ino
|
4refr0nt/iot-manager-demo
|
5ceed46ccf538e5bac9b92a03452eed21d27f74f
|
[
"MIT"
] | 38
|
2016-01-30T11:59:14.000Z
|
2022-02-15T17:46:06.000Z
|
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include <Adafruit_BMP085.h> // https://github.com/vieiraf/bmp085driver
Adafruit_BMP085 bmp;
String davlen;
String temp;
const char *ssid = "****"; // cannot be longer than 32 characters!
const char *pass = "*****"; // WiFi password
String prefix = "/IoTmanager"; // global prefix for all topics - must be some as mobile device
String deviceID = "dev04"; // thing ID - unique device id in our project
WiFiClient wclient;
// config for cloud mqtt broker by DNS hostname ( for example, cloudmqtt.com use: m20.cloudmqtt.com - EU, m11.cloudmqtt.com - USA )
String mqttServerName = "m20.cloudmqtt.com"; // for cloud broker - by hostname, from CloudMQTT account data
int mqttport = 11536; // default 1883, but CloudMQTT.com use other, for example: 13191, 23191 (SSL), 33191 (WebSockets) - use from CloudMQTT account data
String mqttuser = "*****"; // from CloudMQTT account data
String mqttpass = "*****"; // from CloudMQTT account data
PubSubClient client(wclient, mqttServerName, mqttport); // for cloud broker - by hostname
// config for local mqtt broker by IP address
//IPAddress server(192, 168, 1, 100); // for local broker - by address
//int mqttport = 1883; // default 1883
//String mqttuser = "test"; // from broker config
//String mqttpass = "test"; // from broker config
//PubSubClient client(wclient, server, mqttport); // for local broker - by address
String val;
String ids = "";
int newValue, newtime, oldtime, freeheap;
const int nWidgets = 2;
String sTopic [nWidgets];
String stat [nWidgets];
int pin [nWidgets];
String thing_config[nWidgets];
void FreeHEAP() {
if ( ESP.getFreeHeap() < freeheap ) {
if ( ( freeheap != 100000) ) {
Serial.print("Memory leak detected! old free heap = ");
Serial.print(freeheap);
Serial.print(", new value = ");
Serial.println(ESP.getFreeHeap());
}
freeheap = ESP.getFreeHeap();
}
}
String setStatus ( String s ) {
return "{\"status\":\"" + s + "\"}";
}
String setStatus ( int s ) {
return "{\"status\":\"" + String(s) + "\"}";
}
void initVar() {
sTopic[0] = prefix + "/" + deviceID + "/BMP180_temp";
stat [0] = setStatus (0);
sTopic[1] = prefix + "/" + deviceID + "/BMP180_davlen";
stat [1] = setStatus (1);
StaticJsonBuffer<8096> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
JsonObject& cfg = jsonBuffer.createObject();
root["id"] = 0;
root["page"] = "BMP180";
root["widget"] = "display-value";
root["class1"] = "item no-border"; // class for 1st div
root["style1"] = ""; // style for 1st div
root["descr"] = "Температура"; // text for description
root["class2"] = "balanced"; // class for description from Widgets Guide - Color classes
root["style2"] = "font-size:20px;float:left;padding-top:10px;font-weight:bold;"; // style for description
root["topic"] = sTopic[0];
root["class3"] = ""; // class for 3 div - SVG
root["style3"] = "float:right;"; // style for 3 div - SVG
root["height"] = "40"; // SVG height without "px"
root["color"] = "#52FF00"; // color for active segments
root["inactive_color"] = "#414141"; // color for inactive segments
root["digits_count"] = 6; // how many digits
root.printTo(thing_config[0]);
/////
root["id"] = 1;
root["page"] = "BMP180";
root["widget"] = "display-value";
root["class1"] = "item no-border"; // class for 1st div
root["style1"] = ""; // style for 1st div
root["descr"] = "Давление (мм.рт.ст)"; // text for description
root["class2"] = "balanced"; // class for description from Widgets Guide - Color classes
root["style2"] = "font-size:20px;float:left;padding-top:10px;font-weight:bold;"; // style for description
root["topic"] = sTopic[1];
root["class3"] = ""; // class for 3 div - SVG
root["style3"] = "float:right;"; // style for 3 div - SVG
root["height"] = "40"; // SVG height without "px"
root["color"] = "#52FF00"; // color for active segments
root["inactive_color"] = "#414141"; // color for inactive segments
root["digits_count"] = 3; // how many digits
root.printTo(thing_config[1]);
//////////////////////////////////////
}
void pubStatus(String t, String payload) {
if (client.publish(t + "/status", payload)) {
Serial.println("Publish new status for " + t + ", value: " + payload);
} else {
Serial.println("Publish new status for " + t + " FAIL!");
}
FreeHEAP();
}
void pubConfig() {
bool success;
success = client.publish(MQTT::Publish(prefix, deviceID).set_qos(1));
if (success) {
delay(500);
for (int i = 0; i < nWidgets; i = i + 1) {
success = client.publish(MQTT::Publish(prefix + "/" + deviceID + "/config", thing_config[i]).set_qos(1));
if (success) {
Serial.println("Publish config: Success (" + thing_config[i] + ")");
} else {
Serial.println("Publish config FAIL! (" + thing_config[i] + ")");
}
delay(150);
}
}
if (success) {
Serial.println("Publish config: Success");
} else {
Serial.println("Publish config: FAIL");
}
for (int i = 0; i < nWidgets; i = i + 1) {
pubStatus(sTopic[i], stat[i]);
delay(100);
}
}
void callback(const MQTT::Publish& sub) {
Serial.print("Get data from subscribed topic ");
Serial.print(sub.topic());
Serial.print(" => ");
Serial.println(sub.payload_string());
if ( sub.payload_string() == "HELLO" ) { // handshaking
pubConfig();
}
}
void setup() {
Wire.pins(0, 2);
if (!bmp.begin()) {
Serial.println("Could not find a valid BMP085 sensor, check wiring!");
while (1) {}
}
delay(50);
temp = String(bmp.readTemperature());
davlen= String(bmp.readPressure()/133);
stat[0] = setStatus( temp );
stat[1] = setStatus( davlen );
WiFi.mode(WIFI_STA);
initVar();
oldtime = 0;
Serial.begin(115200);
delay(10);
Serial.println();
Serial.println();
Serial.println("MQTT client started.");
FreeHEAP();
freeheap = 100000;
WiFi.disconnect();
WiFi.printDiag(Serial);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
Serial.print("Connecting via WiFi to ");
Serial.print(ssid);
Serial.println("...");
WiFi.begin(ssid, pass);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
return;
}
Serial.println("");
Serial.println("WiFi connect: Success");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
Serial.println("Connecting to MQTT server ...");
bool success;
if (mqttuser.length() > 0) {
success = client.connect( MQTT::Connect( deviceID ).set_auth(mqttuser, mqttpass) );
} else {
success = client.connect( deviceID );
}
if (success) {
client.set_callback(callback);
Serial.println("Connect to MQTT server: Success");
client.subscribe(prefix); // for receiving HELLO messages and handshaking
pubConfig();
} else {
Serial.println("Connect to MQTT server: FAIL");
delay(1000);
}
}
if (client.connected()) {
newtime = millis();
if (newtime - oldtime > 10000) { // publish data every 100 sec
temp = String(bmp.readTemperature());
davlen= String(bmp.readPressure()/133);
stat[0] = setStatus( temp );
stat[1] = setStatus( davlen );
for (int i = 0; i < nWidgets; i = i + 1) {
pubStatus(sTopic[i], stat[i]);
delay(100);
}
oldtime = newtime;
}
client.loop();
}
}
}
| 35.884298
| 187
| 0.543989
|
ef565a4cceaf53340ad2448c541e27d964448a91
| 5,168
|
ino
|
Arduino
|
Code/WiFiBox.ino
|
EngineeringDads/WiFi-Messagebox
|
fee1d4ba4fde781637a55387041d11850caa8ca7
|
[
"MIT"
] | 1
|
2022-01-04T17:17:06.000Z
|
2022-01-04T17:17:06.000Z
|
Code/WiFiBox.ino
|
EngineeringDads/WiFi-Messagebox
|
fee1d4ba4fde781637a55387041d11850caa8ca7
|
[
"MIT"
] | 1
|
2022-01-17T18:25:23.000Z
|
2022-01-18T02:54:02.000Z
|
Code/WiFiBox.ino
|
EngineeringDads/WiFi-Messagebox
|
fee1d4ba4fde781637a55387041d11850caa8ca7
|
[
"MIT"
] | null | null | null |
#include <Wire.h>
#include "SSD1306Wire.h"
#include "font.h"
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <EEPROM.h>
#include <TZ.h>
#include <Servo.h>
#include "OLEDDisplayUI.h"
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define ID_ADDR 142
#define READ_ADDR 144
const int scanningDelay = 60 * 1000;
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
//Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
SSD1306Wire oled(0x3C, SDA, SCL);
OLEDDisplayUi ui (&oled);
Servo myservo;
int pos = 90;
int increment = -1;
int lightValue;
String line;
String mode;
char idSaved = '0';
bool wasRead = true;
const char* ssid = //Enter WIFI SSID
const char* password = //Enter WIFI password
String url = //Enter GITHUB url
void wifiConnect() {
if (WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
Serial.print("..done. IP ");
Serial.println(WiFi.localIP());
}
void drawMessage(const String& message) {
oled.clear();
if (mode[0] == 't') {
oled.setFont(Rancho_Regular_16);
oled.setTextAlignment(TEXT_ALIGN_CENTER);
oled.drawStringMaxWidth(64, 20, 128, message);
}
else {
for (int i = 0; i <= message.length(); i++) {
int x = i % 129;
int y = i / 129;
if (message[i] == '1') {
oled.setPixel(x,y);
}
}
}
//display.display();
oled.display();
}
void getGistMessage() {
Serial.println("Getting Message");
const int httpsPort = 443;
const char* host = "gist.githubusercontent.com";
const char fingerprint[] = "70 94 DE DD E6 C4 69 48 3A 92 70 A1 48 56 78 2D 18 64 E0 B7";
WiFiClientSecure client;
client.setFingerprint(fingerprint);
Serial.print("connecting to ");
Serial.println(host);
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
return;
}
Serial.print("requesting URL: ");
Serial.println(url);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"User-Agent: ESP8266\r\n" +
"Connection: close\r\n\r\n");
Serial.println("request sent");
while (client.connected()) {
String temp = client.readStringUntil('\n');
if (temp == "\r") {
Serial.println("headers received");
break;
}
}
String id = client.readStringUntil('\n');
Serial.printf("\tid: '%s', last processed id: '%c'\n", id.c_str(), idSaved);
if (id[0] != idSaved) { // new message
wasRead = 0;
idSaved = id[0];
mode = client.readStringUntil('\n');
Serial.println("\tmode: " + mode);
line = client.readStringUntil(0);
Serial.println("\tmessage: " + line);
drawMessage(line);
} else {
Serial.println("\t-> message id wasn't updated");
oled.clear();
oled.display();
}
}
void spinServo() {
for (pos = 84; pos <= 96; pos+= +1) {
myservo.write(pos);
delay(15); //
}
for (pos = 96; pos >= 84; pos+= -1) {
myservo.write(pos);
delay(15); //
}
for (pos = 84; pos <= 96; pos+= +1) {
myservo.write(pos);
delay(15); //
}
for (pos = 96; pos >= 84; pos+= -1) {
myservo.write(pos);
delay(15); //
}
for (pos = 84; pos <= 96; pos+= +1) {
myservo.write(pos);
delay(15); //
}
for (pos = 96; pos >= 84; pos+= -1) {
myservo.write(pos);
delay(15); //
}
delay(1500);
}
void setup() {
Serial.begin(115200);
myservo.attach(16);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.setSleepMode(WIFI_NONE_SLEEP);
WiFi.begin(ssid, password);
int counter = 0;
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
while (WiFi.status() != WL_CONNECTED) {
delay(2000);
oled.init();
oled.flipScreenVertically();
oled.setColor(WHITE);
oled.setFont(ArialMT_Plain_16);
oled.setTextAlignment(TEXT_ALIGN_CENTER);
oled.clear();
oled.drawStringMaxWidth(64,22,128, "WAITING TO CONNECT...");
oled.display();
}
delay(2000);
oled.clear();
oled.setTextAlignment(TEXT_ALIGN_LEFT);
oled.setFont(Satisfy_Regular_18);
oled.setColor(WHITE);
oled.drawString(19,23,"HI <3");
oled.display();
delay(100);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
wifiConnect();
}
if (wasRead) {
getGistMessage();
}
while (!wasRead) {
yield();
spinServo();
lightValue = analogRead(0);
Serial.println(lightValue);
if (lightValue > 300) {
Serial.printf("Message Read");
wasRead = 1;
myservo.write(90);
}
}
delay(scanningDelay);
}
| 22.08547
| 92
| 0.575077
|
8e9753ccef11dd7be1c834fe8a10a702e067a2ff
| 10,649
|
ino
|
Arduino
|
Tempo1.1.ino
|
carlsbug/DrumMeterProject
|
3d8efcc463fd1fe3b6b2085f8d186717e3997e83
|
[
"MIT"
] | null | null | null |
Tempo1.1.ino
|
carlsbug/DrumMeterProject
|
3d8efcc463fd1fe3b6b2085f8d186717e3997e83
|
[
"MIT"
] | null | null | null |
Tempo1.1.ino
|
carlsbug/DrumMeterProject
|
3d8efcc463fd1fe3b6b2085f8d186717e3997e83
|
[
"MIT"
] | null | null | null |
/**
* This class measures the tempo as you tap the drum
* and calculates the BPM and shows up on the 7 segment displays as a 3 digits
* @author KeonwoongMin
*
*/
const int a = 2;
const int b = 3;
const int c = 4;
const int d = 5;
const int e = 6;
const int f = 7;
const int g = 8;
int x = 0;
int y = 0;
int z = 0;
int ON = LOW;
int OFF = HIGH;
const int digit1Power = A0;
const int digit2Power = A1;
const int digit3Power = A2;
//////////////////////
//piezo
const int PIEZO_PIN = A5;
int PIEZO_VALUE1=0;
int PIEZO_VALUE2=0 ;
int PIEZO_VALUE3=0;
int PIEZO_VALUE4=0;
int PIEZO_VALUE5=0;
int PIEZO_VALUE6=0;
int PIEZO_VALUE7=0;
int BPM;
int timeInterval = 0;
float time0;
float time1;
float time2;
float time3;
float time4;
float time5;
float time6;
float time7;
int count = -1;
float tempTime = 0;
float finalTimeInterval = 0;
int tappingPower = 900;
int differencePower = 200;
int delayPower = 2;
float interval0 = 0;
float interval1 = 0;
float interval2 = 0;
float interval3 = 0;
float interval4 = 0;
float interval5 = 0;
float interval6 = 0;
int timeIntervalCount = 0;
int tempCount = 0;
//float myIntervals[4];
//potentiometer
//const int Poten_pin = A3;
void setup() {
Serial.begin(9600);
//displays
pinMode(a, OUTPUT);
pinMode(b, OUTPUT);
pinMode(c, OUTPUT);
pinMode(d, OUTPUT);
pinMode(e, OUTPUT);
pinMode(f, OUTPUT);
pinMode(g, OUTPUT);
pinMode(digit1Power, OUTPUT);
pinMode(digit2Power, OUTPUT);
pinMode(digit3Power, OUTPUT);
}
void loop()
{
// int potenValue = analogRead(Poten_pin);
// Serial.println(potenValue);
// delay(.3);
float myTemp = analogRead(PIEZO_PIN);
// if(BPM == 999)
// {
// firstDigit(-1);
// delay(1);
// secondDigit(-1);
// delay(1);
// thirdDigit(-1);
//// delay(1);
// }
// else
{
firstDigit((BPM/ 1U) %10);
// delay(3);
secondDigit((BPM/ 10U) %10);
// delay(3);
thirdDigit((BPM/ 100U) %10);
// delay(3);
}
if(analogRead(PIEZO_PIN) - myTemp > 20)
{
delay(100);
// Serial.println(++tempCount);
tempTime = millis();
if(tempTime > 0)
{ // find out how to blink dp instead of blinking whole numbers
count++;
count = count%5;
if(count == 0)
{
time0 = tempTime;
}
else if(count == 1)
{
time1 = tempTime;
}
else //if(count == 2)
{
time2 = tempTime;
}
}
interval0 = abs(time1 - time0);
interval1 = abs(time2 - time1);
// interval2 = abs(time3 - time2);
// interval3 = abs(time4 - time3);
if(count == 2)
{
float myIntervals[2] = {interval0, interval1};
finalTimeInterval = getFinalTimeInterval(myIntervals);
// finalTimeInterval =( interval0+interval1+interval2+interval3 )/4;
BPM = 60000/(finalTimeInterval);
if(BPM > 260)
{
BPM = 999;
}
}
}
}
void firstDigit(int x)
{
digitalWrite(digit1Power,HIGH);
digitalWrite(digit2Power,LOW);
digitalWrite(digit3Power,LOW);
switch(x)
{
case -1:
digitalWrite(a,OFF);
digitalWrite(b,OFF);
digitalWrite(c,OFF);
digitalWrite(d,OFF);
digitalWrite(e,OFF);
digitalWrite(f,OFF);
digitalWrite(g,ON);
break;
case 0:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(e,ON);
digitalWrite(f,ON);
digitalWrite(g,OFF);
break;
case 1:
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(a,OFF);
digitalWrite(d,OFF);
digitalWrite(e,OFF);
digitalWrite(f,OFF);
digitalWrite(g,OFF);
break;
case 2:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(g,ON);
digitalWrite(e,ON);
digitalWrite(d,ON);
digitalWrite(c,OFF);
digitalWrite(f,OFF);
break;
case 3:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(g,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(e,OFF);
digitalWrite(f,OFF);
break;
case 4:
digitalWrite(f,ON);
digitalWrite(g,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(a,OFF);
digitalWrite(d,OFF);
digitalWrite(e,OFF);
break;
case 5:
digitalWrite(a,ON);
digitalWrite(f,ON);
digitalWrite(g,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(b,OFF);
digitalWrite(e,OFF);
break;
case 6:
digitalWrite(a,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(e,ON);
digitalWrite(f,ON);
digitalWrite(g,ON);
digitalWrite(b,OFF);
break;
case 7:
digitalWrite(a,ON);
digitalWrite(f,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(d,OFF);
digitalWrite(e,OFF);
digitalWrite(g,OFF);
break;
case 8:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(e,ON);
digitalWrite(f,ON);
digitalWrite(g,ON);
break;
case 9:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(f,ON);
digitalWrite(g,ON);
digitalWrite(e,OFF);
break;
}
}
void secondDigit(int y)
{
digitalWrite(digit1Power,LOW);
digitalWrite(digit2Power,HIGH);
digitalWrite(digit3Power,LOW);
switch(y)
{
case -1:
digitalWrite(a,OFF);
digitalWrite(b,OFF);
digitalWrite(c,OFF);
digitalWrite(d,OFF);
digitalWrite(e,OFF);
digitalWrite(f,OFF);
digitalWrite(g,ON);
break;
case 0:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(e,ON);
digitalWrite(f,ON);
digitalWrite(g,OFF);
break;
case 1:
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(a,OFF);
digitalWrite(d,OFF);
digitalWrite(e,OFF);
digitalWrite(f,OFF);
digitalWrite(g,OFF);
break;
case 2:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(g,ON);
digitalWrite(e,ON);
digitalWrite(d,ON);
digitalWrite(c,OFF);
digitalWrite(f,OFF);
break;
case 3:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(g,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(e,OFF);
digitalWrite(f,OFF);
break;
case 4:
digitalWrite(f,ON);
digitalWrite(g,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(a,OFF);
digitalWrite(d,OFF);
digitalWrite(e,OFF);
break;
case 5:
digitalWrite(a,ON);
digitalWrite(f,ON);
digitalWrite(g,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(b,OFF);
digitalWrite(e,OFF);
break;
case 6:
digitalWrite(a,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(e,ON);
digitalWrite(f,ON);
digitalWrite(g,ON);
digitalWrite(b,OFF);
break;
case 7:
digitalWrite(a,ON);
digitalWrite(f,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(d,OFF);
digitalWrite(e,OFF);
digitalWrite(g,OFF);
break;
case 8:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(e,ON);
digitalWrite(f,ON);
digitalWrite(g,ON);
break;
case 9:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(f,ON);
digitalWrite(g,ON);
digitalWrite(e,OFF);
break;
}
}
void thirdDigit(int z)
{
digitalWrite(digit1Power,LOW);
digitalWrite(digit2Power,LOW);
digitalWrite(digit3Power,HIGH);
switch(z)
{
case -1:
digitalWrite(a,OFF);
digitalWrite(b,OFF);
digitalWrite(c,OFF);
digitalWrite(d,OFF);
digitalWrite(e,OFF);
digitalWrite(f,OFF);
digitalWrite(g,ON);
break;
case 0:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(e,ON);
digitalWrite(f,ON);
digitalWrite(g,OFF);
break;
case 1:
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(a,OFF);
digitalWrite(d,OFF);
digitalWrite(e,OFF);
digitalWrite(f,OFF);
digitalWrite(g,OFF);
break;
case 2:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(g,ON);
digitalWrite(e,ON);
digitalWrite(d,ON);
digitalWrite(c,OFF);
digitalWrite(f,OFF);
break;
case 3:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(g,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(e,OFF);
digitalWrite(f,OFF);
break;
case 4:
digitalWrite(f,ON);
digitalWrite(g,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(a,OFF);
digitalWrite(d,OFF);
digitalWrite(e,OFF);
break;
case 5:
digitalWrite(a,ON);
digitalWrite(f,ON);
digitalWrite(g,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(b,OFF);
digitalWrite(e,OFF);
break;
case 6:
digitalWrite(a,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(e,ON);
digitalWrite(f,ON);
digitalWrite(g,ON);
digitalWrite(b,OFF);
break;
case 7:
digitalWrite(a,ON);
digitalWrite(f,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(d,OFF);
digitalWrite(e,OFF);
digitalWrite(g,OFF);
break;
case 8:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(e,ON);
digitalWrite(f,ON);
digitalWrite(g,ON);
break;
case 9:
digitalWrite(a,ON);
digitalWrite(b,ON);
digitalWrite(c,ON);
digitalWrite(d,ON);
digitalWrite(f,ON);
digitalWrite(g,ON);
digitalWrite(e,OFF);
break;
}
}
//void countMethod(int count, int _tempTime)
//{
// int tempCount = count%5;
// int tempTime = _tempTime;
// switch(tempCount)
// case 0:
// time0 =
// break;
//
//
//}
float getFinalTimeInterval(float intervals[])
{
float result = intervals[0];
for(int i = 1; i < 2; i++)
{
result = result + intervals[i];
}
result = result / 2;
return result;
}
| 20.597679
| 78
| 0.577049
|
04f09c6f8180f7e24e01eaf5cc2884c396fc83ef
| 310
|
ino
|
Arduino
|
joystick X theremin.ino
|
Samael696/arduino
|
44c44781ea52d0de3aff245f000f0a2fa01d98db
|
[
"MIT"
] | null | null | null |
joystick X theremin.ino
|
Samael696/arduino
|
44c44781ea52d0de3aff245f000f0a2fa01d98db
|
[
"MIT"
] | 1
|
2021-11-28T14:32:06.000Z
|
2021-11-28T14:32:06.000Z
|
joystick X theremin.ino
|
Samael696/arduino
|
44c44781ea52d0de3aff245f000f0a2fa01d98db
|
[
"MIT"
] | 8
|
2021-11-03T12:45:36.000Z
|
2022-02-09T12:18:44.000Z
|
int sensorValue;
const int ledPin = 8;
void setup(){
Serial.begin(9600);
} //Fin de la funcion setup.
void loop() {
sensorValue = analogRead(A0);
Serial.println(sensorValue);
int pitch = map(sensorValue, 0, 1024, 50, 4000);
tone(8,pitch,20);
delay(10);
}
| 10.333333
| 48
| 0.577419
|
eb6c7f4c4c29ac34acedbc3f313188a3ce1f41f1
| 2,218
|
ino
|
Arduino
|
Relay_4wheel_Control/Relay_4wheel_Control.ino
|
adinath1/A4Arduino
|
54429f095223db8016ede54188cc927784f4f02b
|
[
"Apache-2.0"
] | null | null | null |
Relay_4wheel_Control/Relay_4wheel_Control.ino
|
adinath1/A4Arduino
|
54429f095223db8016ede54188cc927784f4f02b
|
[
"Apache-2.0"
] | null | null | null |
Relay_4wheel_Control/Relay_4wheel_Control.ino
|
adinath1/A4Arduino
|
54429f095223db8016ede54188cc927784f4f02b
|
[
"Apache-2.0"
] | 1
|
2021-09-06T06:20:07.000Z
|
2021-09-06T06:20:07.000Z
|
#define IN1 2 //WHEEL-2
#define IN2 3 //WHEEL-2
#define IN3 4 //WHEEL-1
#define IN4 5 //WHEEL-1
#define IN5 6 //WHEEL-3
#define IN6 7 //WHEEL-3
#define IN7 8 //WHEEL-4
#define IN8 9 //WHEEL-4
// defines pins numbers
const int trigPin = A0;
const int echoPin = A1;
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
pinMode(IN5, OUTPUT);
pinMode(IN6, OUTPUT);
pinMode(IN7, OUTPUT);
pinMode(IN8, OUTPUT);
}
void stopping(){
digitalWrite(IN1,LOW);
digitalWrite(IN2,LOW);
digitalWrite(IN3,LOW);
digitalWrite(IN4,LOW);
digitalWrite(IN5,LOW);
digitalWrite(IN6,LOW);
digitalWrite(IN7,LOW);
digitalWrite(IN8,LOW);
}
void straight(){
digitalWrite(IN1,LOW);
digitalWrite(IN2,HIGH);
digitalWrite(IN3,LOW);
digitalWrite(IN4,HIGH);
digitalWrite(IN5,LOW);
digitalWrite(IN6,HIGH);
digitalWrite(IN7,LOW);
digitalWrite(IN8,HIGH);
}
void left(){
digitalWrite(IN1,LOW);
digitalWrite(IN2,HIGH);
digitalWrite(IN3,LOW);
digitalWrite(IN4,HIGH);
digitalWrite(IN5,LOW);
digitalWrite(IN6,LOW);
digitalWrite(IN7,LOW);
digitalWrite(IN8,LOW);
}
void right(){
digitalWrite(IN1,LOW);
digitalWrite(IN2,LOW);
digitalWrite(IN3,LOW);
digitalWrite(IN4,LOW);
digitalWrite(IN5,LOW);
digitalWrite(IN6,HIGH);
digitalWrite(IN7,LOW);
digitalWrite(IN8,HIGH);
}
void loop(){
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
if (distance < 20)
{
left();
delay(1000);
straight();
}
else
{
straight();
}
}
| 22.632653
| 74
| 0.688458
|
a0be49c4f9c8685cfc7ae37aaacc21df0ad55dbd
| 15,549
|
ino
|
Arduino
|
teensyduino/libraries/Talkie/examples/SayQAcorn/SayQAcorn.ino
|
newdigate/teensy-build
|
1d24e37efb756023f6609dcf082c6ad16d4ad543
|
[
"MIT"
] | 4
|
2017-10-06T05:48:30.000Z
|
2018-03-30T06:20:22.000Z
|
teensyduino/libraries/Talkie/examples/SayQAcorn/SayQAcorn.ino
|
newdigate/teensy-build
|
1d24e37efb756023f6609dcf082c6ad16d4ad543
|
[
"MIT"
] | null | null | null |
teensyduino/libraries/Talkie/examples/SayQAcorn/SayQAcorn.ino
|
newdigate/teensy-build
|
1d24e37efb756023f6609dcf082c6ad16d4ad543
|
[
"MIT"
] | 3
|
2017-10-06T06:01:44.000Z
|
2018-05-25T06:37:19.000Z
|
// Talkie library
// Copyright 2011 Peter Knight
// This code is released under GPLv2 license.
//
// The following phrases are derived from those built into the
// Acorn Computers Speech Synthesiser add-on from 1983.
//
// A male voice with an RP English accent, voiced by Kenneth Kendall.
//
// Due to the large vocabulary, this file takes up 16Kbytes of flash.
// To save space, just copy and paste the words you need.
#define ACORN
#include <Talkie.h>
#ifdef ACORN
const uint8_t spPAUSE1[] PROGMEM = {0x08, 0x14, 0xC1, 0xDD, 0x45, 0x64, 0x03, 0x00, 0xFC, 0x4A, 0x56, 0x26, 0x3A, 0x06, 0x0A};
const uint8_t spPAUSE2[] PROGMEM = {0x08, 0x14, 0xC1, 0xDD, 0x45, 0x64, 0x03, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x4A, 0x46, 0x51, 0x39, 0x79, 0x15, 0x0A};
const uint8_t spTONE1[] PROGMEM = {0x8D, 0xF2, 0xDE, 0xDD, 0xDD, 0x93, 0x74, 0xAA, 0x53, 0x9D, 0xEA, 0x54, 0xA7, 0x3A, 0xD5, 0xA9, 0x4E, 0x75, 0xAA, 0x53, 0x9D, 0xEA, 0x54, 0xA7, 0x3A, 0xD5, 0xA9, 0x4E, 0x75, 0xAA, 0x53, 0x9D, 0xEA, 0x54, 0xA7, 0x3A, 0xD5, 0xA9, 0x4E, 0x75, 0xAA, 0x53, 0x9D, 0xEA, 0x54, 0xA7, 0x3A, 0xD5, 0xA9, 0x4E, 0x75, 0xAA, 0x53, 0x9D, 0xFA, 0x4A, 0x26, 0x51, 0x39, 0x79, 0x15, 0x0A};
const uint8_t spTONE2[] PROGMEM = {0x4D, 0xF1, 0xDE, 0xDD, 0xDD, 0x93, 0x74, 0xA5, 0x2B, 0x5D, 0xE9, 0x4A, 0x57, 0xBA, 0xD2, 0x95, 0xAE, 0x74, 0xA5, 0x2B, 0x5D, 0xE9, 0x4A, 0x57, 0xBA, 0xD2, 0x95, 0xAE, 0x74, 0xA5, 0x2B, 0x5D, 0xE9, 0x4A, 0x57, 0xBA, 0xD2, 0x95, 0xAE, 0x74, 0xA5, 0x2B, 0x5D, 0xE9, 0x4A, 0x57, 0xBA, 0xD2, 0x95, 0xAE, 0x74, 0xA5, 0x2B, 0x5D, 0xF9, 0x11, 0x5A};
const uint8_t spTHREE[] PROGMEM = {0x08, 0xA8, 0xC2, 0x8C, 0x02, 0x04, 0x68, 0x2A, 0xDC, 0xF9, 0x51, 0x5B, 0x96, 0x79, 0x8D, 0x10, 0xE5, 0xCA, 0x2E, 0x9A, 0x76, 0x72, 0xD0, 0xC2, 0x5C, 0x25, 0x21, 0x23, 0xCD, 0x0C, 0x4F, 0xD4, 0x22, 0x7A, 0x46, 0x34, 0x3E, 0xF1, 0x48, 0x86, 0xD2, 0xB1, 0xEA, 0x24, 0x33, 0x16, 0x62, 0xE7, 0xAA, 0x55, 0xAC, 0xD4, 0x04, 0xD5, 0x8D, 0x47, 0xB3, 0x53, 0x33, 0xE4, 0x2C, 0x69, 0xED, 0x4E, 0x81, 0x30, 0x53, 0xA7, 0xF5, 0xBB, 0x14, 0x43, 0xF4, 0x92, 0x36, 0xEC, 0x92, 0x04, 0xD5, 0x4B, 0xD2, 0xB8, 0xAB, 0x23, 0xF4, 0x34, 0xCE, 0x63, 0x19, 0x57, 0x73, 0x84, 0xAE, 0x26, 0x69, 0x9C, 0x8D, 0xC0, 0xAB, 0x6B, 0x87, 0xB1, 0x7B, 0x94, 0x99, 0x8A, 0xF2, 0x5A, 0x66};
const uint8_t spEIGH_[] PROGMEM = {0x23, 0x1E, 0xC5, 0x58, 0x33, 0xA7, 0x9E, 0xA0, 0x6A, 0xF1, 0xAD, 0x9E, 0xB2, 0xE2, 0xEE, 0x49, 0xAB, 0x3A, 0xCA, 0x2A, 0x66, 0x72, 0x94, 0xE9, 0xDA, 0xBB, 0x0A, 0xC3, 0x30, 0x8C, 0xB5, 0x1D, 0x5B, 0x4C, 0x42, 0xB9, 0xBB, 0x88, 0x6C, 0x00, 0x80, 0xFF, 0x4E};
const uint8_t spNINE_[] PROGMEM = {0xA1, 0x4A, 0x4C, 0xF4, 0x31, 0xDD, 0x85, 0x32, 0x71, 0xB6, 0xC7, 0x74, 0x57, 0xF2, 0x4C, 0x4D, 0x1F, 0x33, 0x79, 0xCB, 0x1A, 0x48, 0x3E, 0xD6, 0xFA, 0x27, 0xE9, 0xB2, 0xD5, 0xC4, 0x1B, 0x9D, 0xB8, 0xD9, 0x4B, 0x17, 0x4F, 0x74, 0xD2, 0xAE, 0x6E, 0x42, 0x3C, 0xD1, 0x29, 0xA7, 0xE9, 0xAA, 0x90, 0x54, 0xA7, 0x9A, 0xBE, 0x3D, 0x52, 0x5A, 0x9D, 0x66, 0xC5, 0x51, 0x49, 0x6B, 0x74, 0xDA, 0x95, 0x46, 0x30, 0xA2, 0xD1, 0xE8, 0x66, 0x2E, 0xE4, 0xCA, 0xCA, 0x6D, 0x58, 0x21, 0x89, 0x3A, 0x23, 0x87, 0x21, 0x73, 0xB5, 0x71, 0x4D, 0x6A, 0x86, 0x20, 0x2C, 0xCE, 0xCD, 0xC9, 0xFF, 0x41};
const uint8_t spACORN[] PROGMEM = {0x23, 0x9B, 0x35, 0x85, 0xD3, 0x96, 0x9C, 0x64, 0xD6, 0x12, 0x0A, 0x5F, 0x7C, 0xA2, 0x95, 0xD6, 0x30, 0x6C, 0xF1, 0x89, 0x56, 0x18, 0x86, 0xCC, 0x45, 0x2B, 0x5A, 0xA1, 0x11, 0x2B, 0x1B, 0xB7, 0x68, 0x34, 0x06, 0xCF, 0x9E, 0x94, 0xB2, 0x91, 0x19, 0x32, 0xAB, 0x96, 0x2A, 0x84, 0x72, 0x77, 0x11, 0xD9, 0x00, 0x0A, 0x08, 0x51, 0xC9, 0x02, 0x25, 0x8F, 0x6D, 0x54, 0x4D, 0x66, 0xB6, 0x22, 0x86, 0x09, 0x33, 0xDA, 0xD5, 0xDA, 0xE8, 0x2A, 0xD3, 0xB0, 0x4F, 0xEB, 0x92, 0xA9, 0xCA, 0xA0, 0xBC, 0x6D, 0x48, 0xA6, 0x2A, 0x83, 0xF2, 0x95, 0x29, 0xD9, 0xEC, 0x34, 0xEC, 0x9B, 0xE6, 0x90, 0xAA, 0x5D, 0x78, 0x73, 0x98, 0x63, 0xC9, 0x74, 0xD6, 0x57, 0x6E, 0x8E, 0xCB, 0x42, 0x6C, 0x66, 0xB9, 0x29, 0x0D, 0x4B, 0xE6, 0x8E, 0x1B, 0xC6, 0x94, 0x2C, 0x84, 0xA2, 0x73, 0x98, 0xB2, 0x71, 0x0B, 0xF0, 0xCC, 0x6E, 0x4E, 0x3A, 0xD4, 0xD8, 0xB3, 0xAA, 0xB9, 0x68, 0x33, 0x23, 0xD5, 0xF2, 0x25, 0x51, 0x15, 0x31, 0x41};
const uint8_t spCASSETTE[] PROGMEM = {0x06, 0x68, 0x86, 0x65, 0x84, 0x55, 0x8B, 0x74, 0xB9, 0xAD, 0x13, 0xB5, 0xEC, 0x1A, 0x16, 0x8D, 0x4F, 0xD6, 0xC3, 0x68, 0x98, 0xB4, 0x3A, 0x79, 0x77, 0xA5, 0x69, 0xB6, 0xBA, 0x14, 0xD5, 0xAB, 0xB9, 0x75, 0x29, 0x04, 0x2C, 0xA4, 0x86, 0x80, 0x83, 0x23, 0x10, 0x70, 0x99, 0x3B, 0x03, 0x3E, 0xCB, 0x64, 0xC0, 0x67, 0x91, 0x02, 0xB8, 0x2A, 0x42, 0x01, 0x4B, 0x95, 0x2D, 0xB7, 0x59, 0x97, 0xD2, 0x58, 0x7C, 0xA2, 0xEE, 0x52, 0xC2, 0x7D, 0xF1, 0xC9, 0xBA, 0x2F, 0x09, 0xB7, 0xD5, 0xA7, 0xEA, 0x3E, 0x25, 0xDC, 0x57, 0xA7, 0xA6, 0x19, 0x93, 0x8A, 0x98, 0x89, 0x1A, 0xA1, 0xDC, 0x5D, 0x44, 0x36, 0x80, 0x00, 0xAE, 0x48, 0x93, 0x00, 0x02, 0xAA, 0x6F, 0xF8, 0x25, 0x51, 0x15, 0x61, 0x41, 0x25, 0x41, 0x09, 0x61};
const uint8_t spCOMPUTER[] PROGMEM = {0x06, 0x28, 0x29, 0x68, 0x44, 0x29, 0xAA, 0xA6, 0xD6, 0xEC, 0x15, 0xE7, 0x9C, 0xE6, 0x64, 0xAB, 0x5A, 0x9E, 0xBD, 0x96, 0x41, 0xB6, 0x0D, 0x79, 0xB2, 0xDC, 0x48, 0xDD, 0xCD, 0x94, 0x49, 0x53, 0x15, 0x7B, 0x12, 0x54, 0x09, 0xE5, 0xEE, 0x22, 0xB2, 0x81, 0x01, 0xD5, 0x86, 0x97, 0xA0, 0x47, 0x22, 0xCF, 0xAA, 0xDC, 0xFC, 0x26, 0x8D, 0xB2, 0x7D, 0xF5, 0xF2, 0x33, 0x6D, 0xCD, 0xB0, 0xD7, 0x3B, 0xE8, 0x11, 0x2A, 0x84, 0x72, 0x77, 0x11, 0xD9, 0xA0, 0x80, 0x6D, 0x35, 0x1D, 0xB0, 0x89, 0xFB, 0x48, 0x8A, 0x35, 0x75, 0xED, 0xDA, 0xAB, 0xAA, 0xDE, 0x2D, 0x24, 0x57, 0xAF, 0xB6, 0xF9, 0xB6, 0x14, 0x5D, 0x5D, 0xA6, 0x52, 0xD3, 0x5C, 0x73, 0xB6, 0xDB, 0xB3, 0x4F, 0x4F, 0x89, 0x31, 0xFF, 0x15, 0x61, 0x51, 0x25, 0x25, 0x79, 0x61};
const uint8_t spFILE[] PROGMEM = {0x08, 0xE8, 0xD2, 0x95, 0x00, 0x4D, 0xA7, 0x09, 0xA0, 0xC8, 0xF0, 0xE6, 0xE5, 0x54, 0x9E, 0x4A, 0x8F, 0x4E, 0x50, 0xFC, 0x95, 0xB9, 0x36, 0xB8, 0xE1, 0x89, 0xAA, 0xB9, 0x52, 0xF3, 0x86, 0x27, 0x6E, 0xFA, 0xDA, 0xCD, 0x5A, 0x9E, 0xB4, 0xEA, 0x6B, 0x77, 0x6B, 0x79, 0x8A, 0xA6, 0xB7, 0x32, 0xA4, 0xD3, 0xA9, 0xBA, 0xDD, 0xC8, 0x94, 0x55, 0xA7, 0xEB, 0xA1, 0x3D, 0x83, 0x17, 0x9F, 0xBE, 0x87, 0x90, 0x08, 0x5B, 0x3C, 0x86, 0xEE, 0x4C, 0xB2, 0x6C, 0x71, 0x99, 0x8A, 0x97, 0x48, 0xAF, 0xD9, 0x61, 0xCE, 0x4E, 0x2B, 0xB4, 0xE6, 0x84, 0x25, 0x79, 0xCF, 0x22, 0x5F, 0xED, 0x67, 0x33, 0x85, 0xEE, 0x66, 0xD2, 0x8D, 0xDD, 0x18, 0x62, 0x64, 0x52, 0xAC, 0xB2, 0xE3, 0xFF, 0x15, 0x65, 0x25, 0x49, 0x31};
const uint8_t spFROM[] PROGMEM = {0x08, 0xE8, 0xDA, 0x84, 0x02, 0x0A, 0x68, 0x26, 0x54, 0x03, 0xAE, 0x88, 0x83, 0x2A, 0xC4, 0x73, 0x97, 0x2A, 0x2D, 0x8D, 0x90, 0xC8, 0xBD, 0xEA, 0x1C, 0xAD, 0x22, 0xA8, 0xF7, 0x69, 0xB2, 0xAF, 0x8A, 0xA4, 0x3E, 0xA7, 0xCD, 0xBE, 0x2A, 0x12, 0xF7, 0x9C, 0x2E, 0x9B, 0x6D, 0x0B, 0xEA, 0x72, 0xFA, 0x6C, 0x6E, 0x34, 0xB8, 0xF5, 0xEA, 0xB3, 0xBE, 0xB5, 0xE0, 0xD6, 0xA3, 0xCF, 0x7A, 0x5A, 0x43, 0x3D, 0xB7, 0x2E, 0xAB, 0xB6, 0x14, 0x52, 0x5D, 0xDA, 0x24, 0x5A, 0x43, 0x58, 0x4B, 0x6E, 0x43, 0x13, 0x9D, 0x85, 0x91, 0xB6, 0xF1, 0xCD, 0xFF, 0x71};
const uint8_t spILLEGAL[] PROGMEM = {0x25, 0x19, 0x4C, 0xA9, 0x6F, 0x42, 0xF7, 0x2C, 0x67, 0x21, 0x5F, 0x20, 0x38, 0xC3, 0x1E, 0x96, 0xE4, 0x70, 0x65, 0x4B, 0x5F, 0xDD, 0xA2, 0x43, 0x85, 0xAD, 0xA2, 0xF5, 0x08, 0xB6, 0x36, 0xD0, 0xD6, 0x26, 0x2B, 0x9A, 0xD6, 0x40, 0xBB, 0xAA, 0xAC, 0x64, 0x79, 0x03, 0xDD, 0xAE, 0x3D, 0xB2, 0x99, 0x08, 0x6A, 0xBA, 0x72, 0xA9, 0x56, 0x37, 0xE0, 0xE9, 0x46, 0xA6, 0x5A, 0xDD, 0x81, 0xAA, 0x67, 0x21, 0x50, 0x04, 0x77, 0x11, 0x91, 0x0D, 0xAE, 0x28, 0xA9, 0xC1, 0xD4, 0x6C, 0x97, 0x36, 0xC7, 0x46, 0xF7, 0x48, 0x34, 0xFA, 0xAA, 0xC3, 0x4A, 0x7D, 0xF1, 0x18, 0xB2, 0x8F, 0x0C, 0xCE, 0x35, 0x65, 0x8A, 0xB1, 0xDC, 0x39, 0x5B, 0x87, 0x39, 0x94, 0x72, 0xE3, 0x5E, 0x1C, 0xA6, 0x10, 0xDB, 0x83, 0xB2, 0xAB, 0x1B, 0xA3, 0x1B, 0x6B, 0xB4, 0xB5, 0x7E, 0xF8, 0x5A, 0x39, 0x49};
const uint8_t spIS[] PROGMEM = {0xC9, 0x5F, 0x3E, 0x90, 0xB2, 0x17, 0xDF, 0xE0, 0x04, 0xDB, 0x04, 0x72, 0xF5, 0xA2, 0x13, 0x6E, 0x1D, 0xC8, 0xD5, 0x8B, 0x4E, 0xB4, 0x5C, 0x23, 0x65, 0x2F, 0x3A, 0xE9, 0x76, 0x85, 0x1C, 0xB5, 0xE8, 0x94, 0x33, 0x24, 0x89, 0xD6, 0xA2, 0xD5, 0xCD, 0xD4, 0x24, 0x54, 0x8B, 0xC6, 0xD8, 0x0D, 0x4B, 0xF8, 0xD6, 0x29, 0x63, 0xE2, 0x6E, 0x9D, 0x1D, 0x3B, 0x8F, 0x66, 0x3C, 0xD0, 0xCD, 0xA3, 0x12, 0xDA, 0x89, 0x01, 0x13, 0xB0, 0x23, 0xE0, 0x61, 0x76, 0x04, 0x7C, 0x4A, 0xFA, 0x29};
const uint8_t spNEGATIVE[] PROGMEM = {0x26, 0x2E, 0x4C, 0x24, 0xCC, 0x13, 0xC5, 0x32, 0x14, 0x49, 0xD0, 0x9C, 0xA4, 0x9B, 0x92, 0x25, 0xC9, 0x33, 0x9C, 0x6E, 0x46, 0x32, 0x94, 0x91, 0x7B, 0x2C, 0x3E, 0xD1, 0x74, 0x21, 0x6E, 0xD1, 0xF8, 0x84, 0xCB, 0x26, 0x9B, 0x7B, 0xE3, 0x13, 0x4C, 0x93, 0xE8, 0x9D, 0xAB, 0x46, 0x30, 0x4A, 0x41, 0x44, 0xCE, 0x22, 0x49, 0xD7, 0x06, 0x16, 0xB5, 0x7A, 0x64, 0xDD, 0x15, 0x87, 0x8A, 0xE2, 0x95, 0x75, 0xA3, 0xD0, 0x13, 0xB5, 0x56, 0xDA, 0x94, 0x70, 0x75, 0xD4, 0x26, 0x9D, 0x50, 0xEE, 0x2E, 0x22, 0x1B, 0x0C, 0xB0, 0xA8, 0x85, 0x03, 0x16, 0x0B, 0x0D, 0xED, 0x16, 0x4E, 0x5A, 0x16, 0xBB, 0xB4, 0xC3, 0x2A, 0xA5, 0x57, 0x9D, 0x32, 0x74, 0x27, 0x1C, 0x59, 0x73, 0xC2, 0xD2, 0x8D, 0x70, 0x65, 0xCE, 0x76, 0x4B, 0x33, 0x22, 0xE5, 0x39, 0xCB, 0x2D, 0xD5, 0x93, 0xA5, 0xD5, 0x2C, 0x33, 0x67, 0x23, 0x5A, 0x5A, 0x35, 0xC5, 0x5C, 0x55, 0x88, 0xA9, 0x35, 0x36, 0xF3, 0x70, 0xA9, 0xA9, 0xAA, 0x98, 0x00, 0x4D, 0x9B, 0xFC, 0x75, 0x51, 0x39};
const uint8_t spNO[] PROGMEM = {0xAC, 0xEF, 0xCC, 0xD9, 0x25, 0x6C, 0xBB, 0xB6, 0x50, 0xD1, 0xC7, 0x74, 0x17, 0x9A, 0x42, 0xD9, 0x1E, 0xD3, 0x5D, 0xAA, 0x2B, 0x51, 0x7D, 0x2C, 0x77, 0x29, 0xAF, 0xC4, 0xF4, 0x31, 0x93, 0xB7, 0xAC, 0x81, 0xE4, 0x63, 0xAD, 0x7F, 0xD2, 0x2E, 0x5B, 0x4D, 0xBC, 0xD1, 0x89, 0x9B, 0x6E, 0x33, 0xF5, 0x4D, 0x27, 0x6B, 0x26, 0x3D, 0xD8, 0x56, 0x9F, 0xA2, 0xEA, 0x0E, 0x53, 0xDB, 0x74, 0xAA, 0xA6, 0x32, 0x42, 0xE5, 0xD3, 0xEE, 0xC7, 0xD8, 0x44, 0xA7, 0x19, 0x7E, 0x0E, 0x53, 0x32, 0xE3, 0x6C, 0xF6, 0x28, 0x8C, 0xC1, 0xB7, 0x19, 0xE5, 0x9C, 0x38, 0xDA, 0xF1, 0xFF, 0x15, 0x79, 0x39};
const uint8_t spNUMBER[] PROGMEM = {0xA6, 0x0A, 0x42, 0x72, 0xB9, 0xDC, 0x84, 0x32, 0x0A, 0x89, 0xA3, 0x72, 0x13, 0xF2, 0xC0, 0x35, 0x0E, 0xDB, 0x4D, 0x49, 0x13, 0x57, 0x3D, 0xAA, 0xA4, 0x27, 0xAE, 0xAE, 0xC3, 0x25, 0x12, 0x9F, 0xA8, 0xBA, 0x2D, 0x37, 0x4F, 0x74, 0x82, 0x62, 0xAF, 0xC3, 0x3C, 0xD5, 0xF1, 0x8B, 0xBD, 0x0E, 0xB5, 0x44, 0xCB, 0xAF, 0x72, 0xAD, 0x91, 0xDC, 0xAC, 0xA0, 0xCA, 0xB1, 0x46, 0x4A, 0x33, 0x82, 0x6C, 0x46, 0x03, 0xA4, 0x4B, 0x8A, 0xB2, 0x0C, 0x2B, 0x90, 0x2D, 0x2A, 0x33, 0xD2, 0xB2, 0xC4, 0x3E, 0x8B, 0xCA, 0xCA, 0xD2, 0x10, 0x5F, 0xD5, 0xAA, 0xE2, 0xDB, 0x8C, 0x65, 0x53, 0xAB, 0x73, 0x09, 0x57, 0xAE, 0xDB, 0x6D, 0x28, 0xB1, 0xDC, 0xC5, 0x1F, 0xB7, 0x29, 0x87, 0xF0, 0xD0, 0xBE, 0x94, 0xE7, 0xB0, 0x64, 0x1F, 0x16, 0x5A, 0x53, 0xEC, 0xFA, 0x79};
const uint8_t spPARAMETER[] PROGMEM = {0x04, 0xD0, 0xA2, 0x3D, 0xA5, 0xC5, 0xA7, 0x9B, 0x6B, 0xCD, 0x91, 0xE6, 0x21, 0x85, 0xE3, 0x71, 0x7B, 0xDA, 0xB2, 0x1C, 0xB8, 0x38, 0x3C, 0x6E, 0xCA, 0xD2, 0xC5, 0x32, 0xF5, 0xB6, 0x31, 0x6B, 0x69, 0x39, 0x6C, 0x61, 0xE9, 0x65, 0x45, 0xA5, 0x5B, 0x71, 0x45, 0xA3, 0x13, 0xD4, 0x9C, 0x11, 0x9A, 0x8D, 0x4E, 0xD0, 0xEC, 0x46, 0xBA, 0xD5, 0x5A, 0x49, 0x89, 0x9E, 0x42, 0x39, 0xB9, 0xE4, 0xC9, 0x49, 0x31, 0x74, 0xBB, 0x92, 0x67, 0x23, 0xA5, 0x50, 0xDD, 0x4A, 0x9E, 0x8C, 0xB4, 0x42, 0xAE, 0x3B, 0x65, 0x2D, 0x5E, 0xC6, 0x3E, 0xA5, 0xB5, 0xD5, 0x69, 0x28, 0xC7, 0x62, 0xD2, 0x0A, 0xE5, 0xEE, 0x22, 0xB2, 0x41, 0x01, 0x9B, 0x65, 0x1A, 0xA0, 0xE0, 0xF0, 0xD6, 0x24, 0xEF, 0x96, 0xDA, 0xB5, 0xCE, 0xD0, 0x82, 0x7B, 0xAA, 0xAE, 0x1E, 0x53, 0x4D, 0x15, 0xA1, 0xF2, 0xB8, 0x8D, 0x25, 0x57, 0x84, 0xEA, 0xE2, 0x32, 0x96, 0x9C, 0x11, 0xEC, 0x93, 0xFF, 0x51, 0x61, 0x39, 0x51, 0x05};
const uint8_t spPROGRAMME[] PROGMEM = {0x0C, 0x48, 0x2E, 0x95, 0x03, 0x2E, 0x0A, 0x8D, 0x3D, 0xDA, 0x13, 0xD5, 0x68, 0xF9, 0xA9, 0x73, 0x68, 0xC7, 0x94, 0x13, 0x94, 0x62, 0xA9, 0xC6, 0xAB, 0x4F, 0x50, 0x63, 0x84, 0x19, 0xAD, 0x3E, 0x41, 0x0B, 0xEE, 0x6E, 0xB8, 0xE9, 0x04, 0xD5, 0x69, 0x84, 0xF0, 0xAB, 0x11, 0x66, 0xE7, 0x66, 0x22, 0xAF, 0x5C, 0x14, 0xA3, 0x2B, 0xAB, 0x2E, 0x34, 0xA9, 0x54, 0x19, 0x1D, 0x96, 0x4A, 0xE5, 0x3E, 0xAB, 0xB8, 0x44, 0x9C, 0x50, 0xA7, 0x66, 0x21, 0xA4, 0x71, 0x52, 0x95, 0x33, 0x17, 0x66, 0xA7, 0x1D, 0x75, 0x69, 0x1A, 0x94, 0xE9, 0x75, 0xB5, 0xA5, 0xA9, 0x9B, 0xE7, 0x9A, 0x33, 0xB4, 0xD8, 0xE1, 0xC1, 0x5D, 0xCE, 0xD8, 0xFC, 0x44, 0x24, 0x75, 0x3E, 0x53, 0x8B, 0xE5, 0x19, 0xBC, 0x78, 0xCC, 0x35, 0x76, 0x64, 0xF2, 0xED, 0x36, 0xD7, 0x54, 0x51, 0xCE, 0xB3, 0xEB, 0x1C, 0xE6, 0xEC, 0x34, 0x0C, 0xAC, 0x89, 0x9F, 0xED, 0xF2, 0x45};
const uint8_t spTHIS[] PROGMEM = {0xAA, 0xF2, 0xD2, 0x6C, 0xA4, 0x2A, 0xAA, 0xCA, 0x4B, 0xB5, 0xB6, 0x6C, 0x18, 0xCA, 0xAA, 0x94, 0x53, 0xB4, 0xF1, 0x8A, 0x3B, 0x0B, 0xEC, 0xD2, 0x45, 0x27, 0xEC, 0xDC, 0x71, 0xCA, 0x67, 0x9D, 0x68, 0x48, 0xC7, 0xE9, 0x58, 0x74, 0xD2, 0x69, 0x13, 0x22, 0x63, 0xF1, 0xA9, 0x86, 0x35, 0xEC, 0xCC, 0xC5, 0xAD, 0xEE, 0x5E, 0x68, 0xE4, 0xE2, 0x2A, 0x20, 0xE3, 0x10, 0x01, 0x2C, 0x62, 0x66, 0x80, 0xC7, 0xDC, 0x15, 0xF0, 0x98, 0x94, 0x00, 0x3E, 0xB7, 0x10, 0xC0, 0xA3, 0x96, 0x0C, 0xF8, 0x42, 0x9D, 0x01, 0xDF, 0x09, 0x33, 0xE0, 0x1B, 0x31, 0x02, 0x7C, 0xA7, 0x42, 0x80, 0x6F, 0x94, 0x10, 0xF0, 0x95, 0x39, 0x02, 0x1A, 0x0E, 0xFD, 0x51, 0x59, 0x49, 0x15};
const uint8_t spYOUR[] PROGMEM = {0xA1, 0x69, 0x86, 0xD1, 0xA7, 0x2B, 0xE5, 0x3A, 0x55, 0x2D, 0x08, 0xDA, 0xC4, 0xCA, 0x56, 0x16, 0xA9, 0x5C, 0xA3, 0x3D, 0x4F, 0x99, 0x44, 0x59, 0x85, 0xF4, 0x5A, 0x65, 0x74, 0xE3, 0xA9, 0xDC, 0xFB, 0x96, 0xA7, 0x4A, 0x7A, 0xA2, 0x8C, 0x72, 0x9F, 0x2A, 0xDA, 0xC9, 0x54, 0xCE, 0xBD, 0xEA, 0x10, 0x26, 0x42, 0xB4, 0xF7, 0xAA, 0xA3, 0xDF, 0x08, 0xD1, 0xDE, 0xA3, 0x8E, 0x6E, 0x23, 0x44, 0x73, 0x8F, 0x3A, 0x9A, 0x8D, 0x54, 0xC9, 0x35, 0xEA, 0xE4, 0xBA, 0xD2, 0xB0, 0xF7, 0x68, 0x92, 0xDF, 0x74, 0x91, 0x9C, 0xA5, 0x89, 0xBD, 0xD3, 0x48, 0x3B, 0xF8, 0xF6, 0xFF, 0x2D};
const uint8_t * indexArray [] {spTHIS, spIS, spNO, spNEGATIVE, spPARAMETER, spPROGRAMME, spNUMBER, spILLEGAL, spCASSETTE, spPAUSE1, spPAUSE2};
#endif
Talkie voice;
#define qBlink() (digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN) )) // This toggles the Teensy 3.2 Builtin LED pin 13
void setup() {
while (!Serial && 5000 > millis());
Serial.println("\nSetting up");
pinMode(LED_BUILTIN, OUTPUT);
qBlink();
pinMode(5, OUTPUT);
digitalWrite(5, HIGH);//Enable Amplified PROP shield
delay(10);
voice.say( spACORN ); // This orignal function when used blocks until all queued sounds have played
}
int wordarray[] {0, 1, 2, 3, 6, 9, 0, 1, 2, 3, 4, 9, 7, 8, 10, 7, 8, 10};
int wordarraysize = sizeof (wordarray) / 4;
void loop() {
arrayInterface (wordarray, wordarraysize);
uint8_t xx = voice.active(), yy;
while ( (yy = voice.active()) > 15 ) {
if ( xx != yy ) {
qBlink();
xx = yy;
Serial.print( "." );
}
delay (5);
}
}
uint8_t aI_cnt = 0;
bool waitAcorn = true;
void arrayInterface (int * wordArray, int wordArraySize) {
Serial.print( "Array Adding: Active=" );
Serial.print( voice.active() );
if ( 2 < ++aI_cnt ) {
if ( waitAcorn ) voice.say( spACORN ); // This orignal function when used blocks until all queued sounds have played
else voice.sayQ( 0 ); // Empty queue to test code
waitAcorn = !waitAcorn;
aI_cnt = 0;
Serial.print( " EMPTY QUEUE: " );
while ( voice.active() ) Serial.print( "^" ); // Allow silence to come, a PAUSE is played to turn off synthesis
Serial.print( " :: Active=" );
Serial.println( voice.active() );
delay(1000); // Sweet Silence!
}
for (uint8_t i = 0; i < wordArraySize; i++) {
qBlink();
Serial.print( " Q=" );
Serial.print( voice.sayQ (indexArray[wordArray[i]]) );
}
Serial.print( ":: Array Added: Active=" );
Serial.println( voice.active() );
}
| 165.414894
| 963
| 0.665187
|
e49ea6cd17f3329eb72034ebb8c286598b13c4b4
| 1,143
|
ino
|
Arduino
|
simulator/demo/q20_dashMCU/q20_dashMCU.ino
|
qfsae/Q20
|
4c9936b6a1051fbd1f90b69efa4d42c1ac01554f
|
[
"MIT"
] | 3
|
2020-05-17T17:45:16.000Z
|
2020-07-13T14:13:13.000Z
|
simulator/demo/q20_dashMCU/q20_dashMCU.ino
|
joshuavaneck/Q20
|
4c9936b6a1051fbd1f90b69efa4d42c1ac01554f
|
[
"MIT"
] | 7
|
2020-03-06T19:37:07.000Z
|
2020-05-05T20:33:32.000Z
|
simulator/demo/q20_dashMCU/q20_dashMCU.ino
|
bchampp/Q20
|
f363d477d68edfb522beb2ba82ab767fecb8d05d
|
[
"MIT"
] | 1
|
2020-11-09T08:53:32.000Z
|
2020-11-09T08:53:32.000Z
|
/* Code going from dash MCU CAN to dash Teensy
- Receive gear, tps and rpm over CAN
- Send ^ over Serial to Teensy
*/
#include "mcp_can.h"
#include <SPI.h>
#define SPI_CS_PIN 10
MCP_CAN CAN(SPI_CS_PIN);
unsigned long rpmID = 0x00;
unsigned long tpsID = 0x08;
unsigned long gearID = 0xC0;
byte gear;
int rpm;
float tps;
unsigned char message[8] = {0, 0, 0, 0, 0, 0, 0, 0};
void setup() {
Serial.begin(115200);
Serial.println("Starting");
while (CAN.begin(CAN_250KBPS) != CAN_OK) {
Serial.println("CAN BUS init failure");
Serial.println("Trying again");
delay(100);
}
Serial.println("CAN Bus Initialized!");
}
void loop() {
if (!SENDING) {
/* This stuff needs to get updated to recieve msgs from the ETC as well, and transmit all of them over CAN with unique ID's */
unsigned char len = 0;
unsigned char buf[8];
if (CAN_MSGAVAIL == CAN.checkReceive()) {
CAN.readMsgBuf(&len, buf);
unsigned long id = CAN.getCanId();
Serial.write(buf[0]);
}
} else {
unsigned long sendingID = 0x00;
CAN.sendMsgBuf(sendingID, 0, 8, message);
delay(100);
message[0]++;
}
}
| 22.411765
| 130
| 0.646544
|
76a56315c642fba792ab6f4684ee9ebc3c556b00
| 4,353
|
ino
|
Arduino
|
LegacyVersions/ESP32_Example/ESP32_Scale/ESP32_Scale.ino
|
CalPlug/Espressif_ESP32-Scale
|
c8062dbbdb8533bac6efa3a0b81d86fd5b26555d
|
[
"BSD-Source-Code"
] | 23
|
2018-04-05T20:10:41.000Z
|
2022-01-28T16:29:47.000Z
|
LegacyVersions/ESP32_Example/ESP32_Scale/ESP32_Scale.ino
|
CalPlug/Espressif_ESP32-Scale
|
c8062dbbdb8533bac6efa3a0b81d86fd5b26555d
|
[
"BSD-Source-Code"
] | null | null | null |
LegacyVersions/ESP32_Example/ESP32_Scale/ESP32_Scale.ino
|
CalPlug/Espressif_ESP32-Scale
|
c8062dbbdb8533bac6efa3a0b81d86fd5b26555d
|
[
"BSD-Source-Code"
] | 15
|
2018-01-13T01:30:39.000Z
|
2021-03-07T21:04:57.000Z
|
//PROJECT LIBRA SCALE MEASUREMENT SYSTEM
//CODE BY MICHAEL KLOPFER + Calit2 Team (2017)
#include <Hx711.h> //Load Cell A/D (HX711 library)
#include <Adafruit_TLC59711.h> //12 Ch LED Controller, uses SPI only MOSI and CLK
#include <SPI.h>
//Constants
#define portTICK_PERIOD_MS 10
//Interface Assignments
#define HX711CLK 19
#define HX711DA 18
#define PIEZO 4
#define TAREBTN 21
#define TLC59711CLK 23
#define TLC59711DA 5
//Peripheral Setup
#define NUM_TLC59711 1 // How many boards do you have chained? (Only 1 in this example)
//Define Objects
Hx711 scale(HX711DA, HX711CLK); // Object for scale - Hx711.DOUT - pin #A2 & Hx711.SCK - pin #A3 ---this sensor uses a propriatary synchronus serial communication, not I2C
Adafruit_TLC59711 tlc = Adafruit_TLC59711(NUM_TLC59711, TLC59711CLK, TLC59711DA);
//----------------------------------
//Global Variables
float calibrated_scale_weight_g=0; //Holding variable for weight
float calibrated_scale_weight_g_1 = 0; //For Averaging
float calibrated_scale_weight_g_2 = 0; //For Averaging
float calibrated_scale_weight_g_3 = 0; //For Averaging
float tare_subtraction_factor=0; //When TARE is processed, this value is subtracted for the displayed weight
//Initial Calibration Factors and offsets
float scale_gain=-.0022103; //Initial Sensor Calibration Offset Value (fill in the `ratio` value here) [ratio = (w - offset) / 1000] where W is a known weight, say 1000 grams
float scale_offset=36820; //Initial Sensor Calibration Offset Value (fill in the `offset` value here)
float inherent_offset=33781; //Weight of unloaded sensor
//Piezo Parameters
int freq1 = 2000;
int freq2 = 125;
int dutyCycle = 50;
int channel = 0;
int resolution = 8;
int piezoch = 3;
//------------------------------------
//---------------------------------------------------------
void setup()
{
Serial.begin(115200); //begin Serial for LCD
//User Interface Buttons Initialize
pinMode(TAREBTN, INPUT_PULLUP); //Tare Button
pinMode(PIEZO, OUTPUT); //Select Button
digitalWrite(PIEZO, LOW);
//Initalize Piezo
ledcSetup(channel, freq1, resolution);
ledcAttachPin(4, channel);
//Initialize Piezo Driver
tlc.begin();
tlc.write();
//Set the offset and gain values
scale.setScale(scale_gain); //Gain
scale.setOffset(scale_offset); //Offset
Serial.println("****************END OF BIOS MESSAGES****************");
Serial.println("");
}
//---------------------------------------------------------
void loop()
{
//Read scale Value - rememberm this can have multiple calls that are averaged, check the library for the HX711 if this is not running properly!
calibrated_scale_weight_g_1=scale.getGram() - inherent_offset; //subtract inherent offset from pan weight (Read 1)
calibrated_scale_weight_g_2=scale.getGram() - inherent_offset; //subtract inherent offset from pan weight (Read 2)
calibrated_scale_weight_g_3=scale.getGram() - inherent_offset; //subtract inherent offset from pan weight (Read 3)
calibrated_scale_weight_g = (calibrated_scale_weight_g_1 + calibrated_scale_weight_g_2 + calibrated_scale_weight_g_3)/3; //return mean average from 3 readings
if (digitalRead(TAREBTN) != 0) //Look for Tare button Press
{
tare_subtraction_factor = calibrated_scale_weight_g;
}
calibrated_scale_weight_g = calibrated_scale_weight_g - tare_subtraction_factor; //Calculate weight
//Serial.println(scale.averageValue()); //output of value prior to gram calculation
Serial.print("Weight in grams: ");
Serial.println(calibrated_scale_weight_g);
Serial.print("Weight in Oz: ");
Serial.println(calibrated_scale_weight_g*0.035274);
Serial.println();
//Demo lights - state 1 (all ON)
tlc.setLED(0, 65534, 65534, 65534);
tlc.write();
tlc.setLED(1, 65534, 65534, 65534);
tlc.write();
tlc.setLED(2, 65534, 65534, 65534);
tlc.write();
tlc.setLED(3, 65534, 65534, 65534);
tlc.write();
//Make a Sound!
//ledcWriteTone(channel, freq2);
vTaskDelay(1000 / portTICK_PERIOD_MS);
//Demo lights - state 1 (all Off)
tlc.setLED(0, 0, 0, 0);
tlc.write();
tlc.setLED(1, 0, 0, 0);
tlc.write();
tlc.setLED(2, 0, 0, 0);
tlc.write();
tlc.setLED(3, 0, 0, 0);
tlc.write();
//Make a Sound!
//ledcWriteTone(channel, freq1);
//ledcWrite(channel, dutyCycle);
}
| 33.744186
| 177
| 0.687342
|
e426ebcda6c45a2e7f3e6a9c27b9f6638180ae41
| 6,748
|
ino
|
Arduino
|
motorControl/motorControl.ino
|
brightnite13/PiPythonSerialtoProMini
|
2b3e3872722fc4ae44533e64f020d7fd44ad69a3
|
[
"Apache-2.0"
] | null | null | null |
motorControl/motorControl.ino
|
brightnite13/PiPythonSerialtoProMini
|
2b3e3872722fc4ae44533e64f020d7fd44ad69a3
|
[
"Apache-2.0"
] | null | null | null |
motorControl/motorControl.ino
|
brightnite13/PiPythonSerialtoProMini
|
2b3e3872722fc4ae44533e64f020d7fd44ad69a3
|
[
"Apache-2.0"
] | null | null | null |
import time
import Serial
//////////////// GLOBALS /////////////////
#define maxMotorPower = 90;
#define minMotorPower = 50;
signed float calibrationConstant;
float motorSpeed;
void setup() {
// initialize serial connection
Serial.begin(115200);
// set the motor pins
pinMode(3,OUTPUT);
pinMode(5,OUTPUT;
// initialize global constants
calibrationConstant = 0;
minMotorPower = 45;
maxMotorPower = 90;
}
void autoForward()
{
dirSet("0F");
dirSet("1F");
motorOn();
// if !pollCheckLeft then correct left
// if !pollCheckRight then correct right
// if !pollcheckForward then stop
return;
}
void autoBackward()
{
dirSet("0R");
dirSet("1R");
motorOn();
// if !pollCheckLeft then correct left
// if !pollCheckRight then correct right
// if !pollcheckBack then stop
return;
}
void
//////////////// FUNCTIONS /////////////////
void dirSet(String twoDig)
{
String firstChar = twoDig.substring(0,1);
int pinNum = firstChar.toInt();
String secondChar = twoDig.substring(1,2);
//PRINT CHECK
Serial.println("first Char = ");
Serial.println(firstChar);
Serial.println("pinNum = ");
Serial.println(pinNum);
Serial.println("secondChar = ");
Serial.println(secondChar);
if (firstChar=="A")
{
if (twoDig.substring(1,2) == "R") // If forward
outputState = tca9555.setOutON(0, outputState);
if (twoDig.substring(1,2) == "F") // If reverse
outputState = tca9555.setOutOFF(0, outputState);
if (twoDig.substring(1,2) == "R") // If forward
outputState = tca9555.setOutON(1, outputState);
if (twoDig.substring(1,2) == "F") // If reverse
outputState = tca9555.setOutOFF(1, outputState);
tca9555.setOutputStates(1, outputState); // set extender to reflect changes
tca9555.setOutputStates(0, outputState); // set extender to reflect changes
}
else
{
if (twoDig.substring(1,2) == "R") // If forward
outputState = tca9555.setOutON(pinNum, outputState);
if (twoDig.substring(1,2) == "F") // If reverse
outputState = tca9555.setOutOFF(pinNum, outputState);
tca9555.setOutputStates(pinNum, outputState); // set extender to reflect changes
}
return;
}
// IN: Takes in a five digit string formatted for zero point (-like) rotation
// DESC:
void rotation(String fiveDig)
{
if (fiveDig.subString(0,1) == "L")
{
dirSet("0R");
dirSet("1F");
}
if (fiveDig.subString(0,1) == "R")
{
dirSet("0F");
dirSet("1R");
}
motorOn(75);
delay(fiveDig.substring(1).toInt());
motorOff();
return;
}
void motorOff()
{
analogWrite(3,0);
analogWrite(5,0);
Serial.print("Motors off");
return;
}
void motorOn(float mSpeed)
{
analogWrite(3, mSpeed+calibrationConstant);
analogWrite(5, mSpeed);
Serial.print("Left Speed = ",mSpeed+calibrationConstant);
Serial.print("Right Speed = ",mSpeed);
return;
}
// IN: Takes in a five digit string formatted for linear forward/backward motion
// DESC:
void linearMotion(String fiveDig)
{
// Set direction
if (fiveDig.subString(0,1) == "F")
{
dirSet("0F");
dirSet("1F");
}
if (fiveDig.subString(0,1) == "R")
{
dirSet("0R");
dirSet("1R");
}
// Set speed
analogWrite(3, fiveDig.substring(1).toInt()+calibrationConstant);
analogWrite(5, fiveDig.substring(1).toInt());
Serial.print("Left Speed = ",fiveDig.substring(1).toInt()+calibrationConstant);
Serial.print("Right Speed = ",fiveDig.substring(1).toInt());
return;
}
// IN: Calibrates the fixed motor speed for straight line movement
// DESC:
void motorCalibration(){
while 1{
float rSpeed = 75;
float lSpeed = 75;
if(Serial.available()>0)
{
incomingString = Serial.readString();
for (int k = 0; k < incomingString.length(); k++)
{
if (incomingString.substring(k,k+1) == "Q") //If "Q" then quit back to main loop
{
Serial.print("Now Quitting Calibration");
return;
}
if (incomingString.substring(k,k+1) == "O") //If "O" then increment calibration by 2.5
{
calibrationConstant += 2.5;
Serial.print(calibrationConstant);
}
if (incomingString.substring(k,k+1) == "L") //If "L" then decrement calibration by 2.5
{
calibrationConstant += 2.5;
Serial.print(calibrationConstant);
}
if (incomingString.substring(k,k+1) == "I") //If "I" then manual increment by three digit float to the tenth ##.# (do not include decimal)
{
calibrationConstant += incomingString.substring(k+1,k+4).toInt() / 10;
Serial.print(calibrationConstant);
}
if (incomingString.substring(k,k+1) == "K") //If "K" manual decrement by three digit float to the tenth
{
calibrationConstant -= incomingString.substring(k+1,k+4).toInt() / 10;
Serial.print(calibrationConstant);
}
}
// print new speeds
Serial.print("Pin 3 at speed: ", (lspeed + calibrationConstant));
Serial.print("Pin 5 at speed: ", rspeed);
Serial.print("Calibration Constant Set To: ", calibrationConstant);
}
// adjust to new speed
analogWrite(3, lspeed + calibrationConstant);
analogWrite(5, rSpeed);
}
}
void loop()
{
String incomingString;
if(Serial.available()>0){ // loop to monitor and read serial commands
incomingString = Serial.readString(); // string to hold incoming serial data
for (int i = 0; i < incomingString.length(); i++)
{
if (incomingString.substring(i,i+1) == "C") //If "C" run Motor Speed Calibration
{
Serial.print("Begin Motor Callibration");
motorCalibration();
}
if (incomingString.substring(i,i+1) == "V") //If "V" run Wall Following mode
{
Serial.print("Begin Wall Following");
//wallFollow();
}
if (incomingString.substring(i,i+1) == "W") //If "W" begin forward motion
{
String temp = "F";
linearMotion(temp + incomingString.substring(i+1,i+4);
}
if (incomingString.substring(i,i+1) == "S") //If "S" begin reverse motion
{
String temp = "R";
linearMotion(temp + incomingString.substring(i+1,i+4);
}
if (incomingString.substring(i,i+1) == "A") //If "A" begin left turn
{
String temp = "L";
rotation(temp + incomingString.substring(i+1,i+4);
}
if (incomingString.substring(i,i+1) == "D") //If "A" begin left turn
{
String temp = "R";
rotation(temp + incomingString.substring(i+1,i+4);
}
}
}
}
| 28.472574
| 146
| 0.602993
|
ae22c3c4d7818e9ef109943637562de771fde3a4
| 1,680
|
ino
|
Arduino
|
Eeprom.ino
|
filmote/LayingPipe
|
c0102412e2ae79a20c8a8dd8b2561490b863a442
|
[
"BSD-3-Clause"
] | 1
|
2019-08-18T21:16:53.000Z
|
2019-08-18T21:16:53.000Z
|
Eeprom.ino
|
Press-Play-On-Tape/LayingPipe
|
c0102412e2ae79a20c8a8dd8b2561490b863a442
|
[
"BSD-3-Clause"
] | 1
|
2018-02-12T21:06:54.000Z
|
2018-02-12T22:32:03.000Z
|
Eeprom.ino
|
Press-Play-On-Tape/LayingPipe
|
c0102412e2ae79a20c8a8dd8b2561490b863a442
|
[
"BSD-3-Clause"
] | 2
|
2017-12-08T21:10:30.000Z
|
2018-02-21T13:39:11.000Z
|
#define EEPROM_START EEPROM_STORAGE_SPACE_START
#define EEPROM_START_C1 EEPROM_START
#define EEPROM_START_C2 EEPROM_START + 1
#define EEPROM_5X5 EEPROM_START + 2
#define EEPROM_6X6 EEPROM_START + 3
#define EEPROM_7X7 EEPROM_START + 4
#define EEPROM_8X8 EEPROM_START + 5
#define EEPROM_9X9 EEPROM_START + 6
#define EEPROM_PUZZLE_OFFSET EEPROM_START - 3
/* ----------------------------------------------------------------------------
* Is the EEPROM initialised?
*
* Looks for the characters 'L' and 'P' in the first two bytes of the EEPROM
* memory range starting from byte EEPROM_STORAGE_SPACE_START. If not found,
* it resets the settings ..
*/
bool initEEPROM() {
byte c1 = EEPROM.read(EEPROM_START_C1);
byte c2 = EEPROM.read(EEPROM_START_C2);
if (c1 != 76 || c2 != 80) { // LP 76 80
EEPROM.update(EEPROM_START_C1, 76);
EEPROM.update(EEPROM_START_C2, 80);
EEPROM.update(EEPROM_5X5, 0);
EEPROM.update(EEPROM_6X6, 0);
EEPROM.update(EEPROM_7X7, 0);
EEPROM.update(EEPROM_8X8, 0);
EEPROM.update(EEPROM_9X9, 0);
}
}
/* ----------------------------------------------------------------------------
* Update the saved puzzle index for the nominated level.
*/
void updateEEPROM(byte puzzleLevel, byte index) {
EEPROM.update(EEPROM_PUZZLE_OFFSET + puzzleLevel, index);
}
/* ----------------------------------------------------------------------------
* Read the saved puzzle index for the nominated level.
*/
byte readEEPROM(byte puzzleLevel) {
return EEPROM.read(EEPROM_PUZZLE_OFFSET + puzzleLevel);
}
| 29.473684
| 79
| 0.577976
|
6bd937fc4ee9f0eb2abcf4fb6dbf60dddf3605dc
| 2,256
|
ino
|
Arduino
|
TeachLearn/TeachLearn.ino
|
Aakriti05/Conveels
|
f05daa408efcdb55aac11a8e4682dc187cef327f
|
[
"Apache-2.0"
] | null | null | null |
TeachLearn/TeachLearn.ino
|
Aakriti05/Conveels
|
f05daa408efcdb55aac11a8e4682dc187cef327f
|
[
"Apache-2.0"
] | null | null | null |
TeachLearn/TeachLearn.ino
|
Aakriti05/Conveels
|
f05daa408efcdb55aac11a8e4682dc187cef327f
|
[
"Apache-2.0"
] | null | null | null |
int LeftMotorForward = 10;
int LeftMotorBackward = 11;
int RightMotorForward = 6;
int RightMotorBackward = 5;
char CurrentInput = 'x';
char LastInput = 'x';
char mode;
char directions[1000];
void setup()
{// put your setup code here, to run once:
pinMode(LeftMotorForward, OUTPUT);
pinMode(LeftMotorBackward, OUTPUT);
pinMode(RightMotorForward, OUTPUT);
pinMode(RightMotorBackward, OUTPUT);
directions[0] = '\0';
Serial.begin(9600);
Serial.println("Enter mode of the wheelchair : \n 0 for self-driven mode \n 1 for giving directions (Teach Mode) ");
}
void forward()
{
digitalWrite(RightMotorForward, HIGH);
digitalWrite(LeftMotorForward, HIGH);
delay(500);
}
void backward()
{
digitalWrite(RightMotorBackward, HIGH);
digitalWrite(LeftMotorBackward, HIGH);
delay(500);
}
void right()
{
digitalWrite(RightMotorForward, HIGH);
digitalWrite(LeftMotorForward, LOW);
delay(500);
}
void left()
{
digitalWrite(RightMotorForward, LOW);
digitalWrite(LeftMotorForward, HIGH);
delay(500);
}
void pause()
{
digitalWrite(RightMotorForward, LOW);
digitalWrite(LeftMotorForward, LOW);
digitalWrite(RightMotorBackward, LOW);
digitalWrite(LeftMotorBackward, LOW);
delay(500);
}
void loop()
{ // put your main code here, to run repeatedly:
while(!Serial.available());
mode = Serial.read();
Serial.println(mode);
if(mode == '0')
{
for(int i=0;directions[i]!='\0';i++)
{
if(directions[i]=='w') forward();
else if(directions[i] =='a') left();
else if(directions[i] == 'd') right();
else if(directions[i] == 's') backward();
}
pause();
}
else if(mode == '1')
{
Serial.println("Enter directions : w/a/s/d for forward/left/backward/right and e to exit Teach Mode");
Serial.flush();
while(!Serial.available());
int j=0;
char c;
do
{
c = Serial.read();
if(c!='e')
{
directions[j++]=c;
}
Serial.println(j);
delay(500);
}while(c!='e');
directions[++j]='\0';
}
Serial.println("Enter mode of the wheelchair : \n 0 for self-driven mode \n 1 for giving directions(Teach Mode) ");
}
| 22.56
| 124
| 0.618351
|
166cca82d0e9fb941516e743d1f1a2aafbc7a2dd
| 795
|
ino
|
Arduino
|
tests/transmitter_arduino/transmitter_arduino.ino
|
tfrec-kalcsits/SensorSystem-Networking
|
829c287999b32fed37cc707f8cfcff209bdb11dc
|
[
"MIT"
] | 2
|
2018-06-30T06:05:29.000Z
|
2021-08-24T22:34:19.000Z
|
tests/transmitter_arduino/transmitter_arduino.ino
|
tfrec-kalcsits/SensorSystem-Networking
|
829c287999b32fed37cc707f8cfcff209bdb11dc
|
[
"MIT"
] | 13
|
2018-07-07T00:11:08.000Z
|
2018-09-05T02:49:11.000Z
|
Networking/tests/transmitter_arduino/transmitter_arduino.ino
|
tfrec-kalcsits/SensorSystem
|
04a66cb3c30dc7b9fbbf1e0b9cc7747fe03b6950
|
[
"MIT"
] | null | null | null |
#include <radioreceiver.h>
#include <radiotransmitter.h>
#include <rf24radioreceiver.h>
#include <rf24radiotransmitter.h>
using namespace sensorsystem;
RadioTransmitter * transmitter;
int ambient;
byte address[6] = "00001";
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("============= BEGIN ===========");
transmitter = new RF24RadioTransmitter(7, 8, address);
ambient = 0;
}
void loop() {
// put your main code here, to run repeatedly:
Serial.print("Sending packet with temperature: ");
Serial.println(ambient);
Packet temp;
temp.ambient_temperature = ambient;
if(transmitter->sendPacket(temp))
Serial.println("Successful transmission");
else
Serial.println("Transmission failed");
ambient++;
delay(3000);
}
| 24.090909
| 56
| 0.696855
|
5951589af145827d70ad8a892be6b7cc6c2498d1
| 1,111
|
ino
|
Arduino
|
pwm-servo/pwm-servo.ino
|
gordon-krefting/arduino-snippets
|
97d859a763e4f008289409f450ba23c0d8decd0d
|
[
"Unlicense"
] | null | null | null |
pwm-servo/pwm-servo.ino
|
gordon-krefting/arduino-snippets
|
97d859a763e4f008289409f450ba23c0d8decd0d
|
[
"Unlicense"
] | null | null | null |
pwm-servo/pwm-servo.ino
|
gordon-krefting/arduino-snippets
|
97d859a763e4f008289409f450ba23c0d8decd0d
|
[
"Unlicense"
] | null | null | null |
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
#define SERVOMIN 194
#define SERVOMAX 630
#define POT_PIN A0
void setup() {
Serial.begin(9600);
Serial.println("Starting...");
pwm.begin();
pwm.setPWMFreq(60);
}
void loop() {
int pot_value = analogRead(POT_PIN) / 5 * 5;
int pulse_len = map(pot_value, 0, 1023, SERVOMIN, SERVOMAX);
Serial.print("Pot Value: ");
Serial.print(pot_value);
Serial.print(" Pulse: ");
Serial.println(pulse_len);
pwm.setPWM(0, 0, pulse_len);
}
void loop_old() {
int pulse_length = map(0, 0, 180, SERVOMIN, SERVOMAX);
Serial.println("0 Degrees");
pwm.setPWM(0, 0, pulse_length);
delay(1000);
pulse_length = map(90, 0, 180, SERVOMIN, SERVOMAX);
Serial.println("90 Degrees");
pwm.setPWM(0, 0, pulse_length);
delay(1000);
pulse_length = map(180, 0, 180, SERVOMIN, SERVOMAX);
Serial.println("180 Degrees");
pwm.setPWM(0, 0, pulse_length);
delay(1000);
pulse_length = map(90, 0, 180, SERVOMIN, SERVOMAX);
Serial.println("90 Degrees");
pwm.setPWM(0, 0, pulse_length);
delay(1000);
}
| 22.673469
| 62
| 0.681368
|
d7d7392d64491a925901ca73a1a63f8c96af4cc9
| 5,380
|
ino
|
Arduino
|
esp32lib/DNSServer/examples/CaptivePortal/CaptivePortal.ino
|
KarlPekaway/btc-18years-box
|
6b348bf8feb48e2a77fef61790da36e56a30e30f
|
[
"Apache-2.0"
] | null | null | null |
esp32lib/DNSServer/examples/CaptivePortal/CaptivePortal.ino
|
KarlPekaway/btc-18years-box
|
6b348bf8feb48e2a77fef61790da36e56a30e30f
|
[
"Apache-2.0"
] | null | null | null |
esp32lib/DNSServer/examples/CaptivePortal/CaptivePortal.ino
|
KarlPekaway/btc-18years-box
|
6b348bf8feb48e2a77fef61790da36e56a30e30f
|
[
"Apache-2.0"
] | null | null | null |
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#define STATUS_PIN LED_BUILTIN
#define DCF_PIN 2
int HIGH_Start = 0;
int HIGH_Ende = 0;
int HIGH_Zeit = 0;
int LOW_Start = 0;
int LOW_Ende = 0;
int LOW_Zeit = 0;
bool Signal = false;
bool neueMinute = false;
int BIT = -1;
int ZEIT[65];
int ZEIT_STUNDE;
int ZEIT_MINUTE;
int ZEIT_TAG;
int ZEIT_MONAT;
int ZEIT_JAHR;
int ZEIT_WOCHENTAG;
int PAR_STUNDE;
int PAR_MINUTE;
int PAR_BEGINN;
const byte DNS_PORT = 53;
IPAddress apIP(192, 168, 1, 1);
DNSServer dnsServer;
WiFiServer server(80);
String responseHTML = ""
"<!DOCTYPE html><html><head><title>Happy Birthday!</title></head><body>"
"<h1>Hello World!</h1><p> Hier für dich ein Wallet mit bisschen Geld drauf, also vielleicht :D "
"Puplic Key: sdjfnsiefsdfskjdfsebfisdfj Private-Key: sdfbshbfsjd sjh </p></body></html>";
void setup() {
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
WiFi.softAP("Happy Birthday Gustav");
// if DNSServer is started with "*" for domain name, it will reply with
// provided IP to all DNS request
dnsServer.start(DNS_PORT, "*", apIP);
server.begin();
Serial.begin(115200);
pinMode(DCF_PIN, INPUT);
pinMode(STATUS_PIN, OUTPUT);
Serial.println("Syncronisierung");
}
void loop() {
dnsServer.processNextRequest();
WiFiClient client = server.available(); // listen for incoming clients
if (client) {
String currentLine = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (c == '\n') {
if (currentLine.length() == 0) {
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
client.print(responseHTML);
break;
} else {
currentLine = "";
}
} else if (c != '\r') {
currentLine += c;
}
}
}
client.stop();
}
if (BIT > 60) {neueMinute = false;}
int DCF_SIGNAL = digitalRead(DCF_PIN);
if (DCF_SIGNAL == HIGH && Signal == false) {
Signal = true;
HIGH_Start = millis();
LOW_Ende = HIGH_Start;
LOW_Zeit = LOW_Ende - LOW_Start;
if (neueMinute == true) {
PrintBeschreibung(BIT);
//Serial.print("Bit");
//Serial.print (BIT);
//Serial.print (": ");
ZEIT[BIT] = (BIT_Zeit(LOW_Zeit));
Serial.print (ZEIT[BIT]);
//Serial.println ();
}
else {
Serial.print(".");
}
}
if (DCF_SIGNAL == LOW && Signal == true) {
Signal = false;
HIGH_Ende = millis();
LOW_Start = HIGH_Ende;
HIGH_Zeit = HIGH_Ende - HIGH_Start;
NEUMINUTE(LOW_Zeit);
}
}
int BIT_Zeit (int LOW_Zeit) {
if (LOW_Zeit >= 851 && LOW_Zeit <= 950) {return 0;}
if (LOW_Zeit >= 750 && LOW_Zeit <= 850) {return 1;}
if (LOW_Zeit <= 350) {BIT-=1;return 0;}
}
void NEUMINUTE (int LOW_Zeit) {
if (LOW_Zeit >= 1700) {
BIT = 0;
neueMinute = true;
ZEIT_STUNDE = ZEIT[29]*1+ZEIT[30]*2+ZEIT[31]*4+ZEIT[32]*8+ZEIT[33]*10+ZEIT[34]*20;
ZEIT_MINUTE = ZEIT[21]*1+ZEIT[22]*2+ZEIT[23]*4+ZEIT[24]*8+ZEIT[25]*10+ZEIT[26]*20+ZEIT[27]*40;
PAR_STUNDE = ZEIT[35];
PAR_MINUTE = ZEIT[28];
ZEIT_TAG = ZEIT[36]*1+ZEIT[37]*2+ZEIT[38]*4+ZEIT[39]*8+ZEIT[40]*10+ZEIT[41]*20;
ZEIT_MONAT = ZEIT[45]*1+ZEIT[46]*2+ZEIT[47]*4+ZEIT[48]*8+ZEIT[49]*10;
ZEIT_JAHR = 2000+ZEIT[50]*1+ZEIT[51]*2+ZEIT[52]*4+ZEIT[53]*8+ZEIT[54]*10+ZEIT[55]*20+ZEIT[56]*40+ZEIT[57]*80;
PAR_BEGINN = ZEIT[20];
Serial.println();
Serial.println("*****************************");
Serial.print ("Uhrzeit: ");
Serial.println();
Serial.print (ZEIT_STUNDE);
Serial.print (":");
Serial.print (ZEIT_MINUTE);
Serial.println();
Serial.println();
Serial.print ("Datum: ");
Serial.println();
Serial.print (ZEIT_TAG);
Serial.print (".");
Serial.print (ZEIT_MONAT);
Serial.print (".");
Serial.print (ZEIT_JAHR);
Serial.println();
Serial.println("*****************************");
if (ZEIT_JAHR == 2020 && ZEIT_MONAT == 7 && ZEIT_TAG == 25)
Serial.println("BOX OFFEN!");
} else {BIT++;}
}
void PrintBeschreibung(int BitNummer) {
switch (BitNummer) {
case 0: Serial.println("\n# START MINUTE (IMMER 0)"); break;
case 1: Serial.println("\n# WETTERDATEN"); break;
case 15: Serial.println("\n# RUFBIT"); break;
case 16: Serial.println("\n# MEZ/MESZ"); break;
case 17: Serial.println("\n# MESZ"); break;
case 18: Serial.println("\n# MEZ"); break;
case 19: Serial.println("\n# SCHALTSEKUNDE"); break;
case 20: Serial.println("\n# BEGIN ZEITINFORMATION (IMMER 1)"); break;
case 21: Serial.println("\n# MINUTEN"); break;
case 28: Serial.println("\n# PARITAET MINUTE"); break;
case 29: Serial.println("\n# STUNDE");break;
case 35: Serial.println("\n# PARITAET STUNDE"); break;
case 36: Serial.println("\n# TAG"); break;
case 42: Serial.println("\n# WOCHENTAG"); break;
case 45: Serial.println("\n# MONAT"); break;
case 50: Serial.println("\n# JAHR"); break;
case 58: Serial.println("\n# PARITAET DATUM"); break;
}
}
| 28.924731
| 114
| 0.579182
|
455cbd23e39e5731e746df4f147dde1553b2729a
| 720
|
ino
|
Arduino
|
dobieranie.ino
|
hubi95/Arduino-card-machine
|
c3f19779c4956d2a718bcc47c5c713c7e296fd87
|
[
"MIT"
] | null | null | null |
dobieranie.ino
|
hubi95/Arduino-card-machine
|
c3f19779c4956d2a718bcc47c5c713c7e296fd87
|
[
"MIT"
] | null | null | null |
dobieranie.ino
|
hubi95/Arduino-card-machine
|
c3f19779c4956d2a718bcc47c5c713c7e296fd87
|
[
"MIT"
] | null | null | null |
void liczba_kart()
{
x++;
switch (x)
{
case 1:
digitalWrite(led, HIGH);
delay(200);
break;
case 2:
digitalWrite(led2, HIGH);
delay(200);
break;
case 3:
digitalWrite(led3, HIGH);
delay(200);
break;
case 4:
digitalWrite(led4, HIGH);
delay(200);
break;
case 5:
digitalWrite(led5, HIGH);
delay(200);
break;
case 6:
digitalWrite(led, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
digitalWrite(led5, LOW);
x = 0;
delay(200);
break;
}
}
void dobranie()
{
servoO.write(90);
servoS.write(180);
delay(300);
for (int y = x; y > 0; y--)
{
wyrzut();
}
wy_poz_ram();
}
| 15
| 29
| 0.555556
|
a06d0dbe960dab7feaf011f005e0fc0710d7e44a
| 3,608
|
ino
|
Arduino
|
arduino/sensors/index2.ino
|
GeorgeShao/HomeNode
|
259295ff8715ebe4348d5098d32fb6bbc60a8a7a
|
[
"MIT"
] | null | null | null |
arduino/sensors/index2.ino
|
GeorgeShao/HomeNode
|
259295ff8715ebe4348d5098d32fb6bbc60a8a7a
|
[
"MIT"
] | null | null | null |
arduino/sensors/index2.ino
|
GeorgeShao/HomeNode
|
259295ff8715ebe4348d5098d32fb6bbc60a8a7a
|
[
"MIT"
] | null | null | null |
//The following is an arbitrary number of data points
#define DATAPOINTS 10
//The following is the number of iterations before we wipe the data
#define DAILYITERATIONS 10
//the following is the tolerance to change before the temperature/humidity is updated
#define TOLERANCE 1
//We will enter each datapoint into an array, and for the sake of demonstration,
//We will call a random number generator
float storage[DATAPOINTS];
float moistureStorage[DATAPOINTS];
float moistureCounter = 0;
float counter = 0;
float pastAverages[DAILYITERATIONS] = {0};
float moisturePastAverage[DAILYITERATIONS] = {0};
int counter2 = 0;
float timer = 0;
float activeData[2];
char address = '2';
void setup() {
Serial.begin(9600);
randomSeed(analogRead(0));
timer = millis();
}
float readLight(){
int data = analogRead(A0);
return convertData(data);
}
float readMoisture(){
int data = analogRead(A1);
return convertData(data);
}
float convertData(float data){
return (float)map(data, 1023, 0, 0, 100);
}
int i = 0;
void loop() {
/*for (int i = 0; i < DATAPOINTS; i++){
//storage[i] = generate(1);
//Serial.println(storage[i]);
storage[i] = readLight();
delay(100);
counter += storage[i];
}*/
if(millis() - timer > 100){
timer = millis();
storage[i] = readLight();
moistureStorage[i] = readMoisture();
counter += storage[i];
moistureCounter += moistureStorage[i];
i++;
}
if(i >= DATAPOINTS){
i = 0;
float average = counter / DATAPOINTS;
float moistureAverage = moistureCounter / DATAPOINTS;
//Serial.println("AVERAGE:");
//Serial.println(average);
pastAverages[counter2] = average;
moisturePastAverage[counter2] = moistureAverage;
counter2 += 1;
//Serial.println(counter2);
counter = 0;
moistureCounter = 0;
}
int flag = 0;
int moistureFlag = 0;
if (counter2 > 6){
for (int i = 1; i < 3; i++){
if (abs(pastAverages[counter2] - pastAverages[counter2 - i]) >= TOLERANCE){
flag = 1;
if (abs(moisturePastAverage[counter2] - moisturePastAverage[counter2 - i]) >= TOLERANCE){
moistureFlag = 1;
}
}
}
if (flag == 1 || counter2 <= 6){
//Serial.println("Temperature: ");
//Serial.println(pastAverages[counter2]);
activeData[0] = pastAverages[counter2-1];
}
if (moistureFlag == 1 || counter2 <= 6){
//Serial.println("Temperature: ");
//Serial.println(pastAverages[counter2]);
activeData[1] = moisturePastAverage[counter2-1];
}
if(Serial.available()){
char c = Serial.read();
if(c == address){
Serial.print("light/");
Serial.print(activeData[0]);
Serial.print("/moisture/");
Serial.print(activeData[1]);
Serial.print("\\\n\r");
}
}
}
}
float generate(int num){
float randNumber = random(100);
delay(100);
return randNumber / 15.00 + 200.00 / 8.00;
}
//NOTES
//use the sensor every 6 seconds and store temperature / humidity as a datapoint
//once there are 10 datapoints, compute average
//We must first include in the loop to check the last 5 displayed temperatures and
//and whether its displayAverage5 is within TOLERANCE of the average. If so, keep the displayed
//temperature the same and wipe the data points
//else{
//if abs(average - oldaverage) >= TOLERANCE
// oldAverage = average
// return oldAverage to the display
//else
//for (int i = 0; i < DATAPOINTS; i++){
//storage[i] = 0;
//}
// We will keep the displayed temperature the same while it isn't updated
//}
//random number generator
| 24.214765
| 95
| 0.647727
|
230d7ccf2cbea88562bbb22a1f01cd18867959d9
| 2,337
|
ino
|
Arduino
|
layout_initializer/layout_initializer.ino
|
aziddy/AZK-MacroKeyboard-Platform
|
d4179f390d62e5807a33befe4d0339ba45add672
|
[
"CC0-1.0"
] | null | null | null |
layout_initializer/layout_initializer.ino
|
aziddy/AZK-MacroKeyboard-Platform
|
d4179f390d62e5807a33befe4d0339ba45add672
|
[
"CC0-1.0"
] | null | null | null |
layout_initializer/layout_initializer.ino
|
aziddy/AZK-MacroKeyboard-Platform
|
d4179f390d62e5807a33befe4d0339ba45add672
|
[
"CC0-1.0"
] | null | null | null |
#include <Arduino.h>
#include <EEPROM.h>
#include <Keyboard.h>
/* Related Code Documents:
* https://www.arduino.cc/en/Reference/EEPROMObject
*/
#define number_of_keys 4
int key[127][4];
void setup() {
delay(5000);
initialize_serial();
/* special key definitions can be founder here
* https://github.com/arduino-libraries/Keyboard/blob/master/src/Keyboard.h
* (MAC) command ⌘ == KEY_LEFT_GUI
*/
/*
* Four, 8bit EEPROM spaces are allocated to each key to allow for shortcut combinations up to 4 keys
*/
// 2 key layout
key[0][0] = KEY_LEFT_CTRL;
key[0][1] = KEY_LEFT_SHIFT;
key[0][2] = 'M';
key[0][3] = 0;
key[1][0] = KEY_LEFT_CTRL;
key[1][1] = KEY_LEFT_SHIFT;
key[1][2] = 'D';
key[1][3] = 0;
// 4 key layout
key[2][0] = 0xB0;
key[2][1] = 0;
key[2][2] = 0;
key[2][3] = 0;
key[3][0] = 0xEA;
key[3][1] = 0;
key[3][2] = 0;
key[3][3] = 0;
write_eeprom();
serial_report_eeprom();
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
// DONT NEED TO EDIT CODE BELOW
void write_eeprom(){
// First EEPROM index specifies how many keys the layout has
EEPROM[0] = number_of_keys;
for(int i = 0; i < number_of_keys; i++ ){
EEPROM[1+(i*4)] = key[i][0];
EEPROM[2+(i*4)] = key[i][1];
EEPROM[3+(i*4)] = key[i][2];
EEPROM[4+(i*4)] = key[i][3];
}
}
void serial_report_eeprom(){
Serial.print("Number of Keys ");
int numberOfKeys = EEPROM[0];
Serial.println(numberOfKeys);
Serial.println("");
Serial.println("/////////////////");
Serial.println("");
for(int i = 0; i < numberOfKeys; i++ ){
Serial.print("Key ");
Serial.print(i);
Serial.print(": ");
Serial.print(EEPROM[1+(i*4)], HEX);
Serial.print("-");
Serial.print(EEPROM[2+(i*4)], HEX);
Serial.print("-");
Serial.print(EEPROM[3+(i*4)], HEX);
Serial.print("-");
Serial.println(EEPROM[4+(i*4)], HEX);
Serial.println("");
Serial.println("/////////////////");
Serial.println("");
}
}
void initialize_serial(){
Serial.begin(9600);
while (!Serial) {
// wait for serial port to connect. Needed for Native USB only
}
Serial.println("Serial Initialized");
}
void loop(){
}
| 19.475
| 104
| 0.536157
|
9693122920e011a82f95df35a9ee04b9a9aa2541
| 4,487
|
ino
|
Arduino
|
biometric_identification/src/calc_circumference_online/calc_circumference.ino
|
banacer/lab221
|
7096233877c6b73719c1352ecd8d1896ac858d0d
|
[
"MIT"
] | 1
|
2016-05-08T06:32:24.000Z
|
2016-05-08T06:32:24.000Z
|
biometric_identification/src/calc_circumference_online/calc_circumference.ino
|
banacer/lab221
|
7096233877c6b73719c1352ecd8d1896ac858d0d
|
[
"MIT"
] | null | null | null |
biometric_identification/src/calc_circumference_online/calc_circumference.ino
|
banacer/lab221
|
7096233877c6b73719c1352ecd8d1896ac858d0d
|
[
"MIT"
] | null | null | null |
#include <XBee.h>
#include <math.h>
#include "Timer.h"
Timer t;
int pingPin[3] = {3, 5, 7};
short inc = 0, Pin;
XBee xbee = XBee();
// allocate three bytes for to hold a 10-bit analog reading
uint8_t payload[3];
// with Series 1 you can use either 16-bit or 64-bit addressing
// 16-bit addressing: Enter address of remote XBee, typically the coordinator
Tx16Request tx = Tx16Request(0x2210, payload, sizeof(payload));
struct point {
double x;
double y;
};
TxStatusResponse txStatus = TxStatusResponse();
int statusLed = 11;
int errorLed = 12;
short temp = 0, lowest, tempInch = 0, refVal = 11;
float inches, cm;
short duration = 0;
float w_max = 145.0;
short started = 0;
short done = 0;
double ul = 0;
double ur = 0;
double first = 0;
double last = 0;
struct point l_prev,r_prev;
double left_sum = 0, right_sum = 0;
double length = 0;
double circumference = 0;
short s_circum = 0;
float time2cm(float duration)
{
cm = duration/29.0/2.0;
return cm;
}
void getDuration()
{
pinMode(Pin, OUTPUT);
digitalWrite(Pin, LOW);
delayMicroseconds(2);
digitalWrite(Pin, HIGH);
delayMicroseconds(5);
digitalWrite(Pin, LOW);
pinMode(Pin, INPUT);
duration = pulseIn(Pin, HIGH);
//return duration;
}
double euclideanDistance(struct point a, struct point b)
{
return sqrt(pow(a.x-b.x,2) + pow(a.y-b.y,2));
}
void setup()
{
Serial.begin(9600);
xbee.setSerial(Serial);
l_prev.x = 0;
l_prev.y = 0;
r_prev.x = 0;
r_prev.y = 0;
}
void loop()
{
Pin = pingPin[inc];
getDuration();
cm = time2cm(duration);
if(inc == 3)
{
length+= 0.08*13;
if(cm >= w_max) //IGNORE THIS READING
{
//length = 0;
//w_max = cm;
}
else if(cm <= 0.7*w_max)
{
ul = cm;
}
else if (0.9*w_max <= cm && cm <= 0.99*w_max) // THIS MAY MEAN THAT NO ONE IS PASSING BY
{
//INITIALIZE ALL VARIABLES AND FINISH UP THE CALCULATION IF NOT YET DONE
if(first != 0 && last != 0)
{
if(right_sum > 0)
{
circumference = left_sum + right_sum + first +last + 10;
//SENDING THE CIRCUMFERENCE
s_circum = (short) circumference;
payload[0] = 6;
payload[1] = s_circum >> 8 & 0xff;
payload[2] = s_circum & 0xff;
xbee.send(tx);
//cout << "circumference: " << circumference << ", left: " << left_sum << ", right: " << right_sum << ", first: " << first << ", last: " << last << endl;
//cout << "circumference: "<< circumference << endl;
}
//printf("circumference = %f\n",circumference);
//INITIALIZING VARIABLES
length = 0;
left_sum = 0;
right_sum = 0;
r_prev.x = 0;
r_prev.y = 0;
l_prev.x = 0;
l_prev.y = 0;
first = 0;
last = 0;
}
}
}
if(inc == 4)
{
length+= 0.08;
if(cm <= 0.7*w_max && ul > 0)
{
ur = cm;
double width = w_max - ur - ul;
if(width > 0)
{
if(first == 0 || (length - r_prev.y) > 10)// the second condition is when the first is very noted long go
{
first = width;
//cout << "first: " <<first << ", length: " << length << endl;
}
else
last = width;
//now compute the lengths
struct point r_current,l_current;
if(r_prev.y == 0 && l_prev.y == 0) // THIS IS BECAUSE IT THE FIRST POINT SO JUST SAVE IT IN THE PREVIOUS TO BE USE IN THE NEXT ROUND
{
r_prev.x = width/2;
r_prev.y = length;
l_prev.x = width/2;
l_prev.y = length;
}
else
{
r_current.x = width/2;
r_current.y = length;
l_current.x = width/2;
l_current.y = length;
if((l_current.y - l_prev.y) < 5.0)
{
//cout << "width: " << width << ", ur: " << ur <<", ul: " << ul << ", length: "<< length <<endl;
left_sum += euclideanDistance(l_current,l_prev);
right_sum += euclideanDistance(r_current,r_prev);
}
else
{
left_sum = 0;
right_sum = 0;
}
r_prev.x = r_current.x;
r_prev.y = r_current.y;
l_prev.x = l_current.x;
l_prev.y = l_current.y;
}
}
}
}
inc++;
inc = inc % 3;
}
| 23.369792
| 159
| 0.520392
|
2506f4a466746a6a3b945b22c13cb9faa364b151
| 4,655
|
ino
|
Arduino
|
esp_lego_motor/source.ino
|
jmettraux/arduini
|
62e7a992d04d32f88fd463955bc0b300df969b89
|
[
"MIT"
] | null | null | null |
esp_lego_motor/source.ino
|
jmettraux/arduini
|
62e7a992d04d32f88fd463955bc0b300df969b89
|
[
"MIT"
] | null | null | null |
esp_lego_motor/source.ino
|
jmettraux/arduini
|
62e7a992d04d32f88fd463955bc0b300df969b89
|
[
"MIT"
] | null | null | null |
#include <ESP8266WiFi.h>
#include ".wifi.h"
WiFiServer server(80);
void motorStop() {
digitalWrite(D5, LOW); digitalWrite(D6, LOW); digitalWrite(D7, LOW);
digitalWrite(D0, LOW); digitalWrite(D1, LOW); digitalWrite(D2, LOW);
}
void motorForward() {
digitalWrite(D5, HIGH); digitalWrite(D6, LOW); digitalWrite(D7, HIGH);
digitalWrite(D0, LOW); digitalWrite(D1, HIGH); digitalWrite(D2, HIGH);
delay(1000); motorStop();
}
void motorBackward() {
digitalWrite(D5, LOW); digitalWrite(D6, HIGH); digitalWrite(D7, HIGH);
digitalWrite(D0, HIGH); digitalWrite(D1, LOW); digitalWrite(D2, HIGH);
delay(1000); motorStop();
}
void motorLeft() {
digitalWrite(D5, HIGH); digitalWrite(D6, LOW); digitalWrite(D7, HIGH);
digitalWrite(D0, HIGH); digitalWrite(D1, LOW); digitalWrite(D2, HIGH);
delay(250); motorStop();
}
void motorRight() {
digitalWrite(D5, LOW); digitalWrite(D6, HIGH); digitalWrite(D7, HIGH);
digitalWrite(D0, LOW); digitalWrite(D1, HIGH); digitalWrite(D2, HIGH);
delay(250); motorStop();
}
void setup() {
pinMode(D5, OUTPUT);
pinMode(D6, OUTPUT);
pinMode(D7, OUTPUT); // EN1,2
pinMode(D0, OUTPUT);
pinMode(D1, OUTPUT);
pinMode(D2, OUTPUT); // EN3,4
motorStop();
// Kick in serial
Serial.begin(115200);
delay(10);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(WIFI_SSID);
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if ( ! client) return;
// Wait until the client sends some data
Serial.println("new client");
while ( ! client.available()) delay(1);
// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
// Match the request
if (request.indexOf("/FORWARD") != -1) motorForward();
else if (request.indexOf("/BACKWARD") != -1) motorBackward();
else if (request.indexOf("/LEFT") != -1) motorLeft();
else if (request.indexOf("/RIGHT") != -1) motorRight();
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<head>");
client.println("<style>");
client.println(" body {");
client.println(" font-size: 200%;");
client.println(" }");
client.println(" table {");
client.println(" width: 100%;");
client.println(" }");
client.println(" td {");
client.println(" width: 49%;");
client.println(" text-align: center;");
client.println(" height: 7em;");
client.println(" pointer: cursor;");
client.println(" color: white;");
client.println(" }");
client.println(" td.forward {");
client.println(" background-color: blue;");
client.println(" }");
client.println(" td.backward {");
client.println(" background-color: green;");
client.println(" }");
client.println(" td.left {");
client.println(" background-color: green;");
client.println(" }");
client.println(" td.right {");
client.println(" background-color: blue;");
client.println(" }");
client.println("</style>");
client.println("</head>");
client.println("<table>");
client.println(" <tr>");
client.println(" <td class=\"forward\" onclick=\"forward();\">FORWARD</td>");
client.println(" <td class=\"backward\" onclick=\"backward();\">BACKWARD</td>");
client.println(" </tr>");
client.println(" <tr>");
client.println(" <td class=\"left\" onclick=\"left();\">LEFT</td>");
client.println(" <td class=\"right\" onclick=\"right();\">RIGHT</td>");
client.println(" </tr>");
client.println("</table>");
client.println("<script>");
client.println(" function forward() { window.location.href = '/FORWARD'; }");
client.println(" function backward() { window.location.href = '/BACKWARD'; }");
client.println(" function left() { window.location.href = '/LEFT'; }");
client.println(" function right() { window.location.href = '/RIGHT'; }");
client.println("</script>");
client.println("</html>");
delay(1);
Serial.println("Client disconnected");
Serial.println("");
}
| 28.558282
| 85
| 0.63652
|
80a005cc03b4d565cf1a2d7d7db489b04488408a
| 1,407
|
ino
|
Arduino
|
_secundaria/luces-de-feria/arduino.ino
|
chetosvsgeez/elcableamarillo.github.io
|
3313e872650f6f7530e1d106e9ef28b88e947bf8
|
[
"MIT"
] | 1
|
2019-08-20T10:02:47.000Z
|
2019-08-20T10:02:47.000Z
|
_secundaria/luces-de-feria/arduino.ino
|
chetosvsgeez/elcableamarillo.github.io
|
3313e872650f6f7530e1d106e9ef28b88e947bf8
|
[
"MIT"
] | null | null | null |
_secundaria/luces-de-feria/arduino.ino
|
chetosvsgeez/elcableamarillo.github.io
|
3313e872650f6f7530e1d106e9ef28b88e947bf8
|
[
"MIT"
] | null | null | null |
int pinArray[] = {4,5, 6, 7,8,9,10,11,12};
int count = 1;
int espera = 100;
void setup(){
for (count=1; count<9; count++){
pinMode(pinArray[count], OUTPUT);
}
}
void loop(){
for (count=1;count<9;count++) {
digitalWrite(pinArray[count], HIGH);
delay(espera);
digitalWrite(pinArray[count], LOW);
delay(espera);
}
for (count=9;count>=1;count--) {
digitalWrite(pinArray[count], HIGH);
delay(espera);
digitalWrite(pinArray[count], LOW);
delay(espera);
}
for (count=1;count<9;count++) {
digitalWrite(pinArray[count], HIGH);
delay(espera);
digitalWrite(pinArray[count + 1], HIGH);
delay(espera);
digitalWrite(pinArray[count], LOW);
delay(espera*2);
}
for (count=9;count>1;count--) {
digitalWrite(pinArray[count], HIGH);
delay(espera);
digitalWrite(pinArray[count - 1], HIGH);
delay(espera);
digitalWrite(pinArray[count], LOW);
delay(espera*2);
}
for (count=1;count<4;count++) {
digitalWrite(pinArray[count], HIGH);
digitalWrite(pinArray[count+3], HIGH);
digitalWrite(pinArray[count+6], HIGH);
delay(300);
digitalWrite(pinArray[count], LOW);
digitalWrite(pinArray[count+3], LOW);
digitalWrite(pinArray[count+6], LOW);
delay(300);
}
}
| 28.14
| 48
| 0.567164
|
9c0c280abb966482490a6599eafcaadbaeda0d1f
| 2,517
|
ino
|
Arduino
|
ENGR1357_Project.ino
|
lukasbuse4/ENGR-Autonomous-Robot
|
57d5b0f14dc15a1465f5be37dc58195468a3eabb
|
[
"BSD-3-Clause"
] | null | null | null |
ENGR1357_Project.ino
|
lukasbuse4/ENGR-Autonomous-Robot
|
57d5b0f14dc15a1465f5be37dc58195468a3eabb
|
[
"BSD-3-Clause"
] | null | null | null |
ENGR1357_Project.ino
|
lukasbuse4/ENGR-Autonomous-Robot
|
57d5b0f14dc15a1465f5be37dc58195468a3eabb
|
[
"BSD-3-Clause"
] | null | null | null |
#include <Servo.h>
void navigate_maze();
int find_hole();
void speed_changer(int);
void side_speed_changer(int);
void reset_pos(int);
Servo front_right_wheel;
#define echoPin 7 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 8 //attach pin D3 Arduino to pin Trig of HC-SR04
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
// Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
// Serial.println("with Arduino UNO R3");
void setup()
{
// put your setup code here, to run once:
front_right_wheel.attach();
navigate_maze();
}
void loop()
{
// put your main code here, to run repeatedly:
}
void navigate_maze()
{
int drive_back = find_hole();
reset(drive_back);
drive_back = find_hole();
reset(drive_back);
}
int find_hole()
{
int delay_cntr;
side_speed_changer(88);
//set wheels to a certain speed(needs to be slow, 90 being no movement)
while(true)
{
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(5);
delay_cntr += 5;
if(distance > 10)
{
side_speed_changer(90);
//set speed to 0;
break;
}
}
//drive forward
return delay_cntr;
}
void speed_changer(int spd)
{
//sets speed based on passed in value
//depending on how the wheels are set up the value might
//have to be inverse on one side, need to come up with logic for that
//probably something like - int inverse_spd = -1*(180 - spd);
}
void side_speed_changer(int spd)
{
//set middle wheel to whatever speed is passed in
}
void reset_pos(int drive_back)
{
speed_changer(92);
delay(drive_back);
return;
}
| 22.473214
| 90
| 0.686929
|
8562d1a25919b599f9a1ef3451062032433f6947
| 706
|
ino
|
Arduino
|
_tutorials/ir-emitter/ir-emitter.ino
|
AvinashPudale/port
|
ae62f709eb9f32c367ea39a5e378c94185853f9c
|
[
"MIT"
] | 27
|
2019-07-25T04:03:13.000Z
|
2022-03-12T09:56:21.000Z
|
_tutorials/ir-emitter/ir-emitter.ino
|
AvinashPudale/port
|
ae62f709eb9f32c367ea39a5e378c94185853f9c
|
[
"MIT"
] | 14
|
2019-07-17T03:46:32.000Z
|
2022-03-17T07:54:37.000Z
|
_tutorials/ir-emitter/ir-emitter.ino
|
AvinashPudale/port
|
ae62f709eb9f32c367ea39a5e378c94185853f9c
|
[
"MIT"
] | 18
|
2019-10-05T14:12:45.000Z
|
2021-12-09T10:36:54.000Z
|
#include <IRLibAll.h>
IRrecvPCI myReceiver(2); // Arduino UNO PIN 2
IRdecode myDecoder;
IRsend mySender;
void setup() {
Serial.begin(9600);
myReceiver.enableIRIn();
Serial.println("Ready to receive IR signals...");
Serial.println("Ready to receive character into the serial monitor...");
}
void loop() {
if (myReceiver.getResults()) {
myDecoder.decode();
myDecoder.dumpResults(true);
myReceiver.enableIRIn();
}
// Send a character into the serial monitor
if (Serial.read() != -1) {
// Decoded NEC(1): Value:CE01F Adrs:0 (32 bits)
mySender.send(NEC, 0xce01f, 32); // Get the HEX code with IR receiver
Serial.println("Sent Eco Blank to the projector");
}
}
| 22.774194
| 74
| 0.672805
|
e91b9010c07730b912ff0f361e360b4495e07ace
| 2,612
|
ino
|
Arduino
|
HHH_UIT/bai1/OLP_1.ino
|
OLP-FOSS/OLP-FOSS-2017
|
8c760c7cf1e81564b6ed00b0b539fa5b20f586ce
|
[
"Apache-2.0"
] | 2
|
2018-09-10T12:27:15.000Z
|
2018-10-20T06:35:00.000Z
|
HHH_UIT/OLP_1.ino
|
OLP-FOSS/OLP-FOSS-2017
|
8c760c7cf1e81564b6ed00b0b539fa5b20f586ce
|
[
"Apache-2.0"
] | 1
|
2017-12-07T07:17:45.000Z
|
2017-12-07T07:17:45.000Z
|
HHH_UIT/bai1/OLP_1.ino
|
OLP-FOSS/OLP-FOSS-2017
|
8c760c7cf1e81564b6ed00b0b539fa5b20f586ce
|
[
"Apache-2.0"
] | 19
|
2017-12-07T00:42:54.000Z
|
2018-11-28T11:23:25.000Z
|
// Import required libraries
#include "ESP8266WiFi.h"
#include "DHT.h"
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <WiFiServer.h>
#include <WiFiUdp.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h"
// DHT11 sensor pins
#define DHTPIN 5
#define DHTTYPE DHT11
#define LEDPIN 4
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE, 15);
const char* device_id = "team06";
// WiFi parameters
const char* ssid = "Pyrus";
const char* password = "741456963";
const char* server = "192.168.43.61";
WiFiClient espClient;
PubSubClient mqttclient(espClient);
// Variables to be exposed to the API
float temperature;
float humidity;
void connect_wifi();
void callback(char* topic, byte* payload, unsigned int length);
void setup(void)
{
// Start Serial
Serial.begin(115200);
// WIFI-connect
connect_wifi();
// Init DHT
dht.begin();
pinMode(LEDPIN, OUTPUT);
//mqtt-init
mqttclient.setServer(server,1883);
reconnect();
mqttclient.setCallback(callback);
mqttclient.subscribe("LED");
Serial.println("Waiting...");
}
void loop() {
reconnect();
// Reading temperature and humidity
humidity = dht.readHumidity();
temperature = dht.readTemperature();
char buff_hu[10];
dtostrf(humidity,0,0,buff_hu);
char buff_te[10];
dtostrf(temperature,0,0,buff_te);
Serial.print("HUD:");
Serial.println(humidity);
Serial.print("TEM:");
Serial.println(temperature);
reconnect();
mqttclient.publish("TEMP",buff_te);
mqttclient.publish("HUMI",buff_hu);
mqttclient.loop();
delay(1000);
}
void connect_wifi(){
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
while (!mqttclient.connected()) {
Serial.print("Trying MQTT connection...");
if (mqttclient.connect(device_id)) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.println(mqttclient.state());
delay(5000);
}
}
}
void callback(char* topic, byte* payload, unsigned int length)
{
String inString="";
for (int i = 0; i < length; i++) {
inString += (char)payload[i];
}
if(inString == "ON"){
digitalWrite(LEDPIN, HIGH);
Serial.println("TRUE");
}
if(inString == "OFF"){
digitalWrite(LEDPIN, LOW);
Serial.println("False");
}
}
| 20.248062
| 63
| 0.667688
|
30dd6f6e259103ee455bc81c915ad7576a3aa53c
| 4,234
|
ino
|
Arduino
|
Files/EEPROM_Programmer/ControlUnit/functions.ino
|
cepdnaclk/e15-co221-SAP-I-Computer
|
ccef2d452ca80bb8034829272c982778cb88951d
|
[
"Apache-2.0"
] | null | null | null |
Files/EEPROM_Programmer/ControlUnit/functions.ino
|
cepdnaclk/e15-co221-SAP-I-Computer
|
ccef2d452ca80bb8034829272c982778cb88951d
|
[
"Apache-2.0"
] | null | null | null |
Files/EEPROM_Programmer/ControlUnit/functions.ino
|
cepdnaclk/e15-co221-SAP-I-Computer
|
ccef2d452ca80bb8034829272c982778cb88951d
|
[
"Apache-2.0"
] | null | null | null |
void debug() {
Serial.println(">> Debug\n");
char address[8] = {};
char binary[17] = {};
address[7] = '\0';
binary[16] = '\0';
setWriteMode();
for (int i = 0; i < 16; i++) {
// Write each Instruction
for (int j = 0; j < 8; j++) {
// Write each Machine Code
Serial.print("write >\t");
setWriteMode();
writeAddress(i * 8 + j);
delay(10);
writeOutput(data[i * 8 + j]);
delay(10);
//--- Debug Section ----------------------------------------------
//if (data[i * 8 + j] == 0 )continue;
for (int k = 0; k < 7; k++) {
address[k] = (bitRead(i * 8 + j, 6 - k) == 1) ? '1' : '0' ;
if (k == 4)Serial.print(' ');
Serial.print(address[k]);
}
Serial.print(":\t");
for (int k = 0; k < 16; k++) {
binary[k] = (bitRead(i * 8 + j, 15 - k) == 1) ? '1' : '0' ;
if (k == 8)Serial.print(' ');
Serial.print(binary[k]);
}
Serial.print("\n");
//--- Read Section ----------------------------------------------
setReadMode();
uint16_t dataRead = readOutput();
Serial.print("read >\t");
for (int k = 0; k < 7; k++) {
address[k] = (bitRead(i * 8 + j, 6 - k) == 1) ? '1' : '0' ;
if (k == 4)Serial.print(' ');
Serial.print(address[k]);
}
Serial.print(":\t");
for (int k = 0; k < 16; k++) {
binary[k] = (bitRead(dataRead, 15 - k) == 1) ? '1' : '0' ;
if (k == 8)Serial.print(' ');
Serial.print(binary[k]);
}
Serial.print("\n");
}
Serial.println();
Serial.println();
}
setReadMode();
}
void writeData() {
Serial.println(">> Write data to EEPROM\n");
char address[8] = {};
char binary[17] = {};
address[7] = '\0';
binary[16] = '\0';
setWriteMode();
for (int i = 0; i < 16; i++) {
// Write each Instruction
for (int j = 0; j < 8; j++) {
// Write each Machine Code
Serial.print("write >\t");
setWriteMode();
writeAddress(i * 8 + j);
delay(10);
writeOutput(data[i * 8 + j]);
delay(10);
//--- Debug Section ----------------------------------------------
//if (data[i * 8 + j] == 0 )continue;
for (int k = 0; k < 7; k++) {
address[k] = (bitRead(i * 8 + j, 6 - k) == 1) ? '1' : '0' ;
if (k == 4)Serial.print(' ');
Serial.print(address[k]);
}
Serial.print(":\t");
for (int k = 0; k < 16; k++) {
binary[k] = (bitRead(data[i * 8 + j], 15 - k) == 1) ? '1' : '0' ;
if (k == 8)Serial.print(' ');
Serial.print(binary[k]);
}
Serial.print("\n");
//--- Read Section ----------------------------------------------
setReadMode();
uint16_t dataRead = readOutput();
Serial.print("read >\t");
for (int k = 0; k < 7; k++) {
address[k] = (bitRead(i * 8 + j, 6 - k) == 1) ? '1' : '0' ;
if (k == 4)Serial.print(' ');
Serial.print(address[k]);
}
Serial.print(":\t");
for (int k = 0; k < 16; k++) {
binary[k] = (bitRead(dataRead, 15 - k) == 1) ? '1' : '0' ;
if (k == 8)Serial.print(' ');
Serial.print(binary[k]);
}
Serial.print("\n");
}
Serial.println();
Serial.println();
}
setReadMode();
}
void readData() {
Serial.println(">> Read data from EEPROM\n");
char address[8] = {};
char binary[17] = {};
address[7] = '\0';
binary[16] = '\0';
setReadMode();
for (int i = 0; i < 16; i++) {
// Write each Instruction
for (int j = 0; j < 8; j++) {
// Write each Machine Code
writeAddress(i * 8 + j);
delay(10);
uint16_t dataRead = readOutput();
//if (dataRead == 0 )continue;
for (int k = 0; k < 7; k++) {
address[k] = (bitRead(i * 8 + j, 6 - k) == 1) ? '1' : '0' ;
if (k == 4)Serial.print(' ');
Serial.print(address[k]);
}
Serial.print(":\t");
for (int k = 0; k < 16; k++) {
binary[k] = (bitRead(dataRead, 15 - k) == 1) ? '1' : '0' ;
if (k == 8)Serial.print(' ');
Serial.print(binary[k]);
}
Serial.print("\n");
}
Serial.println();
}
}
| 22.641711
| 73
| 0.42017
|
124ebfdb16122d0d58c078e03bc0973e3c69bb72
| 5,744
|
ino
|
Arduino
|
src_code/Open Loop/Openloop_SAT2_main/Openloop_SAT2_main.ino
|
ajinsunny/EAS_Code
|
9139370e96a0933cf9c8a89a30e5b76364d17a51
|
[
"Apache-2.0"
] | 1
|
2019-12-07T20:20:46.000Z
|
2019-12-07T20:20:46.000Z
|
src_code/Open Loop/Openloop_SAT2_main/Openloop_SAT2_main.ino
|
ajinsunny/Single-Degree-of-Freedom-Experiments-Demonstrating-Electromagnetic-Formation-Flying-for-Small-Satell
|
9139370e96a0933cf9c8a89a30e5b76364d17a51
|
[
"Apache-2.0"
] | null | null | null |
src_code/Open Loop/Openloop_SAT2_main/Openloop_SAT2_main.ino
|
ajinsunny/Single-Degree-of-Freedom-Experiments-Demonstrating-Electromagnetic-Formation-Flying-for-Small-Satell
|
9139370e96a0933cf9c8a89a30e5b76364d17a51
|
[
"Apache-2.0"
] | 1
|
2020-01-17T03:08:34.000Z
|
2020-01-17T03:08:34.000Z
|
/*
Small Satellite Position Control Software.
Filename: Open_Loop_SAT2_main.ino
Author: Ajin Sunny
Last Modified by: Ajin Sunny
Written for Thesis: One dimensional Electromagnetic Actuation and Pulse Sensing.
Version: 1.0
Date: 02-25-2019
Last Updated: 05-24-2019
*/
//HEADER FILES
#include <DueTimer.h>
#include <SineWaveDue.h>
#include <SD.h>
#include <SPI.h>
#include <VL53L0X.h>
#include "Arduino.h"
#include "DFRobot_VL53L0X.h"
char incomingByte;
DFRobotVL53L0X sensor; //SENSOR OBJECT
File myFile; // FILE OBJECT
unsigned long period = 50000;
double dist[8] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0};
unsigned int i = 0;
double V_final = 0.0;
double velocity_final_final = 0.0;
double velocity_final[8] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0};
double vel[8] = {0.0,0.0,0.0,0.0,0.0,0.0,0.0};
double previous_velocity = 0.0;
double current_velocity = 0.0;
float Amplitude;
double a = 0.9;
void setup()
{
analogReadResolution(10);
analogWriteResolution(10);
pinMode(9, OUTPUT);
Serial.begin(115200);
//delay(20000);
while (!Serial)
{
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Initializing SD card...");
// see if the card is present and can be initialized:
if (!SD.begin(4)) {
Serial.println("Card failed, or not present");
// don't do anything more:
while (1);
}
Serial.println("card initialized.");
Wire.begin();
//Set I2C sub-device address
sensor.begin(0x50);
//Set to Back-to-back mode and high precision mode
sensor.setMode(Continuous, High);
//Laser rangefinder begins to work
sensor.start();
myFile = SD.open("sat2.csv", FILE_WRITE);
myFile.println(" ");
myFile.print("Time");
myFile.print(",");
myFile.print("Distance");
myFile.print(",");
myFile.print("Velocity");
myFile.print(",");
myFile.print("Digital Amplitude");
myFile.print(",");
myFile.println("Amplitude");
while(Serial.available()==0){}
incomingByte = Serial.read();
if(incomingByte == 'A')
{
Serial.println(incomingByte);
}
}
void loop()
{
S.startSinusoid1(10);
while(millis() < period)
{
if(myFile)
{
//delay(50);
// //Serial.print("Voltage value: ");
// //Serial.println(S.return_voltage());
//dist[i] = sensorRead();
// double disp = sensor.getDistance()/10;
// Serial.println(disp);
//i++;
V_final = velocity_func();
Serial.print("Time: ");
Serial.println(millis());
myFile.print(millis());
myFile.print(",");
Serial.print("Distance: ");
Serial.println(dist[i]);
myFile.print(dist[i]);
myFile.print(",");
Serial.print("Velocity: ");
Serial.println(V_final);
myFile.print(V_final);
Serial.print("Digital Amplitude: ");
Serial.println(S.returnAmplitude());
myFile.print(S.returnAmplitude());
myFile.print(",");
Amplitude = (S.returnAmplitude() * 2.16)/490;
Serial.print("Amplitude: ");
Serial.println(Amplitude);
myFile.println(Amplitude);
// Serial.print("Velocity: ");
// Serial.println(V_final);
// myFile.print(V_final);
// myFile.print(",");
// // myFile.print("Time: ");
// myFile.println(millis());
//
// //delay(1000);
}
}
myFile.close();
//SD.remove("sat2.csv");
S.stopSinusoid();
exit(0);
}
// sw.playTone2(1000, 1200);
// delay(1000);
// sw.stopTone();
// sw.playTone(5000, 1000);
// for( int i; i<10; i++){
// digitalWrite(9, HIGH);
// sw.playToneDecay(400, .1*i);
// delay(1000);
// digitalWrite(9, LOW);
// delay(100);
// }
//double velocity_func(double dist[2])
//{
// delta_pos = dist[i] - dist[i - 1];
// velocity = delta_pos/0.016;
// return velocity;
//}
/*------------- VELOCITY FUNCTION---------------*/
double velocity_func()
{
for(int k = 0; k < 8; k++)
{
dist[i] = sensordistRead(); // Captures the distance
if(dist[i] > 220.00)
{
dist[i] = dist[i-1];
}
vel[i] = (dist[i] - dist[i - 1])/0.038; // Calculates the velocity
current_velocity = vel[i+1]; // current velocity
previous_velocity = vel[i-1]; // previous velocity
velocity_final[i+1] = a*velocity_final[i] + (1-a)*current_velocity; // forward euler formula for the velocity.
velocity_final_final = velocity_final_final + velocity_final[i+1]; //sum the velocity to a double point variable.
// //Time
// Serial.print("Time: ");
// Serial.println(millis());
// myFile.print(millis());
// myFile.print(",");
//
// //Distance
// Serial.print("Distance: ");
// Serial.println(dist[i]);
// myFile.println(dist[i]);
// myFile.print(",");
if (i == 7)
{
dist[0]=dist[i-1]; //shifts the array back to the 0th element of the array.
vel[0] = vel[i-1];
velocity_final[0] = velocity_final[i-1];
i = 0; // sets the counter back to the first position.
}
i++;
}
// //Time
// Serial.print("Time: ");
// Serial.println(millis());
// myFile.print(millis());
// myFile.print(",");
//
// //Distance
// Serial.print("Distance: ");
// Serial.println(dist[i]);
// myFile.print(dist[i]);
// myFile.print(",");
velocity_final_final = velocity_final_final/7; //Average the velocity.
return velocity_final_final;
// //Velocity
// Serial.print("Velocity: ");
// Serial.println(velocity_final_final);
// myFile.println(velocity_final_final);
}
double sensordistRead()
{
double relative_dist;
relative_dist = ((sensor.getDistance()/10)+20);
return relative_dist;
}
| 23.255061
| 120
| 0.592444
|
156c64ef2337f6e5a8808037d796fda7aa9f11c6
| 985
|
ino
|
Arduino
|
Tone_RS-VS/Tone_RS-VS.ino
|
derfaq/Rolling-Shutter-Video-Synth
|
b5b2ef1ac443537f4e934fda1f105efb95d692c0
|
[
"CC-BY-4.0"
] | 1
|
2017-10-28T19:30:05.000Z
|
2017-10-28T19:30:05.000Z
|
Tone_RS-VS/Tone_RS-VS.ino
|
derfaq/Rolling-Shutter-Video-Synth
|
b5b2ef1ac443537f4e934fda1f105efb95d692c0
|
[
"CC-BY-4.0"
] | 1
|
2017-08-30T15:01:19.000Z
|
2017-08-30T15:01:19.000Z
|
Tone_RS-VS/Tone_RS-VS.ino
|
derfaq/Rolling-Shutter-Video-Synth
|
b5b2ef1ac443537f4e934fda1f105efb95d692c0
|
[
"CC-BY-4.0"
] | null | null | null |
/* Tone_RS-VS.ino
*
* A Very very simple Rolling Shutter Video Synth (RS-VS)
*
* Description
* This scketch generate a tone signal (square) over pin 5,
* With a frequencie wich depends on the value of one potentiometer
* conected to A0.
*
* The circuit:
* * One potentiometer connected to A0.
* Center pin of the potentiometer goes to the analog pin,
* side pins of the potentiometer go to +5V and ground
* * LED w/ 150 ~ 470 ohm resistor,
*/
#define LED_PIN 5
void setup() {
// initialize serial communications (for debugging only):
Serial.begin(9600);
}
void loop() {
// read the potentiometer:
int sensorReading = analogRead(A0);
Serial.println(sensorReading);
// map the analog input range
// to the output pitch range (31 - 1000 Hz)
int thisPitch = map(sensorReading, 0, 1023, 31, 1000);
// play the pitch:
tone(LED_PIN, thisPitch);
delay(10); // delay in between reads for stability
}
| 23.452381
| 70
| 0.657868
|
2e9c09fa0f2dbb98cd5857f6b16203c4e03c6a10
| 1,414
|
ino
|
Arduino
|
poli2_launch/scripts/arduino/sonar/sonar_driver/sonar_driver.ino
|
IsaacSheidlower/poli2
|
c44b4bfa1b470660b100ee1879adef23641086f5
|
[
"BSD-2-Clause"
] | null | null | null |
poli2_launch/scripts/arduino/sonar/sonar_driver/sonar_driver.ino
|
IsaacSheidlower/poli2
|
c44b4bfa1b470660b100ee1879adef23641086f5
|
[
"BSD-2-Clause"
] | 37
|
2017-06-16T17:37:53.000Z
|
2020-01-08T17:01:19.000Z
|
poli2_launch/scripts/arduino/sonar/sonar_driver/sonar_driver.ino
|
IsaacSheidlower/poli2
|
c44b4bfa1b470660b100ee1879adef23641086f5
|
[
"BSD-2-Clause"
] | 4
|
2018-09-07T18:02:22.000Z
|
2021-12-10T23:04:37.000Z
|
/*
* This file polls a single MaxBotix MB 1230 sonar and publishes data
* as a Range message.
* This is not a driver, but could be modified and called by a driver in the event
* that multiple devices are being polled by the arduino.
*
* NOTE: we assume the input voltage is 5V and not 3V, which requires a different conversion factor
*
* Author: Maxwell Svetlik 2017
*/
#include <ros.h>
#include <sensor_msgs/Range.h>
sensor_msgs::Range sonar_msg;
ros::Publisher pub_sonar("/sonar", &sonar_msg);
ros::NodeHandle nh;
const int anPin = 1;
long anVolt, mm;
void setup() {
nh.getHardware()->setBaud(115200);
nh.initNode();
nh.advertise(pub_sonar);
Serial.begin(115200);
sonar_msg.radiation_type = sonar_msg.ULTRASOUND;
sonar_msg.min_range = 0.2;
sonar_msg.max_range = 2.6;
sonar_msg.header.frame_id = "sonar_link_1";
sonar_msg.field_of_view = 0.306;
}
void read_sensor(){
anVolt = analogRead(anPin);
mm = anVolt * 10;
}
//serial monitor debug
void print_range(){
Serial.print("S1");
Serial.print("=");
Serial.print(mm);
}
void loop() {
read_sensor();
sonar_msg.header.stamp = nh.now();
sonar_msg.range = float(mm)/1000.0;
//for costmap clearing purposes, set range to max range
if(sonar_msg.range > sonar_msg.max_range)
sonar_msg.range = sonar_msg.max_range;
pub_sonar.publish(&sonar_msg);
//print_range();
delay(50);
nh.spinOnce();
}
| 23.180328
| 99
| 0.699434
|
7bc1b63f207c64ba44cdbf78b04f786ba586ddcc
| 5,170
|
ino
|
Arduino
|
mozziscout_chordorgan/mozziscout_chordorgan.ino
|
todbot/MozziScout
|
e20a61915154a367d2dbbb1f3cde8f547268cdbb
|
[
"MIT"
] | 18
|
2021-12-14T06:16:03.000Z
|
2022-01-23T17:05:50.000Z
|
mozziscout_chordorgan/mozziscout_chordorgan.ino
|
todbot/MozziScout
|
e20a61915154a367d2dbbb1f3cde8f547268cdbb
|
[
"MIT"
] | null | null | null |
mozziscout_chordorgan/mozziscout_chordorgan.ino
|
todbot/MozziScout
|
e20a61915154a367d2dbbb1f3cde8f547268cdbb
|
[
"MIT"
] | null | null | null |
/**
* MozziScout "Chord Organ"-like synth
* based on Music Thing Modular's Chord Organ
* https://musicthing.co.uk/pages/chord.html
*
* To change parameters:
* - Press high D# to increment chord
* - Press high C# to decrement chord
*
* MozziScout is just like normal Oskitone Scout,
* but pins 9 & 11 are swapped, so we can use Mozzi
*
* @todbot 21 Dec 2021
**/
#include <MozziGuts.h>
#include <Oscil.h>
#include <tables/triangle_analogue512_int8.h>
#include <tables/square_analogue512_int8.h>
#include <tables/saw_analogue512_int8.h>
#include <tables/cos2048_int8.h> // for filter modulation
#include <ADSR.h>
#include <Portamento.h>
#include <mozzi_midi.h> // for mtof()
#include <mozzi_rand.h> // for rand()
#include <Keypad.h>
// SETTINGS
#define NUM_VOICES 5
int octave = 2;
int detune = 50; // 50 sounds pretty good for octave 2
int portamento_time = 50; // milliseconds
int env_release_time = 750; // milliseconds
byte note_offset = 12 + (octave * 12) - 1; // FIXME
byte chord_id = 0;
// stolen from Chord Organ config page http://polyfather.com/chord_organ/
byte chord_notes[][5] = {
{0,4,7,12,0}, // 0 Major
{0,3,7,12,0}, // 1 Minor
{0,4,7,11,0}, // 2 Major 7th
{0,3,7,10,0}, // 3 Minor 7th
{0,4,7,11,14}, // 4 Major 9th
{0,3,7,10,14}, // 5 Minor 9th
{0,5,7,12,0}, // 6 Suspended 4th
{0,7,12,0,7}, // 7 Power 5th
{0,5,12,0,5}, // 8 Power 4th
{0,4,7,8,0}, // 9 Major 6gh
{0,3,7,8,0}, // 10 Minor 6th
{0,3,6,0,3}, // 11 Diminished
{0,4,8,0,4}, // 12
{0,0,0,0,0}, // 13 Root
{-12,-12,0,0,0}, // 14 2 down octave
{-12,0,0,12,24}, // 15 1 down oct, 1 up, 2 up oct
};
#define chord_count (sizeof(chord_notes) / sizeof(chord_notes[0]))
// Set up keyboard
const byte ROWS = 4;
const byte COLS = 5;
byte key_indexes[ROWS][COLS] = { // note this goes from 1-17, 0 is undefined
{1, 5, 9, 12, 15},
{2, 6, 10, 13, 16},
{3, 7, 11, 14, 17},
{4, 8}
};
byte rowPins[ROWS] = {7, 8, 11, 10}; // MozziScout: note pin 11 instead on 9 here
byte colPins[COLS] = {2, 3, 4, 5, 6};
Keypad keys = Keypad(makeKeymap(key_indexes), rowPins, colPins, ROWS, COLS);
// Set up keyboard done
Oscil<SAW_ANALOGUE512_NUM_CELLS, AUDIO_RATE> aOscs[ NUM_VOICES];
Oscil<COS2048_NUM_CELLS, CONTROL_RATE> kFilterMod(COS2048_DATA); // filter mod
ADSR <CONTROL_RATE, AUDIO_RATE> envelope;
Portamento <CONTROL_RATE> portamentos[NUM_VOICES];
byte note, last_note;
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
startMozzi();
for( int i=0; i<NUM_VOICES; i++) {
aOscs[i].setTable( SAW_ANALOGUE512_DATA );
portamentos[i].setTime(portamento_time);
}
envelope.setADLevels(255, 255);
envelope.setTimes(100, 200, 20000, env_release_time);
Serial.println("mozziscout_chordorgan");
}
// loop can only contain audioHook
void loop() {
audioHook();
}
// mozzi function, used to update modulation-rate things
void updateControl() {
scanKeys();
envelope.update();
for( int i=0; i<NUM_VOICES; i++) {
Q16n16 pf = portamentos[i].next(); // Q16n16 is a fixed-point fraction in 32-bits (16bits . 16bits)
aOscs[i].setFreq_Q16n16(pf);
//aOscs[i].setFreq_Q16n16(pf + Q7n8_to_Q15n16(rand(detune))); // this does not sound as good
}
}
// mozzi function, used to update audio
AudioOutput_t updateAudio() {
long asig = 0;
for ( int i = 0; i < NUM_VOICES; i++) {
asig += aOscs[i].next();
}
return MonoOutput::fromAlmostNBit(18, asig * envelope.next());
}
bool chord_switched = false;
// read the keys, trigger notes
void scanKeys() {
if ( !keys.getKeys() ) { return; } // no keys, get out
for (int k = 0; k < LIST_MAX; k++) { // Scan the whole key list.
//if ( !keys.key[k].stateChanged ) { continue; } // skip keys that haven't changed
byte key = keys.key[k].kchar;
byte kstate = keys.key[k].kstate;
if ( kstate == PRESSED || kstate == HOLD) {
note = note_offset + key;
Serial.print("chord:"); Serial.print((byte)chord_id); Serial.print(" key:"); Serial.print((byte)key); Serial.println(" presssed/hold");
digitalWrite(LED_BUILTIN, HIGH);
switch(key) {
case 14: // high C#
chord_id = (chord_id - 1) % chord_count;
note = last_note;
chord_switched = true;
break;
case 16: // high D#
chord_id = (chord_id + 1) % chord_count;
note = last_note;
chord_switched = true;
break;
default:
chord_switched = false;
} // switch
for( int i=0; i<NUM_VOICES; i++) {
portamentos[i].start(Q8n0_to_Q16n16(note + chord_notes[chord_id][i]) + Q7n8_to_Q15n16(rand(detune)));
//portamentos[i].start(Q8n0_to_Q16n16(note + chord_notes[chord_id][i]));
}
if( !chord_switched ) {
envelope.noteOn();
}
last_note = note;
}
else if( kstate == RELEASED ) {
Serial.print("chord:"); Serial.print((byte)chord_id); Serial.print(" key:"); Serial.print((byte)key); Serial.println(" released");
digitalWrite(LED_BUILTIN, LOW);
if( !chord_switched ) {
envelope.noteOff();
}
}
}
}
| 29.884393
| 141
| 0.624178
|
46e5e05b58dfe22e64c2febd6361f84609581ecb
| 273
|
ino
|
Arduino
|
Tests/test_servo_and_line/test_servo_and_line.ino
|
clm293/ece-3400-fa18
|
34f4a95b5b94647dd2c3d1c14924682ef631d4c3
|
[
"MIT"
] | 1
|
2020-11-25T21:24:26.000Z
|
2020-11-25T21:24:26.000Z
|
Tests/test_servo_and_line/test_servo_and_line.ino
|
PBC48/ECE-3400-Fall-2018
|
34f4a95b5b94647dd2c3d1c14924682ef631d4c3
|
[
"MIT"
] | 2
|
2020-04-30T12:57:24.000Z
|
2022-02-13T00:25:23.000Z
|
Tests/test_servo_and_line/test_servo_and_line.ino
|
clm293/ece-3400-fa18
|
34f4a95b5b94647dd2c3d1c14924682ef631d4c3
|
[
"MIT"
] | null | null | null |
#include "robot.h"
#include "line_sensor.h"
void setup(){
Serial.begin(9600);
robot_init();
line_sensor_init();
}
void loop(){
Serial.print("SL: ");Serial.print(AVERAGE_L);
Serial.print("--------SR: ");Serial.println(AVERAGE_R);
robot_calibrate();
}
| 17.0625
| 57
| 0.6337
|
ad90c675f3f796b43e76494334ba9cb7f2c60c5d
| 3,281
|
ino
|
Arduino
|
arduino_2_voltage_led/arduino_2_voltage_led.ino
|
craic/arduino_power
|
162dc8ba2b693e649d586a893b5e0c7be5fd57f3
|
[
"MIT"
] | 6
|
2016-12-16T12:18:43.000Z
|
2017-01-09T19:26:45.000Z
|
arduino_2_voltage_led/arduino_2_voltage_led.ino
|
craic/arduino_power
|
162dc8ba2b693e649d586a893b5e0c7be5fd57f3
|
[
"MIT"
] | null | null | null |
arduino_2_voltage_led/arduino_2_voltage_led.ino
|
craic/arduino_power
|
162dc8ba2b693e649d586a893b5e0c7be5fd57f3
|
[
"MIT"
] | null | null | null |
/*
arduino_power_2_voltage_led
Copyright 2016 Robert Jones Craic Computing LLC
Freely distributed under the terms of the MIT open source license
Uses the Adafruit PowerBoost 500C arduino shield
Measure voltage and display using an RGB led
*/
// Global variables for Arduino Power
const int arduinoPowerEnablePin = 8;
const int arduinoPowerButtonPin = 2;
const int arduinoPowerGreenLedPin = 6;
const int arduinoPowerRedLedPin = 7;
const int arduinoPowerVoltagePin = A0;
float arduinoPowerVoltage = 0.0;
// Note the volatile type - used to read the button state (not used here)
volatile int arduinoPowerButtonState = 0;
void arduinoPowerSetup() {
// Setup the pins
pinMode(arduinoPowerRedLedPin, OUTPUT);
pinMode(arduinoPowerGreenLedPin, OUTPUT);
pinMode(arduinoPowerButtonPin, INPUT);
pinMode(arduinoPowerEnablePin, OUTPUT);
// On Arduino boot, set the Enable Pin high - this keeps the PowerBoost On
digitalWrite(arduinoPowerEnablePin, HIGH);
// need to delay for three seconds to allow the Arduino to 'boot'
// before attaching the interrupt
delay(3000);
// Attach an interrupt to the ISR vector
// pin 2 is linked to Interrupt 0 (INT0)
attachInterrupt(0, arduinoPowerInterrupt, RISING);
}
void arduinoPowerInterrupt() {
// shutdown the PowerBoost when the button is pressed while Arduino
// is running - this only works when the button is released...
// This is because the power ON circuit is also activated when the button is down
digitalWrite(arduinoPowerEnablePin, LOW);
}
// Set an RGB LED - this version assumes a common anode
void arduinoPowerLed(String color) {
if(color == "red") {
digitalWrite(arduinoPowerGreenLedPin, HIGH);
digitalWrite(arduinoPowerRedLedPin, LOW);
} else if(color == "yellow") {
digitalWrite(arduinoPowerGreenLedPin, LOW);
digitalWrite(arduinoPowerRedLedPin, LOW);
} else if(color == "green") {
digitalWrite(arduinoPowerGreenLedPin, LOW);
digitalWrite(arduinoPowerRedLedPin, HIGH);
} else {
// turn the LED off
digitalWrite(arduinoPowerGreenLedPin, HIGH);
digitalWrite(arduinoPowerRedLedPin, HIGH);
}
}
void arduinoPowerMonitor() {
float maxVoltage = 4.25;
float minVoltage = 3.75;
arduinoPowerVoltage = float(analogRead(arduinoPowerVoltagePin)) / 1024.0 * 5.0;
float fractionalVoltage = (arduinoPowerVoltage - minVoltage) / (maxVoltage - minVoltage);
if(fractionalVoltage > 1.0) {
fractionalVoltage = 1.0;
} else if(fractionalVoltage < 0.0) {
fractionalVoltage = 0.0;
}
// Modify the cutoff values to suit
if (fractionalVoltage > 0.5) {
arduinoPowerLed("green");
} else if (fractionalVoltage > 0.25) {
arduinoPowerLed("yellow");
} else {
arduinoPowerLed("red");
}
}
// Regular Arduino setup() and loop() functions
void setup() {
arduinoPowerSetup();
// Add any other setup here
// In this example pin 13 is set as an output
// this has an on-board LED attached
pinMode(13, OUTPUT);
}
void loop() {
// Monitor the power status
arduinoPowerMonitor();
// Flash the on-board LED attached to Pin 13 just to show some activity
digitalWrite(13, HIGH);
delay(250);
digitalWrite(13, LOW);
// Delay 1 second
delay(1000);
}
| 26.039683
| 91
| 0.714416
|
d3476cabc2df9742774e24d6b880c7cdc731b994
| 904
|
ino
|
Arduino
|
Apollo.ino
|
m1cr0lab-gamebuino/apollo
|
79c71d0ca44301d05d284a7f2bc5137fe80c911a
|
[
"MIT"
] | 1
|
2021-07-28T12:35:52.000Z
|
2021-07-28T12:35:52.000Z
|
Apollo.ino
|
m1cr0lab-gamebuino/apollo
|
79c71d0ca44301d05d284a7f2bc5137fe80c911a
|
[
"MIT"
] | null | null | null |
Apollo.ino
|
m1cr0lab-gamebuino/apollo
|
79c71d0ca44301d05d284a7f2bc5137fe80c911a
|
[
"MIT"
] | null | null | null |
/**
* -------------------------------------------------------------------------
* Apollo
* -------------------------------------------------------------------------
* a tiny game for the Gamebuino META retro gaming handheld
* inspired by the famous Lunar Lander
* https://youtu.be/McAhSoAEbhM
* https://en.wikipedia.org/wiki/Lunar_Lander_(1979_video_game)
* -------------------------------------------------------------------------
* © 2021 Steph @ m1cr0lab
* https://gamebuino.m1cr0lab.com
* -------------------------------------------------------------------------
*/
#include <Gamebuino-Meta.h>
#include "src/engine/Game.h"
Game game;
void setup() {
gb.begin();
game.begin();
}
void loop() {
gb.waitForUpdate();
game.loop();
}
| 28.25
| 76
| 0.337389
|
24613e872ea0eb3b7ce0b624ae0d2467807ddda9
| 104
|
ino
|
Arduino
|
Driver/src/src.ino
|
edmw/weatherstation
|
e377fddd5c5246e3e8a819ba8a612996b983feb8
|
[
"MIT"
] | 1
|
2017-10-26T12:43:59.000Z
|
2017-10-26T12:43:59.000Z
|
Driver/src/src.ino
|
edmw/weatherstation
|
e377fddd5c5246e3e8a819ba8a612996b983feb8
|
[
"MIT"
] | null | null | null |
Driver/src/src.ino
|
edmw/weatherstation
|
e377fddd5c5246e3e8a819ba8a612996b983feb8
|
[
"MIT"
] | null | null | null |
extern const int SKETCH_VERSION = 1;
// => Driver.cpp
extern void setup(void);
extern void loop(void);
| 17.333333
| 36
| 0.721154
|
2750a11f3d1ddc7d4b788e5257eafd0a3f69f6d4
| 7,448
|
ino
|
Arduino
|
v2/CTD_UPCT_v2/CTD_UPCT_v2.ino
|
Raniita/Accuatic-Probe
|
fc0054b5c1a3a9be979379d8c7838cf1406c473f
|
[
"MIT"
] | 1
|
2021-11-13T14:55:21.000Z
|
2021-11-13T14:55:21.000Z
|
v2/CTD_UPCT_v2/CTD_UPCT_v2.ino
|
Raniita/Ocean-CTD
|
fc0054b5c1a3a9be979379d8c7838cf1406c473f
|
[
"MIT"
] | null | null | null |
v2/CTD_UPCT_v2/CTD_UPCT_v2.ino
|
Raniita/Ocean-CTD
|
fc0054b5c1a3a9be979379d8c7838cf1406c473f
|
[
"MIT"
] | null | null | null |
//====================================================================
//============================= Librarys =============================
//====================================================================
#include <avr/pgmspace.h>
#include <TSYS01.h>
#include <MS5837.h>
#include <cyclopSensor.h>
#include <Wire.h>
#include <SPI.h>
// Ethernet Librarys (w5100 == Ethernet, w5500 == Ethernet, Ethernet3)
// Ethernet3 not working XD, better use standard Ethernet...
#include <Ethernet.h>
#include <EthernetUdp.h>
//#include <Ethernet3.h>
//#include <EthernetUdp3.h>
//====================================================================
//============================= Configurations =======================
//====================================================================
// Serial configuration
#define BAUDRATE 115200
// Cyclops Sensors
// Plateado
#define cdom_type "cdom"
#define cdom_id '1'
#define cdom_read A1
#define cdom_x10 5
#define cdom_x100 6
#define cdom_maxPPB 1500
// Negro
#define phy_type "phy"
#define phy_id '2'
#define phy_read A0
#define phy_x10 7
#define phy_x100 8
#define phy_maxPPB 750
// Amarillo
#define chl_type "chl"
#define chl_id '3'
#define chl_read A2
#define chl_x10 2
#define chl_x100 3
#define chl_maxPPB 500
// Local configs
byte mac[6] = { 0x90, 0xA2, 0xDA, 0x2A, 0xB8, 0xCE };
unsigned int local_port = 55055;
// IP Static config (Router Amarillo == DHCP)
IPAddress ip(10, 0, 1, 10);
IPAddress gw(10, 0, 1, 1);
IPAddress my_dns(1, 1, 1, 1);
IPAddress subnet(255, 255, 255, 0);
unsigned int server_port = 45045;
// UDP configs
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
String datReq; //String for our data
int packetSize; //Size of the packet
//====================================================================
//============================= Definitions ==========================
//====================================================================
// Sensores
cyclopSensor cdom(cdom_id, cdom_read, cdom_x10, cdom_x100);
cyclopSensor phy(phy_id, phy_read, phy_x10, phy_x100);
cyclopSensor chl(chl_id, chl_read, chl_x10, chl_x100);
String cdom_measure, cdom_mv, cdom_gain;
String phy_measure, phy_mv, phy_gain;
String chl_measure, chl_mv, chl_gain;
String ms_pressure, ms_temp, ms_depth, ms_alt;
String ts_temp;
String message;
MS5837 presion;
TSYS01 temp;
bool presion_fail = false;
int retry = 0;
// Utilidades
EthernetUDP udp;
//====================================================================
//=========================== Setup ==================================
//====================================================================
void setup(){
Serial.begin(BAUDRATE);
Serial.println(F("Initializated serial connection"));
delay(300);
// Configuracion cyclops
cdom.setMaxPPB(cdom_maxPPB);
phy.setMaxPPB(phy_maxPPB);
chl.setMaxPPB(chl_maxPPB);
Serial.println("CDOM Gain: x" + (String) cdom.getGain());
Serial.println("Phy Gain: x" + (String) phy.getGain());
Serial.println("CHL Gain: x" + (String) chl.getGain());
// Configuracion Ethernet
Serial.println(F("Initialize Ethernet with DHCP:"));
// Static w5100
//Ethernet.begin(mac, ip, my_dns, gw, subnet);
// Static w5500 (Ethernet3)
//Ethernet.begin(mac, ip, subnet, gw);
// DHCP
if(Ethernet.begin(mac) == 0){
// 1 min aprox to fail
Serial.println(F("Error on Ethernet. DHCP Server not found."));
Serial.println(F("Setting static IP Adress."));
Ethernet.begin(mac, ip, my_dns, gw, subnet);
//while(true){
// delay(1);
//}
}
delay(1000);
udp.begin(local_port);
Serial.print(F("IP: "));
Serial.println(Ethernet.localIP());
Serial.print(F("Port: "));
Serial.println(local_port);
// Configuracion I2C sensors
Wire.begin();
delay(100);
// Go UP Sensors
temp.init();
while (!presion.init()){
if(retry > 10) {
presion_fail = true;
break;
} else {
retry++;
}
Serial.println(F("Presion sensor failed"));
delay(2000);
}
if(presion_fail == false){
presion.setModel(MS5837::MS5837_30BA);
presion.setFluidDensity(1029); // kg/m^3 (1029 for seawater)
}
Serial.println(F("Ready: "));
delay(500);
}
//====================================================================
//============================= Loop =================================
//====================================================================
void loop(){
packetSize = udp.parsePacket();
if (packetSize > 0){
udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
datReq = packetBuffer;
Serial.println("Received: " + datReq);
memset(packetBuffer, 0, UDP_TX_PACKET_MAX_SIZE);
// Mandamos lo recibido a la funcion
// Si es alguno de nuestros sensores, mandamos la medida
// Si no es, no hacemos nada
read_sensor(datReq);
}
}
//====================================================================
//====================== Functions as helpers! =======================
//====================================================================
void send_message(String msg){
udp.beginPacket(udp.remoteIP(), udp.remotePort());
udp.print(msg);
udp.endPacket();
//memset(packetBuffer, 0, UDP_TX_PACKET_MAX_SIZE);
}
void read_sensor(String mSensor){
// Formato de los mensajes:
// <type>;<gain>;<measure>;<mv> (cyclops)
// <type>;<pressure>;<temp>;<depth>;<altitude>
// <type>;<measure> (i2c sensors)
if(mSensor == "cdom"){
cdom_measure = (String) cdom.measure();
cdom_mv = (String) cdom.getMV();
cdom_gain = (String) cdom.getGain();
message = "cdom;" + cdom_gain + ";" + cdom_measure + ";" + cdom_mv;
Serial.println("CDOM => x" + cdom_gain + " value: " + cdom_measure + " mV: " + cdom_mv);
send_message(message);
}
if(mSensor == "phy"){
phy_measure = (String) phy.measure();
phy_mv = (String) phy.getMV();
phy_gain = (String) phy.getGain();
message = "phy;" + phy_gain + ";" + phy_measure + ";" + phy_mv;
Serial.println("PHY => x" + phy_gain + " value: " + phy_measure + " mV: " + phy_mv);
send_message(message);
}
if(mSensor == "chl"){
chl_measure = (String) chl.measure();
chl_mv = (String) chl.getMV();
chl_gain = (String) chl.getGain();
message = "chl;" + chl_gain + ";" + chl_measure + ";" + chl_mv;
Serial.println("CHL => x" + chl_gain + " value: " + chl_measure + " mV: " + chl_mv);
send_message(message);
}
if(mSensor == "ms5"){
if(presion_fail == true){
// Presion sensor doesnt boot. ERROR
message = "ms5;error";
Serial.println("MS5837 => Error, sensor doesnt boot");
send_message(message);
} else {
presion.read();
ms_pressure = (String) presion.pressure();
ms_temp = (String) presion.temperature();
ms_depth = (String) presion.depth();
ms_alt = (String) presion.altitude();
message = "ms5;" + ms_pressure + ";" + ms_temp + ";" + ms_depth + ";" + ms_alt;
Serial.println("MS5837 => " + ms_pressure + " mbar, " + ms_temp + " C, " +
ms_depth + " m, " + ms_alt + " m above sea");
send_message(message);
}
}
if(mSensor == "temp"){
temp.read();
ts_temp = (String) temp.temperature();
message = "temp;" + ts_temp;
Serial.println("TSYS01 => " + ts_temp + " C");
send_message(message);
}
if(mSensor == "ping"){
message = "pong";
Serial.println(F("PING => PONG!"));
send_message(message);
}
}
| 27.791045
| 92
| 0.540951
|
550c38d48e9557ecb5b82710e809e2f3111e7d40
| 3,347
|
ino
|
Arduino
|
hardware/motordriver/motordriver.ino
|
kingkevlar/airhockey
|
8883034e4968039c6258ba62b8dfb1bcacb025ec
|
[
"MIT"
] | 2
|
2017-05-12T21:52:21.000Z
|
2017-07-26T04:34:24.000Z
|
hardware/motordriver/motordriver.ino
|
jnez71/airhockey
|
8883034e4968039c6258ba62b8dfb1bcacb025ec
|
[
"MIT"
] | null | null | null |
hardware/motordriver/motordriver.ino
|
jnez71/airhockey
|
8883034e4968039c6258ba62b8dfb1bcacb025ec
|
[
"MIT"
] | null | null | null |
/*
Program to be run on an arduino with a Dual-VNH5019 Motor Shield.
Listens for serial packet to set motor efforts.
Sends out serial packet with angular odometry from encoders.
*/
///////////////////////////////////////////////// DEPENDENCIES
// Motor driver library
// <https://github.com/pololu/dual-vnh5019-motor-shield> & <https://www.pololu.com/product/2507>
#include "/home/jason/Arduino/libraries/DualVNH5019MotorShield/DualVNH5019MotorShield.h"
#include "/home/jason/Arduino/libraries/DualVNH5019MotorShield/DualVNH5019MotorShield.cpp"
// Encoder library
// <https://www.pjrc.com/teensy/td_libs_Encoder.html> & <http://www.cui.com/product/resource/amt10.pdf>
#define ENCODER_OPTIMIZE_INTERRUPTS // used on import
#include "/home/jason/Arduino/libraries/Encoder/Encoder.h" // MODIFY: remove privacy on constructor
#include "/home/jason/Arduino/libraries/Encoder/Encoder.cpp"
///////////////////////////////////////////////// DEFINITIONS
// Motor driver
DualVNH5019MotorShield md;
// NOT NEEDED: do conversion outside of arduino instead
// Encoder tics to degrees:
// (revs/tic) * (degs/rev) = 1/2048 * 360
// #define ENC_SCALE 0.17578125
// Scale factor from effort% to cmd points
#define CMD_SCALE -4
// Communication management
#define ENC_REQUEST '1'
#define CMD_REQUEST '2'
///////////////////////////////////////////////// VARIABLES
// Motor commands
long cmd_x = 0;
long cmd_y = 0;
// Angular odometry
long odom_x = 0;
long odom_y = 0;
// Encoder objects
Encoder enc_x(18, 19); // MUST USE AT LEAST ONE EXTERNAL INTERRUPT
Encoder enc_y(20, 21); // MUST USE AT LEAST ONE EXTERNAL INTERRUPT
// Communication management
char request = '0';
///////////////////////////////////////////////// FUNCTIONS
void send_long(long arg)
{
// Get access to the float as a byte-array
byte* data = (byte*) &arg;
// Write the data to serial
Serial.write(data, sizeof(arg));
}
void stopIfFault()
{
// Stop and alert if first motor faulted
if (md.getM1Fault()){
Serial.println("M1 fault");
while(true);
}
// Stop and alert if second motor faulted
if (md.getM2Fault()){
Serial.println("M2 fault");
while(true);
}
}
///////////////////////////////////////////////// SET-UP ARDUINO
void setup()
{
// Open serial port and override timeout duration
Serial.begin(9600);
Serial.setTimeout(3);
// Set LED indicator pin to output
pinMode(13, OUTPUT);
// Initialize md library
md.init();
// Make sure md output is zero
md.setM1Speed(0);
md.setM2Speed(0);
}
///////////////////////////////////////////////// MAIN
void loop()
{
// Get latest encoder value
odom_x = enc_x.read();// * ENC_SCALE;
odom_y = enc_y.read();// * ENC_SCALE;
// Read request from computer
while(request == '0'){
if(Serial.available() > 0){
request = Serial.read();
}
}
// Send angular odometry
if(request == ENC_REQUEST){
send_long(odom_x);
send_long(odom_y);
}
// Receive motor commands
else if(request == CMD_REQUEST){
// First int has x command
cmd_x = Serial.parseInt() * CMD_SCALE;
md.setM1Speed(cmd_x);
stopIfFault();
// Second int has y command
cmd_y = Serial.parseInt() * CMD_SCALE;
md.setM2Speed(cmd_y);
stopIfFault();
// Acknowledge that we received
Serial.write('0');
}
// Reset request manager
request = '0';
}
| 25.356061
| 103
| 0.634001
|
87a4bfcd1fcc7209b7772b811e722399e5bc9e3c
| 152
|
ino
|
Arduino
|
part2/PinAccessSlow/PinAccessSlow.ino
|
LuckyResistor/templates-for-embedded
|
b2a8286e4d2f313bc398de2ee74782d74c7b60b1
|
[
"MIT"
] | 2
|
2019-07-31T13:27:24.000Z
|
2019-11-27T11:49:07.000Z
|
part2/PinAccessSlow/PinAccessSlow.ino
|
LuckyResistor/templates-for-embedded
|
b2a8286e4d2f313bc398de2ee74782d74c7b60b1
|
[
"MIT"
] | null | null | null |
part2/PinAccessSlow/PinAccessSlow.ino
|
LuckyResistor/templates-for-embedded
|
b2a8286e4d2f313bc398de2ee74782d74c7b60b1
|
[
"MIT"
] | 1
|
2019-07-31T13:28:00.000Z
|
2019-07-31T13:28:00.000Z
|
const uint8_t cLedPin = 13;
void setup() {
pinMode(cLedPin, OUTPUT);
}
void loop() {
digitalWrite(cLedPin, HIGH);
digitalWrite(cLedPin, LOW);
}
| 13.818182
| 30
| 0.677632
|
7fd6fb31fc67df7ec06c82e142f8926f937487e4
| 2,387
|
ino
|
Arduino
|
arduinoNano/dcMotor_pwm/dcMotor_pwm.ino
|
yumion/arduino
|
deb063991c77a4cbdfc97a3d9106173faad16d77
|
[
"Apache-2.0"
] | 1
|
2019-06-12T14:58:38.000Z
|
2019-06-12T14:58:38.000Z
|
arduinoNano/dcMotor_pwm/dcMotor_pwm.ino
|
yumion/arduino
|
deb063991c77a4cbdfc97a3d9106173faad16d77
|
[
"Apache-2.0"
] | null | null | null |
arduinoNano/dcMotor_pwm/dcMotor_pwm.ino
|
yumion/arduino
|
deb063991c77a4cbdfc97a3d9106173faad16d77
|
[
"Apache-2.0"
] | null | null | null |
// Specify pin# where Rotary encoder connected to
const uint8_t speeds = 50;
// グローバル変数の宣言
char input[1]; // 文字列格納用
int i = 0; // 文字数のカウンタ
int val = 0; // 受信した数値
int rot=0; // 回転指示用
void setup() {
Serial.begin(9600);
pinMode(5, OUTPUT); // AIN1
pinMode(6, OUTPUT); // AIN2
pinMode(10, OUTPUT); // BIN1
pinMode(11, OUTPUT); // BIN2
Serial.println("CarMovement: 53.=break, 49.=forward, 50.=back, 51.=cw, 52.=ccw");
}
// シリアル通信で受信したデータを数値に変換
int serialNum(){
// データ受信した場合の処理
if (Serial.available()) {
input[i] = Serial.read();
// 文字数が3以上 or 末尾文字がある場合の処理
if (i > 0 || input[i] == "\0") {
// if (i > 2) {
//input[i+1] = '\0'; // 末尾に終端文字の挿入
val = atoi(input); // 文字列を数値に変換
Serial.write(input); // 文字列を送信
Serial.write("\n");
i = 0; // カウンタの初期化
}
else { i++; }
}
return val;
}
/*
// シリアル通信で受信したデータを数値に変換
int serialNum(){
// データ受信した場合の処理
if (Serial.available()) {
for(i=0;i<=1;i++){
input[i] = Serial.read();}
val = atoi(input); // 文字列を数値に変換
Serial.write(input); // 文字列を送信
Serial.write("\n");
i = 0; // カウンタの初期化
}
return val;
}
*/
void loop() {
rot = serialNum();
//rot = Serial.read();
//Serial.write(rot);
//Serial.write("\n");
if(rot == 49){
//Serial.println("正転");
analogWrite(5, speeds); // AIN1:1
analogWrite(6, 0); // AIN2:0
analogWrite(10, speeds); // BIN1:1
analogWrite(11, 0); // BIN2:0
//delay(5000);
}
else if(rot == 50){
//Serial.println("逆転");
analogWrite(5, 0); // AIN1:0
analogWrite(6, speeds); // AIN2:1
analogWrite(10, 0); // BIN1:0
analogWrite(11, speeds); // BIN2:1
//delay(5000);
}
else if(rot == 51){
//Serial.println("右周り");
analogWrite(5, speeds); // AIN1:1
analogWrite(6, 0); // AIN2:0
analogWrite(10, 0); // BIN1:0
analogWrite(11, speeds); // BIN2:1
}
else if(rot == 52){
//Serial.println("左周り");
analogWrite(5, 0); // AIN1:0
analogWrite(6, speeds); // AIN2:1
analogWrite(10, speeds); // BIN1:1
analogWrite(11, 0); // BIN2:0
}
else{
//Serial.println("空転");
analogWrite(5, 0); // AIN1:0
analogWrite(6, 0); // AIN2:0
analogWrite(10, 0); // BIN1:0
analogWrite(11, 0); // BIN2:0
//delay(1000);
}
}
| 23.401961
| 83
| 0.528697
|
6cd9751bc679f5a500b0232f3a4b1b8f0d1b2697
| 241
|
ino
|
Arduino
|
Relatorios/Tarefa 05/teste_arduino/teste_arduino.ino
|
RafaelAmauri/Arquitetura-de-Computadores-2
|
5f5a0164cf25c037a174a1598a428da815207b07
|
[
"MIT"
] | null | null | null |
Relatorios/Tarefa 05/teste_arduino/teste_arduino.ino
|
RafaelAmauri/Arquitetura-de-Computadores-2
|
5f5a0164cf25c037a174a1598a428da815207b07
|
[
"MIT"
] | null | null | null |
Relatorios/Tarefa 05/teste_arduino/teste_arduino.ino
|
RafaelAmauri/Arquitetura-de-Computadores-2
|
5f5a0164cf25c037a174a1598a428da815207b07
|
[
"MIT"
] | null | null | null |
long c;
byte i, j;
long inicio, fim, tempo;
void setup() {
Serial.begin(9600);
}
void loop() {
i=1;
j=3;
inicio=micros();
for(c=0;c<1000000;c=c+1)i=i|j;
fim=micros();
tempo=(fim-inicio);
Serial.print("tempo= ");
Serial.println(tempo);
}
| 12.05
| 30
| 0.634855
|
2f775bdd18d1c07747fa436028a5970fbc9f4f50
| 5,208
|
ino
|
Arduino
|
boards/milador-nrf52-0.1.0/libraries/Bluefruit52Lib/examples/Peripheral/adv_AdafruitColor/adv_AdafruitColor.ino
|
milador/milador-arduino
|
d0f9ebe33e0e67a921f96d0e278d9d646b8bad91
|
[
"MIT"
] | null | null | null |
boards/milador-nrf52-0.1.0/libraries/Bluefruit52Lib/examples/Peripheral/adv_AdafruitColor/adv_AdafruitColor.ino
|
milador/milador-arduino
|
d0f9ebe33e0e67a921f96d0e278d9d646b8bad91
|
[
"MIT"
] | null | null | null |
boards/milador-nrf52-0.1.0/libraries/Bluefruit52Lib/examples/Peripheral/adv_AdafruitColor/adv_AdafruitColor.ino
|
milador/milador-arduino
|
d0f9ebe33e0e67a921f96d0e278d9d646b8bad91
|
[
"MIT"
] | null | null | null |
/*********************************************************************
This is an example for our nRF52 based Bluefruit LE modules
Pick one up today in the adafruit shop!
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
MIT license, check LICENSE for more information
All text above, and the splash screen below must be included in
any redistribution
*********************************************************************/
/* This sketch demonstrates the Bluefruit.Advertising API(). When powered up,
* the Bluefruit module will start advertising a packet compatible with the
* AdafruitColor class from CircuitPython:
* https://github.com/adafruit/Adafruit_CircuitPython_BLE/blob/master/adafruit_ble/advertising/adafruit.py
* In other words, `ble.start_scan(AdafruitColor)` in CircuitPython will hear
* an advertisement containing the color 0x0F0033 (violet) from this device.
*/
#include <bluefruit.h>
#define ADV_TIMEOUT 0 // seconds. Set this higher to automatically stop advertising after a time
// The following code is for setting a name based on the actual device MAC address
// Where to go looking in memory for the MAC
typedef volatile uint32_t REG32;
#define pREG32 (REG32 *)
#define MAC_ADDRESS_HIGH (*(pREG32 (0x100000a8)))
#define MAC_ADDRESS_LOW (*(pREG32 (0x100000a4)))
void byte_to_str(char* buff, uint8_t val) { // convert an 8-bit byte to a string of 2 hexadecimal characters
buff[0] = nibble_to_hex(val >> 4);
buff[1] = nibble_to_hex(val);
}
char nibble_to_hex(uint8_t nibble) { // convert a 4-bit nibble to a hexadecimal character
nibble &= 0xF;
return nibble > 9 ? nibble - 10 + 'A' : nibble + '0';
}
void setup()
{
// Serial.begin(115200);
// while ( !Serial ) delay(10);
Serial.println("Bluefruit52 Color Advertising Example");
Serial.println("----------------------------------------\n");
Bluefruit.begin();
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
char ble_name[14] = "BluefruitXXXX"; // Null-terminated string must be 1 longer than you set it, for the null
// Replace the XXXX with the lowest two bytes of the MAC Address
// The commented lines show you how to get the WHOLE MAC address
// uint32_t addr_high = ((MAC_ADDRESS_HIGH) & 0x0000ffff) | 0x0000c000;
uint32_t addr_low = MAC_ADDRESS_LOW;
// Serial.print("MAC Address: ");
// Serial.print((addr_high >> 8) & 0xFF, HEX); Serial.print(":");
// Serial.print((addr_high) & 0xFF, HEX); Serial.print(":");
// Serial.print((addr_low >> 24) & 0xFF, HEX); Serial.print(":");
// Serial.print((addr_low >> 16) & 0xFF, HEX); Serial.print(":");
// Serial.print((addr_low >> 8) & 0xFF, HEX); Serial.print(":");
// Serial.print((addr_low) & 0xFF, HEX); Serial.println("");
// Fill in the XXXX in ble_name
byte_to_str(&ble_name[9], (addr_low >> 8) & 0xFF);
byte_to_str(&ble_name[11], addr_low & 0xFF);
// Set the name we just made
Bluefruit.setName(ble_name);
// start advertising
startAdv();
Serial.print("Advertising is started: ");
Serial.println(ble_name);
}
void startAdv(void)
{
// Advertising packet
Bluefruit.Advertising.clearData();
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
Bluefruit.Advertising.setType(BLE_GAP_ADV_TYPE_NONCONNECTABLE_SCANNABLE_UNDIRECTED);
// This is the data format that will match CircuitPython's AdafruitColor
struct ATTR_PACKED
{
uint16_t manufacturer;
uint8_t color_len;
uint16_t color_type;
uint8_t color_info[4];
} color_data =
{
.manufacturer = 0x0822, // Adafruit company ID
.color_len = sizeof(color_data) - 3, // length of data to follow
.color_type = 0x0000, // Type specifier of this field, which AdafruitColor defines as 0x0000
.color_info = { 0x33, 0x00, 0x0F, 0x00 }, // { 0xBB, 0xGG, 0xRR, 0xIgnore}
};
// BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA is 0xFF
Bluefruit.Advertising.addData(BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA, &color_data, sizeof(color_data));
// Tell the BLE device we want to send our name in a ScanResponse if asked.
Bluefruit.ScanResponse.addName();
/* Start Advertising
* - Enable auto advertising if disconnected
* - Interval: fast mode = 20 ms, slow mode = 152.5 ms
* - Timeout for fast mode is 30 seconds
* - Start(timeout) with timeout = 0 will advertise forever (until connected)
*
* For recommended advertising interval
* https://developer.apple.com/library/content/qa/qa1931/_index.html
*/
Bluefruit.Advertising.setStopCallback(adv_stop_callback);
Bluefruit.Advertising.restartOnDisconnect(true);
Bluefruit.Advertising.setInterval(32, 244); // in units of 0.625 ms
Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode
Bluefruit.Advertising.start(ADV_TIMEOUT); // Stop advertising entirely after ADV_TIMEOUT seconds
}
void loop()
{
}
/**
* Callback invoked when advertising is stopped by timeout
*/
void adv_stop_callback(void)
{
Serial.println("Advertising time passed, advertising will now stop.");
}
| 39.157895
| 118
| 0.695469
|
54c5800045868c83e282e7856e8b20a2f6cdda42
| 485
|
ino
|
Arduino
|
WS2812B RGB Strip Code/RGB_Hue_Snake.ino
|
Rhys-Grover/ArduinoCode
|
8a9a7ee8b85c389408c799eb640a1b71e4b815f5
|
[
"CC0-1.0"
] | null | null | null |
WS2812B RGB Strip Code/RGB_Hue_Snake.ino
|
Rhys-Grover/ArduinoCode
|
8a9a7ee8b85c389408c799eb640a1b71e4b815f5
|
[
"CC0-1.0"
] | null | null | null |
WS2812B RGB Strip Code/RGB_Hue_Snake.ino
|
Rhys-Grover/ArduinoCode
|
8a9a7ee8b85c389408c799eb640a1b71e4b815f5
|
[
"CC0-1.0"
] | null | null | null |
#include <FastLED.h>
#define numled 300
#define datapin 10
CRGB leds[numled];
void setup() {
Serial.begin(57600);
Serial.println("resetting");
LEDS.addLeds<WS2812,datapin,RGB>(leds,numled);
LEDS.setBrightness(84);
}
void fadeall() { for(int i = 0; i < numled; i++) { leds[i].nscale8(250); } }
void loop() {
static uint8_t hue = 0;
for(int i = 0; i < numled; i++) {
leds[i] = CHSV(hue++, 255, 255);
FastLED.show();
fadeall();
delay(10);
}
| 19.4
| 77
| 0.593814
|
bd1f958605cfdf703e854b0c2c2eecbce9946bfe
| 8,014
|
ino
|
Arduino
|
examples/Tm1637Demo/Tm1637Demo.ino
|
bxparks/AceSegment
|
732df1bf4e22ab214010e9e4b534b338896ffedc
|
[
"MIT"
] | 4
|
2021-04-19T16:47:34.000Z
|
2022-02-06T03:48:17.000Z
|
examples/Tm1637Demo/Tm1637Demo.ino
|
bxparks/AceSegment
|
732df1bf4e22ab214010e9e4b534b338896ffedc
|
[
"MIT"
] | 9
|
2018-04-03T23:28:56.000Z
|
2021-05-14T21:44:04.000Z
|
examples/Tm1637Demo/Tm1637Demo.ino
|
bxparks/AceSegment
|
732df1bf4e22ab214010e9e4b534b338896ffedc
|
[
"MIT"
] | 1
|
2021-08-18T22:03:51.000Z
|
2021-08-18T22:03:51.000Z
|
/*
* A demo of a single TM1637 LED module, with the digits [0,3] or [0,5]
* scrolling to the left every second, and the brightness changing each
* iteration.
*
* Supported microcontroller environments:
*
* * AUNITER_MICRO_TM1637: SparkFun Pro Micro + 4-digit LED module
* * AUNITER_MICRO_TM1637_6: SparkFun Pro Micro + 6-digit LED module
* * AUNITER_SAMD_TM1637: SAMD21 M0 Mini + 4-digit LED module
* * AUNITER_STM32_TM1637: STM32 F1 Blue Pill + 4-digit LED module
* * AUNITER_D1MINI_LARGE_TM1637: WeMos D1 Mini ESP8266
* * AUNITER_ESP32_TM1637: ESP32 Dev Kit v1
*/
#include <Arduino.h>
#include <AceCommon.h> // incrementMod()
#include <AceTMI.h>
#include <AceSegment.h> // Tm1637Module
using ace_common::incrementMod;
using ace_common::incrementModOffset;
using ace_common::TimingStats;
using ace_tmi::SimpleTmiInterface;
using ace_segment::LedModule;
using ace_segment::Tm1637Module;
using ace_segment::kDigitRemapArray6Tm1637;
// Select TM1637 protocol version, either SimpleTmiInterface or
// SimpleTmiFastInterface.
#define TMI_INTERFACE_TYPE_NORMAL 0
#define TMI_INTERFACE_TYPE_FAST 1
// Select the TM1637Module flush() method.
#define TM_FLUSH_METHOD_NORMAL 0
#define TM_FLUSH_METHOD_INCREMENTAL 1
//----------------------------------------------------------------------------
// Hardware configuration.
//----------------------------------------------------------------------------
// Configuration for Arduino IDE
#if ! defined(EPOXY_DUINO) && ! defined(AUNITER)
#define AUNITER_MICRO_TM1637
#endif
#if defined(EPOXY_DUINO)
#define TMI_INTERFACE_TYPE TMI_INTERFACE_TYPE_NORMAL
#define TM_FLUSH_METHOD TM_FLUSH_METHOD_INCREMENTAL
const uint8_t CLK_PIN = A0;
const uint8_t DIO_PIN = 9;
const uint8_t NUM_DIGITS = 4;
#elif defined(AUNITER_MICRO_TM1637)
#define TMI_INTERFACE_TYPE TMI_INTERFACE_TYPE_FAST
#define TM_FLUSH_METHOD TM_FLUSH_METHOD_INCREMENTAL
const uint8_t CLK_PIN = A0;
const uint8_t DIO_PIN = 9;
const uint8_t NUM_DIGITS = 4;
#elif defined(AUNITER_MICRO_TM1637_6)
#define TMI_INTERFACE_TYPE TMI_INTERFACE_TYPE_FAST
#define TM_FLUSH_METHOD TM_FLUSH_METHOD_INCREMENTAL
const uint8_t CLK_PIN = A0;
const uint8_t DIO_PIN = 9;
const uint8_t NUM_DIGITS = 6;
#elif defined(AUNITER_SAMD_TM1637)
#define TMI_INTERFACE_TYPE TMI_INTERFACE_TYPE_NORMAL
#define TM_FLUSH_METHOD TM_FLUSH_METHOD_INCREMENTAL
const uint8_t CLK_PIN = 13;
const uint8_t DIO_PIN = 11;
const uint8_t NUM_DIGITS = 4;
#elif defined(AUNITER_STM32_TM1637)
#define TMI_INTERFACE_TYPE TMI_INTERFACE_TYPE_NORMAL
#define TM_FLUSH_METHOD TM_FLUSH_METHOD_INCREMENTAL
const uint8_t CLK_PIN = PB3;
const uint8_t DIO_PIN = PB4;
const uint8_t NUM_DIGITS = 4;
#elif defined(AUNITER_D1MINI_LARGE_TM1637)
#define TMI_INTERFACE_TYPE TMI_INTERFACE_TYPE_NORMAL
#define TM_FLUSH_METHOD TM_FLUSH_METHOD_INCREMENTAL
const uint8_t CLK_PIN = D5;
const uint8_t DIO_PIN = D7;
const uint8_t NUM_DIGITS = 4;
#elif defined(AUNITER_ESP32_TM1637)
#define TMI_INTERFACE_TYPE TMI_INTERFACE_TYPE_NORMAL
#define TM_FLUSH_METHOD TM_FLUSH_METHOD_INCREMENTAL
const uint8_t CLK_PIN = 14;
const uint8_t DIO_PIN = 13;
const uint8_t NUM_DIGITS = 4;
#else
#error Unknown AUNITER environment
#endif
//------------------------------------------------------------------
// AceSegment Configuration
//------------------------------------------------------------------
// For a SimpleTmiInterface (non-fast), time to send 4 digits:
// * 12 ms at 50 us delay, but does not work with off-the-shelf TM1637 module.
// * 17 ms at 75 us delay.
// * 22 ms at 100 us delay.
// * 43 ms at 200 us delay.
const uint8_t DELAY_MICROS = 100;
#if TMI_INTERFACE_TYPE == TMI_INTERFACE_TYPE_NORMAL
using TmiInterface = SimpleTmiInterface;
TmiInterface tmiInterface(DIO_PIN, CLK_PIN, DELAY_MICROS);
#elif TMI_INTERFACE_TYPE == TMI_INTERFACE_TYPE_FAST
#include <digitalWriteFast.h>
#include <ace_tmi/SimpleTmiFastInterface.h>
using ace_tmi::SimpleTmiFastInterface;
using TmiInterface = SimpleTmiFastInterface<DIO_PIN, CLK_PIN, DELAY_MICROS>;
TmiInterface tmiInterface;
#else
#error Unknown TMI_INTERFACE_TYPE
#endif
#if defined(AUNITER_MICRO_TM1637_6)
const uint8_t* const remapArray = ace_segment::kDigitRemapArray6Tm1637;
#else
const uint8_t* const remapArray = nullptr;
#endif
Tm1637Module<TmiInterface, NUM_DIGITS> ledModule(tmiInterface, remapArray);
void setupAceSegment() {
tmiInterface.begin();
ledModule.begin();
}
//----------------------------------------------------------------------------
// The TM1637 controller supports up to 6 digits.
const uint8_t PATTERNS[6] = {
0b00111111, // 0
0b00000110, // 1
0b01011011, // 2
0b01001111, // 3
0b01100110, // 4
0b01101101, // 5
};
TimingStats stats;
uint8_t digitIndex = 0;
uint8_t brightness = 1;
// Every second, scroll the display and change the brightness.
void updateDisplay() {
static uint16_t prevChangeMillis;
uint16_t nowMillis = millis();
if ((uint16_t) (nowMillis - prevChangeMillis) >= 1000) {
prevChangeMillis = nowMillis;
// Update the display
uint8_t j = digitIndex;
for (uint8_t i = 0; i < NUM_DIGITS; ++i) {
// Write a decimal point every other digit, for demo purposes.
uint8_t pattern = PATTERNS[j] | ((j & 0x1) ? 0x80 : 0x00);
ledModule.setPatternAt(i, pattern);
incrementMod(j, (uint8_t) NUM_DIGITS);
}
incrementMod(digitIndex, (uint8_t) NUM_DIGITS);
// Update the brightness. The TM1637 has 8 levels of brightness.
ledModule.setBrightness(brightness);
incrementModOffset(brightness, (uint8_t) 7, (uint8_t) 1);
}
}
// Every 20 ms, flushIncremental() to the LED module, which updates only a
// single digit per call, taking only ~10 ms using a 100 us delay. Each call to
// flushIncremental() updates only one digit, so to avoid making the incremental
// update distracting to the human eye, we need to call this somewhat rapidly.
// Every 20 ms seems to work pretty well.
void flushIncrementalModule() {
static uint16_t prevFlushMillis;
uint16_t nowMillis = millis();
if ((uint16_t) (nowMillis - prevFlushMillis) >= 20) {
prevFlushMillis = nowMillis;
// Flush incrementally, and measure the time.
uint16_t startMicros = micros();
ledModule.flushIncremental();
uint16_t elapsedMicros = (uint16_t) micros() - startMicros;
stats.update(elapsedMicros);
}
}
// Every 100 ms, unconditionally flush() to the LED module which updates all
// digits, including brightness, taking about 22 ms (4 digits) to 28 ms
// (6-digits) using a 100 us delay.
void flushModule() {
static uint16_t prevFlushMillis;
uint16_t nowMillis = millis();
if ((uint16_t) (nowMillis - prevFlushMillis) >= 100) {
prevFlushMillis = nowMillis;
// Flush incrementally, and measure the time.
uint16_t startMicros = micros();
ledModule.flush();
uint16_t elapsedMicros = (uint16_t) micros() - startMicros;
stats.update(elapsedMicros);
}
}
// Every 5 seconds, print stats about how long flush() or flushIncremental()
// took.
void printStats() {
#if ENABLE_SERIAL_DEBUG >= 1
static uint16_t prevStatsMillis;
// Every 5 seconds, print out the statistics.
uint16_t nowMillis = millis();
if ((uint16_t) (nowMillis - prevStatsMillis) >= 5000) {
prevStatsMillis = nowMillis;
Serial.print("min/avg/max:");
Serial.print(stats.getMin());
Serial.print('/');
Serial.print(stats.getAvg());
Serial.print('/');
Serial.println(stats.getMax());
stats.reset();
}
#endif
}
//-----------------------------------------------------------------------------
void setup() {
delay(1000);
#if ENABLE_SERIAL_DEBUG >= 1
Serial.begin(115200);
while (!Serial);
#endif
setupAceSegment();
}
void loop() {
updateDisplay();
#if TM_FLUSH_METHOD == TM_FLUSH_METHOD_NORMAL
flushModule();
#elif TM_FLUSH_METHOD == TM_FLUSH_METHOD_INCREMENTAL
flushIncrementalModule();
#else
#error Unknown TM_FLUSH_METHOD
#endif
printStats();
}
| 29.571956
| 80
| 0.703144
|
c0bca458c5ecd4abb224900cf0bd91923dbf1722
| 2,149
|
ino
|
Arduino
|
examples/joystickRotaryEncoder/joystickRotaryEncoder.ino
|
mastersin/IoAbstraction
|
071d687b1736e38d8dd5f9f49e9bd001c7844dad
|
[
"Apache-2.0"
] | null | null | null |
examples/joystickRotaryEncoder/joystickRotaryEncoder.ino
|
mastersin/IoAbstraction
|
071d687b1736e38d8dd5f9f49e9bd001c7844dad
|
[
"Apache-2.0"
] | null | null | null |
examples/joystickRotaryEncoder/joystickRotaryEncoder.ino
|
mastersin/IoAbstraction
|
071d687b1736e38d8dd5f9f49e9bd001c7844dad
|
[
"Apache-2.0"
] | null | null | null |
/**
* This is a simple example of using the Joystick rotary encoder. It assumes you have a potentiometer
* based analog joystick connected to an analog input port.
*
* Shows the value of a rotary encoder over the serial port. Wiring, wire the joystick as per instructions
* and take note of the analog input pin you've used.
*/
#include<TaskManagerIO.h>
#include <IoAbstraction.h>
#include <JoystickSwitchInput.h>
#define ANALOG_INPUT_PIN A0
// we need to create an analog device that the joystick encoder will use to get readings.
// In this case on arduino analog pins.
ArduinoAnalogDevice analogDevice;
// and we must tell switches where the buttons are located, in this case on arduino pins.
IoAbstractionRef arduinoPins = ioUsingArduino();
void onEncoderChange(int newValue) {
Serial.print("New joystick value: ");
Serial.print(newValue);
Serial.print(", analog in ");
Serial.println(analogDevice.getCurrentValue(ANALOG_INPUT_PIN));
}
void setup() {
Serial.begin(115200);
// MKR boards require the line below to wait for the serial port, uncomment if needed
// However, it doesn't work on some other boards and locks them up.
//while(!Serial);
Serial.println("Starting joystick rotary encoder example");
// first initialise switches using pull up switch logic.
switches.initialise(arduinoPins, true);
// now register the joystick
setupAnalogJoystickEncoder(&analogDevice, ANALOG_INPUT_PIN, onEncoderChange);
// once you've registed the joystick above with switches, you can then alter the mid point and tolerance if needed
// here we set the midpoint to 65% and the tolerance (or point at which we start reading) at +-5%.
reinterpret_cast<JoystickSwitchInput*>(switches.getEncoder())->setTolerance(.65F, 0.05F);
// now set the range to 500 and current value to 250
switches.changeEncoderPrecision(500, 250);
// and that's it, task manager and switches does the register
Serial.println("Started joystick example");
}
void loop() {
// we must always call this every loop cycle and as frequently as possible
taskManager.runLoop();
}
| 36.423729
| 118
| 0.736156
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.