how can i add a while statement to this code for my binary game on the arduino uno - arduino-uno

this is my code
const int buttonPin = 2; // de pin van het knopje
const int ledPin = 4; // ledjes 1 tm 4
const int ledPin2= 6;
const int ledPin3= 8;
const int ledPin4= 10;
const int ledPinGOED= 12; // de ledpin die aangeeft of het antwoord goed of fout is
int buttonState = LOW; // staat van de buttonpin
int x = 0; // aan x word een willekeurige waarde toegekend die in binair word weergegeven
int teller = 0; // teller is de waarde die bijhoudt hoeveel er op de knop gedrukt is
int LastbuttonState = LOW; // de laatste status van de button
void setup() {
randomSeed(analogRead(0)); // Start de randomseed generator
pinMode(ledPin, OUTPUT); // Zet de ledpins op output
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(ledPin4, OUTPUT);
pinMode(ledPinGOED, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT); // Zet de button op input
}
void loop(){
if (x == 0) { // als int getal op 0 staat word er een nieuw random getal gekozen
x = random(1, 16);
}
if (x >= 8) { // als x gelijk of groter is dan 8 gaat het ledje branden
digitalWrite(ledPin4, HIGH);
x=x-8;
}if(x >= 4) { // als x gelijk of groter is dan 4 gaat het ledje branden
digitalWrite(ledPin3, HIGH);
x=x-4;
}if(x >= 2) { // als x gelijk of groter is dan 2 gaat het ledje branden
digitalWrite(ledPin2, HIGH);
x=x-2;
}if(x = 1) { // als x gelijk is aan 1 gaat het ledje branden
digitalWrite(ledPin, HIGH);
x=x-1;
}
if
(unsigned long start = millis ()) { // lange variabele die geen negatieven opslaat, start waarde is de timer vanaf wanneer de knop voor het laatst ingedrukt is uitgedrukt in millis
while (millis() - start <=2000){ // als er 2 seconden voorbij zijn dan gaat de statement door naar de volgende if statements
buttonState = digitalRead(buttonPin); // de knop word gelezen vanuit pin 2
delay(100); // er word 100ms gewacht tussen de read en de if statement om misreads te voorkomen (werkt niet perfect)
if (LastbuttonState == LOW and buttonState == HIGH){ // als de knop ingedrukt word
LastbuttonState = buttonState; // Lastbuttonstate word buttonstate
teller=teller+1; // er word 1 bij teller opgeteld
start = millis();} // startwaarde word gereset
else { (LastbuttonState = buttonState); // anders blijft de lastbuttonstate hetzelfde
}
}
if (teller==x) { // als teller gelijk is aan het getal gaan de 4 ledjes uit en brand het goede ledje voor 2 seconden
digitalWrite(ledPin, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
digitalWrite(ledPinGOED, HIGH);
delay (2000);
digitalWrite(ledPinGOED, LOW);
x=0; // x word gereset naar 0 (dit triggert de loop)
teller=0; // teller word gereset naar 0
}
else if (teller<=getal or teller>=getal){ // als teller kleiner of groter is dan het getal gaan de 4 ledjes uit en knippert het goede ledje
digitalWrite(ledPin, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(ledPin4, LOW);
digitalWrite(ledPinGOED, HIGH);
delay (500);
digitalWrite(ledPinGOED, LOW);
delay (500);
digitalWrite(ledPinGOED, HIGH);
delay (500);
digitalWrite(ledPinGOED, LOW);
x=0; // x word gereset naar 0 (dit triggert de loop)
teller=0; // teller word gereset naar 0
}
} }
where could i use a while statement here?
i already have it near the end but the teacher said it should be used in the binary part of the code, i might be able to change an if statement but i can't figure out which one

Related

How to code Arduino used countdown timer (buzzer), 4 pir sensors, and relay? They worked parallel but what I need is work sequentially

How do you program Arduino to do a countdown timer 10 times using a buzzer, then after that, the light will turn on (relay). In addition, 4 PIR sensors will detect movement, if there is movement, the light will turn off for 10 seconds after which the light will turn on again. I already try to code but something feels off because the light is on at the start and the sensor detects when the timer is still running.
Here is the code that I try to code:
#define relayPin 12
#define pirPin1 8
#define pirPin2 9
#define pirPin3 10
#define pirPin4 11
int val1 = 0,val2 = 0, val3 = 0, val4 = 0 ;
long buzzerFrequency = 1000;
float buzzerDuration = 100;
int startNumber = 9; //countdown starts with this number
int endNumber = 0; //countdown ends with this number
const int buzzerPin = 6;
void setup() {
// put your setup code here, to run once:
pinMode(buzzerPin,OUTPUT);
pinMode(relayPin,OUTPUT);
pinMode(pirPin1, INPUT);
pinMode(pirPin2, INPUT);
pinMode(pirPin3, INPUT);
pinMode(pirPin4, INPUT);
Serial.begin(115200);
}
void buzzer(){
if (startNumber >= endNumber) {
for (int i = 0; i <= 1; i++){
tone(buzzerPin,buzzerFrequency,buzzerDuration);
}
delay(1000);
startNumber--;
}
}
void allPir(){
val1 = digitalRead(pirPin1);
val2 = digitalRead(pirPin2);
val3 = digitalRead(pirPin3);
val4 = digitalRead(pirPin4);
if(val1 == HIGH || val2 == HIGH || val3 == HIGH || val4 == HIGH){
digitalWrite(relayPin, HIGH);
Serial.println("Movement! delay 10 second");
Serial.println("Light off");
delay(10000);
}else{
digitalWrite(relayPin, LOW);
Serial.println("No Movement");
Serial.println("Light on");
}
}
void loop() {
// put your main code here, to run repeatedly:
buzzer();
allPir();
}
The countdown should have finished first with a buzzer sound, then the light will turn on, then the PIR sensor will check the environment. How to fix it? and what do I need to add?

Issue while reading data from I2c Slave device with PIC16F886

I am newbie to Pic Programming, I am using MPLAb & Hitech compiler to execute above code. I am trying to Interface PIC16F886 with ISL12022M Real time I2C device. i copied code example written for DS1307 interface with 16F887A PIC. I have capable to inteface Basic functionality with above . In below code While write into ISL12022M o could able to see data what i have send in memory register But as when Trying to read rtc time i could able to read last memory write value From SSPBUF. let me know any error in below code.
once I2c read value should be displayed on 4 digit seven segment display.
I think I am doing Misatake in this part. while Reading data i m just sending address so whatever last written in address it displaying.
#include <htc.h>
#include <stdio.h>
#include<pic.h>
#include<stdint.h>
#define _XTAL_FREQ 40000000
unsigned int i=0;
unsigned int k=0;
unsigned int count;
#define Pulse RA5
#define LED RC0
#define LED1 RC2
#define CONTROLREG 0xFF
#define SDA RC4 // Data pin for i2c
#define SCK RC3 // Clock pin for i2c
#define SDA_DIR TRISC4 // Data pin direction
#define SCK_DIR TRISC3 // Clock pin direction
#define DP RA4
#define I2C_SPEED 100 // kbps
unsigned short int cnt, num,Dgt=0;;
unsigned short int temp1,temp2,temp3;
unsigned short sec;
unsigned short min;
unsigned short hour;
unsigned short date;
unsigned short month;
unsigned short year;
unsigned short day;
unsigned short int temp=0;
unsigned short r_data;
#define Seg1 0x01
#define Seg2 0x02
#define Seg3 0x04
#define Seg4 0x08
void SetSeg(unsigned short data, unsigned short segno)
{
switch(data)
{
case 0: PORTB = 0x3F; break;
case 1: PORTB = 0x06; break;
case 2: PORTB = 0x5B; break;
case 3: PORTB = 0x4F; break;
case 4: PORTB = 0x66; break;
case 5: PORTB = 0x6D; break;
case 6: PORTB = 0x7D; break;
case 7: PORTB = 0x07; break;
case 8: PORTB = 0x7F; break;
case 9: PORTB = 0x6F; break;
default : PORTB = 0X00; break;
}
if(segno==1)
{
PORTA = Seg4;
}
if(segno==2)
{
PORTA = Seg3;
}
if(segno==3)
{
PORTA = Seg2;
}
if(segno==4)
{
PORTA = Seg1;
}
}
void Delay(int k)
{
int j;
for(j=0;j<k;j++);
}
void InitI2C(void)
{
SDA_DIR = 1; // Make SDA and
SCK_DIR =0; // SCK pins input
SSPCON = 0b00111000; //enables port for i2c
SSPCON2 = 0b00000000;
SSPADD = 10; // 100KHz = 8MHz/4(SSPADD+1)
// SSPSTAT = 0b11000000; // Slew rate disabled
}
void i2c_waitForIdle(void)
{
unsigned int i2ctimeout;
while(1)
{
i2ctimeout++;
if(i2ctimeout > 10)
{
i2ctimeout = 0;
return;
}
}
}
void I2C_Start(void)
{
SEN = 1; // Send start bit
i2c_waitForIdle();
/* while(!SSPIF); // Wait for it to complete
SSPIF = 0; // Clear the flag bit*/
}
void I2C_ReStart(void)
{
RSEN = 1; // Send Restart bit
i2c_waitForIdle();
/* while(!SSPIF); // Wait for it to complete
SSPIF = 0; // Clear the flag bit
while(RSEN==1);*/
}
void I2C_Stop(void)
{
PEN = 1; // Send stop bit
i2c_waitForIdle();
}
void I2C_Send_ACK(void)
{
ACKDT = 0; // 0 means ACK
ACKEN = 1; // Send ACKDT value
i2c_waitForIdle();
}
void I2C_Send_NACK(void)
{
ACKDT = 1; // 1 means NACK
ACKEN = 1; // Send ACKDT value
i2c_waitForIdle();
}
unsigned char I2C_Write( unsigned char i2cWriteData )
{
i2c_waitForIdle();
SSPBUF = i2cWriteData;
return (!ACKSTAT); // function returns '1'
}
int I2C_Read( unsigned char ack )
{
unsigned char i2cReadData;
//unsigned int i2cReadData;
i2c_waitForIdle();
RCEN = 1;
SDA=1;
SCK=1;
i2c_waitForIdle();
i2cReadData = SSPBUF;
SCK=0;
i2c_waitForIdle();
SCK=1;
if(ack)
{
ACKDT = 0;
}
else
{
ACKDT = 1;
}
ACKEN = 1; // send acknowledge sequence
return( i2cReadData );
}
unsigned int bcdtodecimal(unsigned int bcd)
{
unsigned int decimal;
decimal = (((bcd & 0xF0) >> 4) * 10) + (bcd & 0x0F);
return decimal;
}
void Init_ISL12022M(void)
{
I2C_Start(); // Start I2C communication
I2C_Write(0XD0); //Write Device Address
I2C_Write(0X08); //
I2C_Write(0X41); // Write 0x00 to Control register to disable SQW-Out
I2C_Stop(); // Stop I2C communication after initilizing
}
unsigned int Write_ISL12022M(unsigned short address, unsigned short w_data)
{
I2C_Start(); // Start I2C communication
I2C_Write(0XD0);
I2C_Write(address); //write address to write data
I2C_Write(w_data); //write data into hexadecimal
I2C_Stop();//stop I2C communication
return(w_data);
}
unsigned short Read_ISL12022M(unsigned short address)
{
I2C_Start();
I2C_Write(address); //address 0x68 followed by direction bit (0 for write, 1 for read) 0x68 followed by 0 --> 0xD0
I2C_Write(address);
I2C_ReStart();
I2C_Write(0xD1); //0x68 followed by 1 --> 0xD1
r_data=I2C_Read(0);
I2C_Stop();
return(r_data);
}
void SetDateTime()
{
I2C_Start();
I2C_Write(0xD0);
I2C_Write(0x00);
sec= Write_ISL12022M(0X00, 12); //01 sec
min = Write_ISL12022M(0X01,52); //01 sec
hour = Write_ISL12022M(0X02,9); //01 sec
day= Write_ISL12022M(0X03,7); //01 sec
date = Write_ISL12022M(0X04, 29); //01 sec
month =Write_ISL12022M(0X05,07); //01 sec
year = Write_ISL12022M(0X06,17); //01 sec
I2C_Stop();
}
void RTC_GetDateTime()
{
I2C_Start(); // Start I2C communication
I2C_Send_ACK();
sec = I2C_Read(1); // read second and return Positive ACK
I2C_Send_ACK();
min = I2C_Read(1); // read minute and return Positive ACK
I2C_Send_ACK();
hour= I2C_Read(0); // read hour and return Negative/No ACK
I2C_Send_ACK();
day = I2C_Read(1); // read weekDay and return Positive ACK
I2C_Send_ACK();
date= I2C_Read(1); // read Date and return Positive ACK
I2C_Send_ACK();
month=I2C_Read(1); // read Month and return Positive ACK
I2C_Send_ACK();
year =I2C_Read(0); // read Year and return Negative/No ACK
I2C_Send_ACK();
I2C_Stop(); // Stop I2C communication after reading the Date
}
void interrupt isr(void)
{
if(TMR1IF==1)
{
TMR1H=0xF6; // Load the time value(0xBDC) for 100ms delay
TMR1L=0x18; //Timer1 Interrupt for 65000
TMR1IF=0; // Clear timer interrupt flag
Dgt++;
if(Dgt>=5)
{
Dgt=0;
LED=!LED;
}
}
}
void Timer1_Interrupt()
{
INTCON = 0b00000000;
PIE1=0b00000001;
PIR1=0x01;
TMR1H=0x0B;
TMR1L=0xDC;
T1CON=0x31;
}
void Init_Controller()
{
cnt=100;
TRISC=0b01000000; // Intialize INput & output pheripherals
TRISB=0b10000000;
PORTB = 0b00000000;
TRISA=0b0000000;
ADCON0 = 0b00000000;
ANSEL = 0b00000000;
Timer1_Interrupt();
}
void main(void)
{
Init_Controller();
/* GIE=1;
PEIE=1;
TMR1IE=1; */
InitI2C();
Init_ISL12022M();
SetDateTime();
while(1)
{
RTC_GetDateTime();
SetSeg(year/ 10,2);
SetSeg(year%10,1);
}
}
The lines like:
I2C_Write(0XD0); //Write Device Address
are not a valid device addresses. Use 0xDE (or 0xAE for User SRAM)
From the datasheet:
Following a start condition, the master must output a Slave Address Byte. The 7 MSBs are the device identifiers. These bits are “1101111” for the RTC registers and “1010111” for the User SRAM.

How to get Ultrasonic Sensor to work properly with Arduino Uno?

I have a HC-SR04 Ultrasonic sensor connected to my Arduino Uno. The problem I'm having is when I check the Serial Monitor to see if the sensor is working: it only says "Out of Range" regardless of the distance. I believe I may have the distance calculation wrong because the RedLED stays on and the buzzer doesn't go off.
Here's my .ino code:
#define trigPin 6
#define echoPin 7
#define RedLED 9
#define buzzer 3
int sound = 500;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(RedLED, OUTPUT);
pinMode(buzzer, OUTPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/5) / 29.1;
if (distance < 20) {
digitalWrite(RedLED, HIGH);
sound = 1000;
}
else {
digitalWrite(RedLED,LOW);
}
if (distance > 20 || distance <= 0){
Serial.println("Out of range");
noTone(buzzer);
}
else {
Serial.print(distance);
Serial.println(" cm");
tone(buzzer, sound);
}
delay(300);
}
Can't post a comment so I'll post it in Answer.
Check that you have connected VCC to 5v and not to 3.3v.
I think your calculations are ok. Also to exclude calculations just print the duration and see if it changes.

AVR Atmega8 ADC input causes Crash

i am trying to Read an Voltage Level via a ADC0 of my ATmega8, because of querying a 1 Pin 4x4 Matrix Keypad. The Problem is everytime I apply a Voltage to the ADC higher than GND the Atmega is stopping to do his work. The PWM outputs are still working, but communication via i2c is impossible and the LCD is clear.
My wiring is simple, AREF & AVCC are set to 5V, GND is set to GND and PC0 is my Input. Is there anything I fail to Notice? Thank You for your help.
Here is my Code:
void Initialisierung(void)
{
char text [2];
lcd_init();
cli();
//### TWI
init_twi_slave(SLAVE_ADRESSE); //TWI als Slave mit Adresse slaveadr starten
sei();
lcd_setcursor( 0, 1 );
lcd_string(">Booting...");
lcd_setcursor( 0, 2 );
itoa (SLAVE_ADRESSE,text,16);
lcd_string("I2C Adress=0x");
lcd_string(text);
for (int Index=0; Index<85; ++Index) {
rxbuffer[Index] = 0x20;
}
rxbuffer[81]=0xFF;
rxbuffer[82]=0xFF;
rxbuffer[83]=0xFF;
rxbuffer[84]=0xFF;
}
//update LCD
void lcd_update(void){
for (int o=1;o<=4; o++)
for (int i=1; i<=20; i++){
lcd_setcursor( i-1, o );
lcd_data(rxbuffer[i+((o-1)*20)]);
}
}
An here is the main function:
int main(void)
{
DDRC &= ~(1 << PC0);
PORTC &= ~(1 << PC0);
Initialisierung();
DDRB = (1 << DDB1) | (1 << DDB2);
OCR1A = eeprom_read_word(&brightness); // PWM einstellen,
OCR1B = eeprom_read_word(&contrast);
ICR1 = 1000; // TOP-wert
TCCR1A = (1<<COM1A1) | (1<<COM1B1) | (1<<WGM11); // 2-Kanal "non-inverting"
TCCR1B = (1<<WGM13)|(1<<WGM12) | (1<<CS11);
//Initialize ADC
ADCSRA = (1<<ADEN) | (1<<ADPS2) | (1<<ADPS0);
ADMUX=0x00;
unsigned int adc_value=0; // Variable to hold ADC result
char text[2];
while(1)
{
ADCSRA |= (1<<ADSC); // Start conversion
while (ADCSRA & (1<<ADSC)); // wait for conversion to complete
adc_value = ADCW; //Store ADC value
itoa (adc_value,text,16);
lcd_setcursor( 0,4 );
lcd_string(text);
for (int Index=0; Index<85; ++Index) {
txbuffer[Index] = rxbuffer[Index];
}
uint16_t brightness_i2c=0;
uint16_t contrast_i2c=0;
brightness_i2c=(rxbuffer[81]<<8)|(rxbuffer[82]);
contrast_i2c=(rxbuffer[83]<<8)|(rxbuffer[84]);
if (rxbuffer[0]==1){
lcd_update();
rxbuffer[0]=4;
}else if(brightness_i2c!=eeprom_read_word(&brightness) && brightness_i2c!=0xFFFF){
eeprom_write_word(&brightness,brightness_i2c);
OCR1A = eeprom_read_word(&brightness);
}else if (contrast_i2c!=eeprom_read_word(&contrast) && contrast_i2c!=0xFFFF){
eeprom_write_word(&contrast,contrast_i2c);
OCR1B = eeprom_read_word(&contrast);
}else{
for (uint8_t i=0; i<50; i++) _delay_ms(10);
lcd_setcursor( 19, 4 );
lcd_data(0xFF);
for (uint8_t i=0; i<50; i++) _delay_ms(10);
lcd_setcursor( 19, 4 );
lcd_data(0x20);
}
}
}
I finally got it:
I setup the ADC with interrupts but not freerunning:
ADCSRA =(1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADIE)| (1<<ADPS0);
And call the ADC everytime at the end of my While loop:
ADCSRA |= (1<<ADSC);
Here is the Code for the ISR:
ISR(ADC_vect)
{
char text[5];
itoa (ADC,text,16);
lcd_setcursor( 0,4 );
lcd_string(text);
}
Thanks for your time ;)

Arduino Uno code broken

I am having trouble making this binary counter, to count minutes and seconds. When I try to verify, I get the error below. How do I fix this broken code?
Error message
Expected `;' before '}' token
Code
#define DATA 0
#define LATCH 1
#define CLOCK 2
#define DATA2 3
#define LATCH2 4
#define CLOCK2 5
void setup()
(
pinMode{LATCH, OUTPUT};
pinMode(CLOCK, OUTPUT);
pinMode(DATA, OUTPUT);
pinMode(LATCH2, OUTPUT);
pinMode(CLOCK2, OUTPUT);
pinMode(DATA2, OUTPUT);
)
void loop()
{
int i;
for (i = 0; i < 256; i++)
{
digitalWrite(LATCH, LOW);
shiftOut(DATA, CLOCK, MSBFIRST, i);
digitalWrite(LATCH, HIGH);
delay(200);
}
int c;
for (c = 0; c < 256; c++)
{
digitalWrite(LATCH2, LOW);
shiftOut(DATA2, CLOCK2, MSBFIRST, c);
digitalWrite(LATCH2, HIGH);
delay(100)
}
}
The problem is in this section (also pinMode{LATCH, OUTPUT};, as in comments):
void setup()
(
pinMode{LATCH, OUTPUT};
pinMode(CLOCK, OUTPUT);
pinMode(DATA, OUTPUT);
pinMode(LATCH2, OUTPUT);
pinMode(CLOCK2, OUTPUT);
pinMode(DATA2, OUTPUT);
)
The parenthesis pair should be a pair of curly brackets (braces):
void setup()
{
pinMode(LATCH, OUTPUT);
pinMode(CLOCK, OUTPUT);
pinMode(DATA, OUTPUT);
pinMode(LATCH2, OUTPUT);
pinMode(CLOCK2, OUTPUT);
pinMode(DATA2, OUTPUT);
}

Resources