Practical system programming




C#

 

 

/*

In this firmware can be activated address bus A0, A1, A2 and A3

This firmware operates with microcontrollers ATMEGA328P

A firmware can be debugged on the ARDUINO UNO R3

*/

 

void setup() {

// put your setup code here, to run once:

pinMode(14, OUTPUT); //

pinMode(15, OUTPUT); //

pinMode(16, OUTPUT); //

pinMode(17, OUTPUT); //

//

digitalWrite(14, HIGH); //set pullup on analog pin with address bus A0

digitalWrite(15, HIGH); //set pullup on analog pin with address bus A1

digitalWrite(16, HIGH); //set pullup on analog pin with address bus A2

digitalWrite(17, HIGH); //set pullup on analog pin with address bus A3

}

 

void loop() {

// put your main code here, to run repeatedly:

 

}

 

 

 

/*

In this firmware can be activated address bus A0, A1, A2, A3, A4 and A5

This firmware operates with microcontrollers ATMEGA328P

A firmware can be debugged on the ARDUINO UNO R3

*/

 

 

void setup() {

// put your setup code here, to run once:

pinMode(14, OUTPUT); //

pinMode(15, OUTPUT); //

pinMode(16, OUTPUT); //

pinMode(17, OUTPUT); //

pinMode(18, OUTPUT); //

pinMode(19, OUTPUT); //

//

digitalWrite(14, HIGH); //set pullup on analog pin with address bus A0

digitalWrite(15, HIGH); //set pullup on analog pin with address bus A1

digitalWrite(16, HIGH); //set pullup on analog pin with address bus A2

digitalWrite(17, HIGH); //set pullup on analog pin with address bus A3

digitalWrite(18, HIGH); //set pullup on analog pin with address bus A4

digitalWrite(19, HIGH); //set pullup on analog pin with address bus A5

}

 

void loop() {

// put your main code here, to run repeatedly:

 

}

 

 

/*

In this firmware can be activated address bus A0, A1, A2, A3, SDA and SCL

All address bus A0-A3 have receive the signals

All two wire interface i2c SDA and SCL have send the signals

This firmware operates with microcontrollers ATMEGA328P

A firmware can be debugged on the ARDUINO UNO R3

*/

 

//It includes a protocol into input/output of AVR

#include<avr/io.h>

 

//It includes a protocol into wired devices

#include<Wire.h>

 

void setup() {

// put your setup code here, to run once:

 

//It initializes functions of the pin modes through the protocol of wire

pinMode(A0, OUTPUT); //

pinMode(A1, OUTPUT); //

pinMode(A2, OUTPUT); //

pinMode(A3, OUTPUT); //

pinMode(SDA, OUTPUT); //

pinMode(SCL, OUTPUT); //

 

//It initializes functions of the digital writes from main device to peripheral devices

digitalWrite(A0, HIGH); //

delay(50);

digitalWrite(A0, LOW); //

delay(50);

 

digitalWrite(A1, HIGH); //

delay(50);

digitalWrite(A1, LOW); //

delay(50);

 

digitalWrite(A2, HIGH); //

delay(50);

digitalWrite(A2, LOW); //

delay(50);

 

digitalWrite(A3, HIGH); //

delay(50);

digitalWrite(A3, LOW); //

delay(50);

 

digitalWrite(SDA, HIGH); //

digitalWrite(SCL, HIGH); //

}

 

void loop() {

// After creating a setup() function, which initializes and sets the initial values, the loop() function does precisely what its name suggests, and loops consecutively, allowing your program to change and respond. Use it to actively control the Arduino board.

 

}

//It is tested on Arduino IDE 1.0.5

 

#include <LiquidCrystal.h> // adding library of liquid crystal display

LiquidCrystal lcd(7, 6, 5, 4, 3, 2); // (RS, E, DB4, DB5, DB6, DB7)

 

void setup(){

lcd.begin(16, 2); // Задаем размерность экрана

 

lcd.setCursor(0, 0); // Устанавливаем курсор в начало 1 строки

lcd.print("Hello, world!"); // Выводим текст

lcd.setCursor(0, 1); // Устанавливаем курсор в начало 2 строки

lcd.print("zelectro.cc"); // Выводим текст

}

 

void loop(){

}

 

 

// It is tested on Arduino IDE 1.0.5

 

#include <Wire.h>

#include <LiquidCrystal.h> // adding library of liquid crystal display

// Битовая маска символа улыбки

byte smile[8] =

{

B00010,

B00001,

B11001,

B00001,

B11001,

B00001,

B00010,

};

LiquidCrystal lcd(7, 6, 5, 4, 3, 2); // (RS, E, DB4, DB5, DB6, DB7)

 

void setup(){

lcd.begin(16, 2); // Задаем размерность экрана

 

lcd.createChar(1, smile); // Создаем символ под номером 1

 

lcd.setCursor(0, 0); // Устанавливаем курсор в начало 1 строки

lcd.print("\1"); // Выводим смайлик (символ под номером 1) - "\1"

}

 

void loop(){

}

 

 

//Тестировалось на Arduino IDE 1.0.1

//Время калибровки датчика (10-60 сек. по даташиту)

int calibrationTime = 30;

 

//Время, в которое был принят сигнал отсутствия движения(LOW)

long unsigned int lowIn;

 

//Пауза, после которой движение считается оконченным

long unsigned int pause = 5000;

 

//Флаг. false = значит движение уже обнаружено, true - уже известно, что движения нет

boolean lockLow = true;

//Флаг. Сигнализирует о необходимости запомнить время начала отсутствия движения

boolean takeLowTime;

 

int pirPin = 2; //вывод подключения PIR датчика

int ledPin = 13; //вывод сигнального диода

int relayPin = 4; //реле пин

 

void setup()

{

pinMode(pirPin, INPUT); //

pinMode(ledPin, OUTPUT); //

pinMode(relayPin, OUTPUT); //

 

//!ВНИМАНИЕ! При использовании n-p-n реле необходимо в след. строчке поменять HIGH на LOW

digitalWrite(relayPin, HIGH);

delay(4000);

digitalWrite(pirPin, LOW);

 

//дадим датчику время на калибровку

for(int i = 0; i < calibrationTime; i++)

{

//Во время калибровки будет мигать сигнальный диод

i % 2? digitalWrite(ledPin, HIGH): digitalWrite(ledPin, LOW);

delay(1000);

}

//По окончанию калибровки зажжем сигнальный диод

digitalWrite(ledPin, HIGH);

delay(50);

}

 

void loop()

{

//Если обнаружено движение

if(digitalRead(pirPin) == HIGH)

{

//Если до этого момента еще не включили реле

if(lockLow)

{

lockLow = false;

//Включаем реле.

//!ВНИМАНИЕ! При использовании n-p-n реле необходимо в след. строчке поменять LOW на HIGH

digitalWrite(relayPin, LOW);

delay(50);

}

takeLowTime = true;

}

 

//Ели движения нет

if(digitalRead(pirPin) == LOW)

{

//Если время окончания движения еще не записано

if(takeLowTime)

{

lowIn = millis(); //Сохраним время окончания движения

takeLowTime = false; //Изменим значения флага, чтобы больше не брать время, пока не будет нового движения

}

//Если время без движение превышает паузу => движение окончено

if(!lockLow && millis() - lowIn > pause)

{

//Изменяем значение флага, чтобы эта часть кода исполнилась лишь раз, до нового движения

lockLow = true;

digitalWrite(relayPin, HIGH);

delay(50);

}

}

}

 

 

 

//Тестировалось на Arduino IDE 1.0.1

#include <SD.h>

 

File originalFile; // Файл который будет скопирован

File copiedFile; // Файл - копия

char* ORIGINAL_FILE_NAME = "1.txt"; // Название копируемого файла

char* COPIED_FILE_NAME = "2.txt"; // Название файла копии

char fileText[255]; // Хранилище для текста содержащегося в копируемом файле

 

void setup()

{

Serial.begin(9600);

// SPI SS пин должен быть OUTPUT

pinMode(10, OUTPUT);

 

// Инициализируем СД карту

Serial.print("Initializing SD card...");

if (!SD.begin(4)) {

Serial.println("initialization failed!");

return;

}

Serial.println("initialization done.");

 

// Открываем первый файл

originalFile = SD.open(ORIGINAL_FILE_NAME);

if (originalFile) {

Serial.println(ORIGINAL_FILE_NAME);

 

// Считываем текст из 1 файла

int i = 0;

while (originalFile.available()) {

char c = originalFile.read();

fileText[i++] = c;

Serial.write(c);

}

fileText[i] = 0;

// Закрываем файл

originalFile.close();

} else {

// Если произошла ошибка открытия файла, выводим сообщение

Serial.print("error opening ");

Serial.println(ORIGINAL_FILE_NAME);

}

 

// Открываем (или создаем, если его нет) файл копии

copiedFile = SD.open(COPIED_FILE_NAME, FILE_WRITE);

 

// Записываем в него считанный текст

if (copiedFile) {

Serial.print("Copying...");

copiedFile.println(fileText);

// Закрываем файл

copiedFile.close();

Serial.println("done.");

} else {

// Если произошла ошибка открытия файла, выводим сообщение

Serial.print("error opening ");

Serial.println(COPIED_FILE_NAME);

}

}

// Весь код был выполнен в функции setup

void loop()

{

}

 

 

 

// Тестировалось на Arduino IDE 1.0.1

#include <VirtualWire.h>

 

void setup()

{

Serial.begin(9600);

vw_set_ptt_inverted(true); // Необходимо для DR3100

vw_setup(2000); // Задаем скорость приема

vw_rx_start(); // Начинаем мониторинг эфира

}

 

void loop()

{

uint8_t buf[VW_MAX_MESSAGE_LEN]; // Буфер для сообщения

uint8_t buflen = VW_MAX_MESSAGE_LEN; // Длина буфера

 

if (vw_get_message(buf, &buflen)) // Если принято сообщение

{

// Начинаем разбор

int i;

// Если сообщение адресовано не нам, выходим

if (buf[0]!= 'z')

{

return;

}

char command = buf[2]; // Команда находится на индексе 2

 

// Числовой параметр начинается с индекса 4

i = 4;

int number = 0;

// Поскольку передача идет посимвольно, то нужно преобразовать набор символов в число

while (buf[i]!= ' ')

{

number *= 10;

number += buf[i] - '0';

i++;

}

Serial.print(command);

Serial.print(" ");

Serial.println(number);

}

}

 

 

int val;

int LED = 13;

 

void setup()

{

Serial.begin(9600);

pinMode(LED, OUTPUT);

}

 

void loop()

{

if (Serial.available())

{

val = Serial.read();

// При символе "W" включаем светодиод

if (val == 'W')

{

digitalWrite(LED, HIGH);

}

// При символе "S" выключаем светодиод

if (val == 'S')

{

digitalWrite(LED, LOW);

}

}

}

 

 

 

// Реле модуль подключен к цифровому выводу 4

int Relay = 4;

 

void setup()

{

pinMode(Relay, OUTPUT);

}

 

void loop()

{

digitalWrite(Relay, LOW); // реле включено

delay(2000);

digitalWrite(Relay, HIGH); // реле выключено

delay(2000);

}

 

Button:

 

Pushbuttons or switches connect two points in a circuit when you press them. This example turns on the built-in LED on pin 13 when you press the button.

 

Hardware

 

  • Arduino or Genuino Board
  • Momentary button or Switch
  • 10K ohm resistor
  • hook-up wires
  • breadboard
  • Circuit

 

 

/*

Button

 

Turns on and off a light emitting diode(LED) connected to digital

pin 13, when pressing a pushbutton attached to pin 2.

 

 

The circuit:

* LED attached from pin 13 to ground

* pushbutton attached to pin 2 from +5V

* 10K resistor attached to pin 2 from ground

 

* Note: on most Arduinos there is already an LED on the board

attached to pin 13.

 

 

created 2005

by DojoDave <https://www.0j0.org>

modified 30 Aug 2011

by Tom Igoe

 

This example code is in the public domain.

 

https://www.arduino.cc/en/Tutorial/Button

*/

 

// constants won't change. They're used here to

// set pin numbers:

const int buttonPin = 2; // the number of the pushbutton pin

const int ledPin = 13; // the number of the LED pin

 

// variables will change:

int buttonState = 0; // variable for reading the pushbutton status

 

void setup() {

// initialize the LED pin as an output:

pinMode(ledPin, OUTPUT);

// initialize the pushbutton pin as an input:

pinMode(buttonPin, INPUT);

}

 

void loop() {

// read the state of the pushbutton value:

buttonState = digitalRead(buttonPin);

 

// check if the pushbutton is pressed.

// if it is, the buttonState is HIGH:

if (buttonState == HIGH) {

// turn LED on:

digitalWrite(ledPin, HIGH);

} else {

// turn LED off:

digitalWrite(ledPin, LOW);

}

}

 

 

 

#include <avr/io.h>

int main()

{

//high nibble for output(columns) low for input(rows);

DDRB=0xF0;

//enable internal pullups for PB0-PB3

PORTB=0x0F;

//Port D for indication only

DDRD=0xFF;

while (1) //loop key check forever

{

//first column

PORTB =0b01111111;

//check for rows and send key number to portD

//instead sending key number to PORTD you can use

// any function that serves pressed button

if (bit_is_set(PINB, 3)) PORTD=1;

if (bit_is_set(PINB, 2)) PORTD=2;

if (bit_is_set(PINB, 1)) PORTD=3;

if (bit_is_set(PINB, 0)) PORTD=4;

//second column

PORTB =0b10111111;

if (bit_is_set(PINB, 3)) PORTD=5;

if (bit_is_set(PINB, 2)) PORTD=6;

if (bit_is_set(PINB, 1)) PORTD=7;

if (bit_is_set(PINB, 0)) PORTD=8;

//third column

PORTB =0b11011111;

if (bit_is_set(PINB, 3)) PORTD=9;

if (bit_is_set(PINB, 2)) PORTD=10;

if (bit_is_set(PINB, 1)) PORTD=11;

if (bit_is_set(PINB, 0)) PORTD=12;

//fourth column

PORTB =0b11101111;

if (bit_is_set(PINB, 3)) PORTD=13;

if (bit_is_set(PINB, 2)) PORTD=14;

if (bit_is_set(PINB, 1)) PORTD=15;

if (bit_is_set(PINB, 0)) PORTD=16;

}

}

 

 

/*

LiquidCrystal Library - Autoscroll

 

Demonstrates the use a 16x2 LCD display. The LiquidCrystal

library works with all LCD displays that are compatible with the

Hitachi HD44780 driver. There are many of them out there, and you

can usually tell them by the 16-pin interface.

 

This sketch demonstrates the use of the autoscroll()

and noAutoscroll() functions to make new text scroll or not.

 

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)

 

Library originally added 18 Apr 2008

by David A. Mellis

library modified 5 Jul 2009

by Limor Fried (https://www.ladyada.net)

example added 9 Jul 2009

by Tom Igoe

modified 22 Nov 2010

by Tom Igoe

 

This example code is in the public domain.

 

https://www.arduino.cc/en/Tutorial/LiquidCrystalAutoscroll

 

*/

 

// include the library code:

#include <LiquidCrystal.h>

 

// initialize the library with the numbers of the interface pins

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

 

void setup() {

// set up the LCD's number of columns and rows:

lcd.begin(16, 2);

}

 

void loop() {

// set the cursor to (0,0):

lcd.setCursor(0, 0);

// print from 0 to 9:

for (int thisChar = 0; thisChar < 10; thisChar++) {

lcd.print(thisChar);

delay(500);

}

 

// set the cursor to (16,1):

lcd.setCursor(16, 1);

// set the display to automatically scroll:

lcd.autoscroll();

// print from 0 to 9:

for (int thisChar = 0; thisChar < 10; thisChar++) {

lcd.print(thisChar);

delay(500);

}

// turn off automatic scrolling

lcd.noAutoscroll();

 

// clear screen for the next loop:

lcd.clear();

}

 

 

Winking of the digits by the liquid crystal display:

 

 

/*

This firmware operates with microcontroller ATMEGA328P

This firmware can be debugged on the Arduino UNO R3

This firmware can be flashed by any professional programmer which supports a microcontroller ATMEGA328P

It operates with liquid crystal display LCD-1602

Designed by Dmitry

*/

 

//it configures device drivers:

#include<LiquidCrystal.h>

LiquidCrystal lcd(2, 3, 4, 5, 6, 7); //(RS, EN, D4, D5, D6, D7)

 

//it displays digits and characters:

unsigned char Input_number; //

 

void setup() {

// put your setup code here, to run once:

Serial.begin(9600); //

lcd.setCursor(2, 4); //

lcd.begin(16, 2); //

lcd.print("1"); //

delay(1000); //

lcd.print("2"); //

delay(1000); //

lcd.print("3"); //

delay(1000); //

lcd.print("4"); //

delay(1000); //

lcd.print("5"); //

delay(1000); //

lcd.print("6"); //

delay(1000); //

lcd.print("7"); //

delay(1000); //

lcd.print("8"); //

delay(1000); //

lcd.print("9"); //

delay(1000); //

lcd.print("0"); //

delay(1000); //

lcd.print("#"); //

delay(1000); //

lcd.print("*"); //

delay(1000); //

lcd.println(Input_number); //

}

 

void loop() {

// put your main code here, to run repeatedly:

 

}

 

 

Winking of the relays

 

 

// Прошивка блока "А" исполнительных реле

 

String input_string = "";

 

void setup() {

Serial.begin(9600);

pinMode(4, OUTPUT);

pinMode(5, OUTPUT);

pinMode(6, OUTPUT);

pinMode(7, OUTPUT);

pinMode(8, OUTPUT);

pinMode(9, OUTPUT);

pinMode(10, OUTPUT);

pinMode(11, OUTPUT);

 

digitalWrite(4,HIGH);

digitalWrite(5,HIGH);

digitalWrite(6,HIGH);

digitalWrite(7,HIGH);

digitalWrite(8,HIGH);

digitalWrite(9,HIGH);

digitalWrite(10,HIGH);

digitalWrite(11,HIGH);

}

 

void loop() {

while (Serial.available() > 0) {

char c = Serial.read();

 

 

if (c == '\n') {

 

// Дебаг

Serial.print("Input_string is: ");

Serial.println(input_string);

 

if (input_string=="a4off"){digitalWrite(4,HIGH);}

if (input_string=="a4on"){digitalWrite(4,LOW);}

 

if (input_string=="a5off"){digitalWrite(5,HIGH);}

if (input_string=="a5on"){digitalWrite(5,LOW);}

 

if (input_string=="a6off"){digitalWrite(6,HIGH);}

if (input_string=="a6on"){digitalWrite(6,LOW);}

 

if (input_string=="a7off"){digitalWrite(7,HIGH);}

if (input_string=="a7on"){digitalWrite(7,LOW);}

 

if (input_string=="a8off"){digitalWrite(8,HIGH);}

if (input_string=="a8on"){digitalWrite(8,LOW);}

 

if (input_string=="a9off"){digitalWrite(9,HIGH);}

if (input_string=="a9on"){digitalWrite(9,LOW);}

 

if (input_string=="a10off"){digitalWrite(10,HIGH);}

if (input_string=="a10on"){digitalWrite(10,LOW);}

 

if (input_string=="a11off"){digitalWrite(11,HIGH);}

if (input_string=="a11on"){digitalWrite(11,LOW);}

 

if (input_string=="test"){for (int i=4; i <= 11; i++){ digitalWrite(i,LOW); delay(1000);}

for (int i=4; i <= 11; i++){ digitalWrite(i,HIGH); delay(1000);}}

 

input_string = "";

} else {input_string += c;}

 

}

}



Поделиться:




Поиск по сайту

©2015-2024 poisk-ru.ru
Все права принадлежать их авторам. Данный сайт не претендует на авторства, а предоставляет бесплатное использование.
Дата создания страницы: 2016-07-22 Нарушение авторских прав и Нарушение персональных данных


Поиск по сайту: