Can't read Com port with QB64 - port

I am using Arduino as a slave just to read the voltage of a battery.
The program in Arduino is is C. The computer program is written in QB64
It is connected to a USB com port#3. The slave program and QB64 work fine for making the Pin 13 Blink. But when I ask for a voltage all I get is 10 empty spaces no data.
The following QB64 code is my attempt to read. The comments show some of the results:
CLS
ctr = 1 ' Counts number times you press continue
again:
INPUT "Press any key to continue"; d$ ' Run program to receive voltage
OPEN "Com3:9600,n,8,1,ds0,cs0,rs" FOR RANDOM AS #1
_DELAY .5 ' delay to let com settle
FIELD #1, 35 AS m$
' **** Form Message to send to External Device ****
Command = 2: pin = 4: argument = 0 ' Code to Get analog voltage reading
msg$ = STR$(Command) + "," + STR$(pin) + "," + STR$(argument) + "*"
PRINT "msg$ Sent= "; msg$, CHR$(13) ' Show Message
LSET m$ = msg$
PUT #1, , m$ ' Send message to the external device
_DELAY 1
'***** C code in external device *****
'External device responds to message & prints to Com3 buffer.
' if ( cmd == 2)//getanalog
' {
' int sensorValue = analogRead(pin);//
' delay(10);
' float voltage= sensorValue*(5.0/1023.0);
' Serial.print("Voltage =");
' Serial.print(voltage);
' Serial.print(",");
' Serial.print("*");
' }
CLOSE #1
m$ = "": msg$ = "" ' Wipe out old messages
OPEN "Com3:9600,n,8,1,ds0,cs0,rs" FOR RANDOM AS #1
_DELAY .5 ' Delay to let Com Port settle
FIELD #1, 50 AS m$
t1 = TIMER ' Start time for getdata
getdata:
bytes% = LOC(1) ' Check receive buffer for data
IF bytes% = 0 THEN GOTO getdata 'After thousands of cycles it continues
PRINT "Bytes="; bytes ' Bytes remain at 0
DO UNTIL EOF(1)
GET #1, , m$ ' First GET #1 returns EOF=-1
PRINT "LEN(m$)= "; LEN(m$) ' Length of m$ = 10
IF INSTR(m$, "*") > 0 THEN GOTO duh ' Never finds End of Message (*)
LOOP
IF bytes% = 0 THEN GOTO getdata
t2 = TIMER ' End time, Have data
DeltaT = t2 - t1 ' How long did it take?
GOTO stepover ' If arrived here w/o End of Message signal
duh:
PRINT "DUH instr= "; INSTR(m$, "*") ' Never hits this line
stepover:
tmp$ = "DeltaT= #.### Seconds Until LOC(1) > 0" ' Various times
PRINT USING tmp$; DeltaT
PRINT "m$ Received= "; m$ + "&" ' Prints 10 spaces No Data
PRINT "endofdata= "; endofdata ' endofdata=0, Never got "*"
PRINT "ctr= "; ctr, CHR$(13) ' Show number of times you pressed continue
CLOSE #1
ctr = ctr + 1
GOTO again
Also included in the comments is the Slave program that writes to the com port.
Some lines of QB64 code are not necessary but were included as debugging attempt

Related

My ruby code is reliant on the number of the line appearing before the prompt. How do I fix this?

def main()
count = 1
while count <= 10
puts "#{count}" " Enter integer 1: "
int1=gets.chomp.to_i
count = count + 1
puts "#{count}" " Enter integer 2: "
int2=gets.chomp.to_i
count = count + 1
puts "#{count}" " Enter integer 3: "
int3=gets.chomp.to_i
count = count + 1
puts "#{count}" " Enter integer 4: "
int4=gets.chomp.to_i
count = count + 1
puts "#{count}" " Enter integer 5: "
int5=gets.chomp.to_i
count = count + 1
puts "#{count}" " Enter integer 6: "
int6=gets.chomp.to_i
count = count + 1
puts "#{count}" " Enter integer 7: "
int7=gets.chomp.to_i
count = count + 1
puts "#{count}" " Enter integer 8: "
int8=gets.chomp.to_i
count = count + 1
puts "#{count}" " Enter integer 9: "
int9=gets.chomp.to_i
count = count + 1
puts "#{count}" " Enter integer 10: "
int10=gets.chomp.to_i
count = count + 1
sum=int1+int2+int3+int4+int5+int6+int7+int8+int9+int10
end
puts "Total is: #{sum}"
end
main()
I made a program on ruby that prompts the user to enter a number 10 times and sums all the inputted numbers together. The only problem is that my code is reliant on the number to the corresponding line appearing before the line. For example, the first prompt is "1 Enter integer 1:" while what I'm aiming to make it is "Enter integer 1:".
Another issue I have is that I don't know how to make the input appear on the same line as the prompt. It appears on a new line, for example "1 Enter integer 1: while I want it to be "1 Enter integer 1: 156" 1"
Thank you.
The ruby REPL irb is line-at-a-time, so you can't get your input on the same line in the standard environment. (Other ways of doing it are of course available, up to and including a full Rails app! Which is far more than you want here, of course.)
To resolve your main issue, though, consider using an array to gather your input. You could then condense your code considerably, to something like this:
array = []
for i in 1..10 do
puts "Enter integer #{i}:"
array.push(gets.to_i)
end
sum = array.sum
If you don't need to prompt the user with a counter of the numbers they've entered, you could simplify even further like this:
array = []
10.times do
puts "Enter integer:"
array.push(gets.to_i)
end
sum = array.sum
sum = 0
(1..10).each do |i|
print "#{i} Enter integer: "
sum += gets.chomp.to_i
end
puts "Sum is " + sum.to_s
puts will add a newline to the output, print doesn't.

Zend 2 escaping single-quote

I am using Zend Framework 2 to generate the following escaped single-quote SQL query,
SELECT
`document`.*
FROM
`document`
WHERE
(
`document`.`document_taxon` LIKE '%Men\'s Health %' --escaped quote
AND `document`.`document_source_id` = ' 5 '
AND `document`.`document_published` = ' 1 '
AND `document`.`document_deleted` = ' 0 '
)
ORDER BY
`document_id` DESC
LIMIT 25 OFFSET 0
But I am getting this instead,
SELECT
`document`.*
FROM
`document`
WHERE
(
`document`.`document_taxon` LIKE '%Men's Health%'
AND `document`.`document_source_id` = ' 5 '
AND `document`.`document_published` = ' 1 '
AND `document`.`document_deleted` = ' 0 '
)
ORDER BY
`document_id` DESC
LIMIT 25 OFFSET 0
And here is my code
class DocumentTable extends TableGateway
{
....
$select=$this->getSql()->select();
$select->columns(array('*'));
$select->where
->NEST
->like('document_taxon', '%' . $label . '%')
->and
->equalTo('document_source_id', $sourceId)
->and
->equalTo('document_published', true)
->and
->equalTo('document_deleted', 0)
->UNNEST;
$select->order('document_id DESC');
$select->limit($limit);
$select->offset($offset);
...
}
I tried,
$this->getAdapter()->getPlatform()->quoteValue($string)
\Zend\Db\Sql\Expression("%". $label . "%")
str_replace("'", "\'", $label)
But I didn’t have much luck. I welcome any suggestion to solve this issue.
I worked it out. I was passing a normalized “label” value instead of the raw value. The above code snippet works fine.

How to avoid Round-up from NormalizeDouble and OrderSend Pending Order (SELLLIMIT, BUYLIMIT) get Error -1 Invalid stops

Please advice me how to solve problem when OrderSend Pending Order ( BUYLIMIT, SELLLIMIT) got error -1 Invalid stops.
also tell me the rule of BUYLIMIT and SELLLIMIT.
the simple code like below:
`
double digit = MarketInfo(symbol,MODE_DIGITS);
POPRICE = NormalizeDouble(BBMVAL[0],digit);
TPPRICE = NormalizeDouble(POPRICE + (30*point),digit)
SLPRICE = NormalizeDouble(POPRICE - (30*point),digit)
ticket1=OrderSend(symbol,OP_BUYLIMIT,0.1, POPRICE,Slippage,SLPRICE,TPPRICE,BUYLIMIT,magic,(TimeCurrent()+(3600*2)),CLR_NONE);
Sleep(10);
while(IsTradeContextBusy()) Sleep(100);
RefreshRates();
if(ticket1 < 0)
{
SendMail
(
symbol+"-"+ IntegerToString(Period())+"-" + "FAILED-BUYLIMIT ",
symbol+"-"+ IntegerToString(Period())+"-" + "FAILED-BUYLIMIT "+"(#PO-Price:"+POPRICE+"#TP:"+TPPRICE++"#SL:"+SLPRICE+"#RespID:"+ticket1+"#Status: "+ErrorDescription(GetLastError())+")"
);
ticket1 = 0;
}
if (ticket1 > 0)
{
b_Status = 1;
SendMail
(
symbol+"-"+ IntegerToString(Period())+"-" + "SUCCESSED-BUYLIMIT ",
symbol+"-"+ IntegerToString(Period())+"-" + "SUCCESSED-BUYLIMIT "+"(#PO- Price:"+POPRICE+"#TP:"+TPPRICE+"#SL:"+SLPRICE+"#RespID:"+ticket1+"#Status: "+ErrorDescription(GetLastError())+")"
);
ticket1 = 0;
}
the objective is :
If the pair EURUSD 5-digit, How to make the SLPRICE, POPRICE, TPPRICE always with 5-digit. sometimes with 5 digit and sometime roundup with 4-digit. is it right to use NormalizeDouble ? how to avoid the roundup.
when got Failed ( tiket1 < 0 ), the error is -1 ( invalid stops), what is the real reason of this error. sometimes successed and sometime failed. what is the rules of selllimit and the buylimit.
and when got Failed, there are many emails send to email-address. how to avoid this problem too.
THank you very much.
It is perfectly okay to have a 4 digit price when 5 digit decimal is expected, but since double is a floating-point number, sometimes you don't get the exact price you might expect,
for example:
let's say you are calculating TP for a long trade, 1.10000 + 0.0020 = 1.10020(expected) but you might get something like this 1.10020001, in these cases the price level is rejected, causing errors. That is why price normalizing is important.
In some pairs, you might find that NormalizeDouble() sometimes gives false values, in those cases use the following function.
double NP(const double price)
{
double tickSize = SymbolInfoDouble(Symbol(), SYMBOL_TRADE_TICK_SIZE);
return (MathRound(price / tickSize) * tickSize );
}
As for getting the many emails: you can limit the number of emails per period of time.
Here I made it so that you get 1 email per new candle:
if(ticket1 < 0)
{
static datetime prevTime = 0;
if(Time[0] > prevTime)
{
SendMail
(
symbol + "-" + IntegerToString(Period()) + "-" + "FAILED-BUYLIMIT ",
symbol + "-" + IntegerToString(Period()) + "-" + "FAILED-BUYLIMIT " + "(#PO-Price:" + POPRICE + "#TP:" + TPPRICE++"#SL:" + SLPRICE + "#RespID:" + ticket1 + "#Status: " + ErrorDescription(GetLastError()) + ")"
);
prevTime = Time[0];
}
ticket1 = 0;
}

nest api target temperature for both thermostat modes

Is it possible to fetch target temperature for both thermostat mode (cool, heat) in one call ? For now I have a feeling that I can get target temperature for current thermostat mode and then change thermostat mode to second one and get target temperature for second thermostat mode.
Also the same question for changing target temps. Is it possible to change both target temperature for heat and cool mode in one request ?
Assuming your system can cool and heat, the thermostat has 3 modes: heat, cool, heat-cool.
If you are in heat mode or cool mode you can set target_temperature. If you are in heat-cool mode you can set target_temperature_low_c & target_temperature_high_c.
You can retrieve all target temperatures in one thermostat call:
https://developer-api.nest.com/devices/thermostats/$THERMOSTAT_ID?auth=$AUTH
You can set heat-cool temperatures in one call, but you will need to be in heat-cool mode:
{"target_temperature_low_c": 19, "target_temperature_high_c": 21}
You can set heat or cool temperature in one call, but you will need to be in heat or cool mode:
{"target_temperature_c": 20}
You will need to make 2 calls to set the mode and set the temperature(s) if you are not already in an appropriate mode.
It is possible to get all of the thermostat data, even for multiple thermostats in a single API call. I just posted an opensource application written in python that does it on BitBucket at:
https://bitbucket.org/dwalton64_/window-watcher
The application looks at weather data from weather underground, air quality data from airnow and data from Nest to determine if the user should open or close the windows. I make the API call to Nest, getting all of the data in a single call, and then parse the data in a structure. The application then uses the thermostat hvac mode and the target temperature to see if the user should open the windows.
Here is some Python code I pulled out of my application:
nestUserUrl = "https://developer-api.nest.com/?auth=" + auth_token
nest_user_file = urllib2.urlopen(self.nestUserUrl)
nest_user_json = json.loads(nest_user_file.read())
# copy thermostat data out of the json from Nest
thermostat_data = []
for tstat_id in nest_user_json['devices']['thermostats']:
thermostat_data.append(nest_user_json['devices']['thermostats'][tstat_id])
# create thermostat objects containing the thermostat data we want to access
thermostats = []
for tstat in thermostat_data:
thermostats.append(
NestThermostat(tstat['ambient_temperature_f'], tstat['device_id'],
tstat['hvac_mode'],
tstat['is_online'], tstat['last_connection'],
tstat['name'],
tstat['software_version'], tstat['structure_id'],
tstat['target_temperature_f'],
tstat['target_temperature_high_f'],
tstat['target_temperature_low_f']))
class NestThermostat():
def __init__(self, ambient_temperature_f, device_id, hvac_mode, is_online,
last_connection, name, software_version, structure_id,
target_temperature_f, target_temperature_high_f, target_temperature_low_f):
self.ambient_temperature_f = ambient_temperature_f
self.device_id = device_id
self.hvac_mode = hvac_mode
self.is_online = is_online
self.last_connection = last_connection
self.name = name
self.software_version = software_version
self.structure_id = structure_id
self.target_temperature_f = target_temperature_f
self.target_temperature_high_f = target_temperature_high_f
self.target_temperature_low_f = target_temperature_low_f
def print_current_temp_f(self):
print("Thermostat " + self.name + " measures a current temperature of " + str(
self.ambient_temperature_f) + " degrees F")
def print_target_temp_f(self):
print("Thermostat " + self.name + " is set to " + str(self.target_temperature_f) + " degrees F")
Once I have the data in the thermostat objects, I can use both the hvac mode and the target temperatures:
email = ""
for thermostat in thermostats:
email += "For the thermostat " + thermostat.name + ":\n"
if thermostat.hvac_mode == 'cool':
if myWeather.temp_f < thermostat.target_temperature_f:
open_windows = True
email += " - It is cool outside (" + str(myWeather.temp_f) + " Deg F). \n"
else:
email += " - It is too hot outside to have the windows open. \n"
email += " - Thermostat is set at " + str(thermostat.target_temperature_f) + \
" Deg F\n"
if thermostat.hvac_mode == 'heat-cool':
if thermostat.target_temperature_high_f > myWeather.temp_f > thermostat.target_temperature_low_f:
open_windows = True
email += " - Thermostat is set to heat-cool and it's comfortable out (" + \
str(myWeather.temp_f) + " Deg F). \n"
elif myWeather.temp_f >= thermostat.target_temperature_high_f:
email += " - The thermostat is set to heat-cool and it is hot outside (" + \
str(myWeather.temp_f) + " Deg F). \n"
else:
email += " - The thermostat is set to heat-cool & it is cold outside (" + \
str(myWeather.temp_f) + " Deg F). \n"
email += " - The thermostat is set to cool at " + \
str(thermostat.target_temperature_high_f) + " Deg F\n"
email += " - The thermostat is set to heat at " + \
str(thermostat.target_temperature_low_f) + " Deg F\n"
if thermostat.hvac_mode == 'heat':
if myWeather.temp_f > thermostat.target_temperature_f:
open_windows = True
email += " - The thermostat is set to heat and it is warm outside (" + \
str(myWeather.temp_f) + " Deg F). \n"
else:
email += " - The thermostat is set to heat and it is cool outside (" + \
str(myWeather.temp_f) + " Deg F). \n"
email += " - Thermostat is set at " + str(thermostat.target_temperature_f) + \
" Deg F\n"
email += "\n"
Note that the target temperature for heat and cool mode is the same value: target_temperature_f.

Filehelpers - Complex record layout assistance

We are attempting to use filehelpers for some file interface projects specifically dealing with EDI. The sample definition below makes use of the EDI 858 Specification. Like most interface specs, each vendor has their own flavor. You can find a sample 858 EDI spec here
Our Vendor has their own flavor; this is the sample record definition we are currently using from before conversion:
H1_Record_type As String ' * 8 EDI858FF
H2_TRANS_DATE As String ' * 8 yyyyMMdd
H3_Trans_type As String ' * 2 00 = New, 01 = Cancel Carrier, 03 = Delete, 04 = Change
H4_Pay_type As String ' * 2 PP = Prepaid, CC = Collect, TP = Third Party (our default is PP)
H5_Load As String ' * 30 Authorization
H6_Load_Ready_date As String ' * 12 yyyyMMddHHmm
H7_Commodity As String ' * 10
H8_Customer_HQ_ID As String ' * 20 hard coded '0000000001'
H9_Customer As String
H10_Mill_ID As String ' * 20 Shipping Perdue Location or Destination Perdue Location
H11_Tender_Method As String ' * 10 blank for now
H12_Carrier_ID As String ' * 10 blank for now
H13_Weight As String ' * 7 estimated total load weight
H14_Weight_Qualifier As String ' * 2 blank for now
H15_Total_Miles As String ' * 7 zero for now
H16_Total_quantity As String ' * 7 blank for now
H17_Weight_Unit As String ' * 1 L = pounds, K = Kilograms, L=default
H18_REF As String ' * 3 REF
HR1_Ref_qualifier As String ' * 3 CO = Deliv Dest ref., P8 = Deliv Orig Ref.
HR2_Ref_value As String ' * 80
H19_END_REF As String ' * 7 END REF
H20_SPEC_INSTRUCTION As String ' * 16 SPEC INSTRUCTION
HS1_Qualifier As String ' * 3 1 = Credit Hold, 7T = Export Order, HM = Hazmat, L = Load ready for pickup
' PTS = Tarp, RO = Hot Load, TAR = Full Tarp, WTV = Weight Verification, DDN = Driver needs TWIC
' PR = Prohibited
H21_END_SPEC As String ' * 20 END SPEC INSTRUCTION
H22_NOTE As String ' * 4 NOTE
HN1_Note_Qualifier As String ' * 3 SPH = Special Handling, PRI = Load Priority, DEL = Transit Days
HN2_Note As String ' * 80
H23_END_NOTE As String ' * 8 END NOTE
H24_EQUIPMENT As String ' * 9 EQUIPMENT
H25_END As String ' * 13 END EQUIPMENT
H26_LOAD_CONTACT As String ' * 12 LOAD CONTACT
LC1_Contact_Name As String ' * 60
LC2_Contact_type As String ' * 2 EM= E-mail, FX = Fax, TE = Telephone
LC3_Contact_Data As String ' * 80
H27_END_LOAD_CONTACT As String ' * 16 END LOAD CONTACT
H28_STOP As String ' * 4 STOP There will always be 2 - CL and CU
S1_Stop_Number As String ' * 2
S2_Stop_Reason As String ' * 2 CL = Complete Load, CU = Complete Unload (one of each required for every load)
S3_LOCATION As String ' * 8 LOCATION
SL1_Location_ID As String ' * 20
SL2_Location_Name As String ' * 60
SL3_Location_Add1 As String ' * 55
SL4_Location_Add2 As String ' * 55
SL5_Location_City As String ' * 30
SL6_Location_State As String ' * 2
SL7_Location_Zip As String ' * 10 (use only 5 digits)
SL8_Location_Country As String ' * 3 USA, CAN, MEX
S4_END_LOCATION As String ' * 12 END LOCATION
S5_STOP_DATE As String ' * 9 STOP DATE
SD1_Date_Qualifier As String ' * 3 37 = No earlier than, 38 = No later than, 10 = Expected arrival time, 35 = Actual arrival
' 11 = Actual departure
SD2_Date_Time As String ' * 12 yyyyMMddHHmm
S6_END_STOP_DATE As String ' * 13 END STOP DATE
S7_STOP_REF As String ' * 8 STOP REF
SR1_Reference_Qualifier As String ' 3 72 = Transit Time, DK = Dock Number, OQ = Order Number
SR2_Reference_Value As String ' * 80
S8_END_STOP_REF As String ' * 12 END STOP REF
H29_END_STOP As String ' * 8 END STOP
H30_ORDER As String ' * 5 ORDER
O1_Order_Number As String ' * 80
H31_END_ORDER As String ' * 9 END ORDER
this is a sample message it would normally be in one long line:
EDI858FF~20140611~04~PP~1266010982~201406060700~CANOLA
ML~0000000001~Business Name~RICHLAND~~~60000~~0~~L~REF~SA~Customer
Name~END REF~STOP~01~CL~LOCATION~RICHLAND~~~~~~~~END LOCATION~STOP
DATE~37~201406060000~END STOP DATE~STOP REF~OQ~5568~END STOP REF~END
STOP~STOP~02~CU~LOCATION~261450~~~~~~~~END LOCATION~STOP
DATE~37~201406060000~END STOP DATE~STOP REF~OQ~5568~END STOP REF~END
STOP~ORDER~5568~END ORDER
I really think this may be too complex of a task for Filehelpers, but I wanted to put it out there to the community to see if you all could help.
As you can see the file is mostly tilde delimited, however certain fields in the definition also act as delimiters. For instance REF or STOP both contain additional information that could be many records deep. You could have multiple STOP definitions 1 to 999 location records. I am really really thinking that this is just too much for Filehelpers...
If you were to attempt this configuration for filehelpers, where would you start and how would you handle all the child fields?
FileHelpers is not the ideal tool for such a complex format. These are the reasons:
Not have enough flexibility with regard to identifying and reporting errors.
Difficulties with escaped characters (e.g., when a tilde is within a field and needs to be escaped) I'm not familiar enough with the EDI format to know if this is likely to be an issue.
The master/detail tools provided by FileHelpers are insufficient
For (1), you don't mention whether you are importing or exporting EDI, or both. If you are only exporting EDI, error reporting would not be necessary.
For (2), you could work around the escaping problems by providing your own custom converters for the problem fields, but you might find every single field has a custom converter.
For (3), There are two ways of handling master/detail records with FileHelpers, but neither of them are likely to cover your requirements without some serious hacking
One way would be to use the MasterDetailEngine, but this only supports one detail type and only one level of nesting, so you would have to find workarounds for both of these.
Another way would be to use the to use the MultiRecordEngine. However, it would treat each row as an unrelated record and the hierarchy (that is, which S record belongs to which H record) would be hard to determine.

Resources