Serial monitor problem instantly finishing - arduino-ide

int pinRed=2;
int pinBlue=4;
int pinWhite=6;
String Color;
String question="Which LED would you like to light up Red,Blue or White?";
int delayTime=1000;
void setup() {
Serial.begin(9600);
pinMode(pinRed,OUTPUT);
pinMode(pinBlue,OUTPUT);
pinMode(pinWhite,OUTPUT);
}
void loop() {
Serial.print(question);
while(Serial.available()==0){
}
Color=Serial.readString();
if(Color=="Red" || Color=="red"){
digitalWrite(pinRed,HIGH);
digitalWrite(pinBlue,LOW);
digitalWrite(pinWhite,LOW);
delay(delayTime);
}
if(Color=="Blue" || Color=="blue"){
digitalWrite(pinBlue,HIGH);
digitalWrite(pinRed,LOW);
digitalWrite(pinWhite,LOW);
delay(delayTime);
}
if(Color=="White" || Color=="white"){
digitalWrite(pinWhite,HIGH);
digitalWrite(pinBlue,LOW);
digitalWrite(pinRed,LOW);
delay(delayTime);
}
delay(delayTime);
}
This is my code, but is not working, when I enter a color the serial monitor ask the question again instantly and not led is turning on, I checked the pins and the LEDs work completely fine but I think I have a problem with my serial monitor cause I am having problem with every project using the serial monitor despite even copying codes from the internet, so anyone have any idea what can be the problem(I am on version Arduino 1.8.18)

I do not know for sure as I am not familiar with the particular language/library that you are using. However, the symptoms you describe indicate that your input string does not match any of your targets ('red', 'RED') etc.
I would re-read the description of the Serial.available() function. Is it returning non-zero as soon as the first character is available? If so then your input string from
Color=Serial.readString() will always be aone-character string, eg 'r'.
To test this you could try matching against 'r', 'g', 'b' as strings.....

Related

Putting C++ string in HTML code to show value on webserver

I've set up a webserver running on ESP8266 thats currently hosting 7 sites. The sites is written in plain HTML in each diffrent tab in the arduino ide. I have installed the library Pagebuilder to help with making everything look nice and run.
Except one thing. I have a button connected to my ESP8266 which by the time being imitates a sensor input. basicly when the button is pressed my integer "x" increments with 1. I also managed to make a string that replicates "x" and increments with the same value.
I also have a problem with Printing the IPadresse of the server, but thats not as important as the other.
My plan then was writing the string "score" (which contains x) into the HTML tab where it should be output. this obviously didnt work.
Things I've tried:
Splitting up the HTML code where I want the string to be printed and using client.println("");
This didnt work because the two libraries does not cooperate and WiFiClient does not find Pagebuilders server. (basicly, the client.println does nothing when I used it with Pagebuilder).
Reconstructing the HTML page as a literal really long string, and adding in the String with x like this: "html"+score+"html" and adding it into where the HTML page const char were. (basicly replacing the variable with the text that were in the variable).
This did neighter work because the argument "PageElement" from Pagebuilder does only expect one string, and errors out because theres an additional string inside the HTML string.
I've tried sending it as a post req. but this did not output the value either.
I have run out of Ideas to try.
//root page
#if defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <WiFiClient.h>
#elif defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h>
#include <WebServer.h>
#endif
#include "PageBuilder.h"
#include "currentGame.h" //tab 1
#if defined(ARDUINO_ARCH_ESP8266)
ESP8266WebServer Server;
ESP8266WebServer server;
#endif
int sensorPin = 2; // button input
int sensorValue = 0;
int x = 0; // the int x
String score=""; //the string x will be in
PageElement CURRENT_GAME_ELEMENT(htmlPage1);
PageBuilder CURRENT_GAME("/current-game", {CURRENT_GAME_ELEMENT}); // this //only showes on href /current-game
void button() {
sensorValue = analogRead(sensorPin); //read the voltage
score="Team 1: "+String((int)x+1); //"make" x a string
if (sensorValue <= 10) { // check if button is pressed
x++; // increment x
Serial.println(x);
Serial.println(score);
delay(100);
}
}
void setup() {
Serial.begin(115200);
pinMode(2, INPUT);
WiFi.softAP("SSID", "PASS");
delay(100);
CURRENT_GAME.insert(Server);
Server.begin();
}
void loop() {
Server.handleClient();
button();
}
// tab 1
const char htmlPage1[] PROGMEM = R"=====(
/*
alot of HTML, basicly the whole website...
..............................................
*/
<div class="jumbotron">
<div align="center">
<h1 class="display-4"> score </h1> // <--- this is where
//I want to print the
//string:
</div>
</div>
)=====";
what I want to do is getting the value of the string score displayed on the website. If I put "score" directly into the HTML, the word score will be displayed, not the value. I want the value displayed.
Edit:
I have figured out how to make the string(score) be printed in the HTML code, thus, I only have to convert the HTML code string back to a char. explanation is in comment below.
Edit 2: (-------------------------solution-------------------------)
Many thanks for the help I've gotten and sorry for being so ignorant, its just so hard being so close and that thing doesnt work. but anyways, What I did was following Pagebuilders example, and making another element to print in current game..
String test(PageArgument& args) {
return score;
}
const char html[] = "<div class=\"jumbotron\"><div align=\"center\"><h1 class=\"display-4\">{{NAME}}</h1></div></div>";
PageElement FRAMEWORK_PAGE_ELEMENT(htmlPage0);
PageBuilder FRAMEWORK_PAGE("/", {FRAMEWORK_PAGE_ELEMENT});
PageElement body_elem(html, { {"NAME", test} });
PageElement CURRENT_GAME_ELEMENT(htmlPage1);
PageBuilder CURRENT_GAME("/current-game", { CURRENT_GAME_ELEMENT, body_elem});
suprisingly easy when I first understood it.. Thanks again.
You could try building your string first, then converting it to a const char
like this: const char * c = str.c_str();
if you can't use a pointer you could try this:
string s = "yourHTML" + score + "moreHTML";
int n = s.length();
char char_array[n + 1];
strcpy(char_array, s.c_str());
additionally you could try the stringstream standard library
This sort of thing is often done using magic tags in your markup that are detected by the server code before it serves the HTML and filled in by executing some sort of callback or filling in a variable, or whatever.
So with this in mind and hoping for the best, I nipped over to: PageBuilder on github and looked to see if there was something similar here. Good news! In one of the examples:
const char html[] = "hello <b>{{NAME}}</b>, <br>Good {{DAYTIME}}.";
...
PageElement body_elem(html, { {"NAME", AsName}, {"DAYTIME", AsDayTime} });
Where {{NAME}} and {{DAYTIME}} are magic tokens. AsName and AsDayTime are functions to be called when the respective tag is encountered while the page is being served.
EDIT: in response to a request to explain differently, I'm not convinced I can do a better job of explaining the code than the example on the library's own github page, so I'll try a wordy description instead:
When you want to serve a webpage to a client, the code needs to know what you want to serve. In the simplest case, it's a static page: the same every time. You can just write the HTML, stick it in a string an be done.
whole_page = "<html>My fixed content</html>";
webserver.serve(whole_page);
But you want some dynamic element(s). As noted, you can do it in a few ways, such as serving some static HTML, then the dynamic bit, then some more static HTML. It seems you've not had much luck like this, and it's rather clunky anyway.
Or you can pre-build a new string out of the three bits and serve that in one chunk, but that's also pretty clunky.
(Aside: taking big strings and adding them together is likely to be slow and memory intensive, two things you really don't want on a little CPU like the ESP8266).
So instead, you allow 'magic' markers in the HTML, using a marker in place of the dynamic content, and serve that instead.
whole_page = "<html>My dynamic content. Value is {{my_value}}</html>";
webserver.serve(whole_page, ...);
The clever bit is that as the page is being served, the webserver is watching the text go by, and when it sees a magic tag, it stops and asks you to fill in the blank, then carries on as before.
Obviously, there is some processing overhead with watching for tags, and some programming overhead with telling it what tags to watch for and how to ask you for the data it needs.
I got advice from a friend who told me I should make a unique argument where I wanted the string(x) and then using some syntax to replace it. I also took inspiration from you Jelle..
what I did was make a unique argument "VAR_CURRENT_SCORE" put that into the HTML where I want the score output, then convert htmlPage1 from a char to a string, use string.replace() and replace "VAR_CURRENT_SCORE" with the string(x) score. this workes as I can see in the serial monitor output.
This is what I did:
//root page
String HTMLstring(htmlstringPage);
delay(100);
HTMLstring.replace("VAR_CURRENT_SCORE", score);
delay(50);
Serial.println("string:");
Serial.println(HTMLstring);
//tab 1 char htmlstringPage[] PROGMEM = R"=====(
<div class="jumbotron">
<div align="center">
<h1 class="display-4">VAR_CURRENT_SCORE</h1>
</div>
</div>
)=====";
However, I still have a small problem left which is converting the string back to char to post it to the website.
To convert the string back:
request->send_P(200, "text/html", HTMLstring.c_str());

GCC produces unaligned function address on Cortex M3

I just placed a function to a specific address using a section and then I output the address of that function and the result is the chosen section address + 1.
This is what I did:
void __attribute__((section (".my_fct_address"))) Fct_Ptr_Test (void)
{
...
}
and
void (*fct_ptr) (void);
fct_ptr = Fct_Ptr_Test;
printf ("0X%X\r\n", (uint32_t)(fct_ptr));
fct_ptr ();
in ld-file:
.my_fct_address 0x800F000 :
{
KEEP(*(.my_fct_address)) /* keep my variable even if not referenced */
} > FLASH
The above printf statement outputs 0x800F001 and Fct_Ptr_Test is called properly
If I set
fct_ptr = 0x800F000;
the system crashes.
If I set
fct_ptr = 0x800F001;
everything is fine again.
If I don't place Fct_Ptr_Test in its own section , ie let the linker place it anywhere I also get an odd address.
Now I wonder how 0x800F001 can be a proper address on a 32 bit controller (ARM cortex M3) and what is stored in 0x800F000.
Even more strange: map-file always shows the even addresses
Can anybody help?
Thanks
Martin
Linker sets the least-significant bit of Thumb functions to 1 to facilitate interworking (see docs). Perhaps that's your case?

getItemProperty returns not null - Vaadin bug?

I need help, maybe I am blind. Here is a fragment of my code:
System.out.println("itemPropertyIDS="+item.getItemPropertyIds().toString());
System.out.println("argname="+argName);
Property<?> p = item.getItemProperty(argName);
if (p != null) {
System.out.println("p="+p.toString());
return p.getValue();
}
// Continue ...
It returns a currious null value instead of continue, even if the propertyId doesn't exists.
This is written on my console:
itemPropertyIDS=[iconName, iconResource, nodeType, nodeValue, nodeName, handler, nodeData]
argname=Lab
p=com.vaadin.data.util.IndexedContainer$IndexedContainerProperty#12967
The first row shows list of property names.
I expected getTtemProperty must return null, but not.
The item comes from IndexedContainer.
Can you help me? Any idea? Thanky You.
I tested your code and indeed - property p is not null even though property doesn't exist in IndexedContainer. Reading the comments of Vaadin ticket pasted by kris54321, it makes sense not fixing the bug as some applications may rely on that feature. Fixing the bug may break those apps.
Possible workarounds for this problem:
Check directly the propertyId-collection if property exists in the container:
if(item.getItemPropertyIds().contains(argName) {
Property<?> p = item.getItemProperty(argName);
System.out.println("p="+p.toString());
return p.getValue()
}
Change the logic to check property value
if(item.getItemProperty(argname).getValue() != null) }
//Do things
{
I was forced to make workaround using "item.getItemPropertyIds().contains(argName)". For me, the priority is to check whether the item contains the value (null possible) or not. If yes then I use the value (can be null) else another activity is done.
If they dont want to fix the bug due to application using the bug, then the documentation should be fixed, else all novices in Vaadin (as I am) will be confused.
The implementation in IndexedContainer$IndexedContainer is wrong:
#Override
public Property getItemProperty(Object id) {
return new IndexedContainerProperty(itemId, id);
}
This can never return null as the documentation says.

New to ActionScript3, Making calculator and stuck

first time here on stackoverflow and first time scripting in flashCS6.
ill get down to it - the only lang ive done is html and a bit of css. I tried learning java, but gave up since i realised im making flash games so might as well just do AS3. Its pretty similar and not at all at the same time.
As my first original program (i did a tutorial of pong from a website before, got to know a bit about functions and event handlers[http://as3gametuts.com/2011/03/19/pong-1/]), im trying to create a calculator, and what want to know is how i can return the values from two input fields, put them into a logic calculator (say input a is 1 and input b is 2, and there are four functions, each attached to an event listener for the 4 mathematical operations, and i press addition so the calculator goes 2+1=3)
main question here, how do i get the outut text field to display the answer. In java i just used system.out.println(inputA + inputB).
Here i tried to do out.text = ( a + b) (where out is output , a is input and b is input 2)
Here is the code i have so far:
a is input 1, b is input 2
Out is output
and mul, add, sub and div are symbols containing dynamic test fields with instance names adn, sub, mul and div respectively. The symbol instances are the same as the test instances) Ex: i have a text field that says addition, its instance name is adn, then i convert it to a symbol and make its instance name adn as well.
a.text.restrict = "0-9";
b.text.restrict = "0-9";
mul.addEventListener(MouseEvent.CLICK, output);
adn.addEventListener(MouseEvent.CLICK, addition);
sub.addEventListener(MouseEvent.CLICK, subtraction);
div.addEventListener(MouseEvent.CLICK, division);
a.addEventListener(TextInput,input);
b.addEventListener(TextInput,input);
function output ():void
{
out.text=("test to see if output works")
}
function input (e:TextInput)
{
}
function multiplication (e:MouseEvent)
{
}
function addition (e:MouseEvent)
{
}
function subtraction (e:MouseEvent)
{
}
function division (e:MouseEvent)
{
}
thanks guys, and cheers! Also, ill appreciate if anyone can link me to a good video or text tutorial (series) for AS3 introduction. My main focus is to be making PC games and not apps, so keep that in mind.
Check This Out
Also, don't forget to convert value to string, that may be neccessary:
out.text = String(a + b);
Since a text field will give you the input typecast as a string you will need to type cast them to type Number or type int before you can do any kind of math function on them.
And if you want to create a more complex calculator I would suggest you read up on the Math class
function subtraction (e:MouseEvent)
{
var result:Number = Number(a.text) - Number(b.text)
out.text = String(result)
}

Speech API (SAPI) floating point division by zero in C++ Builder on Windows 7

I use the following code for Text-To-Speech application controls for blind persons in C++ Builder (most likely similar example can be used in Delphi). Main form has KeyPreview property checked to enable key F11 preview to start speaking active (focused) control. The code as it is works but there are some problems. This example is in C++ Builder code but from what I've found, Delphi suffers from same problem and the solution I found is the same. If you have Delphi solution, feel free to post it, it is similar anyway.
#include <sapi.h>
#include <WTypes.h>
//---------------------------------------------------------------------------
// Speak text string (synchronous function)
//---------------------------------------------------------------------------
bool SpeakText(UnicodeString Text)
{
ISpVoice* pVoice = NULL;
if (FAILED(::CoInitialize(NULL))) return false;
Word Saved8087CW = Default8087CW; // Disable floating point division by zero exception caused by Speak
Set8087CW(0x133f);
HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
if (SUCCEEDED(hr))
{
//pVoice->SpeakCompleteEvent()
//pVoice->SetSyncSpeakTimeout(1000);
hr = pVoice->Speak(WideString(Text).c_bstr(), SPF_DEFAULT, NULL);
pVoice->Release();
pVoice = NULL;
}
Set8087CW(Saved8087CW);
::CoUninitialize();
return true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormKeyUp(TObject *Sender, WORD &Key, TShiftState Shift)
{
UnicodeString Speaker;
if (Key == VK_F11)
{
if (Screen->ActiveControl->InheritsFrom(__classid(TButton))) { Speaker += "Button, " + static_cast<TButton*>(Screen->ActiveControl)->Caption + "."; }
else if (Screen->ActiveControl->InheritsFrom(__classid(TEdit))) { Speaker += "Edit box, " + static_cast<TEdit*>(Screen->ActiveControl)->Text + "."; }
}
if (Speaker != "") SpeakText(Speaker);
}
//---------------------------------------------------------------------------
Problems:
pVoice->Speak causes Floating point division by zero if I don't override the exception using the Set8087CW function. This happens only on Windows 7 (possibly Vista and Windows 8 too) but not on Windows XP in the same program (compiled exe). Is there a solution without using Set8087CW? Removing these lines will cause the problem and exception. I have BCB2010.
Function is synchronous and won't shut up or return control to program until it finishes reading text. This is a problem for longer text. It also blocks program events. Is there a way to make it asynchronous or introduce an event to periodically check for F11 key status and if F11 is pressed again it stops reading and uninitializes object? For example poll every 300 ms (or after each word etc.) for key-press F11 and if pressed, stop speaking? Or run it threaded?
Does SAPI has memory leaks as some write on various sites?
Can above code use OleCheck instead of CoCreateInstance and CoUninitialize?
UPDATE for those looking for solution as suggested by Remy Lebeau:
SavedCW = Get8087CW();
Set8087CW(SavedCW | 0x4);
hr = pVoice->Speak(WideString(Text).c_bstr(), SPF_DEFAULT | SPF_ASYNC, NULL);
pVoice->WaitUntilDone(-1); // Waits until text is done... if F11 is pressed simply go out of scope and speech will stop
Set8087CW(SavedCW);
Also found detailed example in CodeRage 4 session: http://cc.embarcadero.com/item/27264
The error does occur in Vista as well. Masking floating point exceptions is the only solution.
To make Speak() run asynchronously, you need to include the SPF_ASYNC flag when calling it. If you need to detect when asynchronous speaking is finished, you can use ISpVoice::WaitUntilDone(), or call ISpVoice::SpeakCompleteEvent() and pass the returned HANDLE to one of the WaitFor...() family of functions, like WaitForSingleObject().
What kind of leaks do other sites talk about?
Not instead of, no. OleCheck() merely checks the value of an HRESULT value and throws an exception if it is an error value. You still have to call COM functions that return the actual HRESULT values in the first place. If anything, OleCheck() would be a replacement for SUCCEEDED() instead.
For what you are attempting, I would suggest the following approach instead:
struct s8087CW
{
Word Saved8087CW;
s8087CW(Word NewCW)
{
Saved8087CW = Default8087CW;
Set8087CW(NewCW);
// alternatively, the VCL documentation says to use SetExceptionMask() instead of Set8087CW() directly...
}
~s8087CW()
{
Set8087CW(Saved8087CW);
}
};
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent *Owner)
: TForm(Owner)
{
::CoInitialize(NULL);
}
//---------------------------------------------------------------------------
__fastcall TForm1::~TForm1()
{
if (pVoice) pVoice->Release();
::CoUninitialize();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormKeyUp(TObject *Sender, WORD &Key, TShiftState Shift)
{
if (Key == VK_F11)
{
TWinControl *Ctrl = Screen->ActiveControl;
if (Ctrl)
{
TButton *btn;
TEdit *edit;
if ((btn = dynamic_cast<TButton*>(Ctrl)) != NULL)
SpeakText("Button, " + btn->Caption);
else if ((edit = dynamic_cast<TEdit*>(Ctrl)) != NULL)
SpeakText("Edit box, " + edit->Text);
}
}
}
//---------------------------------------------------------------------------
ISpVoice* pVoice = NULL;
bool __fastcall TForm1::SpeakText(const String &Text)
{
s8087CW cw(0x133f);
if (!pVoice)
{
if (FAILED(CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice)))
return false;
}
SPVOICESTATUS stat;
pVoice->GetStatus(&stat, NULL);
while (stat.dwRunningState == SPRS_IS_SPEAKING)
{
ULONG skipped;
pVoice->Skip(L"SENTENCE", 1000, &skipped);
pVoice->GetStatus(&stat, NULL);
}
return SUCCEEDED(pVoice->Speak(WideString(Text).c_bstr(), SPF_ASYNC, NULL));
}