Перейти к содержанию

Рекомендуемые сообщения

Велосипедный спидометр на Arduino

я немного переделал код для км/ч, сейчас не могу проверить, правильно ли получилось?

//bike speedometer
//by Amanda Ghassaei 2012
//http://www.instructables.com/id/Arduino-Bike-Speedometer/

/*
* 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.
*
*/

//outputs speed of bicycle to LCD

//calculations
//tire radius ~ 13.5 inches
//circumference = pi*2*r =~85 inches
//max speed of 35mph =~ 616inches/second
//max rps =~7.25

#define reed A0//pin connected to read switch
#include <LiquidCrystal.h>//установил обычный дисплей
LiquidCrystal lcd(12, 11, 5, 4, 3, 6);
//storage variables

int reedVal;
long timer = 0;// time between one full rotation (in ms)
float mph = 0.00;
float circumference;
boolean backlight;

int maxReedCounter = 100;//min time (in ms) of one rotation (for debouncing)
int reedCounter;


void setup(){

reedCounter = maxReedCounter;
circumference = 2095; //здесь явно задал окружность
pinMode(1,OUTPUT);//tx
pinMode(2,OUTPUT);//backlight switch
pinMode(reed, INPUT);
lcd.begin(16, 2);

Serial.write(12);//clear

// TIMER SETUP- the timer interrupt allows preceise timed measurements of the reed switch
//for mor info about configuration of arduino timers see http://arduino.cc/playground/Code/Timer1
cli();//stop interrupts

//set timer1 interrupt at 1kHz
TCCR1A = 0;// set entire TCCR1A register to 0
TCCR1B = 0;// same for TCCR1B
TCNT1 = 0;
// set timer count for 1khz increments
OCR1A = 1999;// = (1/1000) / ((1/(16*10^6))*8) - 1
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS11 bit for 8 prescaler
TCCR1B |= (1 << CS11);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);

sei();//allow interrupts
//END TIMER SETUP

}



ISR(TIMER1_COMPA_vect) {//Interrupt at freq of 1kHz to measure reed switch
reedVal = digitalRead(reed);//get val of A0
if (reedVal){//if reed switch is closed
if (reedCounter == 0){//min time between pulses has passed
mph = (3.6*float(circumference))/float(timer);//calculate miles per hour // и переделал формулу
timer = 0;//reset timer
reedCounter = maxReedCounter;//reset reedCounter
}
else{
if (reedCounter > 0){//don't let reedCounter go negative
reedCounter -= 1;//decrement reedCounter
}
}
}
else{//if reed switch is open
if (reedCounter > 0){//don't let reedCounter go negative
reedCounter -= 1;//decrement reedCounter
}
}
if (timer > 2000){
mph = 0;//if no new pulses from reed switch- tire is still, set mph to 0
}
else{
timer += 1;//increment timer
}
}

void displayMPH(){
lcd.clear();//clear
lcd.print("Speed =");
lcd.setCursor(0, 1);
lcd.print(mph);
//Serial.write(" MPH ");
//Serial.write("0.00 MPH ");
}

void loop(){
//print mph once a second
displayMPH();
delay(1000);
}

как можно добавить одометр?

Ссылка на комментарий
Поделиться на другие сайты

Реклама: ООО ТД Промэлектроника, ИНН: 6659197470, Тел: 8 (800) 1000-321

версия номер два

//bike speedometer

//by Amanda Ghassaei 2012

//<a href="http://www.instructables.com/id/Arduino-Bike-Speedometer/" rel="nofollow">http://www.instructables.com/id/Arduino-Bike-Speedometer/</a>

/*

* 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.

*

*/

//outputs speed of bicycle to LCD

//calculations

//tire radius ~ 13.5 inches

//circumference = pi*2*r =~85 inches

//max speed of 35mph =~ 616inches/second

//max rps =~7.25

#define reed A0//pin connected to read switch

#include <LiquidCrystal.h>//установил обычный дисплей

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

//storage variables

int reedVal;

int odo;//количество оборотов колеса

long timer = 0;// time between one full rotation (in ms)

float mph = 0.00;

float circumference;

boolean backlight;

char vivod;

int maxReedCounter = 100;//min time (in ms) of one rotation (for debouncing)

int reedCounter;

void setup(){

odo=0;

reedCounter = maxReedCounter;

circumference = 2095; //здесь явно задал окружность

pinMode(1,OUTPUT);//tx

pinMode(2,OUTPUT);//backlight switch

pinMode(reed, INPUT);

lcd.begin(16, 2);

Serial.write(12);//clear

// TIMER SETUP- the timer interrupt allows preceise timed measurements of the reed switch

//for mor info about configuration of arduino timers see <a href="http://arduino.cc/playground/Code/Timer1" title="http://arduino.cc/playground/Code/Timer1" rel="nofollow">http://arduino.cc/playground/Code/Timer1</a>

cli();//stop interrupts

//set timer1 interrupt at 1kHz

TCCR1A = 0;// set entire TCCR1A register to 0

TCCR1B = 0;// same for TCCR1B

TCNT1 = 0;

// set timer count for 1khz increments

OCR1A = 1999;// = (1/1000) / ((1/(16*10^6))*8) - 1

// turn on CTC mode

TCCR1B |= (1 << WGM12);

// Set CS11 bit for 8 prescaler

TCCR1B |= (1 << CS11);

// enable timer compare interrupt

TIMSK1 |= (1 << OCIE1A);

sei();//allow interrupts

//END TIMER SETUP

}

ISR(TIMER1_COMPA_vect) {//Interrupt at freq of 1kHz to measure reed switch

reedVal = digitalRead(reed);//get val of A0

if (reedVal){//if reed switch is closed

if (reedCounter == 0){//min time between pulses has passed

mph = (3.6*float(circumference))/float(timer);//calculate miles per hour // и переделал формулу

odo++;

timer = 0;//reset timer

reedCounter = maxReedCounter;//reset reedCounter

}

else{

if (reedCounter > 0){//don't let reedCounter go negative

reedCounter -= 1;//decrement reedCounter

}

}

}

else{//if reed switch is open

if (reedCounter > 0){//don't let reedCounter go negative

reedCounter -= 1;//decrement reedCounter

}

}

if (timer > 2000){

mph = 0;//if no new pulses from reed switch- tire is still, set mph to 0

}

else{

timer += 1;//increment timer

}

}

void displayMPH(){

lcd.clear();//clear

lcd.print("Speed ");

lcd.setCursor(6, 0);

lcd.print(mph);

lcd.setCursor(0, 1);

lcd.print(String(byte(odo*circumference/1000000))+"km "+int(odo*circumference/1000)+"m");

/* lcd.setCursor(9, 1);

lcd.print(int(odo*circumference/1000));*/

}

void loop(){

//print mph once a second

displayMPH();

delay(1000);

}

Ссылка на комментарий
Поделиться на другие сайты

20% скидка на весь каталог электронных компонентов в ТМ Электроникс!

Акция "Лето ближе - цены ниже", успей сделать выгодные покупки!

Плюс весь апрель действует скидка 10% по промокоду APREL24 + 15% кэшбэк и бесплатная доставка!

Перейти на страницу акции

Реклама: ООО ТМ ЭЛЕКТРОНИКС, ИНН: 7806548420, info@tmelectronics.ru, +7(812)4094849

Присоединяйтесь к обсуждению

Вы публикуете как гость. Если у вас есть аккаунт, авторизуйтесь, чтобы опубликовать от имени своего аккаунта.
Примечание: Ваш пост будет проверен модератором, прежде чем станет видимым.

Гость
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Ответить в этой теме...

×   Вставлено с форматированием.   Восстановить форматирование

  Разрешено использовать не более 75 эмодзи.

×   Ваша ссылка была автоматически встроена.   Отображать как обычную ссылку

×   Ваш предыдущий контент был восстановлен.   Очистить редактор

×   Вы не можете вставлять изображения напрямую. Загружайте или вставляйте изображения по ссылке.

Загрузка...
  • Последние посетители   0 пользователей онлайн

    • Ни одного зарегистрированного пользователя не просматривает данную страницу
×
×
  • Создать...