I have made a simple program that controls a 10-LED bar graph and the speed in which the LEDs change is supposed to be controlled by a 10K POT. I am using 16F88 (and CSS Compiler/Mplab v8.91) for this simple Program, but the 10k POT is not responding to a full turn of the POT. Only toward in the Last 5% of MAX on the POT, does the speed change a few steps. From Minimum to 95% (of MAX) there is no change in the speed of output of the LEDs.
All other parts of the code with. Just need to get this POT figured out.
Thanks in Advance!
#include <16f88.h>
#device ADC=10
#device *=16
#ZERO_RAM
//////// Fuses: LP,XT,HS,EC_IO,NOWDT,WDT,NOPUT,PUT,MCLR,NOMCLR,BROWNOUT
//////// Fuses: NOBROWNOUT,LVP,NOLVP,CPD,NOCPD,WRT,NOWRT,DEBUG,NODEBUG,CCPB0
//////// Fuses: CCPB3,PROTECT,NOPROTECT,INTRC,INTRC_IO,RC,RC_IO,FCMEN
//////// Fuses: NOFCMEN,IESO,NOIESO
#fuses INTRC_IO,NOWDT,PUT, NOMCLR, PROTECT, NOBROWNOUT, NOLVP, NOWRT, NOCPD
#use delay(clock=4000000)
#use fast_io(A)
#use fast_io(B)
#byte PORTA = 0x5
#byte PORTB = 0x6
/**********************************************************************/
/* PIC interface */
/**********************************************************************/
#bit LED1 = PORTA.1 //Output
#bit LED2 = PORTA.2
#bit LED3 = PORTA.3
#bit LED4 = PORTA.4
#bit LED5 = PORTA.6
#bit LED6 = PORTA.7
#bit LED7 = PORTB.0
#bit LED8 = PORTB.1
#bit LED9 = PORTB.2
#bit LED10 = PORTB.3
#bit LED_GREEN = PORTB.4
#bit SP_OUT = PORTB.5 //Short Pulse
/**************************************************************************
* Global Variables
**************************************************************************/
int speed, state, adc0;
unsigned int16 t,t1, t2,t3, t4;
short flag, flag1,flag2;
/**************************************************************************
* Speed
**************************************************************************/
void f_speed(void) {
SET_ADC_CHANNEL(0);
delay_us(100);
adc0 = READ_ADC();
if(adc0<1) adc0=1;
if(adc0>0 && adc0<=32)
t2=2800; //280ms
if(adc0>32 && adc0<=64)
t2=2450;; //245ms
if(adc0>64 && adc0<=96)
t2=2100; //210ms
if(adc0>96 && adc0<=128)
t2=1750;
if(adc0>128 && adc0<=160)
t2=1400;
if(adc0>160 && adc0<=192)
t2=1050;
if(adc0>192 && adc0<=224)
t2=700;
if(adc0>224 && adc0<=256)
t2=350; //35ms
}
/**************************************************************************
* Mode 1 basic Scan
**************************************************************************/
void f_mode_1(void) {
// SPM_BASIC_SCAN
if(flag1){
flag1=0;
flag2=1;
t=0;
}
if(flag2){
if(t>10){
SP_OUT=1;
flag2=0;
t4=0;
}
}
switch(state){
case 1:
// PORTA = 0b00000001; // SCAN STARTS
LED1=1;
if(t3>t2){
t3=0;
state=2;
LED1=0;
}
break;
case 2:
LED2=1;
if(t3>t2){
t3=0;
state=3;
LED2=0;
}
break;
case 3:
LED3=1;
if(t3>t2){
t3=0;
state=4;
LED3=0;
}
break;
case 4:
LED4=1;
if(t3>t2){
t3=0;
state=5;
LED4=0;
}
break;
case 5:
LED5=1;
if(t3>t2){
t3=0;
state=6;
LED5=0;
}
break;
case 6:
LED6=1;
if(t3>t2){
t3=0;
state=7;
LED6=0;
}
break;
case 7:
LED7=1;
if(t3>t2){
t3=0;
state=8;
LED7=0;
}
break;
case 8:
LED8=1;
if(t3>t2){
t3=0;
state=9;
LED8=0;
}
break;
case 9:
LED9=1;
if(t3>t2){
t3=0;
state=10;
LED9=0;
}
break;
case 10:
LED10=1;
if(t3>t2){
t3=0;
state=11;
LED10=0;
}
break;
case 11:
LED9=1;
if(t3>t2){
t3=0;
state=12;
LED9=0;
}
break;
case 12:
LED8=1;
if(t3>t2){
t3=0;
state=13;
LED8=0;
}
break;
case 13:
LED7=1;
if(t3>t2){
t3=0;
state=14;
LED7=0;
}
break;
case 14:
LED6=1;
if(t3>t2){
t3=0;
state=15;
LED6=0;
}
break;
case 15:
LED5=1;
if(t3>t2){
t3=0;
state=16;
LED5=0;
}
break;
case 16:
LED4=1;
if(t3>t2){
t3=0;
state=17;
LED4=0;
}
break;
case 17:
LED3=1;
if(t3>t2){
t3=0;
state=18;
LED3=0;
}
break;
case 18:
LED2=1;
if(t3>t2){
t3=0;
state=1;
LED2=0;
}
break;
}
}
/**************************************************************************
* Clear_LED
**************************************************************************/
void Clear_LED(void){
LED1=0;
LED2=0;
LED3=0;
LED4=0;
LED5=0;
LED6=0;
LED7=0;
LED8=0;
LED9=0;
LED10=0;
}
/*************************************************************************
* timer0 Interrupts 100useg
**************************************************************************/
#INT_TIMER0
void TIMER0_isr()
{
set_timer0(156);
t3++; // Speed timer
t4++; //Short pulse timer
if(t4>5000) {
t4=0; //500ms
SP_OUT = 0;
}
}
/*************************************************************************
* timer1 Interrupts 100ms
**************************************************************************/
#INT_TIMER1
void TIMER1_isr()
{
set_timer1(53036);
t++;
t1++;
}
/**************************************************************************
* interruption for change RB4-RB7
**************************************************************************/
#int_rb
void detect_rb_change(void) {
disable_interrupts(INT_RB);
int current;
static int last=0;
current=PORTB;
if ((!bit_test(current,7))&&(bit_test(last,7))) {
flag=!flag;
if(flag){ //ON
LED_GREEN=1;
state=1;
t3=0;
f_speed();
flag1=1;
} else{ //OFF
LED_GREEN=0;
}
}
last=current;
enable_interrupts(INT_RB);
}
/**************************************************************************
* Main Progran
**************************************************************************/
void main()
{
set_tris_a(0x00);
set_tris_b(0x80);
setup_adc_ports(sAN0);
setup_adc(VSS_VDD | ADC_CLOCK_DIV_8);
setup_timer_1(T1_INTERNAL|T1_DIV_BY_8);
setup_timer_0(T0_INTERNAL|T0_DIV_0);
Clear_LED();
LED_GREEN=0;
SP_OUT=0;
flag=false;
state=1;
f_speed();
t3=0;
t1=0;
set_timer1(53036); //Interrupts 100ms
set_timer0(156); //Interrupts 100us
enable_interrupts(INT_TIMER0);
enable_interrupts(INT_RB);
enable_interrupts(INT_TIMER1);
enable_interrupts(GLOBAL);
while(1)
{
if(flag){ //ON
if(t1>10){
t1=0;
f_speed();
}
f_mode_1();
} else{
Clear_LED();
}
}
}
Related
I'm trying to create a bop it game with 2 players where:
Green LED – Gyro Sensor (Z-axis)
Red LED – Temperature sensor
Blue LED – Sound sensor
Yellow LED – Light Sensor
However when I press the left button to start the game, only the yellow light above GND goes on and doesn't respond to anything, what can be wrong with my code?
long randNumber;
int temp;
int val;
int number;
int score;
boolean state;
int light;
uint8_t pixeln = 0;
int sound;
int shake;
unsigned long lastmillis = 0;
boolean game;
const byte numPins = 7;
byte pins[] = {0, 1, 2, 3, 4, 5, 6, 7};
int player1 = 0;
int player2 = 0;
#include "Adafruit_CircuitPlayground.h"
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
CircuitPlayground.begin();
CircuitPlayground.clearPixels();
//timer();
}
void loop() {
if (digitalRead(4) == HIGH && digitalRead(19) == LOW){
Serial.println("Button Pressed");
lastmillis = millis();
for (int i=0; i < 10; i ){
randNumber = random(4);
//Serial.println("Loop");
switch (randNumber){
//Serial.println("Switch");
case 0:
while (pixeln < 10){
CircuitPlayground.setPixelColor(pixeln , 255,0,0);
CircuitPlayground.strip.show();
}
pixeln = 0;
state = true;
temp = analogRead(A0);
//Serial.println(temp);
while (state == true) {
val = analogRead(A0);
number = val - temp;
if (number > 10){
score ;
state = false;
//Serial.println("Temperature");
delay(500);
}
}
break;
case 1:
while (pixeln < 10){
CircuitPlayground.setPixelColor(pixeln , 127,127,0);
CircuitPlayground.strip.show();
}
pixeln = 0;
state = true;
light = analogRead(A5);
//Serial.println(light);
while (state == true) {
val = analogRead(A5);
number = light - val;
if (number > 20){
score ;
state = false;
//Serial.println(number);
delay(500);
}
}
break;
case 2:
while (pixeln < 10){
CircuitPlayground.setPixelColor(pixeln , 0,0,255);
CircuitPlayground.strip.show();
}
pixeln = 0;
state = true;
sound = analogRead(A4);
//Serial.println(sound);
while (state == true) {
val = analogRead(A4);
number = val - sound;
if (number > 50){
score ;
state = false;
//Serial.println(number);
delay(500);
}
}
break;
case 3:
while (pixeln < 10){
CircuitPlayground.setPixelColor(pixeln , 0,255,0);
CircuitPlayground.strip.show();
}
pixeln = 0;
val = CircuitPlayground.motionZ();
//Serial.println(val);
state = true;
while (state == true) {
shake = CircuitPlayground.motionZ();
number = val - shake;
//Serial.println(number);
if (number > 15 or number < -15){
score ;
state = false;
//Serial.println("shake");
delay(500);
}
}
break;
case 4:
CircuitPlayground.clearPixels();
CircuitPlayground.setPixelColor(0, 0,255,0);
CircuitPlayground.setPixelColor(1, 0,255,0);
CircuitPlayground.strip.show();
delay(3000);
break;
case 5:
CircuitPlayground.clearPixels();
CircuitPlayground.setPixelColor(3, 255,0,0);
CircuitPlayground.setPixelColor(4, 255,0,0);
CircuitPlayground.strip.show();
delay(3000);
break;
case 6:
CircuitPlayground.clearPixels();
CircuitPlayground.setPixelColor(5, 127,0,255);
CircuitPlayground.setPixelColor(6, 127,0,255);
CircuitPlayground.strip.show();
delay(3000);
break;
case 7:
CircuitPlayground.clearPixels();
CircuitPlayground.setPixelColor(8, 255,128,0);
CircuitPlayground.setPixelColor(9, 255,128,0);
CircuitPlayground.strip.show();
delay(3000);
}
}
if (CircuitPlayground.slideSwitch()) {
player1 = (millis() - lastmillis) / 1000;
Serial.println(player1);
CircuitPlayground.clearPixels();
byte num = player1;
for (byte i=0; i < numPins; i ){
byte state = bitRead(num, i);
if (state == 1){
CircuitPlayground.setPixelColor(pins[i], 255,255,255);
CircuitPlayground.strip.show();
}
}
} else {
player2 = (millis() - lastmillis) /1000;
Serial.println(player2);
CircuitPlayground.clearPixels();
byte num = player2;
for (byte i=0; i < numPins; i ){
byte state = bitRead(num, i);
if (state == 1){
CircuitPlayground.setPixelColor(pins[i], 255,255,255);
CircuitPlayground.strip.show();
}
}}
CircuitPlayground.playTone(330, 500);
}
while (digitalRead(19) == HIGH && digitalRead(4) == LOW){
if (player1 < player2){
CircuitPlayground.clearPixels();
delay(250);
for (int i =0; i < 5; i ){
CircuitPlayground.setPixelColor(i, 255,255,255);
CircuitPlayground.strip.show();
}
delay(250);
CircuitPlayground.clearPixels();
}
else if (player1 > player2){
CircuitPlayground.clearPixels();
delay(250);
for (int i =5; i < 10; i ){
CircuitPlayground.setPixelColor(i, 255,255,255);
CircuitPlayground.strip.show();
}
delay(250);
CircuitPlayground.clearPixels();
}
else {
CircuitPlayground.clearPixels();
delay(250);
for (int i =0; i < 10; i ){
CircuitPlayground.setPixelColor(i, 255,255,255);
CircuitPlayground.strip.show();
}
delay(250);
CircuitPlayground.clearPixels();
}
}
if (digitalRead(19) == HIGH && digitalRead(4) == HIGH){
player1 = 0;
player2 = 0;
for (int a =0; a < 10; a ){
CircuitPlayground.clearPixels();
delay(100);
for (int i =0; i < 10; i ){
CircuitPlayground.setPixelColor(i, CircuitPlayground.colorWheel(25 * i));
CircuitPlayground.strip.show();
}
delay(100);
CircuitPlayground.clearPixels();
}
}
}
visual after pressing left button:
I'm making a gamepad on a joystick using an arduino pro micro.
Input commands such as up and down from the console, raspberry pi's gpio will output them and the arduino will receive them and input them to the game machine.
I use the ArduinoJoystickLibrary.
https://github.com/MHeironimus/ArduinoJoystickLibrary
I want to play a GBA game, but the Dpad stays typed.
How can I press the up key only once?
Also, in the gif below, the up and down keys are pressed once at a time, but pressing the right key or other keys in the middle does not respond.
As an addendum, I use a game console called retro freak.
retro freak
The code uses the following
arduino_pro_micro_gamepad.ino
#include <Joystick.h>
#define OFFSET_BUTTON 2
#define OFFSET_DPAD 18
Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID,JOYSTICK_TYPE_GAMEPAD,
4, 0, // Button Count, Hat Switch Count
true, true, false, // X and Y, but no Z Axis
false, false, false, // No Rx, Ry, or Rz
false, false, // No rudder or throttle
false, false, false); // No accelerator, brake, or steering
void setup() {
// Initialize Button Pins
pinMode(2, INPUT_PULLUP); // Button 1
pinMode(3, INPUT_PULLUP); // Button 2
pinMode(4, INPUT_PULLUP); // Button 3
pinMode(5, INPUT_PULLUP); // Button 3
pinMode(18, INPUT_PULLUP); // D-pad Up
pinMode(19, INPUT_PULLUP); // D-pad Right
pinMode(20, INPUT_PULLUP); // D-pad Down
pinMode(21, INPUT_PULLUP); // D-pad Left
Joystick.begin();
Joystick.setXAxisRange(-1, 1);
Joystick.setYAxisRange(-1, 1);
Joystick.setYAxis(0);
Joystick.setYAxis(0);
}
// Last state of the buttons
int lastDpadState[4] = {0,0,0,0}; // Up, Right, Down, Left
int lastButtonState[4] = {0,0,0,0}; // Button 1 - 4
void updateDpad() {
for (int i = 0; i <= 3; i++) {
int currentDpadState = digitalRead(i + OFFSET_DPAD);
if (currentDpadState != lastDpadState[i]) {
switch (i) {
case 0: // UP
if (currentDpadState == 1) {
Joystick.setYAxis(-1);
}
break;
case 1: // RIGHT
if (currentDpadState == 1) {
Joystick.setXAxis(1);
}
break;
case 2: // DOWN
if (currentDpadState == 1) {
Joystick.setYAxis(1);
}
break;
case 3: // LEFT
if (currentDpadState == 1) {
Joystick.setXAxis(-1);
}
break;
}
lastDpadState[i] = currentDpadState;
}
}
}
void updateButton() {
for (int i = 0; i <= 3; i++) {
int currentButtonState = !digitalRead(i + OFFSET_BUTTON);
if (currentButtonState != lastButtonState[i]) {
Joystick.setButton(i, currentButtonState);
lastButtonState[i] = currentButtonState;
}
}
}
void loop() {
updateDpad();
updateButton();
delay(5);
}
raspi_game_input.py
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT, initial=GPIO.HIGH)
GPIO.setup(27, GPIO.OUT, initial=GPIO.HIGH)
GPIO.setup(23, GPIO.OUT, initial=GPIO.HIGH)
GPIO.setup(24, GPIO.OUT, initial=GPIO.HIGH)
GPIO.setup(16, GPIO.OUT, initial=GPIO.HIGH)
GPIO.setup(20, GPIO.OUT, initial=GPIO.HIGH)
GPIO.setup(21, GPIO.OUT, initial=GPIO.HIGH)
GPIO.setup(26, GPIO.OUT, initial=GPIO.HIGH)
def on(gpio_number):
GPIO.output(gpio_number, GPIO.LOW)
sleep(0.05)
GPIO.output(gpio_number, GPIO.HIGH)
def key_select(input_key):
if input_key == 'a':
on(17)
elif input_key == 'b':
on(27)
elif input_key == 'home':
on(23)
elif input_key == 'game':
on(24)
elif input_key == 'u':
on(16)
elif input_key == 'd':
on(20)
elif input_key == 'r':
on(21)
elif input_key == 'l':
on(26)
else:
pass
if __name__ == '__main__':
try:
while True:
print('push button')
key = input()
print(f'input is ${key}')
key_select(key)
except KeyboardInterrupt:
GPIO.cleanup()
Just a little fix in the code, in setup();
Joystick.setYAxis(0);
Joystick.setYAxis(0);
change to:
Joystick.setXAxis(0);
Joystick.setYAxis(0);
Try to reset to initial values before... or after the action.
if (currentDpadState != lastDpadState[i]) {
reset();
switch (i) {
...
}
}
void reset(){
Joystick.setXAxis(0);
Joystick.setYAxis(0);
}
My problem was using a joystick instead of a hatSwitch.
The implementation I wanted was to enter the arrow keys only once, so I used hatswitch.
#include <Joystick.h>
#define OFFSET_BUTTON 2
#define OFFSET_DPAD 18
Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID,
JOYSTICK_TYPE_GAMEPAD,
9,1,
false, false, false, false, false, false,
false, false, false, false, false);
void setup() {
pinMode(2, INPUT_PULLUP); // Button 1
pinMode(3, INPUT_PULLUP); // Button 2
pinMode(4, INPUT_PULLUP); // Button 3
pinMode(5, INPUT_PULLUP); // Button 4
pinMode(6, INPUT_PULLUP); // Button 5
pinMode(7, INPUT_PULLUP); // Button 6
pinMode(8, INPUT_PULLUP); // Button 7
pinMode(9, INPUT_PULLUP); // Button 8
pinMode(10, INPUT_PULLUP); // Button 9
pinMode(18, INPUT_PULLUP); // D-pad Up
pinMode(19, INPUT_PULLUP); // D-pad Right
pinMode(20, INPUT_PULLUP); // D-pad Down
pinMode(21, INPUT_PULLUP); // D-pad Left
Joystick.begin();
}
// Last state of the pins
int lastDpadState[2][4] = {{0,0,0,0}, {0,0,0,0}};
int lastButtonState[10] = {0,0,0,0,0,0,0,0,0,0}; // Button 1 - 10
void updateDpad(){
bool valueChanged[2] = {false, false};
int currentPin = 18;
// Read pin values
for (int hatSwitch = 0; hatSwitch < 2; hatSwitch++){
for (int index = 0; index < 4; index++){
int currentDpadState = !digitalRead(currentPin++);
if (currentDpadState != lastDpadState[hatSwitch][index]){
valueChanged[hatSwitch] = true;
lastDpadState[hatSwitch][index] = currentDpadState;
}
}
}
for (int hatSwitch = 0; hatSwitch < 2; hatSwitch++)
{
if (valueChanged[hatSwitch]) {
if ((lastDpadState[hatSwitch][0] == 0)
&& (lastDpadState[hatSwitch][1] == 0)
&& (lastDpadState[hatSwitch][2] == 0)
&& (lastDpadState[hatSwitch][3] == 0)) {
Joystick.setHatSwitch(hatSwitch, -1);
}
if (lastDpadState[hatSwitch][0] == 1) {
Joystick.setHatSwitch(hatSwitch, 0); // up
}
if (lastDpadState[hatSwitch][1] == 1) {
Joystick.setHatSwitch(hatSwitch, 90); // right
}
if (lastDpadState[hatSwitch][2] == 1) {
Joystick.setHatSwitch(hatSwitch, 180); // down
}
if (lastDpadState[hatSwitch][3] == 1) {
Joystick.setHatSwitch(hatSwitch, 270);
}
} // if the value changed
} // for each hat switch
}
void updateButton() {
for (int i = 0; i <= 9; i++) {
int currentButtonState = !digitalRead(i + OFFSET_BUTTON);
if (currentButtonState != lastButtonState[i]) {
Joystick.setButton(i, currentButtonState);
lastButtonState[i] = currentButtonState;
}
}
}
void loop() {
updateDpad();
updateButton();
delay(50);
}
I keep getting the following error message when I'm trying to run my code. I can not figure out how to correct these errors so I can test everything. Even though these are just warning messages and the code says it uploads. I don't get any messages on my serial monitor printing any statements.
Code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F,16,2); // set the LCD address for a 16 chars and 2 line display
const int guessPin = 7;
const int switch0Pin = 13;
const int switch1Pin = 12;
const int switch2Pin = 11;
const int switch3Pin = 10;
const int switch4Pin = 9;
int currentLetterIndex = 0;
int currentClueIndex = 0;
int currentGuess = 0;
int lastGuess = 0;
bool debug = false; // set to false to turn off serial output
unsigned long previousMillis = 0;
long restInterval = 20 * 1000; // 20 second time out to conserve battery
char clueBreak[] = "Get clue at the next house :)";
char hintBreak[] = "ah ah ah... must be patient";
char answerBreak[] = "santa";
char clue1[] = "The place we first meet?";
char hint1[] = "Company... not city";
char answer1[] = "pcc";
char clue2[] = "The play we saw in NY";
char hint2[] = "muppets... no...";
char answer2[] = "avenueq";
char clue3[] = "What we worn in Times Square";
char hint3[] = "look me in the eyes...";
char answer3[] = "diapers";
char clue4[] = "Where I said 'I Love You'";
char hint4[] = "And you later threw up on me...";
char answer4[] = "tonys";
char clue5[] = "";
char hint5[] = "+++ ++ ++++ ++++";
char answer5[] = "";
char clue6[] = "When do we do anything?";
char hint6[] = "'bye' 'see you +++++++'";
char answer6[] = "maybe tomorrow";
char clue7[] = "The animal you pet in gatlinburg";
char hint7[] = "spell the numbers...";
char answer7[] = "jellyfish";
char clue8[] = "These are only in California";
char hint8[] = "the one you used to sleep with";
char answer8[] = "seven eleven";
char clue9[] = "Where did you buy your cat?";
char hint9[] = "(-_-) R-O-B-O-T";
char answer9[] = "japan";
char clue10[] = "The ugliest car color...";
char hint10[] = "your second favorite color";
char answer10[] = "yellow";
char clue11[] = "Our first wine and paint";
char hint11[] = "__ _____ _____";
char answer11[] = "no drama llama";
const int cluesNum = 10; // clues + breaks
char * hints[] = {
hint1,
hint2,
hint3,
hint4,
hint5,
hint6,
hint7,
hint8,
hint9,
hint10,
hint11,
};
char * clues[] = {
clue1,
clue2,
clue3,
clue4,
clue5,
clue6,
clue7,
clue8,
clue9,
clue10,
clue11,
};
char * answers[] = {
answer1,
answer2,
answer3,
answer4,
answer5,
answer6,
answer7,
answer8,
answer9,
answer10,
answer11,
};
char currentLine1[17]; // need extra char for null pointer
char currentLine2[17]; // need extra char for null pointer
bool isDisplayingClue = true;
void setup()
{
pinMode(guessPin, INPUT);
pinMode(switch0Pin, INPUT);
pinMode(switch1Pin, INPUT);
pinMode(switch2Pin, INPUT);
pinMode(switch3Pin, INPUT);
pinMode(switch4Pin, INPUT);
lcd.init();
lcd.backlight();
if (debug)
{
Serial.begin(9600);
}
}
void updateDisplayFromArray(const char *str)
{
int limit = getCharSize(str)-1;
for (int i = 0; i >= 16; i++)
{
if (i <= limit)
{
currentLine1[i] = str[i];
}
if (i+16 <= limit)
{
currentLine2[i] = str[i+16];
}
}
}
int getCharSize(const char *cArray)
{
return sizeof(cArray) / sizeof(char);
}
void logger(const char *message)
{
if (debug)
{
Serial.println(message);
}
}
void restLCD()
{
lcd.setBacklight(0);
lcd.noDisplay();
}
void showLCD()
{
isDisplayingClue = false;
previousMillis = millis();
lcd.setBacklight(50);
lcd.display();
}
void TypeAnimation(const char *line1, const char *line2, int delayTime)
{
lcd.clear();
for (int i = 0; i <= getCharSize(line1)-1; i++) {
lcd.setCursor(i,0);
lcd.print(line1[i]);
delay(delayTime);
}
for (int i = 0; i <= getCharSize(line2)-1; i++) {
lcd.setCursor(i,1);
lcd.print(line2[i]);
delay(delayTime);
if (i == getCharSize(line2)-1) {
delay(1000);
}
}
}
void DelayAnimation(const char *line1, const char *line2, int delayTime)
{
setScreen(line1, line2);
delay(delayTime);
}
void setScreen(const char *line1, const char *line2)
{
lcd.clear();
lcd.setCursor(0,0);
lcd.print(line1);
lcd.setCursor(0,1);
lcd.print(line2);
}
void TestAnimations()
{
showLCD();
PlayGuessingAnimation();
PlayCorrectAnimation();
PlayIncorrectAnimation();
ResetClues();
CurrentStatus();
ShowCurrentGuess();
DisplayClue(5000);
restLCD();
delay(5000);
currentLetterIndex++;
}
void ResetClues()
{
DelayAnimation("Resetting...", "",1500);
DelayAnimation("Merry Christmas!", "My Love :)",4000);
TypeAnimation("Old Man Turtle", "has been taken",250);
TypeAnimation("again...", ":(",250);
TypeAnimation("Solve the clues", "to find him",250);
TypeAnimation("Use the button 2", "submit da letter",250);
DelayAnimation("Now for your 1st", "clue",4000);
TypeAnimation("Goodluck my love", ":)",250);
NextClue();
currentLetterIndex = 0;
currentClueIndex = 0;
}
void ShowFinalAnimation()
{
TypeAnimation("You did it!", "",250);
TypeAnimation("You saved", "Old Man Turtle",250);
TypeAnimation("Old Man Turtle", "has left yo",250);
TypeAnimation("Use the button 2", "submit da letter",250);
DelayAnimation("Now for your 1st", "clue",4000);
TypeAnimation("Goodluck my love", ":)",250);
}
void loop()
{
logger("************* NEW LOOP *************");
//PlayGuessingGame();
TestAnimations();
}
void PlayGuessingGame()
{
bool buttonState = digitalRead(guessPin);
char *state = char(buttonState);
logger(state);
ConvertGuess();
if (buttonState)
{
logger("made it inside button guess clicked");
showLCD();
CheckGuess();
}
else
{
if (lastGuess != currentGuess)
{
logger("The guess has changed");
showLCD();
ShowCurrentGuess();
lastGuess = currentGuess;
}
else
{
logger("The guess hasn't changed :(");
if (!isDisplayingClue)
{
DisplayClue(1);
}
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > restInterval * .7)
{
DelayAnimation(" About to enter ", "-- Rest Mode --",1500);
}
if(currentMillis - previousMillis > restInterval)
{
logger("...REST MODE ACTIVATED...");
restLCD();
}
}
}
if (currentClueIndex > cluesNum)
{
ShowFinalAnimation();
}
}
void ConvertGuess()
{
bitWrite(currentGuess,0, !digitalRead(switch0Pin));
bitWrite(currentGuess,1, !digitalRead(switch1Pin));
bitWrite(currentGuess,2, !digitalRead(switch2Pin));
bitWrite(currentGuess,3, !digitalRead(switch3Pin));
bitWrite(currentGuess,4, !digitalRead(switch4Pin));
logger("Beginning conversion of guess");
logger("Pin 0:" + char(!digitalRead(switch0Pin)));
logger("Pin 1:" + char(!digitalRead(switch1Pin)));
logger("Pin 2:" + char(!digitalRead(switch2Pin)));
logger("Pin 3:" + char(!digitalRead(switch3Pin)));
logger("Pin 4:" + char(!digitalRead(switch4Pin)));
logger("new guess is " + char(ConvertIntToLetter(currentGuess)));
}
void CheckGuess()
{
PlayGuessingAnimation();
char guessLetter = ConvertIntToLetter(currentGuess);
char cLetter = clues[currentClueIndex][currentLetterIndex];
if (guessLetter == '-')
{
ResetClues();
}
else if (guessLetter == '+')
{
CurrentStatus();
}
else if (guessLetter == '?')
{
DisplayHint(5000);
}
else if (guessLetter == cLetter)
{
currentLetterIndex++;
if (currentLetterIndex > getCharSize(clues[currentClueIndex])-1)
{
PlayNextClueAnimation();
currentLetterIndex = 0;
currentClueIndex++;
}
PlayCorrectAnimation();
}
else
{
PlayIncorrectAnimation();
}
}
void ShowCurrentGuess()
{
char guess = char(ConvertIntToLetter(currentGuess));
if (guess == '-')
{
DelayAnimation(" DANGER!!! ", "THIS WILL RESET!",5000);
DelayAnimation("Press the button", "will reset",2000);
}
else if (guess == '+')
{
DelayAnimation("This will", "Show current status",2000);
}
else if (guess == '?')
{
DelayAnimation("This will", "Show you a hint",2000);
}
else if (guess == ' ')
{
DelayAnimation("You're Guessing ", "'_' (space)",1500);
}
else
{
DelayAnimation("You're Guessing ", char(guess),1500);
}
}
void CurrentStatus()
{
char currentAnswer[17] = "";
if (currentLetterIndex == 0)
{
strcpy(currentAnswer, "nothing yet :(");
}
else
{
strcpy(currentAnswer, GetCorrectGuesses());
}
DelayAnimation("You've Guessed ", strcat(char(currentClueIndex), " Clues"), 2000);
DelayAnimation("The Current", "Clues Is...", 2000);
DisplayClue(2000);
DelayAnimation("You've got right", currentAnswer, 3000);
}
char GetCorrectGuesses()
{
char result[17];
for(int i = 0; i >= currentLetterIndex; i++)
{
result[i] = answers[currentClueIndex][i];
}
return result;
}
void DisplayClue(int delayTime)
{
updateDisplayFromArray(clues[currentClueIndex]);
DelayAnimation(currentLine1,currentLine1,delayTime);
isDisplayingClue = true;
}
void DisplayHint(int delayTime)
{
updateDisplayFromArray(hints[currentClueIndex]);
TypeAnimation(currentLine1,currentLine1,delayTime);
}
void NextClue()
{
DelayAnimation(" Are you ready?? ", " Clue #" + char(currentClueIndex+1),3000);
DisplayClue(5000);
}
void PlayGuessingAnimation()
{
TypeAnimation("That is...", "",200);
}
void PlayNextClueAnimation()
{
TypeAnimation("HOORAY!!!", "",200);
DelayAnimation("You Got It Right", " Go You ;) ",2000);
TypeAnimation("On to the next", "",200);
NextClue();
}
void PlayCorrectAnimation()
{
DelayAnimation(" CORRECT!!!! ", "",1500);
}
void PlayIncorrectAnimation()
{
DelayAnimation(" Wrong :( ", " Try Again ",2000);
}
char ConvertIntToLetter(int number)
{
int result = '0';
switch (number)
{
case 0:
result = 'a';
break;
case 1:
result = 'b';
break;
case 2:
result = 'c';
break;
case 3:
result = 'd';
break;
case 4:
result = 'e';
break;
case 5:
result = 'f';
break;
case 6:
result = 'g';
break;
case 7:
result = 'h';
break;
case 8:
result = 'i';
break;
case 9:
result = 'j';
break;
case 10:
result = 'k';
break;
case 11:
result = 'l';
break;
case 12:
result = 'm';
break;
case 13:
result = 'n';
break;
case 14:
result = 'o';
break;
case 15:
result = 'p';
break;
case 16:
result = 'q';
break;
case 17:
result = 'r';
break;
case 18:
result = 's';
break;
case 19:
result = 't';
break;
case 20:
result = 'u';
break;
case 21:
result = 'v';
break;
case 22:
result = 'w';
break;
case 23:
result = 'x';
break;
case 24:
result = 'y';
break;
case 25:
result = 'z';
break;
case 26:
result = '!';
break;
case 27:
result = '%';
break;
case 28:
result = ' ';
break;
case 29:
result = '?';
break;
case 30:
result = '-';
break;
case 31:
result = '+';
}
return result;
}
Error Messages:
C:\Users\jb090\Documents\Arduino\ChristmasBoxV3\ChristmasBoxV3.ino: In function 'void PlayGuessingGame()':
C:\Users\jb090\Documents\Arduino\ChristmasBoxV3\ChristmasBoxV3.ino:263:17: warning: invalid conversion from 'char' to 'char*' [-fpermissive]
char *state = char(buttonState);
^~~~~~~~~~~~~~~~~
C:\Users\jb090\Documents\Arduino\ChristmasBoxV3\ChristmasBoxV3.ino: In function 'void ShowCurrentGuess()':
C:\Users\jb090\Documents\Arduino\ChristmasBoxV3\ChristmasBoxV3.ino:378:40: warning: invalid conversion from 'char' to 'const char*' [-fpermissive]
DelayAnimation("You're Guessing ", char(guess),1500);
^~~~~~~~~~~
C:\Users\jb090\Documents\Arduino\ChristmasBoxV3\ChristmasBoxV3.ino:198:6: note: initializing argument 2 of 'void DelayAnimation(const char*, const char*, int)'
void DelayAnimation(const char *line1, const char *line2, int delayTime)
^~~~~~~~~~~~~~
C:\Users\jb090\Documents\Arduino\ChristmasBoxV3\ChristmasBoxV3.ino: In function 'void CurrentStatus()':
C:\Users\jb090\Documents\Arduino\ChristmasBoxV3\ChristmasBoxV3.ino:391:44: warning: invalid conversion from 'char' to 'const char*' [-fpermissive]
strcpy(currentAnswer, GetCorrectGuesses());
~~~~~~~~~~~~~~~~~^~
In file included from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:25:0,
from sketch\ChristmasBoxV3.ino.cpp:1:
c:\program files (x86)\arduino\hardware\tools\avr\avr\include\string.h:305:14: note: initializing argument 2 of 'char* strcpy(char*, const char*)'
extern char *strcpy(char *, const char *);
^~~~~~
C:\Users\jb090\Documents\Arduino\ChristmasBoxV3\ChristmasBoxV3.ino:393:44: warning: invalid conversion from 'char' to 'char*' [-fpermissive]
DelayAnimation("You've Guessed ", strcat(char(currentClueIndex), " Clues"), 2000);
^~~~~~~~~~~~~~~~~~~~~~
In file included from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:25:0,
from sketch\ChristmasBoxV3.ino.cpp:1:
c:\program files (x86)\arduino\hardware\tools\avr\avr\include\string.h:248:14: note: initializing argument 1 of 'char* strcat(char*, const char*)'
extern char *strcat(char *, const char *);
^~~~~~
C:\Users\jb090\Documents\Arduino\ChristmasBoxV3\ChristmasBoxV3.ino: In function 'char GetCorrectGuesses()':
C:\Users\jb090\Documents\Arduino\ChristmasBoxV3\ChristmasBoxV3.ino:406:10: warning: invalid conversion from 'char*' to 'char' [-fpermissive]
return result;
^~~~~~
C:\Users\jb090\Documents\Arduino\ChristmasBoxV3\ChristmasBoxV3.ino:401:8: warning: address of local variable 'result' returned [-Wreturn-local-addr]
char result[17];
^~~~~~
char and char* is very different !
const char* can be slightly more tricky, but you first have to get the difference between a text and a character.
"Hello World" is a text, and usually treated as a pointer or [const] array.
'A' is a character, and internally stored the same way as the number 65 in a variable of type char.
More:
c# (or java) and c++ are very different, too. And there's a lot of truth in the saying "c++ is for masochists" :)
Your first problem
warning: invalid conversion from 'char' to 'char*'
char *state = char(buttonState);
comes from these lines:
bool buttonState = digitalRead(guessPin);
char *state = char(buttonState);
logger(state);
logger(const char*) needs a text to log, but you have a bool. Not sure how you wrote that in c#, and casting won't help. You eventually might want something like
bool buttonState = digitalRead(guessPin);
logger(buttonState? "guessPin is set": "guessPin is LOW");
You cannot cast a variable as a char by doing char(buttonState). In C you cast as follows: (char)buttonState.
There were some minor errors in my code (like incorrect for loop syntax) that was causing me to have run time errors.
I have a Weather Meter, and I am able to read data from it.
My problem occurs, when I try to use the library UnoWiFiDevEd.h send the data to store the information on the internet.
Arduino tells following:
Global variables use 1648 bytes (80%) of dynamic memory, leaving 400 bytes for local variables.
Maximum is 2048 bytes. Low memory available, stability problems may occur.
I have read, that another means, that the Uno WiFi library itself leads almost 50% Dynamic Memory usage.
Do anyone have an idea, how I can minimize memory usage?
Thank you in advance
#include <UnoWiFiDevEd.h>
//temporary rain
float calcTemp1;
int calcTemp2;
//Wind vane
const float table[16] = {3.84, 1.98, 2.25, 0.41, 0.45, 0.32, 0.90, 0.62, 1.40, 1.19, 3.08, 2.93, 4.62, 4.32, 4.78, 3.43}; //charecter 13 is not correct, but is changed due to failure in windvane
char buffer[20];
//Anometer - windpower
volatile unsigned int windRotation = 0;
//Used for timing
float windTimer = 0;
int angle = 0;
//Rain gauge
float RainMeasurement = 0;
unsigned long LastRainReset = 0;
void setup() {
Serial.begin(9600);
Ciao.begin(); // CIAO INIT
Serial.write(13);
delay(2000);
Serial.println("Initialiserer...");
initWind();
initRain();
Serial.println();
delay(1000);
}
void loop() {
doRequest();
Serial.println();
delay(30000);
}
//Gets data about wind
void getWindData(void)
{
Serial.print("Vindretning: ");
Serial.println(printWindDirection(36));
unsigned long WindReading;
WindReading = Vind_GetHastighed();
sprintf(buffer, "Hastighed: %d m/s ", WindReading);
Serial.println(buffer);
}
//Gets data about rain
void getRainData(void)
{
if (LastRainReset+86400000 < millis()) { // LastRainReset > 24 timer
RainMeasurement = 0;
LastRainReset = millis();
}
calcTemp1 = (float)RainMeasurement;
calcTemp2 = (calcTemp1 - (int)calcTemp1) * 100;
sprintf(buffer, "%0d.%d", (int)calcTemp1, calcTemp2);
Serial.print("Nedb\xF8r: ");
Serial.print(buffer);
Serial.println(" mm");
}
void doRequest(){
String resource = "upload.php?key=secretKey";
resource += "&windDir=";
resource += String(angle);
getWindData();
resource += "&windSpeed=";
resource += String(Vind_GetHastighed());
resource += "&rainAmount=";
getRainData();
resource += String(buffer);
Serial.println(resource);
CiaoData data = Ciao.write("rest", "http://example.com/", resource, "GET");
if (!data.isEmpty()){
Ciao.println( "Link: " + String (resource) );
Ciao.println( "State: " + String (data.get(1)) );
Ciao.println( "Response: " + String (data.get(2)) );
Ciao.println();
}
else{
Ciao.println ("Write Error");
Ciao.println();
}
}
// Initializing processes
void initWind(void)
{
pinMode(3, INPUT);
attachInterrupt(1, windSpeed, RISING);
windTimer=millis();//start timing
Serial.println("* Vindretning");
Serial.println("* Vindhastighed");
}
//initializing rainmeasure
void initRain(void)
{
attachInterrupt(0, Rain_Measure, RISING); //analog port 0
LastRainReset = millis();
Serial.println("* Regn");
}
//Counts amount of rain
void Rain_Measure(void)
{
volatile byte hit = 1;
if (hit == 1) {
hit = 2;
} else if (hit == 2) {
hit = 3;
} else if (hit == 3) {
RainMeasurement = RainMeasurement + 0.2794;
hit = 1;
}
}
//Prints winddirection
String printWindDirection(byte y)
{
// read the analog input into a variable:
String windDir = "unknown";
float voltage = analogRead(0)/204.6;
for (int i = 0; i < 16; i++) {
if (voltage <= table[i]+0.03 && voltage >= table[i]-0.03) {
angle = i;
break;
}
}
//Serial.println(angle); //print the result
switch (angle) {
case 0:
windDir = "N";
break;
case 1:
windDir = "NNE";
break;
case 2:
windDir = "NE";
break;
case 3:
windDir = "E";
break;
case 4:
windDir = "E";
break;
case 5:
windDir = "E";
break;
case 6:
windDir = "SE";
break;
case 7:
windDir = "SSE";
break;
case 8:
windDir = "S";
break;
case 9:
windDir = "SW";
break;
case 10:
windDir = "SW";
break;
case 11:
windDir = "WSW";
break;
case 12:
windDir = "W";
break;
case 13:
windDir = "WNW";
break;
case 14:
windDir = "NW";
break;
case 15:
windDir = "NNW";
break;
default:
break;
}
return windDir;
}
//Prints windspeed
int Vind_GetHastighed()
{
/*
The cup-type anemometer measures wind speed by closing a contact as
a magnet moves past a switch. A wind speed of 1.492 MPH (2.4 km/h)
causes the switch to close once per second.
*/
//Check using Interrupt
float windDtime = millis()-windTimer;
windTimer = millis();
windDtime = windDtime/1000;
float windSpeed = windRotation/windDtime;//rotation per second
windRotation = 0;
windSpeed = windSpeed*2/3;//1 rotation per second equals 2.4 km/h = 2/3 m/s
return int(windSpeed);
}
void windSpeed()
{
windRotation++;
}
Arduino has the F() macro for constant strings to simply indicate that the string should be used from the 'ROM' flash memory of Harvard architecture CPU and not loaded into 'dynamic memory' (RAM). By wrapping constant strings into F macro you reduce the usage of RAM.
The void loop is only running once. Please help. I am inexperienced with Arduino, so any help is much-appreciated. When I open the serial monitor I only see zero once. This code was working earlier today. Sorry if the solution is very simple. Some code has been removed to fit within post restrictions such as ints and ultrasonic declarations and includes.
void setup() {
Serial.begin(9600); //sets up Serial monitor
InfraredSeeker::Initialize();
}
void loop() {
if(u = 1) {
ang = uang;
} else{
ang = irang;
}
Serial.println(uang);
m1 = 200*cos((30-ang)*0.0174533);
m2 = 200*cos((270-ang)*0.0174533);
m3 = 200*cos((150-ang)*0.0174533);
InfraredResult InfraredBall = InfraredSeeker::ReadAC();
switch (InfraredBall.Direction) {
case 1:
irang = 160;
break;
case 2:
irang = 120;
break;
case 3:
irang = 90;
break;
case 4:
irang = 50;
break;
case 5:
irang = 0;
break;
case 6:
irang = 310;
break;
case 7:
irang = 270;
break;
case 8:
irang = 240;
break;
case 9:
irang = 200;
break;
case 0:
irang = 160;
break;
default:
break;
}
lultra = uleft.Ranging(CM);
rultra = urigth.Ranging(CM);
fultra = ufront.Ranging(CM);
if (lultra < 15){
u = 1;
uang = 270;
}
if (rultra < 15) {
u = 1;
uang = 90;
}
if (fultra < 15) {
u = 1;
uang = 180;
}
}